mirror of
https://github.com/tgeorgiadis/quiver-launcher.git
synced 2026-12-06 03:38:02 -05:00
- Updated MainView and CLIHandler to use ShortcutHelper.ResolveLauncherPath for consistent launcher path resolution. - Introduced unit tests for ShortcutHelper to validate launcher path resolution logic, ensuring correct behavior across various scenarios, including AppImage and process paths. Co-authored-by: Cursor <cursoragent@cursor.com>
911 lines
34 KiB
C#
911 lines
34 KiB
C#
using QuiverLauncher.Core.Models;
|
|
using QuiverLauncher.Core.Services;
|
|
using QuiverLauncher.Models;
|
|
using QuiverLauncher.Services;
|
|
using System;
|
|
using System.ComponentModel;
|
|
using System.Diagnostics;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Net.Http;
|
|
using System.Runtime.InteropServices;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace QuiverLauncher
|
|
{
|
|
public class CLIHandler
|
|
{
|
|
private const ConsoleColor ColorTitle = ConsoleColor.Cyan;
|
|
private const ConsoleColor ColorSuccess = ConsoleColor.Green;
|
|
private const ConsoleColor ColorWarning = ConsoleColor.Yellow;
|
|
private const ConsoleColor ColorError = ConsoleColor.Red;
|
|
private const ConsoleColor ColorMuted = ConsoleColor.DarkGray;
|
|
private static readonly QuiverLauncherProfile Profile = QuiverLauncherProfile.Instance;
|
|
private static readonly string Repository = Profile.Repository;
|
|
private GameManager? _gameManager;
|
|
private string _currentVersion = "Unknown";
|
|
private readonly LauncherUpdateService _launcherUpdateService;
|
|
private readonly VelopackUpdateService _velopackUpdateService;
|
|
|
|
public CLIHandler(GameManager? gameManager = null, LauncherUpdateService? launcherUpdateService = null)
|
|
{
|
|
_gameManager = gameManager;
|
|
_launcherUpdateService = launcherUpdateService ?? new LauncherUpdateService();
|
|
_velopackUpdateService = new VelopackUpdateService();
|
|
}
|
|
|
|
public async Task<int> Execute(string[] args)
|
|
{
|
|
if (args.Length == 0)
|
|
{
|
|
ClearTerminal();
|
|
await PrintHeader();
|
|
ShowHelp();
|
|
return 0;
|
|
}
|
|
|
|
var command = args[0].ToLower();
|
|
|
|
try
|
|
{
|
|
switch (command)
|
|
{
|
|
case "--add-steam-shortcut":
|
|
await InitializeGameManager();
|
|
return await AddSteamShortcutCommand(args);
|
|
|
|
case "-h":
|
|
case "--help":
|
|
ClearTerminal();
|
|
await PrintHeader();
|
|
ShowHelp();
|
|
return 0;
|
|
|
|
case "-l":
|
|
case "--list":
|
|
ClearTerminal();
|
|
await PrintHeader();
|
|
await InitializeGameManager();
|
|
return await ListGames();
|
|
|
|
case "-r":
|
|
case "--run":
|
|
ClearTerminal();
|
|
await PrintHeader();
|
|
await InitializeGameManager();
|
|
return await RunGame(GetGameNameFromArgs(args));
|
|
|
|
case "-d":
|
|
case "--download":
|
|
ClearTerminal();
|
|
await PrintHeader();
|
|
await InitializeGameManager();
|
|
return await DownloadGameCommand(GetGameNameFromArgs(args));
|
|
|
|
case "-u":
|
|
case "--update":
|
|
ClearTerminal();
|
|
await PrintHeader();
|
|
await InitializeGameManager();
|
|
return await UpdateAllGames();
|
|
|
|
case "--update-launcher":
|
|
case "--self-update":
|
|
ClearTerminal();
|
|
await PrintHeader();
|
|
return await UpdateLauncher();
|
|
|
|
case "-x":
|
|
case "--uninstall":
|
|
ClearTerminal();
|
|
await PrintHeader();
|
|
await InitializeGameManager();
|
|
return await UninstallGame(GetGameNameFromArgs(args));
|
|
|
|
default:
|
|
ClearTerminal();
|
|
await PrintHeader();
|
|
ShowHelp();
|
|
return PrintError($"Unknown command: {command}");
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
return PrintError($"Critical error: {ex.Message}");
|
|
}
|
|
finally
|
|
{
|
|
_gameManager?.Dispose();
|
|
}
|
|
}
|
|
|
|
private static void ClearTerminal()
|
|
{
|
|
try
|
|
{
|
|
Console.Clear();
|
|
}
|
|
catch
|
|
{
|
|
// Fallback for terminals that don't support Clear()
|
|
// Send ANSI escape sequences that work on most modern terminals
|
|
Console.Write("\x1b[2J\x1b[H");
|
|
}
|
|
}
|
|
|
|
private async Task InitializeGameManager()
|
|
{
|
|
if (_gameManager == null)
|
|
{
|
|
_gameManager = new GameManager();
|
|
var settings = AppSettings.Load();
|
|
settings.EnsureInitialized();
|
|
var originalScope = settings.ListScope;
|
|
settings.ListScope = AppListScope.AllApps;
|
|
AppSettings.Save(settings);
|
|
|
|
await _gameManager.LoadGamesAsync();
|
|
|
|
settings.ListScope = originalScope;
|
|
AppSettings.Save(settings);
|
|
}
|
|
}
|
|
|
|
private string GetGameNameFromArgs(string[] args)
|
|
{
|
|
if (args.Length < 2) return string.Empty;
|
|
return string.Join(" ", args.Skip(1)).Trim('"', '\'');
|
|
}
|
|
|
|
private static string GetExactArg(string[] args, int index)
|
|
{
|
|
return args.Length > index ? args[index] : string.Empty;
|
|
}
|
|
|
|
private void LoadVersion()
|
|
{
|
|
_currentVersion = _velopackUpdateService.CurrentVersion
|
|
?? _launcherUpdateService.ReadInstalledVersion();
|
|
}
|
|
|
|
private async Task CheckForLauncherUpdates()
|
|
{
|
|
try
|
|
{
|
|
if (VelopackUpdateService.ShouldSkipAutomaticSelfUpdate())
|
|
return;
|
|
|
|
var settings = AppSettings.Load();
|
|
var token = settings?.GitHubApiToken;
|
|
var result = await _velopackUpdateService.CheckForUpdatesAsync(
|
|
token,
|
|
allowPrereleaseLauncherUpdates: settings?.AllowPrereleaseLauncherUpdates ?? false);
|
|
if (result.UpdateAvailable && !string.IsNullOrWhiteSpace(result.AvailableVersion))
|
|
{
|
|
WriteColor($" [UPDATE AVAILABLE] ", ColorWarning);
|
|
Console.WriteLine($"New version {result.AvailableVersion} is available! Use --update-launcher to upgrade.");
|
|
Console.WriteLine();
|
|
}
|
|
}
|
|
catch
|
|
{
|
|
// Silently skip update check if offline or error
|
|
}
|
|
}
|
|
|
|
private async Task PrintHeader()
|
|
{
|
|
LoadVersion();
|
|
|
|
Console.WriteLine();
|
|
WriteColor(" __ _ _ _ _ _ _ _ ", ColorTitle);
|
|
WriteColor(" _ ", ColorMuted);
|
|
Console.WriteLine();
|
|
|
|
WriteColor(" / _|| | | | | | | | | | | | |_| ", ColorTitle);
|
|
WriteColor("| | __ _ _ _ _ __ | | ___ _ _ ", ColorMuted);
|
|
Console.WriteLine();
|
|
|
|
WriteColor("| |_ | |_| | | |_| |_| |_| | | | | ", ColorTitle);
|
|
WriteColor("| | / _` | | | | '_ \\| |/ _ \\| | | | ", ColorMuted);
|
|
Console.WriteLine();
|
|
|
|
WriteColor("| _|| _ | | _ _ _ _ | | |_| ", ColorTitle);
|
|
WriteColor("| |_| (_| | |_| | | | | | (_) | |_| | ", ColorMuted);
|
|
Console.WriteLine();
|
|
|
|
WriteColor("| | | | | | | | | | | | | \\ / ", ColorTitle);
|
|
WriteColor("|_|\\__,_|\\__,_|_| |_|_|\\___/ \\__,_| ", ColorMuted);
|
|
Console.WriteLine();
|
|
|
|
WriteColor("|_| |_| |_| |_|_| |_|_|_| \\/ ", ColorTitle);
|
|
WriteColor(" ", ColorMuted);
|
|
Console.WriteLine();
|
|
|
|
Console.WriteLine($" Launcher Version: {_currentVersion}");
|
|
|
|
await CheckForLauncherUpdates();
|
|
PrintLine();
|
|
}
|
|
|
|
private void ShowHelp()
|
|
{
|
|
Console.WriteLine("Usage: QuiverLauncher [command] [game name]");
|
|
Console.WriteLine();
|
|
WriteColor("Commands:", ColorTitle);
|
|
Console.WriteLine();
|
|
PrintHelpItem("-h, --help", "Show this help screen");
|
|
PrintHelpItem("-l, --list", "List all available games");
|
|
PrintHelpItem("-u, --update", "Update all installed games");
|
|
PrintHelpItem("--update-launcher", "Update the launcher itself");
|
|
PrintHelpItem("-d, --download <name>", "Download and install a game");
|
|
PrintHelpItem("-r, --run <name>", "Run a game (auto-updates if needed)");
|
|
PrintHelpItem("-x, --uninstall <name>", "Uninstall a game");
|
|
Console.WriteLine();
|
|
WriteColor("Examples:", ColorMuted);
|
|
Console.WriteLine();
|
|
Console.WriteLine(" QuiverLauncher --list");
|
|
Console.WriteLine(" QuiverLauncher --download Banjo64");
|
|
Console.WriteLine(" QuiverLauncher --run Banjo64");
|
|
Console.WriteLine(" QuiverLauncher -r \"Mario Kart 64\"");
|
|
Console.WriteLine();
|
|
}
|
|
|
|
private async Task<int> AddSteamShortcutCommand(string[] args)
|
|
{
|
|
if (_gameManager?.Games == null)
|
|
return PrintError("App library is not available.");
|
|
|
|
string gameName = GetExactArg(args, 1).Trim('"', '\'');
|
|
bool waitForSteamExit = args.Any(arg => string.Equals(arg, "--wait-for-steam-exit", StringComparison.OrdinalIgnoreCase));
|
|
|
|
if (string.IsNullOrWhiteSpace(gameName))
|
|
return PrintError("No game name was provided for --add-steam-shortcut.");
|
|
|
|
var game = _gameManager.Games
|
|
.FirstOrDefault(g => string.Equals(g?.Name, gameName, StringComparison.Ordinal));
|
|
|
|
if (game == null)
|
|
return PrintError($"Could not find a game named '{gameName}'.");
|
|
|
|
try
|
|
{
|
|
string launcherPath = ShortcutHelper.ResolveLauncherPath() ?? string.Empty;
|
|
if (string.IsNullOrWhiteSpace(launcherPath))
|
|
return PrintError("Could not determine launcher location.");
|
|
|
|
await ShortcutHelper.AddGameToSteamFromCliAsync(
|
|
game,
|
|
launcherPath,
|
|
_gameManager.CacheFolder,
|
|
waitForSteamExit);
|
|
|
|
return 0;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
return PrintError($"Failed to add Steam shortcut: {ex.Message}");
|
|
}
|
|
}
|
|
|
|
private async Task<int> ListGames()
|
|
{
|
|
if (_gameManager?.Games == null || !_gameManager.Games.Any())
|
|
return PrintError("No games found in library.");
|
|
|
|
int maxNameLength = _gameManager.Games.Max(g => g?.Name?.Length ?? 10) + 4;
|
|
if (maxNameLength < 30) maxNameLength = 30;
|
|
|
|
Console.WriteLine();
|
|
WriteColor("Available Apps:", ColorTitle);
|
|
Console.WriteLine();
|
|
Console.WriteLine();
|
|
|
|
foreach (var game in _gameManager.Games.OrderBy(g => g?.Name))
|
|
{
|
|
if (game == null) continue;
|
|
|
|
string name = game.Name ?? "Unknown";
|
|
Console.Write($" {name.PadRight(maxNameLength)} ");
|
|
|
|
string version = CleanVersion(game.LatestVersion);
|
|
string installedVer = CleanVersion(game.InstalledVersion);
|
|
|
|
switch (game.Status)
|
|
{
|
|
case GameStatus.Installed:
|
|
WriteColor("[INSTALLED] ", ColorSuccess);
|
|
Console.WriteLine($" {installedVer}");
|
|
break;
|
|
case GameStatus.UpdateAvailable:
|
|
WriteColor("[UPDATE AVAILABLE]", ColorWarning);
|
|
Console.WriteLine($" {installedVer} -> {version}");
|
|
break;
|
|
default:
|
|
WriteColor("[NOT INSTALLED] ", ColorMuted);
|
|
Console.WriteLine($" Latest: {version}");
|
|
break;
|
|
}
|
|
}
|
|
|
|
Console.WriteLine();
|
|
return 0;
|
|
}
|
|
|
|
private async Task<int> RunGame(string gameName)
|
|
{
|
|
if (string.IsNullOrEmpty(gameName))
|
|
{
|
|
ShowHelp();
|
|
return PrintError("App name required.");
|
|
}
|
|
|
|
var game = FindGame(gameName);
|
|
if (game == null)
|
|
{
|
|
Console.WriteLine();
|
|
WriteColor("Available games: ", ColorMuted);
|
|
Console.WriteLine(string.Join(", ", _gameManager?.Games.Select(g => g.Name) ?? Array.Empty<string>()));
|
|
Console.WriteLine();
|
|
return PrintError($"App not found: '{gameName}'");
|
|
}
|
|
|
|
if (game.Status == GameStatus.NotInstalled)
|
|
{
|
|
return PrintError($"{game.Name} is not installed. Use --download first.");
|
|
}
|
|
|
|
// Auto-update if update is available
|
|
if (game.Status == GameStatus.UpdateAvailable)
|
|
{
|
|
WriteColor($"→ Update available for {game.Name}. Updating first...", ColorWarning);
|
|
Console.WriteLine();
|
|
|
|
int updateResult = await UpdateOrDownloadGame(game, isUpdate: true);
|
|
if (updateResult != 0) return updateResult;
|
|
|
|
// Re-check status after update
|
|
await game.CheckStatusAsync(_gameManager.HttpClient, _gameManager.GamesFolder, forceUpdateCheck: true);
|
|
}
|
|
|
|
var settings = AppSettings.Load();
|
|
var gamesFolder = _gameManager.GamesFolder;
|
|
if (string.IsNullOrEmpty(gamesFolder) || string.IsNullOrEmpty(game.FolderName))
|
|
{
|
|
return PrintError("App folder is not configured.");
|
|
}
|
|
|
|
// Check if need to select executable
|
|
var storedExe = game.LoadSelectedExecutable(gamesFolder);
|
|
|
|
if (string.IsNullOrEmpty(storedExe))
|
|
{
|
|
// Check if there are multiple executables
|
|
var gamePath = game.GetInstallPath(gamesFolder);
|
|
GameInfo.EnsureExecutableAtRoot(gamePath);
|
|
|
|
var executables = GameInfo.GetExecutableCandidates(gamePath, SearchOption.TopDirectoryOnly, out _);
|
|
if (executables.Count == 0)
|
|
{
|
|
executables = GameInfo.GetExecutableCandidates(gamePath, SearchOption.AllDirectories, out _);
|
|
}
|
|
|
|
if (executables.Count == 0)
|
|
{
|
|
return PrintError($"No executable found for {game.Name} in {gamePath}.\nThe game may not have installed correctly, or it's an unsupported format.");
|
|
}
|
|
else if (executables.Count > 1)
|
|
{
|
|
WriteColor($"⚠ Multiple executables found for {game.Name}.", ColorWarning);
|
|
Console.WriteLine();
|
|
Console.WriteLine();
|
|
Console.WriteLine("Please run the game through the App Interface to select the correct executable.");
|
|
Console.WriteLine("After selection, the next time you use --run it will automatically launch that executable.");
|
|
Console.WriteLine();
|
|
WriteColor("Opening launcher in 1 second...", ColorMuted);
|
|
Console.WriteLine();
|
|
|
|
await Task.Delay(1000);
|
|
|
|
// Launch the GUI
|
|
try
|
|
{
|
|
var exePath = Environment.ProcessPath ?? Process.GetCurrentProcess().MainModule?.FileName;
|
|
|
|
if (!string.IsNullOrEmpty(exePath))
|
|
{
|
|
var exeDir = Path.GetDirectoryName(exePath);
|
|
var guiExe = exePath;
|
|
|
|
// If running the CLI version, try to find the GUI version
|
|
if (exePath.Contains("CLI", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
var possibleGuiExe = Path.Combine(exeDir, "QuiverLauncher.exe");
|
|
if (File.Exists(possibleGuiExe))
|
|
{
|
|
guiExe = possibleGuiExe;
|
|
}
|
|
}
|
|
|
|
var psi = new ProcessStartInfo
|
|
{
|
|
FileName = guiExe,
|
|
UseShellExecute = true
|
|
};
|
|
Process.Start(psi);
|
|
|
|
return 0;
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
return PrintError($"Failed to launch GUI: {ex.Message}");
|
|
}
|
|
|
|
return PrintError("Unable to launch GUI.");
|
|
}
|
|
else if (executables.Count == 1)
|
|
{
|
|
game.SelectedExecutable = executables[0];
|
|
game.SaveSelectedExecutable(game.SelectedExecutable, gamesFolder);
|
|
}
|
|
}
|
|
|
|
WriteColor($"→ Launching {game.Name}...", ColorSuccess);
|
|
Console.WriteLine();
|
|
Console.WriteLine();
|
|
|
|
var launchedProcessSource = new TaskCompletionSource<Process?>(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
void OnGameProcessStarted(Process? process) => launchedProcessSource.TrySetResult(process);
|
|
|
|
try
|
|
{
|
|
game.GameProcessStarted += OnGameProcessStarted;
|
|
await game.PerformActionAsync(
|
|
_gameManager.HttpClient,
|
|
gamesFolder,
|
|
settings);
|
|
|
|
game.GameProcessStarted -= OnGameProcessStarted;
|
|
|
|
if (launchedProcessSource.Task.IsCompletedSuccessfully)
|
|
{
|
|
await WaitForLaunchedGameSessionAsync(launchedProcessSource.Task.Result);
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
game.GameProcessStarted -= OnGameProcessStarted;
|
|
return PrintError($"Failed to launch {game.Name}: {ex.Message}");
|
|
}
|
|
}
|
|
|
|
private static async Task WaitForLaunchedGameSessionAsync(Process? process)
|
|
{
|
|
if (process == null)
|
|
return;
|
|
|
|
int? processGroupId = null;
|
|
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
|
|
{
|
|
var currentProcessGroupId = await TryGetProcessGroupIdAsync(Environment.ProcessId);
|
|
var launchedProcessGroupId = await TryGetProcessGroupIdAsync(process.Id);
|
|
if (launchedProcessGroupId.HasValue && launchedProcessGroupId != currentProcessGroupId)
|
|
{
|
|
processGroupId = launchedProcessGroupId;
|
|
}
|
|
}
|
|
|
|
try
|
|
{
|
|
await process.WaitForExitAsync();
|
|
}
|
|
catch
|
|
{
|
|
// The process may already be gone by this point.
|
|
}
|
|
|
|
if (processGroupId.HasValue)
|
|
{
|
|
while (await HasActiveProcessGroupAsync(processGroupId.Value))
|
|
{
|
|
await Task.Delay(1000);
|
|
}
|
|
}
|
|
}
|
|
|
|
private static async Task<int?> TryGetProcessGroupIdAsync(int processId)
|
|
{
|
|
try
|
|
{
|
|
var startInfo = new ProcessStartInfo
|
|
{
|
|
FileName = "ps",
|
|
Arguments = $"-o pgid= -p {processId}",
|
|
UseShellExecute = false,
|
|
RedirectStandardOutput = true,
|
|
RedirectStandardError = true,
|
|
CreateNoWindow = true
|
|
};
|
|
|
|
using var psProcess = Process.Start(startInfo);
|
|
if (psProcess == null)
|
|
return null;
|
|
|
|
var output = await psProcess.StandardOutput.ReadToEndAsync();
|
|
await psProcess.WaitForExitAsync();
|
|
|
|
return psProcess.ExitCode == 0 && int.TryParse(output.Trim(), out var processGroupId)
|
|
? processGroupId
|
|
: null;
|
|
}
|
|
catch
|
|
{
|
|
return null;
|
|
}
|
|
}
|
|
|
|
private static async Task<bool> HasActiveProcessGroupAsync(int processGroupId)
|
|
{
|
|
try
|
|
{
|
|
var startInfo = new ProcessStartInfo
|
|
{
|
|
FileName = "ps",
|
|
Arguments = $"-o pid= -g {processGroupId}",
|
|
UseShellExecute = false,
|
|
RedirectStandardOutput = true,
|
|
RedirectStandardError = true,
|
|
CreateNoWindow = true
|
|
};
|
|
|
|
using var psProcess = Process.Start(startInfo);
|
|
if (psProcess == null)
|
|
return false;
|
|
|
|
var output = await psProcess.StandardOutput.ReadToEndAsync();
|
|
await psProcess.WaitForExitAsync();
|
|
|
|
return psProcess.ExitCode == 0 &&
|
|
output.Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries)
|
|
.Any(line => !string.IsNullOrWhiteSpace(line));
|
|
}
|
|
catch
|
|
{
|
|
return false;
|
|
}
|
|
}
|
|
|
|
private async Task<int> UpdateOrDownloadGame(GameInfo game, bool isUpdate)
|
|
{
|
|
try
|
|
{
|
|
var settings = AppSettings.Load();
|
|
|
|
WriteColor($"→ {(isUpdate ? "Updating" : "Downloading")} {game.Name}...", isUpdate ? ColorWarning : ColorTitle);
|
|
Console.WriteLine();
|
|
Console.WriteLine();
|
|
|
|
// Store initial version for comparison
|
|
string initialVersion = game.InstalledVersion ?? "";
|
|
|
|
// Get the latest release info
|
|
await game.CheckStatusAsync(_gameManager.HttpClient, _gameManager.GamesFolder, forceUpdateCheck: true);
|
|
|
|
string platformIdentifier = GameInfo.GetPlatformIdentifier(settings);
|
|
WriteColor($"→ Detected platform: {platformIdentifier}", ColorMuted);
|
|
Console.WriteLine();
|
|
|
|
if (game.TrySelectPlatformDownload(settings) && game.SelectedDownload != null)
|
|
{
|
|
WriteColor($"→ Selected: {game.SelectedDownload.name}", ColorSuccess);
|
|
Console.WriteLine();
|
|
Console.WriteLine();
|
|
}
|
|
|
|
var downloadTask = game.PerformActionAsync(
|
|
_gameManager.HttpClient,
|
|
_gameManager.GamesFolder,
|
|
settings);
|
|
|
|
// Monitor progress and version changes
|
|
double lastProgress = 0;
|
|
int timeout = 600; // 10 minutes
|
|
int waited = 0;
|
|
|
|
while (waited < timeout)
|
|
{
|
|
// Check if installation completed
|
|
if (game.Status == GameStatus.Installed)
|
|
{
|
|
break;
|
|
}
|
|
|
|
// Check if version changed (installation complete)
|
|
if (!string.IsNullOrEmpty(game.InstalledVersion) &&
|
|
game.InstalledVersion != initialVersion &&
|
|
game.InstalledVersion != "Unknown")
|
|
{
|
|
break;
|
|
}
|
|
|
|
if (game.DownloadProgress > lastProgress + 5 || game.DownloadProgress >= 100)
|
|
{
|
|
Console.Write($"\r Progress: {game.DownloadProgress:F0}% ");
|
|
lastProgress = game.DownloadProgress;
|
|
}
|
|
|
|
await Task.Delay(1000);
|
|
waited++;
|
|
}
|
|
|
|
Console.WriteLine();
|
|
Console.WriteLine();
|
|
|
|
if (waited >= timeout)
|
|
{
|
|
return PrintError("Download timed out.");
|
|
}
|
|
|
|
// Verify installation
|
|
await game.CheckStatusAsync(_gameManager.HttpClient, _gameManager.GamesFolder, forceUpdateCheck: true);
|
|
|
|
if (game.Status == GameStatus.Installed)
|
|
{
|
|
WriteColor($"✓ {game.Name} ", ColorSuccess);
|
|
Console.WriteLine($"{(isUpdate ? "updated" : "installed")} successfully ({CleanVersion(game.InstalledVersion)})");
|
|
Console.WriteLine();
|
|
return 0;
|
|
}
|
|
else
|
|
{
|
|
return PrintError($"{(isUpdate ? "Update" : "Download")} failed. Final status: {game.Status}");
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Console.WriteLine();
|
|
return PrintError($"Failed to {(isUpdate ? "update" : "download")} {game.Name}: {ex.Message}");
|
|
}
|
|
}
|
|
|
|
private async Task<int> DownloadGameCommand(string gameName)
|
|
{
|
|
if (string.IsNullOrEmpty(gameName))
|
|
{
|
|
ShowHelp();
|
|
return PrintError("App name required.");
|
|
}
|
|
|
|
var game = FindGame(gameName);
|
|
if (game == null)
|
|
{
|
|
Console.WriteLine();
|
|
WriteColor("Available games: ", ColorMuted);
|
|
Console.WriteLine(string.Join(", ", _gameManager?.Games.Select(g => g.Name) ?? Array.Empty<string>()));
|
|
Console.WriteLine();
|
|
return PrintError($"App not found: '{gameName}'");
|
|
}
|
|
|
|
if (game.Status == GameStatus.Installed)
|
|
{
|
|
WriteColor($"✓ {game.Name} ", ColorSuccess);
|
|
Console.WriteLine($"is already installed ({CleanVersion(game.InstalledVersion)})");
|
|
Console.WriteLine();
|
|
return 0;
|
|
}
|
|
|
|
if (game.Status == GameStatus.UpdateAvailable)
|
|
{
|
|
return await UpdateOrDownloadGame(game, isUpdate: true);
|
|
}
|
|
|
|
return await UpdateOrDownloadGame(game, isUpdate: false);
|
|
}
|
|
|
|
private async Task<int> UpdateAllGames()
|
|
{
|
|
if (_gameManager?.Games == null || !_gameManager.Games.Any())
|
|
return PrintError("No games found in library.");
|
|
|
|
var installedGames = _gameManager.Games.Where(g => g.Status == GameStatus.Installed || g.Status == GameStatus.UpdateAvailable).ToList();
|
|
|
|
if (!installedGames.Any())
|
|
{
|
|
WriteColor("✓ No installed games to update.", ColorSuccess);
|
|
Console.WriteLine();
|
|
return 0;
|
|
}
|
|
|
|
Console.WriteLine($"Checking {installedGames.Count} installed game(s) for updates...");
|
|
Console.WriteLine();
|
|
|
|
int updatedCount = 0;
|
|
int errorCount = 0;
|
|
|
|
foreach (var game in installedGames)
|
|
{
|
|
if (game.Status == GameStatus.UpdateAvailable)
|
|
{
|
|
int result = await UpdateOrDownloadGame(game, isUpdate: true);
|
|
if (result == 0)
|
|
updatedCount++;
|
|
else
|
|
errorCount++;
|
|
}
|
|
}
|
|
|
|
Console.WriteLine();
|
|
if (updatedCount > 0)
|
|
{
|
|
WriteColor($"✓ Updated {updatedCount} game(s)", ColorSuccess);
|
|
Console.WriteLine();
|
|
}
|
|
if (errorCount > 0)
|
|
{
|
|
WriteColor($"⚠ {errorCount} game(s) failed to update", ColorWarning);
|
|
Console.WriteLine();
|
|
}
|
|
if (updatedCount == 0 && errorCount == 0)
|
|
{
|
|
WriteColor("✓ All games are up to date", ColorSuccess);
|
|
Console.WriteLine();
|
|
}
|
|
|
|
return errorCount > 0 ? 1 : 0;
|
|
}
|
|
|
|
private async Task<int> UpdateLauncher()
|
|
{
|
|
try
|
|
{
|
|
WriteColor("→ Checking for Quiver Launcher updates (Velopack)...", ColorMuted);
|
|
Console.WriteLine();
|
|
|
|
var settings = AppSettings.Load();
|
|
var token = settings?.GitHubApiToken;
|
|
var result = await _velopackUpdateService.CheckForUpdatesAsync(
|
|
token,
|
|
allowPrereleaseLauncherUpdates: settings?.AllowPrereleaseLauncherUpdates ?? false);
|
|
if (result.IsNotInstalled)
|
|
return PrintError("This build is not a Velopack install. Download Quiver-Portable.zip (or Setup) from GitHub Releases.");
|
|
|
|
if (!result.CheckSucceeded)
|
|
return PrintError(result.ErrorMessage ?? "Could not check for launcher updates.");
|
|
|
|
if (!result.UpdateAvailable || result.UpdateInfo == null)
|
|
{
|
|
WriteColor($"✓ Launcher is already up to date ({result.InstalledVersion})", ColorSuccess);
|
|
Console.WriteLine();
|
|
return 0;
|
|
}
|
|
|
|
WriteColor($"→ Downloading launcher {result.AvailableVersion}...", ColorMuted);
|
|
Console.WriteLine();
|
|
|
|
var includePrerelease = result.IncludedPrerelease;
|
|
await _velopackUpdateService.DownloadUpdatesAsync(
|
|
result.UpdateInfo,
|
|
progress: p => Console.Write($"\r Download progress: {p}% "),
|
|
gitHubToken: token,
|
|
includePrerelease: includePrerelease);
|
|
Console.WriteLine();
|
|
|
|
WriteColor("→ Applying update and restarting...", ColorWarning);
|
|
Console.WriteLine();
|
|
_velopackUpdateService.ApplyUpdatesAndRestart(result.UpdateInfo, includePrerelease);
|
|
return 0;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
return PrintError($"Failed to update launcher: {ex.Message}");
|
|
}
|
|
}
|
|
private async Task<int> UninstallGame(string gameName)
|
|
{
|
|
if (string.IsNullOrEmpty(gameName))
|
|
{
|
|
ShowHelp();
|
|
return PrintError("App name required.");
|
|
}
|
|
|
|
var game = FindGame(gameName);
|
|
if (game == null)
|
|
{
|
|
Console.WriteLine();
|
|
WriteColor("Available games: ", ColorMuted);
|
|
Console.WriteLine(string.Join(", ", _gameManager?.Games.Select(g => g.Name) ?? Array.Empty<string>()));
|
|
Console.WriteLine();
|
|
return PrintError($"App not found: '{gameName}'");
|
|
}
|
|
|
|
if (game.Status == GameStatus.NotInstalled)
|
|
{
|
|
WriteColor($"✓ {game.Name} ", ColorMuted);
|
|
Console.WriteLine("is not installed.");
|
|
Console.WriteLine();
|
|
return 0;
|
|
}
|
|
|
|
WriteColor($"→ Uninstalling {game.Name}...", ColorWarning);
|
|
Console.WriteLine();
|
|
|
|
try
|
|
{
|
|
if (string.IsNullOrEmpty(game.FolderName))
|
|
{
|
|
return PrintError("App folder is not configured.");
|
|
}
|
|
|
|
var gamePath = game.GetInstallPath(_gameManager.GamesFolder);
|
|
|
|
if (Directory.Exists(gamePath))
|
|
{
|
|
RecycleBinHelper.MoveToRecycleBin(gamePath);
|
|
}
|
|
|
|
await game.CheckStatusAsync(_gameManager.HttpClient, _gameManager.GamesFolder, forceUpdateCheck: true);
|
|
|
|
WriteColor($"✓ {game.Name} ", ColorSuccess);
|
|
Console.WriteLine("uninstalled successfully.");
|
|
Console.WriteLine();
|
|
return 0;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
return PrintError($"Failed to uninstall {game.Name}: {ex.Message}");
|
|
}
|
|
}
|
|
|
|
private GameInfo? FindGame(string name)
|
|
{
|
|
if (_gameManager?.Games == null) return null;
|
|
|
|
return _gameManager.Games.FirstOrDefault(g =>
|
|
(g?.Name != null && g.Name.Equals(name, StringComparison.OrdinalIgnoreCase)) ||
|
|
(g?.FolderName != null && g.FolderName.Equals(name, StringComparison.OrdinalIgnoreCase)));
|
|
}
|
|
|
|
private string CleanVersion(string? version)
|
|
{
|
|
if (string.IsNullOrEmpty(version)) return "v0.0.0";
|
|
if (version.Equals("Unknown", StringComparison.OrdinalIgnoreCase)) return "Unknown";
|
|
return "v" + version.TrimStart('v', 'V');
|
|
}
|
|
|
|
private int PrintError(string message)
|
|
{
|
|
WriteColor("ERROR: ", ColorError);
|
|
Console.WriteLine(message);
|
|
Console.WriteLine();
|
|
return 1;
|
|
}
|
|
|
|
private void PrintHelpItem(string command, string desc)
|
|
{
|
|
Console.Write(" ");
|
|
WriteColor(command.PadRight(30), ColorSuccess);
|
|
Console.WriteLine(desc);
|
|
}
|
|
|
|
private void PrintLine() => Console.WriteLine(new string('─', 70));
|
|
|
|
private void WriteColor(string text, ConsoleColor color)
|
|
{
|
|
var old = Console.ForegroundColor;
|
|
try
|
|
{
|
|
Console.ForegroundColor = color;
|
|
Console.Write(text);
|
|
}
|
|
finally
|
|
{
|
|
Console.ForegroundColor = old;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|