Skip to content

Commit

Permalink
Reorgnize some miscellaneous functions
Browse files Browse the repository at this point in the history
  • Loading branch information
mtkennerly committed Jun 7, 2024
1 parent 84e0ab5 commit e801df5
Show file tree
Hide file tree
Showing 3 changed files with 111 additions and 94 deletions.
32 changes: 2 additions & 30 deletions src/Api.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ public Runner(ILogger logger, LudusaviPlayniteSettings settings)

try
{
var (code, stdout) = RunCommand(settings.ExecutablePath.Trim(), args, json);
var (code, stdout) = Etc.RunCommand(settings.ExecutablePath.Trim(), args, json);
if (standalone)
{
logger.Debug(string.Format("Ludusavi exited with {0}", code));
Expand All @@ -73,38 +73,10 @@ public Runner(ILogger logger, LudusaviPlayniteSettings settings)
}
}

private (int, string) RunCommand(string command, string args, string stdin)
{
var p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.FileName = command;
p.StartInfo.Arguments = args;
p.StartInfo.StandardOutputEncoding = Encoding.UTF8;
p.Start();

p.StandardInput.WriteLine(stdin);
p.StandardInput.Close();

var stdout = p.StandardOutput.ReadToEnd();
p.WaitForExit();

return (p.ExitCode, stdout);
}

public void FindTitle(Game game, string name, bool hasAltTitle)
{
var names = new List<string> { name };

int? steamId = null;
if (Etc.IsOnSteam(game) && int.TryParse(game.GameId, out var id))
{
steamId = id;
}

if (!Etc.IsOnPc(game) && settings.RetryNonPcGamesWithoutSuffix)
{
names.Add(game.Name);
Expand All @@ -113,7 +85,7 @@ public void FindTitle(Game game, string name, bool hasAltTitle)
var inner = new Requests.FindTitle
{
names = names,
steamId = steamId,
steamId = Etc.SteamId(game),
normalized = this.settings.RetryUnrecognizedGameWithNormalization,
};

Expand Down
92 changes: 92 additions & 0 deletions src/Etc.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,94 @@ public static class Etc
public static Version RECOMMENDED_APP_VERSION = new Version(0, 24, 0);
private static Regex HOME_DIR = new Regex("^~");

public static V GetDictValue<K, V>(Dictionary<K, V> dict, K key, V fallback)
{
if (dict == null || key == null)
{
return fallback;
}

V result;
var found = dict.TryGetValue(key, out result);
if (found)
{
return result;
}
else
{
return fallback;
}
}

public static (int, string) RunCommand(string command, string args)
{
var p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.FileName = command;
p.StartInfo.Arguments = args;
p.StartInfo.StandardOutputEncoding = System.Text.Encoding.UTF8;
p.Start();

var stdout = p.StandardOutput.ReadToEnd();
p.WaitForExit();

return (p.ExitCode, stdout);
}

public static (int, string) RunCommand(string command, string args, string stdin)
{
var p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.FileName = command;
p.StartInfo.Arguments = args;
p.StartInfo.StandardOutputEncoding = System.Text.Encoding.UTF8;
p.Start();

p.StandardInput.WriteLine(stdin);
p.StandardInput.Close();

var stdout = p.StandardOutput.ReadToEnd();
p.WaitForExit();

return (p.ExitCode, stdout);
}

public static bool IsOnSteam(Game game)
{
return game.Source?.Name == "Steam"
|| game.PluginId == Guid.Parse("cb91dfc9-b977-43bf-8e70-55f46e410fab");
}

public static int? SteamId(Game game)
{
if (IsOnSteam(game) && int.TryParse(game.GameId, out var id))
{
return id;
}

return null;
}

public static bool TrySteamId(Game game, out int result)
{
var id = SteamId(game);
if (id != null)
{
result = (int)id;
return true;
}

result = 0;
return false;
}

public static bool IsOnPc(Game game)
{
var pcSpecs = new List<string> { "macintosh", "pc_dos", "pc_linux", "pc_windows" };
Expand All @@ -28,6 +110,16 @@ public static bool IsOnPc(Game game)
|| game.Platforms.Any(x => pcNames.Contains(x.Name));
}

public static string GetTitleId(Game game)
{
return string.Format("{0}:{1}", game.PluginId, game.GameId);
}

public static Platform GetGamePlatform(Game game)
{
return game?.Platforms?.ElementAtOrDefault(0);
}

public static string NormalizePath(string path)
{
return HOME_DIR.Replace(path, Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)).Replace("/", "\\");
Expand Down
81 changes: 17 additions & 64 deletions src/LudusaviPlaynite.cs
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ public override IEnumerable<GameMenuItem> GetGameMenuItems(GetGameMenuItemsArgs
if (menuArgs.Games.Count == 1)
{
var title = menuArgs.Games[0].Name;
string renamed = GetDictValue(settings.AlternativeTitles, title, null);
string renamed = Etc.GetDictValue(settings.AlternativeTitles, title, null);

items.Add(
new GameMenuItem
Expand Down Expand Up @@ -381,7 +381,7 @@ public override void OnApplicationStarted(OnApplicationStartedEventArgs args)
{
try
{
RunCommand("cmd.exe", "/c \"start https://github.com/mtkennerly/ludusavi/releases\"");
Etc.RunCommand("cmd.exe", "/c \"start https://github.com/mtkennerly/ludusavi/releases\"");
}
catch
{ }
Expand Down Expand Up @@ -521,7 +521,7 @@ public void RefreshLudusaviTitles()
{
if (response.findTitle?.titles.Count() == 1)
{
this.titles.Add(GetTitleId(games[i]), response.findTitle?.titles[0]);
this.titles.Add(Etc.GetTitleId(games[i]), response.findTitle?.titles[0]);
}

i += 1;
Expand Down Expand Up @@ -661,31 +661,13 @@ private void ShowFullResults(ApiResponse response)
{ }
}

private (int, string) RunCommand(string command, string args)
{
var p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.FileName = command;
p.StartInfo.Arguments = args;
p.StartInfo.StandardOutputEncoding = Encoding.UTF8;
p.Start();

var stdout = p.StandardOutput.ReadToEnd();
p.WaitForExit();

return (p.ExitCode, stdout);
}

private Version GetLudusaviVersion()
{
int code;
string stdout;
try
{
(code, stdout) = RunCommand(settings.ExecutablePath.Trim(), "--version");
(code, stdout) = Etc.RunCommand(settings.ExecutablePath.Trim(), "--version");
var version = stdout.Trim().Split(' ').Last();
return new Version(version);
}
Expand All @@ -703,7 +685,7 @@ private Version GetLudusaviVersion()

try
{
var (code, stdout) = RunCommand(settings.ExecutablePath.Trim(), fullArgs);
var (code, stdout) = Etc.RunCommand(settings.ExecutablePath.Trim(), fullArgs);
if (standalone)
{
logger.Debug(string.Format("Ludusavi exited with {0}", code));
Expand Down Expand Up @@ -816,14 +798,9 @@ private bool ShouldSkipGame(Game game)
return HasTag(game, Tags.SKIP);
}

string GetTitleId(Game game)
{
return string.Format("{0}:{1}", game.PluginId, game.GameId);
}

string GetTitle(Game game)
{
return GetDictValue(this.titles, GetTitleId(game), null);
return Etc.GetDictValue(this.titles, Etc.GetTitleId(game), null);
}

string GetGameName(Game game)
Expand Down Expand Up @@ -853,12 +830,7 @@ string GetGameNameWithAlt(Game game)

private string AlternativeTitle(Game game)
{
return GetDictValue(settings.AlternativeTitles, game.Name, null);
}

private Platform GetGamePlatform(Game game)
{
return game?.Platforms?.ElementAtOrDefault(0);
return Etc.GetDictValue(settings.AlternativeTitles, game.Name, null);
}

private string GetDisplayName(Game game, BackupCriteria criteria)
Expand All @@ -868,7 +840,7 @@ private string GetDisplayName(Game game, BackupCriteria criteria)
case BackupCriteria.Game:
return GetGameName(game);
case BackupCriteria.Platform:
return GetGamePlatform(game)?.Name ?? "unknown platform";
return Etc.GetGamePlatform(game)?.Name ?? "unknown platform";
default:
throw new InvalidOperationException(String.Format("GetDisplayName got unexpected criteria: {0}", criteria));
}
Expand Down Expand Up @@ -900,7 +872,7 @@ private string FindGame(Game game, string name, OperationTiming timing, BackupCr
{
// There can't be an alt title because the Steam ID/etc would take priority over it.

if (Etc.IsOnSteam(game) && int.TryParse(game.GameId, out var id))
if (Etc.TrySteamId(game, out var id))
{
invocation.SteamId(id);
}
Expand Down Expand Up @@ -949,7 +921,7 @@ private void InitiateOperationSync(Game game, Operation operation, OperationTimi
}
}

if (criteria.ByPlatform() && GetGamePlatform(game) == null)
if (criteria.ByPlatform() && Etc.GetGamePlatform(game) == null)
{
return;
}
Expand Down Expand Up @@ -1407,7 +1379,7 @@ private PlayPreferences GetPlayPreferences(Game game)
var platformBackupDo = (settings.DoPlatformBackupOnNonPcGameStopped || HasTag(game, Tags.PLATFORM_BACKUP) || HasTag(game, Tags.PLATFORM_BACKUP_AND_RESTORE))
&& !HasTag(game, Tags.PLATFORM_NO_BACKUP)
&& !Etc.IsOnPc(game)
&& GetGamePlatform(game) != null;
&& Etc.GetGamePlatform(game) != null;

var prefs = new PlayPreferences
{
Expand Down Expand Up @@ -1469,7 +1441,7 @@ private bool GameHasKnownSaveData(Game game)
return true;
}

if (Etc.IsOnSteam(game) && int.TryParse(game.GameId, out var id) && this.manifestGamesWithSaveDataBySteamId.Contains(id))
if (Etc.TrySteamId(game, out var id) && this.manifestGamesWithSaveDataBySteamId.Contains(id))
{
return true;
}
Expand All @@ -1482,7 +1454,7 @@ private List<ApiBackup> GetBackups(Game game)
if (this.appVersion.supportsApiCommand())
{
var title = GetTitle(game);
var backups = GetDictValue(this.backups, title, new List<ApiBackup>());
var backups = Etc.GetDictValue(this.backups, title, new List<ApiBackup>());

// Sort newest backups to the top.
backups.Sort((x, y) => y.When.CompareTo(x.When));
Expand All @@ -1495,14 +1467,14 @@ private List<ApiBackup> GetBackups(Game game)

if (alt != null)
{
ret = GetDictValue(this.backups, alt, new List<ApiBackup>());
ret = Etc.GetDictValue(this.backups, alt, new List<ApiBackup>());
}
else
{
ret = GetDictValue(
ret = Etc.GetDictValue(
this.backups,
GetGameName(game),
GetDictValue(
Etc.GetDictValue(
this.backups,
game.Name,
new List<ApiBackup>()
Expand All @@ -1518,26 +1490,7 @@ private List<ApiBackup> GetBackups(Game game)

private string GetBackupPath(Game game)
{
return GetDictValue(this.backupPaths, GetTitle(game) ?? GetGameNameWithAlt(game), null);
}

private V GetDictValue<K, V>(Dictionary<K, V> dict, K key, V fallback)
{
if (dict == null || key == null)
{
return fallback;
}

V result;
var found = dict.TryGetValue(key, out result);
if (found)
{
return result;
}
else
{
return fallback;
}
return Etc.GetDictValue(this.backupPaths, GetTitle(game) ?? GetGameNameWithAlt(game), null);
}

private string GetBackupDisplayLine(ApiBackup backup)
Expand Down

0 comments on commit e801df5

Please sign in to comment.