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; 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 => false; /// /// パスワード入力ダイアログに表示する案内メッセージを取得します。 /// public string? PasswordPromptMessage => "暗号化パスワードが設定されている場合は入力してください(未設定・既定の場合は空欄):"; // キャッシュ用の最新平文JSONノード private JsonNode? _cachedRootNode; private bool _wasEncrypted; private string? _usedPassword; /// /// 指定されたセーブファイルが本コーデックで処理可能かを判定します。 /// /// 対象の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(); if (!File.Exists(filePath)) return list; byte[] fileBytes = File.ReadAllBytes(filePath); if (fileBytes.Length == 0) return list; string? jsonText = null; this._wasEncrypted = false; this._usedPassword = null; // 1. まず平文 JSON または Gzip 解凍を試みる try { string text = Encoding.UTF8.GetString(fileBytes); if (text.TrimStart().StartsWith("{") || text.TrimStart().StartsWith("[")) { jsonText = text; } } 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(); } catch { } } // 3. パスワード指定または既定パスワードによる AES 復号を試みる if (jsonText == null) { var candidatePasswords = new List(); if (!string.IsNullOrEmpty(optionalPassword)) { candidatePasswords.Add(optionalPassword); } candidatePasswords.AddRange(new[] { "Moodkie", "password", "", "SaveData" }); foreach (var pwd in candidatePasswords) { var decrypted = this.TryDecryptAes(fileBytes, pwd); if (!string.IsNullOrEmpty(decrypted)) { jsonText = decrypted; this._wasEncrypted = true; this._usedPassword = pwd; break; } } } if (string.IsNullOrEmpty(jsonText)) { // JSON展開ができなかった場合、バイナリキー・バリュー形式として先頭・重要オフセットを抽出 return this.ExtractBinaryPropertiesFallback(fileBytes); } // JSON からプロパティを再帰的に展開 try { this._cachedRootNode = JsonNode.Parse(jsonText); if (this._cachedRootNode is JsonObject rootObj) { this.FlattenJsonObject(rootObj, "", list); } else if (this._cachedRootNode is JsonArray rootArr) { this.FlattenJsonArray(rootArr, "Array", list); } } catch { return this.ExtractBinaryPropertiesFallback(fileBytes); } return list; } /// /// 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._cachedRootNode != null) { // JSON の値を更新 foreach (var prop in properties) { if (prop.RawData is string keyPath) { this.UpdateJsonNodeByPath(this._cachedRootNode, keyPath, prop.EditValue, prop.Type); } } var options = new JsonSerializerOptions { WriteIndented = true, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }; string updatedJson = this._cachedRootNode.ToJsonString(options); byte[] outputBytes = Encoding.UTF8.GetBytes(updatedJson); // もともと暗号化されていた場合は再暗号化 if (this._wasEncrypted) { string pwd = !string.IsNullOrEmpty(optionalPassword) ? optionalPassword : (this._usedPassword ?? "Moodkie"); outputBytes = this.EncryptAes(outputBytes, pwd); } // バックアップ作成 if (File.Exists(filePath)) { File.Copy(filePath, filePath + ".bak", overwrite: true); } File.WriteAllBytes(filePath, outputBytes); 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 { return false; } } /// /// キーパスに基づいて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; } } }