using System; using System.Diagnostics; using System.IO; using System.IO.Compression; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using GameLauncher.Helpers; namespace GameLauncher.Engines.Nwjs { /// /// nw.js 埋め込み package.nw を抽出する外部アンパッカーツールの供給・呼び出しを担う汎用プロバイダ。 /// /// 設計方針(恒久・再利用可能): /// - ツールは `Engines\Nwjs\Tools\` 配下に配置する(エンジン別のツールフォルダ)。 /// - 未配置の場合は初回利用時に自動ダウンロードして同フォルダへ展開する(ユーザー確認なし)。 /// - ネット未接続等で入手できない場合は、例外を投げず null を返して「起動のみ」にフォールバックさせる。 /// - 特定ゲーム専用の決め打ちは禁止。呼び出し規約(引数・出力ディレクトリ)は汎用に扱う。 /// /// 外部ツールは「7-Zip 互換のコマンドライン(-o/-y で展開)」を持つものを第一候補とし、 /// 追加の抽出戦略が増えた場合も同じ呼び出しインターフェースで扱えるようにしてある。 /// public static class NwjsUnpackerToolProvider { /// Engine identifier used to resolve the per-engine tools folder. public const string EngineName = "Nwjs"; /// Fallback tools folder name (legacy layout). public const string ToolsDirName = "Tools"; /// 外部アンパッカーの実行ファイル名(Tools 配下へ配置する想定) public const string DefaultToolExeName = "7z.exe"; /// /// 外部ツールの入手元 URL(7-Zip 公式・Windows x64 版)。ダウンロード後に展開して /// 7z.exe / 7z.dll のみを Tools 配下へ配置します。 /// private static readonly string[] ToolArchiveUrls = { "https://www.7-zip.org/a/7zr.exe", // 単体実行版(依存 DLL 不要) "https://www.7-zip.org/a/7z2408-extra.7z", // 予備(extra パッケージ) }; /// /// Returns the engine-specific tools directory (Engines\Nwjs\Tools). /// Each engine references only its own tools folder, so the NW.js /// unpacker never depends on another engine's files. /// public static string GetToolsDirectory() { return AppPathHelper.GetEngineToolsDirectory(EngineName); } /// 配置済みの外部アンパッカー exe のフルパスを取得します(無ければ null)。 public static string? GetToolPath() { try { var tools = GetToolsDirectory(); // 優先順: 7zr(単体)→ 7z → 汎用名 var candidates = new[] { Path.Combine(tools, "7zr.exe"), Path.Combine(tools, DefaultToolExeName), Path.Combine(tools, "nwjs-unpack.exe"), }; return candidates.FirstOrDefault(File.Exists); } catch { return null; } } /// /// 外部アンパッカーの可用性を判定します。 /// public static bool IsToolAvailable() => GetToolPath() != null; /// /// 外部アンパッカーが未配置の場合、初回利用時に自動ダウンロードして Tools 配下へ配置します。 /// 失敗(ネット未接続等)時は例外を投げず false を返します。 /// public static async Task EnsureToolAvailableAsync(IProgress? progress = null, CancellationToken ct = default) { if (IsToolAvailable()) { return true; } try { var tools = GetToolsDirectory(); Directory.CreateDirectory(tools); foreach (var url in ToolArchiveUrls) { try { progress?.Report($"外部アンパッカーを取得中: {url}"); var fileName = Path.GetFileName(new Uri(url).LocalPath); var dest = Path.Combine(tools, fileName); if (!await DownloadFileAsync(url, dest, progress, ct).ConfigureAwait(false)) { continue; } // 単体実行版(7zr.exe)はそのまま配置 if (fileName.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) { progress?.Report($"外部アンパッカーを配置しました: {dest}"); return IsToolAvailable(); } // .7z アーカイブの場合は 7zr で本体を抽出(可能な範囲で) // 7zr.exe が既に同梱されていればそれを使い、無ければ諦めて次URLへ。 progress?.Report("アーカイブを展開して本体を配置します..."); if (TryExpandArchive(dest, tools, progress)) { return IsToolAvailable(); } } catch (Exception ex) { progress?.Report($"取得元の処理に失敗しました(次候補を試行): {ex.Message}"); } } } catch (Exception ex) { progress?.Report($"外部アンパッカーの取得に失敗しました: {ex.Message}"); } return IsToolAvailable(); } private static async Task DownloadFileAsync(string url, string dest, IProgress? progress, CancellationToken ct) { try { using var http = new HttpClient { Timeout = TimeSpan.FromMinutes(5) }; using var resp = await http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false); if (!resp.IsSuccessStatusCode) { progress?.Report($"ダウンロード失敗 (HTTP {(int)resp.StatusCode}): {url}"); return false; } var total = resp.Content.Headers.ContentLength ?? -1; await using var src = await resp.Content.ReadAsStreamAsync(ct).ConfigureAwait(false); await using var outFs = new FileStream(dest, FileMode.Create, FileAccess.Write, FileShare.None); var buf = new byte[81920]; long written = 0; int read; while ((read = await src.ReadAsync(buf, ct).ConfigureAwait(false)) > 0) { await outFs.WriteAsync(buf.AsMemory(0, read), ct).ConfigureAwait(false); written += read; if (total > 0) { progress?.Report($"ダウンロード中... {written * 100 / total}%"); } } return File.Exists(dest) && new FileInfo(dest).Length > 0; } catch (Exception ex) { progress?.Report($"ダウンロードに失敗しました: {ex.Message}"); return false; } } /// /// ダウンロードした .7z / .zip アーカイブから 7z.exe / 7zr.exe を Tools へ配置します。 /// ZIP は .NET 標準で、.7z は既存 7zr.exe がある場合のみ実行します。 /// private static bool TryExpandArchive(string archivePath, string toolsDir, IProgress? progress) { try { if (archivePath.EndsWith(".zip", StringComparison.OrdinalIgnoreCase)) { using var zip = ZipFile.OpenRead(archivePath); foreach (var entry in zip.Entries) { var name = Path.GetFileName(entry.FullName); if (name.Equals("7zr.exe", StringComparison.OrdinalIgnoreCase) || name.Equals("7z.exe", StringComparison.OrdinalIgnoreCase) || name.Equals("7z.dll", StringComparison.OrdinalIgnoreCase)) { var dest = Path.Combine(toolsDir, name); entry.ExtractToFile(dest, overwrite: true); } } return IsToolAvailable(); } // .7z は既存の 7zr.exe がある場合のみ展開を試みる var existing = Path.Combine(toolsDir, "7zr.exe"); if (!File.Exists(existing)) { return false; } var psi = new ProcessStartInfo { FileName = existing, Arguments = $"x \"{archivePath}\" -o\"{toolsDir}\" -y", WorkingDirectory = toolsDir, CreateNoWindow = true, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true }; using var proc = Process.Start(psi); if (proc == null) { return false; } proc.StandardOutput.ReadToEnd(); proc.StandardError.ReadToEnd(); proc.WaitForExit(); return IsToolAvailable(); } catch (Exception ex) { progress?.Report($"アーカイブ展開に失敗しました: {ex.Message}"); return false; } } /// /// 外部アンパッカーで exe 内の埋め込みコンテナ(package.nw 等)を destDir へ全展開します。 /// 呼び出し規約は「7-Zip 互換: <tool> x <archive> -o<out> -y」を第一候補、 /// 対応しない場合は 2 番目の規約(<tool> <archive> -o <out>)へフォールバックします。 /// /// 成功時 true(destDir に何らかのファイルが展開された場合)。 public static bool ExtractWithExternalTool(string toolPath, string sourceExePath, string destDir, IProgress? progress = null, int timeoutMs = 30 * 60 * 1000) { try { Directory.CreateDirectory(destDir); // 規約1: 7-Zip 互換 if (RunTool(toolPath, $"x \"{sourceExePath}\" -o\"{destDir}\" -y", destDir, progress, timeoutMs, out var code1)) { if (HasAnyExtractedFile(destDir)) { return true; } } progress?.Report($"外部ツール規約1の出力が空でした (code={code1})。規約2を試行します。"); // 規約2: -o if (RunTool(toolPath, $"\"{sourceExePath}\" -o \"{destDir}\"", destDir, progress, timeoutMs, out var code2)) { if (HasAnyExtractedFile(destDir)) { return true; } } progress?.Report($"外部ツールでの展開に失敗しました (code1={code1}, code2={code2})。"); return false; } catch (Exception ex) { progress?.Report($"外部ツール実行中にエラーが発生しました: {ex.Message}"); return false; } } private static bool RunTool(string toolPath, string args, string workDir, IProgress? progress, int timeoutMs, out int exitCode) { exitCode = -1; try { var psi = new ProcessStartInfo { FileName = toolPath, Arguments = args, WorkingDirectory = workDir, CreateNoWindow = true, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true }; using var proc = Process.Start(psi); if (proc == null) { return false; } // 出力を読み切ってから待機(デッドロック回避) var stdout = proc.StandardOutput.ReadToEnd(); var stderr = proc.StandardError.ReadToEnd(); if (!proc.WaitForExit(timeoutMs)) { try { proc.Kill(entireProcessTree: true); } catch { } progress?.Report("外部ツールがタイムアウトしました。"); return false; } exitCode = proc.ExitCode; if (!string.IsNullOrWhiteSpace(stdout)) { progress?.Report(stdout.Trim()); } if (!string.IsNullOrWhiteSpace(stderr)) { progress?.Report($"[stderr] {stderr.Trim()}"); } return exitCode == 0; } catch (Exception ex) { progress?.Report($"外部ツール起動に失敗しました: {ex.Message}"); return false; } } private static bool HasAnyExtractedFile(string dir) { try { return Directory.Exists(dir) && Directory.EnumerateFileSystemEntries(dir).Any(); } catch { return false; } } } }