using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Security.Cryptography; using System.Text; using System.Text.Encodings.Web; using System.Text.Json; using System.Text.Json.Nodes; using GameLauncher.Engines.Unity; using GameLauncher.Models; using GameLauncher.Services.Codecs.Es3; namespace GameLauncher.Services.Codecs { /// /// Easy Save 3 (ES3) 形式のセーブデータ(.sd, .es3, .save, .dat)用コーデック /// public class EasySave3Codec : ISaveDataCodec { /// /// コーデックの表示名を取得します。 /// public string CodecName => "Easy Save 3 (ES3) コーデック"; /// /// パスワード入力が必要かどうかを取得します。 /// 暗号化の有無はファイルごとに異なるため、実際の要否は で判定します。 /// public bool RequiresPassword => true; /// /// パスワード入力ダイアログに表示する案内メッセージを取得します。 /// public string? PasswordPromptMessage => "暗号化パスワードが設定されている場合は入力してください(未設定・既定の場合は空欄):"; /// /// 直近の読み込み時に使用した解析ドキュメント(編集・書き戻し用)。 /// private Es3SaveDocument? _document; /// 直近の読み込み対象ファイルの絶対パス。 private string? _loadedFilePath; /// 直近の読み込み時に暗号化されていたか。 private bool _wasEncrypted; /// 直近の読み込み時に復号に使用したパスワード。 private string? _usedPassword; /// 直近の読み込み時に Gzip 圧縮されていたか。 private bool _wasGzip; /// 直近の読み込み時の診断メッセージ(未対応時の案内表示に使用)。 private readonly List _diagnostics = []; /// /// 直近の読み込みに関する診断メッセージを取得します。 /// public IReadOnlyList Diagnostics => this._diagnostics; /// /// 指定ファイルがパスワード入力(復号)を必要とするかを判定します。 /// /// セーブファイルの絶対パス /// 暗号化されており復号が必要な場合 true public bool NeedsPassword(string filePath) { try { if (!File.Exists(filePath)) { return false; } var bytes = File.ReadAllBytes(filePath); return Es3PasswordResolver.LooksEncrypted(bytes); } catch { return false; } } /// /// 指定されたセーブファイルが本コーデックで処理可能かを判定します。 /// /// 対象のUnityゲーム情報 /// 対象のセーブファイル情報 /// 処理可能な場合は true、それ以外は false public bool CanHandle(UnityGameItem game, SaveFileEntry file) { var ext = Path.GetExtension(file.FilePath).ToLowerInvariant(); if (ext is ".sd" or ".es3" or ".save" or ".dat") { // ES3 の特徴:ファイル名が 0.sd, s.sd, h.sd, SaveFile.es3 など、またはファイルサイズが適度 if (file.FileName.EndsWith(".sd", StringComparison.OrdinalIgnoreCase) || file.FileName.EndsWith(".es3", StringComparison.OrdinalIgnoreCase)) { return true; } } return false; } /// /// セーブファイルからプロパティ一覧を読み込みます。 /// /// セーブファイルの絶対パス /// 任意の暗号化パスワード /// 展開されたセーブデータプロパティのリスト public List LoadProperties(string filePath, string? optionalPassword = null) { var list = new List(); this._diagnostics.Clear(); this._document = null; this._loadedFilePath = filePath; this._wasEncrypted = false; this._usedPassword = null; this._wasGzip = false; if (!File.Exists(filePath)) return list; byte[] fileBytes = File.ReadAllBytes(filePath); if (fileBytes.Length == 0) return list; string? jsonText = null; // 1. まず平文 JSON または Gzip 解凍を試みる try { string text = Encoding.UTF8.GetString(fileBytes); if (text.TrimStart().StartsWith("{") || text.TrimStart().StartsWith("[")) { jsonText = text; this._diagnostics.Add("平文 JSON として読み込みました。"); } } catch { } // 2. Gzip 圧縮の解凍を試みる if (jsonText == null && fileBytes.Length > 2 && fileBytes[0] == 0x1F && fileBytes[1] == 0x8B) { try { using var ms = new MemoryStream(fileBytes); using var gzip = new GZipStream(ms, CompressionMode.Decompress); using var reader = new StreamReader(gzip, Encoding.UTF8); jsonText = reader.ReadToEnd(); this._wasGzip = true; this._diagnostics.Add("Gzip 圧縮を解凍して読み込みました。"); } catch { } } // 3. パスワードを多段フォールバックで解決して AES 復号する if (jsonText == null) { var gameRoot = Path.GetDirectoryName(filePath); var resolution = Es3PasswordResolver.Instance.Resolve( filePath, gameRootDirectory: gameRoot, gameKey: gameRoot, explicitPassword: optionalPassword); this._diagnostics.AddRange(resolution.Diagnostics); if (resolution.Success && !string.IsNullOrEmpty(resolution.Password)) { jsonText = Es3PasswordResolver.TryDecrypt(fileBytes, resolution.Password); if (!string.IsNullOrEmpty(jsonText)) { this._wasEncrypted = true; this._usedPassword = resolution.Password; } } } if (string.IsNullOrEmpty(jsonText)) { this._diagnostics.Add("復号できませんでした。パスワードを手動で入力してください。"); return this.ExtractBinaryPropertiesFallback(fileBytes); } // 4. ES3 の型付き形式を解析してプロパティへ展開 var document = Es3SaveDocument.Parse(jsonText); if (!document.IsLoaded) { this._diagnostics.AddRange(document.Warnings); return this.ExtractBinaryPropertiesFallback(fileBytes); } this._document = document; this._diagnostics.AddRange(document.Warnings); this.FlattenNodes(document.RootNodes, string.Empty, list); return list; } /// /// 型付きノードを平坦化してプロパティ一覧へ変換します(型タグ付きで編集可能にします)。 /// /// 変換対象のノード /// 現在の階層プレフィックス /// 追加先のプロパティリスト private void FlattenNodes(List nodes, string prefix, List list) { foreach (var node in nodes) { var key = string.IsNullOrEmpty(prefix) ? node.Key : $"{prefix}.{node.Key}"; var category = string.IsNullOrEmpty(prefix) ? "基本変数" : prefix; if (node.HasChildren) { list.Add(new SaveDataPropertyEntry { Key = key, Category = category, Type = FormatKindLabel(node), EditValue = node.DisplayValue, Description = $"JSON パス: {node.Path}", RawData = node, Kind = MapToValueKind(node.Kind) }); this.FlattenNodes(node.Children, key, list); continue; } list.Add(new SaveDataPropertyEntry { Key = key, Category = category, Type = FormatKindLabel(node), EditValue = node.DisplayValue, Description = $"JSON パス: {node.Path}", RawData = node, Kind = MapToValueKind(node.Kind) }); } } /// /// ES3 の値種別を、GUI の型別エディタ用の種別へ変換します。 /// /// ES3 の値種別 /// GUI 用の値種別 private static SaveDataPropertyEntry.ValueKind MapToValueKind(Es3ValueKind kind) { return kind switch { Es3ValueKind.Boolean => SaveDataPropertyEntry.ValueKind.Boolean, Es3ValueKind.Integer => SaveDataPropertyEntry.ValueKind.Integer, Es3ValueKind.Float => SaveDataPropertyEntry.ValueKind.Float, Es3ValueKind.String => SaveDataPropertyEntry.ValueKind.String, Es3ValueKind.Enum => SaveDataPropertyEntry.ValueKind.Enum, Es3ValueKind.Array or Es3ValueKind.Dictionary or Es3ValueKind.Object => SaveDataPropertyEntry.ValueKind.Complex, _ => SaveDataPropertyEntry.ValueKind.Unknown }; } /// /// ノードの型名を表示用ラベルに整形します。 /// /// 対象ノード /// 表示用の型ラベル private static string FormatKindLabel(Es3Node node) { var kind = node.Kind switch { Es3ValueKind.Boolean => "bool", Es3ValueKind.Integer => "int", Es3ValueKind.Float => "float", Es3ValueKind.String => "string", Es3ValueKind.Enum => "enum", Es3ValueKind.Array => "array", Es3ValueKind.Dictionary => "dictionary", Es3ValueKind.Object => "object", _ => "unknown" }; return string.IsNullOrEmpty(node.TypeName) ? kind : $"{kind} ({node.TypeName})"; } /// /// JSONオブジェクトを再帰的に走査し、プロパティ一覧に追加します。 /// /// 対象のJSONオブジェクト /// 現在のキー階層プレフィックス /// 追加先のプロパティリスト private void FlattenJsonObject(JsonObject obj, string prefix, List list) { foreach (var kvp in obj) { string key = string.IsNullOrEmpty(prefix) ? kvp.Key : $"{prefix}.{kvp.Key}"; var node = kvp.Value; if (node == null) { list.Add(new SaveDataPropertyEntry { Key = key, Category = string.IsNullOrEmpty(prefix) ? "ルート" : prefix, Type = "null", EditValue = "null", RawData = key }); } else if (node is JsonValue val) { string type = "String"; if (val.TryGetValue(out int intVal)) type = "Int"; else if (val.TryGetValue(out long longVal)) type = "Long"; else if (val.TryGetValue(out double dblVal)) type = "Float"; else if (val.TryGetValue(out bool boolVal)) type = "Bool"; list.Add(new SaveDataPropertyEntry { Key = key, Category = string.IsNullOrEmpty(prefix) ? "基本変数" : prefix, Type = type, EditValue = val.ToString() ?? "", RawData = key }); } else if (node is JsonObject childObj) { // ES3 特有の構造: { "__type": "...", "value": ... } の場合は中身を直接展開 if (childObj.ContainsKey("value") && childObj["value"] is JsonValue directVal) { string type = childObj["__type"]?.ToString() ?? "Object"; list.Add(new SaveDataPropertyEntry { Key = key, Category = prefix, Type = type, EditValue = directVal.ToString() ?? "", RawData = key + ".value" }); } else { this.FlattenJsonObject(childObj, key, list); } } else if (node is JsonArray childArr) { if (childArr.Count <= 20) { this.FlattenJsonArray(childArr, key, list); } else { list.Add(new SaveDataPropertyEntry { Key = key, Category = prefix, Type = $"配列[{childArr.Count}]", EditValue = childArr.ToJsonString(), Description = "要素数が多いためJSON形式で直接編集できます", RawData = key }); } } } } /// /// JSON配列を再帰的に走査し、プロパティ一覧に追加します。 /// /// 対象のJSON配列 /// 現在のキー階層プレフィックス /// 追加先のプロパティリスト private void FlattenJsonArray(JsonArray arr, string prefix, List list) { for (int i = 0; i < arr.Count; i++) { string key = $"{prefix}[{i}]"; var node = arr[i]; if (node is JsonValue val) { list.Add(new SaveDataPropertyEntry { Key = key, Category = prefix, Type = "要素", EditValue = val.ToString() ?? "", RawData = key }); } else if (node is JsonObject childObj) { this.FlattenJsonObject(childObj, key, list); } } } /// /// JSON展開に失敗した場合のフォールバックとしてバイナリ値を抽出します。 /// /// ファイル全体のバイナリデータ /// バイナリ情報プロパティのリスト private List ExtractBinaryPropertiesFallback(byte[] bytes) { var list = new List { new SaveDataPropertyEntry { Key = "FileSize", Category = "ファイル情報", Type = "Int", EditValue = bytes.Length.ToString(), Description = "ファイルサイズ (bytes)" } }; // 先頭 128 バイトから 4 バイト整数と ASCII 文字列を検出してプロパティ化 int limit = Math.Min(bytes.Length - 4, 128); for (int i = 0; i < limit; i += 4) { int val = BitConverter.ToInt32(bytes, i); list.Add(new SaveDataPropertyEntry { Key = $"Offset_0x{i:X2}", Category = "バイナリ変数 (4バイト)", Type = "Int32", EditValue = val.ToString(), Description = $"16進数オフセット 0x{i:X2} の数値", RawData = i }); } return list; } /// /// 編集後のプロパティ一覧をセーブファイルへ書き戻して保存します。 /// /// 保存先セーブファイルの絶対パス /// 編集されたプロパティ一覧 /// 任意の暗号化パスワード /// 保存に成功した場合は true、それ以外は false public bool SaveProperties(string filePath, List properties, string? optionalPassword = null) { try { if (this._document is { IsLoaded: true } document) { // 編集値を解析ツリーへ適用する foreach (var prop in properties) { if (!prop.IsModified || prop.RawData is not Es3Node node) { continue; } if (!node.IsEditable) { continue; } if (document.TrySetValue(node.Path, prop.EditValue, out var applyError)) { node.DisplayValue = prop.EditValue; } else { this._diagnostics.Add($"'{prop.Key}' の適用をスキップしました: {applyError}"); } } // 変更がなければ書き込まない if (!document.HasChanges()) { this._diagnostics.Add("変更点がないため保存をスキップしました。"); return true; } byte[] outputBytes = Encoding.UTF8.GetBytes(document.ToJson()); // もともと Gzip 圧縮されていた場合は再圧縮する if (this._wasGzip) { outputBytes = CompressGzip(outputBytes); } // もともと暗号化されていた場合は同一パスワードで再暗号化する if (this._wasEncrypted) { var pwd = !string.IsNullOrEmpty(optionalPassword) ? optionalPassword! : this._usedPassword ?? string.Empty; outputBytes = Es3PasswordResolver.Encrypt(outputBytes, pwd); } // 往復検証: 書き込み前に「出力バイト列を読み直して構造が一致するか」を確認する if (!this.VerifyRoundTrip(outputBytes, document, out var verifyError)) { this._diagnostics.Add($"往復検証に失敗したため保存を中止しました: {verifyError}"); return false; } // バックアップ作成(既存規約に従い .bak を残す) if (File.Exists(filePath)) { File.Copy(filePath, filePath + ".bak", overwrite: true); } File.WriteAllBytes(filePath, outputBytes); this._diagnostics.Add($"保存しました({outputBytes.Length} bytes)。"); return true; } else { // バイナリオフセット書き換え byte[] fileBytes = File.ReadAllBytes(filePath); foreach (var prop in properties) { if (prop.RawData is int offset && offset + 4 <= fileBytes.Length) { if (int.TryParse(prop.EditValue, out int val)) { var b = BitConverter.GetBytes(val); Array.Copy(b, 0, fileBytes, offset, 4); } } } if (File.Exists(filePath)) { File.Copy(filePath, filePath + ".bak", overwrite: true); } File.WriteAllBytes(filePath, fileBytes); return true; } } catch (Exception ex) { this._diagnostics.Add($"保存中に例外が発生しました: {ex.Message}"); return false; } } /// /// 出力バイト列を読み直して編集内容が保持されているかを検証します(往復検証)。 /// 検証に失敗した場合はファイルへ書き込まず、元データを温存します。 /// /// 書き込み予定のバイト列 /// 編集済みドキュメント /// 検証失敗の理由 /// 検証に成功した場合 true private bool VerifyRoundTrip(byte[] outputBytes, Es3SaveDocument document, out string error) { error = string.Empty; try { string? verifiedJson; if (this._wasEncrypted) { var pwd = this._usedPassword ?? string.Empty; verifiedJson = Es3PasswordResolver.TryDecrypt(outputBytes, pwd); } else if (this._wasGzip) { using var ms = new MemoryStream(outputBytes); using var gzip = new GZipStream(ms, CompressionMode.Decompress); using var reader = new StreamReader(gzip, Encoding.UTF8); verifiedJson = reader.ReadToEnd(); } else { verifiedJson = Encoding.UTF8.GetString(outputBytes); } if (string.IsNullOrEmpty(verifiedJson)) { error = "出力データを復号・解凍できませんでした。"; return false; } var reparsed = Es3SaveDocument.Parse(verifiedJson); if (!reparsed.IsLoaded) { error = "出力データを再解析できませんでした。"; return false; } // ルート直下の要素数が一致することを最低条件とする if (reparsed.RootNodes.Count != document.RootNodes.Count) { error = $"要素数が一致しません(期待 {document.RootNodes.Count} / 実際 {reparsed.RootNodes.Count})。"; return false; } return true; } catch (Exception ex) { error = ex.Message; return false; } } /// /// バイト列を Gzip 圧縮します(元が Gzip だった場合に元形式を維持するため)。 /// /// 平文バイト列 /// 圧縮済みバイト列 private static byte[] CompressGzip(byte[] plainBytes) { using var output = new MemoryStream(); using (var gzip = new GZipStream(output, CompressionLevel.Optimal, leaveOpen: true)) { gzip.Write(plainBytes, 0, plainBytes.Length); } return output.ToArray(); } /// /// キーパスに基づいてJSONノードの値を更新します。 /// /// ルートのJSONノード /// ドット区切りのキーパス /// 更新後の値文字列 /// 値の型名 private void UpdateJsonNodeByPath(JsonNode root, string path, string newValue, string type) { try { // ドットと角括弧でパスを分割 var parts = path.Split(['.', '[', ']'], StringSplitOptions.RemoveEmptyEntries); JsonNode? current = root; for (int i = 0; i < parts.Length - 1; i++) { if (current is JsonObject obj && obj.ContainsKey(parts[i])) { current = obj[parts[i]]; } else if (current is JsonArray arr && int.TryParse(parts[i], out int arrIdx) && arrIdx < arr.Count) { current = arr[arrIdx]; } else { return; } } string lastKey = parts[^1]; if (current is JsonObject finalObj) { finalObj[lastKey] = this.ParseJsonValue(newValue, type); } else if (current is JsonArray finalArr && int.TryParse(lastKey, out int finalIdx) && finalIdx < finalArr.Count) { finalArr[finalIdx] = this.ParseJsonValue(newValue, type); } } catch { } } /// /// 文字列値と型名から対応するJSONノードを生成します。 /// /// 値文字列 /// 型名 /// 生成されたJSONノード private JsonNode? ParseJsonValue(string value, string type) { if (type == "Int" && int.TryParse(value, out int i)) return JsonValue.Create(i); if (type == "Long" && long.TryParse(value, out long l)) return JsonValue.Create(l); if (type == "Float" && double.TryParse(value, out double d)) return JsonValue.Create(d); if (type == "Bool" && bool.TryParse(value, out bool b)) return JsonValue.Create(b); if (type == "null") return null; try { // JSON オブジェクトや配列としてパース可能か試みる if (value.StartsWith("{") || value.StartsWith("[")) { return JsonNode.Parse(value); } } catch { } return JsonValue.Create(value); } /// /// AESアルゴリズムによるセーブデータの復号を試みます。 /// /// 暗号化バイナリデータ /// 復号パスワード /// 復号された平文文字列。失敗時は null private string? TryDecryptAes(byte[] data, string password) { try { byte[] rawUtf8 = Encoding.UTF8.GetBytes(password); var key16 = new byte[16]; Array.Copy(rawUtf8, key16, Math.Min(rawUtf8.Length, 16)); if (data.Length > 16) { var iv = new byte[16]; Array.Copy(data, 0, iv, 0, 16); var cipher = new byte[data.Length - 16]; Array.Copy(data, 16, cipher, 0, cipher.Length); using var aes = Aes.Create(); aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; aes.Key = key16; aes.IV = iv; using var dec = aes.CreateDecryptor(); byte[] plain = dec.TransformFinalBlock(cipher, 0, cipher.Length); string text = Encoding.UTF8.GetString(plain); if (text.Contains("{") || text.Contains("__type") || text.Contains("version")) { return text; } } } catch { } return null; } /// /// 平文バイト配列をAESアルゴリズムで暗号化します。 /// /// 平文バイナリデータ /// 暗号化パスワード /// 暗号化されたバイナリデータ private byte[] EncryptAes(byte[] plainBytes, string password) { byte[] rawUtf8 = Encoding.UTF8.GetBytes(password); var key16 = new byte[16]; Array.Copy(rawUtf8, key16, Math.Min(rawUtf8.Length, 16)); using var aes = Aes.Create(); aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; aes.Key = key16; aes.GenerateIV(); using var enc = aes.CreateEncryptor(); byte[] cipher = enc.TransformFinalBlock(plainBytes, 0, plainBytes.Length); var result = new byte[aes.IV.Length + cipher.Length]; Array.Copy(aes.IV, 0, result, 0, aes.IV.Length); Array.Copy(cipher, 0, result, aes.IV.Length, cipher.Length); return result; } } }