refactor: reorganize engine-based structure and add agent rules
- Engines/ 配下へエンジン別に再編 (Common/Rgss/Tkool/Tyrano/Wolf/Unity/Nwjs) - ゲーム個別処理を Engines/<Engine>/Games/<GameName>/ へ分離し、共通処理から明示呼び出し - 外部ツールを Engines/<Engine>/Tools/ へ移動し、AppPathHelper 経由で解決 - 旧 Tools/ 直下参照と不要な参照ファイル/バックアップを削除 - エージェント規則 AGENTS.md を追加し、README から参照 - publish.ps1 を Engines/<Engine>/Tools/ の再帰配置に対応
This commit is contained in:
1 parent
0d11039ee9
commit
8cea2a147d
47 files changed
+2976
-176
No files matched your search
@@ -0,0 +1,610 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using GameLauncher.Models;
|
||||
using GameLauncher.Engines.Tkool;
|
||||
using GameLauncher.Engines.Unity;
|
||||
|
||||
namespace GameLauncher.Engines.Nwjs
|
||||
{
|
||||
/// <summary>
|
||||
/// ASAR アーカイブ内のファイルエントリ情報
|
||||
/// </summary>
|
||||
public class AsarFileEntry
|
||||
{
|
||||
public string RelativePath { get; set; } = string.Empty;
|
||||
public long Offset { get; set; }
|
||||
public long Size { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ASAR の解析結果情報
|
||||
/// </summary>
|
||||
public class AsarInspectResult
|
||||
{
|
||||
public bool IsValid { get; set; }
|
||||
public bool IsTkoolGame { get; set; }
|
||||
public bool IsTyranoGame { get; set; }
|
||||
public TkoolEngineType EngineType { get; set; } = TkoolEngineType.Unknown;
|
||||
public string Title { get; set; } = string.Empty;
|
||||
public string? RelativePluginsJsPath { get; set; }
|
||||
public string? RelativeIndexPath { get; set; }
|
||||
public long TotalFilesCount { get; set; }
|
||||
public long TotalUnpackedBytes { get; set; }
|
||||
public List<AsarFileEntry> FileEntries { get; set; } = [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Electron 等で利用される app.asar 形式アーカイブの解析・解凍・復元を
|
||||
/// 外部ツール不要かつ純粋な C# のみで安全・高速に行うサービス
|
||||
/// </summary>
|
||||
public class AsarArchiveService
|
||||
{
|
||||
/// <summary>ASARバックアップファイルの拡張子</summary>
|
||||
public const string AsarBackupSuffix = ".original_launcher_backup";
|
||||
|
||||
/// <summary>
|
||||
/// 指定されたゲームフォルダ配下に app.asar または解凍済みバックアップが存在するか検索します。
|
||||
/// </summary>
|
||||
/// <param name="gameRootDir">ゲームのルートディレクトリ</param>
|
||||
/// <param name="asarPath">見つかった asar ファイルパス(または元の asar パス)</param>
|
||||
/// <param name="isExtracted">現在解凍済み状態かどうか</param>
|
||||
/// <returns>ASARパッケージが存在するかどうか</returns>
|
||||
public static bool FindAsarPackage(string gameRootDir, out string? asarPath, out bool isExtracted, out string? extractedDirPath)
|
||||
{
|
||||
asarPath = null;
|
||||
isExtracted = false;
|
||||
extractedDirPath = null;
|
||||
|
||||
if (string.IsNullOrEmpty(gameRootDir) || !Directory.Exists(gameRootDir))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// 検索候補パス: resources\app.asar または 直下の app.asar
|
||||
var candidate1 = Path.Combine(gameRootDir, "resources", "app.asar");
|
||||
var candidate2 = Path.Combine(gameRootDir, "app.asar");
|
||||
|
||||
// 1. 未解凍の app.asar が存在する場合
|
||||
if (File.Exists(candidate1))
|
||||
{
|
||||
asarPath = candidate1;
|
||||
extractedDirPath = Path.Combine(gameRootDir, "resources", "app");
|
||||
isExtracted = Directory.Exists(extractedDirPath) && File.Exists(Path.Combine(extractedDirPath, "package.json"));
|
||||
return true;
|
||||
}
|
||||
if (File.Exists(candidate2))
|
||||
{
|
||||
asarPath = candidate2;
|
||||
extractedDirPath = Path.Combine(gameRootDir, "app");
|
||||
isExtracted = Directory.Exists(extractedDirPath) && File.Exists(Path.Combine(extractedDirPath, "package.json"));
|
||||
return true;
|
||||
}
|
||||
|
||||
// 2. 既に解凍済みで、app.asar がリネームバックアップされている場合
|
||||
var backup1 = candidate1 + AsarBackupSuffix;
|
||||
var appDir1 = Path.Combine(gameRootDir, "resources", "app");
|
||||
if (File.Exists(backup1) && Directory.Exists(appDir1))
|
||||
{
|
||||
asarPath = candidate1;
|
||||
extractedDirPath = appDir1;
|
||||
isExtracted = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
var backup2 = candidate2 + AsarBackupSuffix;
|
||||
var appDir2 = Path.Combine(gameRootDir, "app");
|
||||
if (File.Exists(backup2) && Directory.Exists(appDir2))
|
||||
{
|
||||
asarPath = candidate2;
|
||||
extractedDirPath = appDir2;
|
||||
isExtracted = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ASAR ファイルのヘッダを解析し、ツクールゲームであるかの判定やタイトル・plugins.js位置を抽出します。
|
||||
/// </summary>
|
||||
/// <param name="asarFilePath">app.asar ファイルの物理パス(またはバックアップパス)</param>
|
||||
/// <param name="includeFileList">全ファイルエントリの収集を行うかどうか(解凍時用)</param>
|
||||
public AsarInspectResult InspectAsar(string asarFilePath, bool includeFileList = false)
|
||||
{
|
||||
var result = new AsarInspectResult();
|
||||
|
||||
// バックアップファイルが指定された場合も対応
|
||||
var targetFile = asarFilePath;
|
||||
if (!File.Exists(ToExtendedPath(targetFile)) && File.Exists(ToExtendedPath(targetFile + AsarBackupSuffix)))
|
||||
{
|
||||
targetFile = asarFilePath + AsarBackupSuffix;
|
||||
}
|
||||
|
||||
if (!File.Exists(ToExtendedPath(targetFile)))
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using var fs = new FileStream(ToExtendedPath(targetFile), FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
|
||||
using var br = new BinaryReader(fs);
|
||||
|
||||
if (fs.Length < 16) return result;
|
||||
|
||||
uint u1 = br.ReadUInt32();
|
||||
uint headerSize = br.ReadUInt32();
|
||||
uint u3 = br.ReadUInt32();
|
||||
uint jsonSize = br.ReadUInt32();
|
||||
|
||||
// 妥当性チェック
|
||||
if (u1 != 4 || jsonSize == 0 || jsonSize > 100_000_000 || jsonSize > fs.Length)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
long dataOffset = 8 + (long)headerSize;
|
||||
byte[] jsonBytes = br.ReadBytes((int)jsonSize);
|
||||
string jsonStr = Encoding.UTF8.GetString(jsonBytes);
|
||||
|
||||
using var doc = JsonDocument.Parse(jsonStr);
|
||||
if (!doc.RootElement.TryGetProperty("files", out var filesRoot))
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
result.IsValid = true;
|
||||
|
||||
// ツクール特有ファイルを探す
|
||||
string? systemJsonRelative = null;
|
||||
long systemJsonOffset = -1;
|
||||
long systemJsonSize = -1;
|
||||
|
||||
string? packageJsonRelative = null;
|
||||
long packageJsonOffset = -1;
|
||||
long packageJsonSize = -1;
|
||||
|
||||
TraverseFiles(filesRoot, "", dataOffset, fs.Length, result, includeFileList,
|
||||
ref systemJsonRelative, ref systemJsonOffset, ref systemJsonSize,
|
||||
ref packageJsonRelative, ref packageJsonOffset, ref packageJsonSize);
|
||||
|
||||
if (!string.IsNullOrEmpty(result.RelativePluginsJsPath))
|
||||
{
|
||||
result.IsTkoolGame = true;
|
||||
}
|
||||
else if (result.IsTyranoGame)
|
||||
{
|
||||
result.EngineType = TkoolEngineType.Tyrano;
|
||||
result.RelativePluginsJsPath = result.RelativeIndexPath ?? "index.html";
|
||||
}
|
||||
|
||||
// タイトルの抽出(System.json または package.json から)
|
||||
if (systemJsonOffset >= 0 && systemJsonSize > 0 && systemJsonSize < 5_000_000)
|
||||
{
|
||||
try
|
||||
{
|
||||
fs.Seek(dataOffset + systemJsonOffset, SeekOrigin.Begin);
|
||||
byte[] sBytes = new byte[systemJsonSize];
|
||||
fs.ReadExactly(sBytes, 0, (int)systemJsonSize);
|
||||
string sJson = Encoding.UTF8.GetString(sBytes);
|
||||
var match = Regex.Match(sJson, @"""gameTitle""\s*:\s*""([^""]+)""");
|
||||
if (match.Success && !string.IsNullOrWhiteSpace(match.Groups[1].Value))
|
||||
{
|
||||
result.Title = match.Groups[1].Value.Trim();
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(result.Title) && packageJsonOffset >= 0 && packageJsonSize > 0 && packageJsonSize < 5_000_000)
|
||||
{
|
||||
try
|
||||
{
|
||||
fs.Seek(dataOffset + packageJsonOffset, SeekOrigin.Begin);
|
||||
byte[] pBytes = new byte[packageJsonSize];
|
||||
fs.ReadExactly(pBytes, 0, (int)packageJsonSize);
|
||||
string pJson = Encoding.UTF8.GetString(pBytes);
|
||||
var matchTitle = Regex.Match(pJson, @"""title""\s*:\s*""([^""]+)""");
|
||||
if (matchTitle.Success && !string.IsNullOrWhiteSpace(matchTitle.Groups[1].Value) &&
|
||||
!matchTitle.Groups[1].Value.Contains("ティラノスタジオ", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
result.Title = matchTitle.Groups[1].Value.Trim();
|
||||
}
|
||||
else
|
||||
{
|
||||
var matchDesc = Regex.Match(pJson, @"""description""\s*:\s*""([^""]+)""");
|
||||
if (matchDesc.Success && !string.IsNullOrWhiteSpace(matchDesc.Groups[1].Value) &&
|
||||
!matchDesc.Groups[1].Value.Contains("Electron for RPG", StringComparison.OrdinalIgnoreCase) &&
|
||||
!matchDesc.Groups[1].Value.Contains("TyranoScript", StringComparison.OrdinalIgnoreCase) &&
|
||||
!matchDesc.Groups[1].Value.Contains("ティラノスクリプト", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
result.Title = matchDesc.Groups[1].Value.Trim();
|
||||
}
|
||||
else
|
||||
{
|
||||
var matchName = Regex.Match(pJson, @"""name""\s*:\s*""([^""]+)""");
|
||||
if (matchName.Success && !string.IsNullOrWhiteSpace(matchName.Groups[1].Value) &&
|
||||
!matchName.Groups[1].Value.Equals("aigisfull", StringComparison.OrdinalIgnoreCase) &&
|
||||
!matchName.Groups[1].Value.Contains("tyrano", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
result.Title = matchName.Groups[1].Value.Trim();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 解析失敗時は無効
|
||||
result.IsValid = false;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private void TraverseFiles(
|
||||
JsonElement element,
|
||||
string currentPath,
|
||||
long dataOffset,
|
||||
long fileLength,
|
||||
AsarInspectResult result,
|
||||
bool includeFileList,
|
||||
ref string? systemJsonRelative,
|
||||
ref long systemJsonOffset,
|
||||
ref long systemJsonSize,
|
||||
ref string? packageJsonRelative,
|
||||
ref long packageJsonOffset,
|
||||
ref long packageJsonSize)
|
||||
{
|
||||
if (element.ValueKind != JsonValueKind.Object) return;
|
||||
|
||||
foreach (var prop in element.EnumerateObject())
|
||||
{
|
||||
string name = prop.Name;
|
||||
string path = string.IsNullOrEmpty(currentPath) ? name : $"{currentPath}/{name}";
|
||||
var val = prop.Value;
|
||||
|
||||
if (val.TryGetProperty("files", out var subFiles))
|
||||
{
|
||||
TraverseFiles(subFiles, path, dataOffset, fileLength, result, includeFileList,
|
||||
ref systemJsonRelative, ref systemJsonOffset, ref systemJsonSize,
|
||||
ref packageJsonRelative, ref packageJsonOffset, ref packageJsonSize);
|
||||
}
|
||||
else
|
||||
{
|
||||
// ファイルエントリ
|
||||
long offset = 0;
|
||||
if (val.TryGetProperty("offset", out var offProp))
|
||||
{
|
||||
if (offProp.ValueKind == JsonValueKind.String && long.TryParse(offProp.GetString(), out var o))
|
||||
offset = o;
|
||||
else if (offProp.ValueKind == JsonValueKind.Number && offProp.TryGetInt64(out var oNum))
|
||||
offset = oNum;
|
||||
}
|
||||
|
||||
long size = 0;
|
||||
if (val.TryGetProperty("size", out var sizeProp) && sizeProp.ValueKind == JsonValueKind.Number)
|
||||
{
|
||||
sizeProp.TryGetInt64(out size);
|
||||
}
|
||||
|
||||
// 異常値チェック(ダミーエントリや破損エントリのガード)
|
||||
if (offset < 0 || size < 0 || dataOffset + offset + size > fileLength)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
result.TotalFilesCount++;
|
||||
result.TotalUnpackedBytes += size;
|
||||
|
||||
if (includeFileList)
|
||||
{
|
||||
result.FileEntries.Add(new AsarFileEntry
|
||||
{
|
||||
RelativePath = path,
|
||||
Offset = offset,
|
||||
Size = size
|
||||
});
|
||||
}
|
||||
|
||||
// plugins.js の検出
|
||||
if (name.Equals("plugins.js", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
result.RelativePluginsJsPath = path;
|
||||
}
|
||||
|
||||
// エンジン種別判定 (rmmz_core.js -> MZ, rpg_core.js -> MV, tyrano -> Tyrano)
|
||||
if (name.Equals("rmmz_core.js", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
result.EngineType = TkoolEngineType.MZ;
|
||||
}
|
||||
else if (name.Equals("rpg_core.js", StringComparison.OrdinalIgnoreCase) && result.EngineType == TkoolEngineType.Unknown)
|
||||
{
|
||||
result.EngineType = TkoolEngineType.MV;
|
||||
}
|
||||
else if (name.Equals("tyrano.js", StringComparison.OrdinalIgnoreCase) ||
|
||||
path.Contains("data/scenario", StringComparison.OrdinalIgnoreCase) ||
|
||||
name.Equals("KeyConfig.js", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
result.IsTyranoGame = true;
|
||||
}
|
||||
|
||||
if (name.Equals("index.html", StringComparison.OrdinalIgnoreCase) && result.RelativeIndexPath == null)
|
||||
{
|
||||
result.RelativeIndexPath = path;
|
||||
}
|
||||
|
||||
// タイトル抽出用
|
||||
if (name.Equals("System.json", StringComparison.OrdinalIgnoreCase) && systemJsonOffset < 0)
|
||||
{
|
||||
systemJsonRelative = path;
|
||||
systemJsonOffset = offset;
|
||||
systemJsonSize = size;
|
||||
}
|
||||
else if (name.Equals("package.json", StringComparison.OrdinalIgnoreCase) &&
|
||||
!path.Contains("node_modules", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
// ルートの package.json または project/package.json を最優先
|
||||
if (packageJsonOffset < 0 || path.Equals("package.json", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
packageJsonRelative = path;
|
||||
packageJsonOffset = offset;
|
||||
packageJsonSize = size;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Windowsの260文字制限(MAX_PATH)や予約デバイス名(CON, PRN, AUX, NUL, COM1-9, LPT1-9等)による
|
||||
/// Win32例外(ハンドルが無効です。: '\\.\con' 等)を回避するため、拡張パスプレフィックス \\?\ を付与します。
|
||||
/// </summary>
|
||||
public static string ToExtendedPath(string path)
|
||||
{
|
||||
if (string.IsNullOrEmpty(path)) return path;
|
||||
|
||||
// Windows 環境以外はそのまま
|
||||
if (!OperatingSystem.IsWindows()) return path;
|
||||
|
||||
// 既に \\?\ または \\.\ で始まっている場合はそのまま
|
||||
if (path.StartsWith(@"\\?\", StringComparison.Ordinal) || path.StartsWith(@"\\.\", StringComparison.Ordinal))
|
||||
{
|
||||
return path;
|
||||
}
|
||||
|
||||
// 区切り文字を Windows 標準のバックスラッシュに統一
|
||||
string normalized = path.Replace('/', '\\');
|
||||
|
||||
// ドライブ文字付き絶対パス (例: C:\..., Z:\...) の場合
|
||||
// ※ここで Path.GetFullPath を通すと、ファイル名が con.png などの場合に Win32 が '\\.\con' に解決してしまうため、
|
||||
// 直接 \\?\ を前置することで予約デバイス名の解決を完全にバイパスします。
|
||||
if (normalized.Length >= 2 && char.IsLetter(normalized[0]) && normalized[1] == ':')
|
||||
{
|
||||
return @"\\?\" + normalized;
|
||||
}
|
||||
|
||||
// UNC パス (例: \\server\share\...) の場合
|
||||
if (normalized.StartsWith(@"\\", StringComparison.Ordinal))
|
||||
{
|
||||
return @"\\?\UNC\" + normalized.Substring(2);
|
||||
}
|
||||
|
||||
// 相対パスの場合は安全に絶対パスを取得してからプレフィックスを付与
|
||||
try
|
||||
{
|
||||
string full = Path.GetFullPath(normalized);
|
||||
if (full.StartsWith(@"\\?\", StringComparison.Ordinal) || full.StartsWith(@"\\.\", StringComparison.Ordinal))
|
||||
{
|
||||
return full;
|
||||
}
|
||||
if (full.StartsWith(@"\\", StringComparison.Ordinal))
|
||||
{
|
||||
return @"\\?\UNC\" + full.Substring(2);
|
||||
}
|
||||
return @"\\?\" + full;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return path;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ASAR ファイルを解凍し、outputDir に展開します。
|
||||
/// 展開成功後、元の app.asar を app.asar.original_launcher_backup にリネームして
|
||||
/// Electron が確実に解凍先 app フォルダを読み込んで起動するように準備します。
|
||||
/// </summary>
|
||||
public async Task<(bool Success, string Message)> ExtractAsarAsync(
|
||||
string asarPath,
|
||||
string outputDir,
|
||||
IProgress<(long extractedBytes, long totalBytes, int currentFileIndex, int totalFiles, string currentFileName)>? progress = null,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
return await Task.Run(() =>
|
||||
{
|
||||
var targetAsar = asarPath;
|
||||
var backupAsar = asarPath + AsarBackupSuffix;
|
||||
|
||||
if (!File.Exists(ToExtendedPath(targetAsar)))
|
||||
{
|
||||
if (File.Exists(ToExtendedPath(backupAsar)))
|
||||
{
|
||||
targetAsar = backupAsar;
|
||||
}
|
||||
else
|
||||
{
|
||||
return (false, $"解凍対象の asar ファイルが見つかりません: {asarPath}");
|
||||
}
|
||||
}
|
||||
|
||||
// ヘッダ詳細解析
|
||||
var inspect = InspectAsar(targetAsar, includeFileList: true);
|
||||
if (!inspect.IsValid || inspect.FileEntries.Count == 0)
|
||||
{
|
||||
return (false, "asar ファイルのヘッダ解析に失敗したか、ファイルが含まれていません。");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
// 拡張パス(\\?\)を適用した出力先ルートディレクトリ
|
||||
string extOutputDir = ToExtendedPath(Path.GetFullPath(outputDir));
|
||||
|
||||
if (!Directory.Exists(extOutputDir))
|
||||
{
|
||||
Directory.CreateDirectory(extOutputDir);
|
||||
}
|
||||
|
||||
byte[] buffer = new byte[128 * 1024]; // 128KB バッファ
|
||||
long extractedBytes = 0;
|
||||
long totalBytes = inspect.TotalUnpackedBytes;
|
||||
int totalFiles = inspect.FileEntries.Count;
|
||||
int skippedFilesCount = 0;
|
||||
List<string> errorDetails = [];
|
||||
|
||||
using (var fs = new FileStream(ToExtendedPath(targetAsar), FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
|
||||
using (var br = new BinaryReader(fs))
|
||||
{
|
||||
uint u1 = br.ReadUInt32();
|
||||
uint headerSize = br.ReadUInt32();
|
||||
long dataOffset = 8 + (long)headerSize;
|
||||
|
||||
for (int i = 0; i < inspect.FileEntries.Count; i++)
|
||||
{
|
||||
if (ct.IsCancellationRequested)
|
||||
{
|
||||
return (false, "解凍処理が中断されました。");
|
||||
}
|
||||
|
||||
var entry = inspect.FileEntries[i];
|
||||
|
||||
// extOutputDir (\\?\C:\...) と entry.RelativePath を結合
|
||||
// ※先頭に \\?\ が付いているため、con.png や aux.mp3 などの予約デバイス名があっても
|
||||
// Win32 による \\.\con への置換が発生せず、正常にファイル作成が可能
|
||||
string destFilePath = Path.Combine(extOutputDir, entry.RelativePath.Replace('/', Path.DirectorySeparatorChar));
|
||||
string? parentDir = Path.GetDirectoryName(destFilePath);
|
||||
|
||||
if (!string.IsNullOrEmpty(parentDir) && !Directory.Exists(parentDir))
|
||||
{
|
||||
Directory.CreateDirectory(parentDir);
|
||||
}
|
||||
|
||||
// ファイル書き込み
|
||||
try
|
||||
{
|
||||
fs.Seek(dataOffset + entry.Offset, SeekOrigin.Begin);
|
||||
long remaining = entry.Size;
|
||||
|
||||
using (var outFs = new FileStream(destFilePath, FileMode.Create, FileAccess.Write, FileShare.None))
|
||||
{
|
||||
while (remaining > 0)
|
||||
{
|
||||
int toRead = (int)Math.Min(remaining, buffer.Length);
|
||||
int read = fs.Read(buffer, 0, toRead);
|
||||
if (read == 0) break;
|
||||
|
||||
outFs.Write(buffer, 0, read);
|
||||
remaining -= read;
|
||||
extractedBytes += read;
|
||||
|
||||
progress?.Report((extractedBytes, totalBytes, i + 1, totalFiles, Path.GetFileName(entry.RelativePath)));
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception fileEx)
|
||||
{
|
||||
// 予約文字や排他ロック等の例外が発生した場合、解凍全体を止めずに警告として記録
|
||||
skippedFilesCount++;
|
||||
if (errorDetails.Count < 5)
|
||||
{
|
||||
errorDetails.Add($"{entry.RelativePath} ({fileEx.Message})");
|
||||
}
|
||||
}
|
||||
}
|
||||
} // ここで fs と br が確実に Dispose されてファイルハンドルが解放される
|
||||
|
||||
// 展開が正常完了したら、元の app.asar をリネームバックアップする
|
||||
// (これにより Electron は同階層の解凍 app フォルダを最優先で読み込み、改造プラグインが確実に動作する)
|
||||
string extAsarPath = ToExtendedPath(asarPath);
|
||||
string extBackupAsar = ToExtendedPath(backupAsar);
|
||||
|
||||
if (File.Exists(extAsarPath) && !asarPath.EndsWith(AsarBackupSuffix, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
if (File.Exists(extBackupAsar))
|
||||
{
|
||||
File.Delete(extBackupAsar);
|
||||
}
|
||||
File.Move(extAsarPath, extBackupAsar);
|
||||
}
|
||||
|
||||
string summary = $"ASARの解凍が完了しました。(全 {totalFiles} ファイル展開完了)";
|
||||
if (skippedFilesCount > 0)
|
||||
{
|
||||
summary += $" ※一部ファイル({skippedFilesCount}件)の展開をスキップ: {string.Join(", ", errorDetails)}";
|
||||
}
|
||||
|
||||
return (true, summary);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return (false, $"ASAR解凍中にエラーが発生しました: {ex.Message}");
|
||||
}
|
||||
}, ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 解凍された app フォルダを安全に削除し、バックアップされていた app.asar を元の名前に復元します。
|
||||
/// これによりゲームは完全にオリジナルの app.asar 実行状態へ戻ります。
|
||||
/// </summary>
|
||||
public async Task<(bool Success, string Message)> RestoreAsarAsync(string asarPath, string extractedDir, CancellationToken ct = default)
|
||||
{
|
||||
return await Task.Run(() =>
|
||||
{
|
||||
var backupAsar = asarPath.EndsWith(AsarBackupSuffix, StringComparison.OrdinalIgnoreCase)
|
||||
? asarPath
|
||||
: asarPath + AsarBackupSuffix;
|
||||
|
||||
var originalAsar = asarPath.EndsWith(AsarBackupSuffix, StringComparison.OrdinalIgnoreCase)
|
||||
? asarPath.Substring(0, asarPath.Length - AsarBackupSuffix.Length)
|
||||
: asarPath;
|
||||
|
||||
string extExtractedDir = ToExtendedPath(extractedDir);
|
||||
string extBackupAsar = ToExtendedPath(backupAsar);
|
||||
string extOriginalAsar = ToExtendedPath(originalAsar);
|
||||
|
||||
try
|
||||
{
|
||||
// 1. 解凍ディレクトリの削除(con.png等の特殊名を含むフォルダも拡張パスで安全に削除)
|
||||
if (!string.IsNullOrEmpty(extExtractedDir) && Directory.Exists(extExtractedDir))
|
||||
{
|
||||
Directory.Delete(extExtractedDir, true);
|
||||
}
|
||||
|
||||
// 2. バックアップした asar を元の名前に戻す
|
||||
if (File.Exists(extBackupAsar))
|
||||
{
|
||||
if (File.Exists(extOriginalAsar))
|
||||
{
|
||||
File.Delete(extOriginalAsar);
|
||||
}
|
||||
File.Move(extBackupAsar, extOriginalAsar);
|
||||
}
|
||||
|
||||
return (true, "ゲームを元の app.asar 形式に復元しました。(解凍フォルダは綺麗に削除されました)");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return (false, $"復元処理中にエラーが発生しました: {ex.Message}");
|
||||
}
|
||||
}, ct);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,378 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Linq;
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace GameLauncher.Engines.Nwjs
|
||||
{
|
||||
/// <summary>
|
||||
/// nw.js 系(boxed / FOSSIL 等の単体exe梱包)ツクールゲームから、
|
||||
/// 埋め込まれた package.nw 相当のコンテナを抽出する汎用アンパッカー。
|
||||
///
|
||||
/// 方針(恒久・再利用可能):
|
||||
/// - 特定ゲーム専用ではなく、共通の署名探索アルゴリズムで「埋め込みZIPコンテナ」を探す。
|
||||
/// - exe 全体を一括読みしない。ブロック単位の逐次走査で PK ローカルヘッダ→EOCD を確定する。
|
||||
/// - 抽出先はゲームフォルダ内 `_extracted` のみ(他ゲームへ一切影響しない)。
|
||||
/// - 冪等: 既に展開済み(plugins.js が解決できる)なら再展開しない。
|
||||
///
|
||||
/// 抽出戦略は <see cref="INwjsUnpackStrategy"/> として差し替え可能にしてあり、
|
||||
/// 将来新しい梱包形式が出た場合は戦略を追加するだけで拡張できる。
|
||||
/// </summary>
|
||||
public static class NwjsPackageUnpacker
|
||||
{
|
||||
/// <summary>ゲームフォルダ内の展開先フォルダ名(Asar/SRPG の慣習に合わせる)</summary>
|
||||
public const string ExtractedDirName = "_extracted";
|
||||
|
||||
/// <summary>走査ブロックサイズ(1ブロックあたりの読み込み量)</summary>
|
||||
private const int ScanBlockSize = 4 * 1024 * 1024;
|
||||
|
||||
/// <summary>単一のPKローカルヘッダから読み込める最大ウィンドウ(EOCD 探索用)</summary>
|
||||
private const int MaxSingleZipScan = 256 * 1024 * 1024;
|
||||
|
||||
/// <summary>ゲームフォルダ内の展開先ディレクトリ(物理パス)</summary>
|
||||
public static string GetExtractedDir(string gameRootDir)
|
||||
=> Path.Combine(gameRootDir, ExtractedDirName);
|
||||
|
||||
/// <summary>
|
||||
/// 展開先 `_extracted` に js/plugins.js(または www/js/plugins.js)が存在するか判定します。
|
||||
/// </summary>
|
||||
public static bool IsExtractionComplete(string extractedDir, out string? pluginsJsPath, out string? relativePlugins)
|
||||
{
|
||||
pluginsJsPath = null;
|
||||
relativePlugins = null;
|
||||
try
|
||||
{
|
||||
var candidates = new[]
|
||||
{
|
||||
new { Abs = Path.Combine(extractedDir, "js", "plugins.js"), Rel = "js/plugins.js" },
|
||||
new { Abs = Path.Combine(extractedDir, "js", "plugins", "plugins.js"), Rel = "js/plugins/plugins.js" },
|
||||
new { Abs = Path.Combine(extractedDir, "www", "js", "plugins.js"), Rel = "www/js/plugins.js" },
|
||||
};
|
||||
foreach (var c in candidates)
|
||||
{
|
||||
if (File.Exists(c.Abs))
|
||||
{
|
||||
pluginsJsPath = c.Abs;
|
||||
relativePlugins = c.Rel;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 指定パス直下から js/plugins.js を解決します(_extracted 配下優先)。
|
||||
/// </summary>
|
||||
public static string? ResolvePluginsJs(string rootDir)
|
||||
{
|
||||
try
|
||||
{
|
||||
var candidates = new[]
|
||||
{
|
||||
Path.Combine(rootDir, "js", "plugins.js"),
|
||||
Path.Combine(rootDir, "js", "plugins", "plugins.js"),
|
||||
Path.Combine(rootDir, "www", "js", "plugins.js"),
|
||||
Path.Combine(rootDir, "package.nw", "js", "plugins.js"),
|
||||
};
|
||||
return candidates.FirstOrDefault(File.Exists);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 判定に必要な署名情報。汎用の埋め込みZIPコンテナ有無を表します。
|
||||
/// </summary>
|
||||
public sealed class EmbeddedZipProbeResult
|
||||
{
|
||||
/// <summary>PK ローカルヘッダ(PK\x03\x04)の先頭オフセット(見つかった場合)</summary>
|
||||
public long? LocalHeaderOffset { get; init; }
|
||||
|
||||
/// <summary>EOCD(PK\x05\x06)の末尾オフセット(見つかった場合)</summary>
|
||||
public long? EocdOffset { get; init; }
|
||||
|
||||
/// <summary>コンテナ内に package.json 文字列が見つかったか</summary>
|
||||
public bool HasPackageJson { get; init; }
|
||||
|
||||
/// <summary>標準ZIPとして展開可能そうか</summary>
|
||||
public bool IsZipExtractable => LocalHeaderOffset.HasValue && EocdOffset.HasValue;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 埋め込みコンテナ(package.nw = 標準ZIP)を逐次走査で探索します。全走査でも
|
||||
/// exe を一括メモリへ載せないため、1.14GB級でも安全です。
|
||||
/// </summary>
|
||||
/// <param name="exePath">対象の単体exeパス</param>
|
||||
/// <param name="progress">進捗通知(任意)</param>
|
||||
/// <param name="maxScanBytes">先頭から走査する最大バイト数(既定は末尾まで)</param>
|
||||
public static EmbeddedZipProbeResult ProbeEmbeddedZip(string exePath, IProgress<string>? progress = null, long maxScanBytes = long.MaxValue)
|
||||
{
|
||||
if (!File.Exists(exePath))
|
||||
{
|
||||
return new EmbeddedZipProbeResult();
|
||||
}
|
||||
|
||||
long? localHeader = null;
|
||||
bool hasPackageJson = false;
|
||||
|
||||
using var fs = new FileStream(exePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
|
||||
long fileSize = fs.Length;
|
||||
long scanLimit = Math.Min(fileSize, maxScanBytes);
|
||||
|
||||
var buf = new byte[ScanBlockSize];
|
||||
long pos = 0;
|
||||
// ブロック境界をまたぐPK検出のため、直前3バイトを保持する
|
||||
int carry = 0;
|
||||
byte b1 = 0, b2 = 0, b3 = 0;
|
||||
|
||||
progress?.Report($"埋め込みZIPコンテナを走査中... ({fileSize:N0} bytes)");
|
||||
|
||||
while (pos < scanLimit)
|
||||
{
|
||||
int toRead = (int)Math.Min(buf.Length, scanLimit - pos);
|
||||
fs.Seek(pos, SeekOrigin.Begin);
|
||||
int read = fs.Read(buf, 0, toRead);
|
||||
if (read <= 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
for (int i = 0; i < read; i++)
|
||||
{
|
||||
byte cur = buf[i];
|
||||
if (carry == 3 && b1 == 0x50 && b2 == 0x4B && b3 == 0x03 && cur == 0x04 && localHeader == null)
|
||||
{
|
||||
// ローカルヘッダ先頭位置 = (今回ブロック開始 - 3) + (i - 3)
|
||||
long abs = pos + i - 3;
|
||||
if (abs >= 0)
|
||||
{
|
||||
localHeader = abs;
|
||||
progress?.Report($"埋め込みZIPローカルヘッダを検出: offset={abs:N0}");
|
||||
}
|
||||
}
|
||||
|
||||
if (b1 == 0x50 && b2 == 0x4B && b3 == 0x03 && cur == 0x04)
|
||||
{
|
||||
b1 = b2; b2 = b3; b3 = cur;
|
||||
}
|
||||
else
|
||||
{
|
||||
b1 = b2; b2 = b3; b3 = cur;
|
||||
}
|
||||
if (carry < 3)
|
||||
{
|
||||
carry++;
|
||||
}
|
||||
}
|
||||
|
||||
// ブロック内で package.json 文字列を軽く探索(タイトル推定用・厳密性は不要)
|
||||
if (!hasPackageJson)
|
||||
{
|
||||
var ascii = System.Text.Encoding.ASCII.GetString(buf, 0, read);
|
||||
if (ascii.IndexOf("package.json", StringComparison.Ordinal) >= 0)
|
||||
{
|
||||
hasPackageJson = true;
|
||||
}
|
||||
}
|
||||
|
||||
pos += read;
|
||||
progress?.Report($"走査中... {pos:N0} / {fileSize:N0} bytes");
|
||||
}
|
||||
|
||||
// EOCD(PK\x05\x06)は末尾近傍にある。末尾 64KB を走査。
|
||||
long? eocd = null;
|
||||
if (localHeader.HasValue)
|
||||
{
|
||||
int tailLen = (int)Math.Min(64 * 1024, fileSize);
|
||||
var tail = new byte[tailLen];
|
||||
fs.Seek(fileSize - tailLen, SeekOrigin.Begin);
|
||||
int tr = fs.Read(tail, 0, tailLen);
|
||||
for (int i = tr - 4; i >= 0; i--)
|
||||
{
|
||||
if (tail[i] == 0x50 && tail[i + 1] == 0x4B && tail[i + 2] == 0x05 && tail[i + 3] == 0x06)
|
||||
{
|
||||
eocd = (fileSize - tailLen) + i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
// 末尾64KBに無ければローカルヘッダ以降の限定ウィンドウも確認(巨大な付加データ対策)
|
||||
if (eocd == null)
|
||||
{
|
||||
eocd = FindEocdNearOffset(fs, localHeader.Value, fileSize);
|
||||
}
|
||||
}
|
||||
|
||||
return new EmbeddedZipProbeResult
|
||||
{
|
||||
LocalHeaderOffset = localHeader,
|
||||
EocdOffset = eocd,
|
||||
HasPackageJson = hasPackageJson
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ローカルヘッダ以降を(最大<see cref="MaxSingleZipScan"/>まで)限定走査し、EOCD 位置を探します。
|
||||
/// </summary>
|
||||
private static long? FindEocdNearOffset(FileStream fs, long start, long fileSize)
|
||||
{
|
||||
long limit = Math.Min(fileSize, start + MaxSingleZipScan);
|
||||
// 末尾から逆方向に少しずつ探す方が現実的だが、境界が読めない場合は後方優先で探す
|
||||
long window = 4 * 1024 * 1024;
|
||||
for (long end = limit; end > start; end -= window)
|
||||
{
|
||||
long begin = Math.Max(start, end - window);
|
||||
int len = (int)(end - begin);
|
||||
if (len <= 4)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
var buf = new byte[len];
|
||||
fs.Seek(begin, SeekOrigin.Begin);
|
||||
int read = fs.Read(buf, 0, len);
|
||||
for (int i = read - 4; i >= 0; i--)
|
||||
{
|
||||
if (buf[i] == 0x50 && buf[i + 1] == 0x4B && buf[i + 2] == 0x05 && buf[i + 3] == 0x06)
|
||||
{
|
||||
return begin + i;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// exe 内に埋め込まれた ZIP(package.nw)を、指定の展開先へ冪等に全展開します。
|
||||
/// 標準ZIPとして解釈できる場合のみ成功します。
|
||||
/// </summary>
|
||||
/// <returns>展開後の js/plugins.js の相対パス(/区切り)。解決できなければ null。</returns>
|
||||
public static string? ExtractEmbeddedZip(string exePath, string destDir, IProgress<string>? progress = null)
|
||||
{
|
||||
try
|
||||
{
|
||||
var probe = ProbeEmbeddedZip(exePath, progress);
|
||||
if (!probe.IsZipExtractable)
|
||||
{
|
||||
progress?.Report("埋め込みZIPコンテナを確定できませんでした(非標準コンテナの可能性)。");
|
||||
return null;
|
||||
}
|
||||
|
||||
Directory.CreateDirectory(destDir);
|
||||
|
||||
using var fs = new FileStream(exePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
|
||||
long zipLength = probe.EocdOffset!.Value + 22 - probe.LocalHeaderOffset!.Value;
|
||||
fs.Seek(probe.LocalHeaderOffset!.Value, SeekOrigin.Begin);
|
||||
|
||||
// EOCD を含む範囲だけを ZipArchive へ渡す(exe 末尾の付加データを切り離す)
|
||||
using var slice = new SubStream(fs, probe.LocalHeaderOffset!.Value, zipLength);
|
||||
using var zip = new ZipArchive(slice, ZipArchiveMode.Read);
|
||||
|
||||
foreach (var entry in zip.Entries)
|
||||
{
|
||||
var entryRel = entry.FullName.Replace('/', Path.DirectorySeparatorChar);
|
||||
var dest = Path.Combine(destDir, entryRel);
|
||||
|
||||
// ディレクトリエントリ
|
||||
if (string.IsNullOrEmpty(entry.Name))
|
||||
{
|
||||
Directory.CreateDirectory(dest);
|
||||
continue;
|
||||
}
|
||||
|
||||
var parent = Path.GetDirectoryName(dest);
|
||||
if (!string.IsNullOrEmpty(parent))
|
||||
{
|
||||
Directory.CreateDirectory(parent);
|
||||
}
|
||||
|
||||
using (var src = entry.Open())
|
||||
using (var outFs = new FileStream(dest, FileMode.Create, FileAccess.Write, FileShare.None))
|
||||
{
|
||||
src.CopyTo(outFs);
|
||||
}
|
||||
}
|
||||
|
||||
progress?.Report("埋め込みZIPコンテナの展開が完了しました。");
|
||||
return IsExtractionComplete(destDir, out _, out var rel) ? rel : null;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
progress?.Report($"埋め込みZIP展開中にエラーが発生しました: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 指定範囲のみを読み出す読み取り専用ストリーム(ZIP末尾の付加データ分離用)。
|
||||
/// </summary>
|
||||
private sealed class SubStream : Stream
|
||||
{
|
||||
private readonly Stream _base;
|
||||
private readonly long _start;
|
||||
private readonly long _length;
|
||||
private long _pos;
|
||||
|
||||
public SubStream(Stream baseStream, long start, long length)
|
||||
{
|
||||
_base = baseStream;
|
||||
_start = start;
|
||||
_length = length;
|
||||
}
|
||||
|
||||
public override bool CanRead => true;
|
||||
public override bool CanSeek => true;
|
||||
public override bool CanWrite => false;
|
||||
public override long Length => _length;
|
||||
public override long Position
|
||||
{
|
||||
get => _pos;
|
||||
set => _pos = value;
|
||||
}
|
||||
|
||||
public override int Read(byte[] buffer, int offset, int count)
|
||||
{
|
||||
long remaining = _length - _pos;
|
||||
if (remaining <= 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
int toRead = (int)Math.Min(count, remaining);
|
||||
_base.Seek(_start + _pos, SeekOrigin.Begin);
|
||||
int read = _base.Read(buffer, offset, toRead);
|
||||
_pos += read;
|
||||
return read;
|
||||
}
|
||||
|
||||
public override long Seek(long offset, SeekOrigin origin)
|
||||
{
|
||||
_pos = origin switch
|
||||
{
|
||||
SeekOrigin.Begin => offset,
|
||||
SeekOrigin.Current => _pos + offset,
|
||||
SeekOrigin.End => _length + offset,
|
||||
_ => _pos
|
||||
};
|
||||
return _pos;
|
||||
}
|
||||
|
||||
public override void Flush() { }
|
||||
public override void SetLength(long value) => throw new NotSupportedException();
|
||||
public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 抽出戦略の抽象。標準ZIP以外の独自コンテナが出た場合に差し替え可能にするための骨組み。
|
||||
/// </summary>
|
||||
public interface INwjsUnpackStrategy
|
||||
{
|
||||
string Name { get; }
|
||||
bool CanHandle(string exePath);
|
||||
string? Extract(string exePath, string destDir, IProgress<string>? progress);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,341 @@
|
||||
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
|
||||
{
|
||||
/// <summary>
|
||||
/// nw.js 埋め込み package.nw を抽出する外部アンパッカーツールの供給・呼び出しを担う汎用プロバイダ。
|
||||
///
|
||||
/// 設計方針(恒久・再利用可能):
|
||||
/// - ツールは `Engines\Nwjs\Tools\` 配下に配置する(エンジン別のツールフォルダ)。
|
||||
/// - 未配置の場合は初回利用時に自動ダウンロードして同フォルダへ展開する(ユーザー確認なし)。
|
||||
/// - ネット未接続等で入手できない場合は、例外を投げず null を返して「起動のみ」にフォールバックさせる。
|
||||
/// - 特定ゲーム専用の決め打ちは禁止。呼び出し規約(引数・出力ディレクトリ)は汎用に扱う。
|
||||
///
|
||||
/// 外部ツールは「7-Zip 互換のコマンドライン(-o/-y で展開)」を持つものを第一候補とし、
|
||||
/// 追加の抽出戦略が増えた場合も同じ呼び出しインターフェースで扱えるようにしてある。
|
||||
/// </summary>
|
||||
public static class NwjsUnpackerToolProvider
|
||||
{
|
||||
/// <summary>Engine identifier used to resolve the per-engine tools folder.</summary>
|
||||
public const string EngineName = "Nwjs";
|
||||
|
||||
/// <summary>Fallback tools folder name (legacy layout).</summary>
|
||||
public const string ToolsDirName = "Tools";
|
||||
|
||||
/// <summary>外部アンパッカーの実行ファイル名(Tools 配下へ配置する想定)</summary>
|
||||
public const string DefaultToolExeName = "7z.exe";
|
||||
|
||||
/// <summary>
|
||||
/// 外部ツールの入手元 URL(7-Zip 公式・Windows x64 版)。ダウンロード後に展開して
|
||||
/// 7z.exe / 7z.dll のみを Tools 配下へ配置します。
|
||||
/// </summary>
|
||||
private static readonly string[] ToolArchiveUrls =
|
||||
{
|
||||
"https://www.7-zip.org/a/7zr.exe", // 単体実行版(依存 DLL 不要)
|
||||
"https://www.7-zip.org/a/7z2408-extra.7z", // 予備(extra パッケージ)
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static string GetToolsDirectory()
|
||||
{
|
||||
return AppPathHelper.GetEngineToolsDirectory(EngineName);
|
||||
}
|
||||
|
||||
/// <summary>配置済みの外部アンパッカー exe のフルパスを取得します(無ければ null)。</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 外部アンパッカーの可用性を判定します。
|
||||
/// </summary>
|
||||
public static bool IsToolAvailable() => GetToolPath() != null;
|
||||
|
||||
/// <summary>
|
||||
/// 外部アンパッカーが未配置の場合、初回利用時に自動ダウンロードして Tools 配下へ配置します。
|
||||
/// 失敗(ネット未接続等)時は例外を投げず false を返します。
|
||||
/// </summary>
|
||||
public static async Task<bool> EnsureToolAvailableAsync(IProgress<string>? 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<bool> DownloadFileAsync(string url, string dest, IProgress<string>? 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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ダウンロードした .7z / .zip アーカイブから 7z.exe / 7zr.exe を Tools へ配置します。
|
||||
/// ZIP は .NET 標準で、.7z は既存 7zr.exe がある場合のみ実行します。
|
||||
/// </summary>
|
||||
private static bool TryExpandArchive(string archivePath, string toolsDir, IProgress<string>? 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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 外部アンパッカーで exe 内の埋め込みコンテナ(package.nw 等)を destDir へ全展開します。
|
||||
/// 呼び出し規約は「7-Zip 互換: <tool> x <archive> -o<out> -y」を第一候補、
|
||||
/// 対応しない場合は 2 番目の規約(<tool> <archive> -o <out>)へフォールバックします。
|
||||
/// </summary>
|
||||
/// <returns>成功時 true(destDir に何らかのファイルが展開された場合)。</returns>
|
||||
public static bool ExtractWithExternalTool(string toolPath, string sourceExePath, string destDir, IProgress<string>? 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: <tool> <archive> -o <out>
|
||||
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<string>? 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
# nw.js boxed 解凍用 外部アンパッカー
|
||||
|
||||
このフォルダには、GameLauncher が **nw.js boxed 系ツクールゲーム**(例: `Game_boxed.exe` のように
|
||||
ゲーム本体を exe へ内包した形態)の埋め込みコンテナ(`package.nw` = 標準ZIP)を展開するために
|
||||
利用する外部アンパッカーを配置します。
|
||||
|
||||
## 対象
|
||||
- `*boxed*.exe`(nw.js 埋め込み。`package.nw` / `package.json` を含む)
|
||||
- その他、単体exeへ `package.nw` 相当の埋め込みZIPを持つツクール MZ/MV ゲーム
|
||||
|
||||
## 使用するツール
|
||||
- `7zr.exe`(7-Zip 公式の単体実行版・依存DLL不要)を第一候補とします。
|
||||
- 代替として `7z.exe`(+ `7z.dll`)も検出対象です。
|
||||
|
||||
## 配置方法
|
||||
- **同梱されている場合**: この `Tools\` フォルダに `7zr.exe` を置いてください。
|
||||
`publish.ps1` 実行時に `Z:\自作ソフト\GameLauncher\Tools\` へコピーされます。
|
||||
- **未配置の場合**: GameLauncher 実行時、boxed 解凍が必要になった時点で
|
||||
7-Zip 公式(https://www.7-zip.org/a/7zr.exe)から自動ダウンロードし、配置を試みます
|
||||
(ネット未接続などで取得に失敗した場合は「起動のみ」にフォールバックし、ゲーム自体は起動できます)。
|
||||
|
||||
## 実装上の参照
|
||||
- 取得・呼び出し: `Services\NwjsUnpackerToolProvider.cs`
|
||||
- 埋め込みZIP検出・展開: `Services\NwjsPackageUnpacker.cs`
|
||||
- オーケストレーター(戦略: 組み込みZIP → 外部ツール): `Services\TkoolPackagedExtractionService.cs`
|
||||
|
||||
## 呼び出し規約
|
||||
- 第一候補: `7zr.exe x "<exe>" -o"<out>" -y`
|
||||
- フォールバック: `7zr.exe "<exe>" -o "<out>"`
|
||||
|
||||
## ライセンス
|
||||
7-Zip は GNU LGPL + unRAR restriction の下で配布されています。
|
||||
再頒布する場合は 7-Zip のライセンス条項(https://www.7-zip.org/license.txt)に従ってください。
|
||||
Reference in new issue
Block a user