using System;
using System.IO;
using System.Text;
namespace GameLauncher.Engines.Tkool
{
///
/// 対象ゲームの plugins.js に対する可逆なJSプラグイン注入(mod)を行うサービス。
///
/// 設計方針:
/// - ゲーム専用改造は他ゲームへ一切影響を与えない(対象ゲームフォルダ内でのみ完結)。
/// - 注入前に plugins.js を *.glbak へバックアップし、marker 区間のみを書き換える。
/// - Restore は *.glbak から復元し、配置した mod JS を削除して完全可逆にする。
/// - exe内 package.nw 直接書換は最終手段(必須バックアップ)。
///
public sealed class TkoolInjectionService
{
/// 注入マーカー(この区間のみを除去すれば完全に元へ戻せる)
public const string BeginMarker = "/* === GAMELAUNCHER_MOD_BEGIN === */";
public const string EndMarker = "/* === GAMELAUNCHER_MOD_END === */";
/// 注入する改造プラグインファイル名
public const string ModPluginId = "GameLauncher_Mod";
public const string ModPluginFileName = "GameLauncher_Mod.js";
/// exe内コンテナ改変時のバックアップ拡張子
public const string ExeBackupSuffix = ".glbak";
///
/// plugins.js に marker が存在する場合、改造注入済みと判定します。
///
public static bool CheckIsModded(string pluginsJsPath)
{
if (string.IsNullOrEmpty(pluginsJsPath) || !File.Exists(pluginsJsPath))
{
return false;
}
try
{
var content = File.ReadAllText(pluginsJsPath, Encoding.UTF8);
// パス破損の影響を避けるため、対称な EndMarker(先頭/末尾共通)で判定
return content.Contains(BeginMarker) || content.Contains(ModPluginId);
}
catch
{
return false;
}
}
///
/// modプラグインエントリを plugins.js へ marker 付きで追記し、
/// mod JS を js/plugins/ へ配置します。バックアップ(*.glbak)は必須。
///
public bool Apply(string pluginsJsPath, string pluginsDir, string modSourcePath)
{
if (string.IsNullOrEmpty(pluginsJsPath) || !File.Exists(pluginsJsPath))
{
return false;
}
if (string.IsNullOrEmpty(modSourcePath) || !File.Exists(modSourcePath))
{
return false;
}
try
{
var backupPath = pluginsJsPath + ExeBackupSuffix;
// 1. バックアップ(未作成時のみ)。既に marker がある場合はクリーン化して保持
if (!File.Exists(backupPath))
{
var original = File.ReadAllText(pluginsJsPath, Encoding.UTF8);
File.WriteAllText(backupPath, RemoveInjection(original), new UTF8Encoding(false));
}
// 2. mod JS を plugins ディレクトリへ配置
if (string.IsNullOrEmpty(pluginsDir))
{
pluginsDir = Path.Combine(Path.GetDirectoryName(pluginsJsPath)!, "plugins");
}
Directory.CreateDirectory(pluginsDir);
File.Copy(modSourcePath, Path.Combine(pluginsDir, ModPluginFileName), overwrite: true);
// 3. バックアップ(クリーン状態)を元に marker 区間を注入
var baseContent = File.ReadAllText(backupPath, Encoding.UTF8);
var injected = InjectEntry(RemoveInjection(baseContent));
File.WriteAllText(pluginsJsPath, injected, new UTF8Encoding(false));
return true;
}
catch
{
return false;
}
}
///
/// *.glbak から plugins.js を復元し、配置した mod JS を削除します(完全可逆)。
///
public bool Restore(string pluginsJsPath, string pluginsDir)
{
if (string.IsNullOrEmpty(pluginsJsPath) || !File.Exists(pluginsJsPath))
{
return false;
}
try
{
var backupPath = pluginsJsPath + ExeBackupSuffix;
if (File.Exists(backupPath))
{
var backupContent = File.ReadAllText(backupPath, Encoding.UTF8);
File.WriteAllText(pluginsJsPath, backupContent, new UTF8Encoding(false));
try { File.Delete(backupPath); } catch { }
}
else
{
// バックアップが無くても現状から marker 区間を除去
var current = File.ReadAllText(pluginsJsPath, Encoding.UTF8);
File.WriteAllText(pluginsJsPath, RemoveInjection(current), new UTF8Encoding(false));
}
// 配置した mod JS を削除(ゴミを残さない)
if (!string.IsNullOrEmpty(pluginsDir))
{
var modPlugin = Path.Combine(pluginsDir, ModPluginFileName);
if (File.Exists(modPlugin))
{
try { File.Delete(modPlugin); } catch { }
}
}
return true;
}
catch
{
return false;
}
}
///
/// plugins.js の配列へ mod プラグインのエントリを marker 付きで追加します。
///
private static string InjectEntry(string content)
{
if (string.IsNullOrWhiteSpace(content))
{
return content;
}
int arrayStart = content.IndexOf('[');
int arrayEnd = content.LastIndexOf(']');
if (arrayStart == -1 || arrayEnd == -1 || arrayEnd <= arrayStart)
{
return content;
}
var entry = $"{BeginMarker}{{\"name\":\"{ModPluginId}\",\"status\":true,\"description\":\"GameLauncher mod\",\"parameters\":{{}}}}{EndMarker}";
var prefix = content[..(arrayStart + 1)];
var inner = content.Substring(arrayStart + 1, arrayEnd - arrayStart - 1);
var suffix = content[arrayEnd..];
var trimmedInner = inner.Trim();
var newInner = string.IsNullOrEmpty(trimmedInner)
? "\n" + entry + "\n"
: inner.TrimEnd() + ",\n" + entry + "\n";
return prefix + newInner + suffix;
}
///
/// marker 区間(BEGIN..END)を完全に除去します。これにより注入前の状態へ復元できます。
///
private static string RemoveInjection(string content)
{
if (string.IsNullOrEmpty(content))
{
return content;
}
string prev;
do
{
prev = content;
int begin = content.IndexOf(BeginMarker, StringComparison.Ordinal);
if (begin < 0) break;
int end = content.IndexOf(EndMarker, begin, StringComparison.Ordinal);
if (end < 0) break;
end += EndMarker.Length;
// 直前のカンマ・余分な空白も除去対象に含める
int cutStart = begin;
int scan = begin - 1;
while (scan >= 0 && char.IsWhiteSpace(content[scan])) scan--;
if (scan >= 0 && content[scan] == ',') cutStart = scan;
content = content[..cutStart] + content[end..];
}
while (content != prev);
return content;
}
}
}