- 自インスタンスメンバーアクセスへの this. 付与(28ファイル) - .editorconfig に準拠したインデント・波括弧・空白スタイルの適用 - UTF-8 (BOMあり)、CRLF改行コード、行末空白除去の整合性検証
521 lines
21 KiB
C#
521 lines
21 KiB
C#
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
|
|
{
|
|
/// <summary>
|
|
/// Easy Save 3 (ES3) 形式のセーブデータ(.sd, .es3, .save, .dat)用コーデック
|
|
/// </summary>
|
|
public class EasySave3Codec : ISaveDataCodec
|
|
{
|
|
/// <summary>
|
|
/// コーデックの表示名を取得します。
|
|
/// </summary>
|
|
public string CodecName => "Easy Save 3 (ES3) コーデック";
|
|
|
|
/// <summary>
|
|
/// パスワード入力が必要かどうかを取得します。
|
|
/// </summary>
|
|
public bool RequiresPassword => false;
|
|
|
|
/// <summary>
|
|
/// パスワード入力ダイアログに表示する案内メッセージを取得します。
|
|
/// </summary>
|
|
public string? PasswordPromptMessage => "暗号化パスワードが設定されている場合は入力してください(未設定・既定の場合は空欄):";
|
|
|
|
// キャッシュ用の最新平文JSONノード
|
|
private JsonNode? _cachedRootNode;
|
|
private bool _wasEncrypted;
|
|
private string? _usedPassword;
|
|
|
|
/// <summary>
|
|
/// 指定されたセーブファイルが本コーデックで処理可能かを判定します。
|
|
/// </summary>
|
|
/// <param name="game">対象のUnityゲーム情報</param>
|
|
/// <param name="file">対象のセーブファイル情報</param>
|
|
/// <returns>処理可能な場合は true、それ以外は false</returns>
|
|
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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// セーブファイルからプロパティ一覧を読み込みます。
|
|
/// </summary>
|
|
/// <param name="filePath">セーブファイルの絶対パス</param>
|
|
/// <param name="optionalPassword">任意の暗号化パスワード</param>
|
|
/// <returns>展開されたセーブデータプロパティのリスト</returns>
|
|
public List<SaveDataPropertyEntry> LoadProperties(string filePath, string? optionalPassword = null)
|
|
{
|
|
var list = new List<SaveDataPropertyEntry>();
|
|
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<string>();
|
|
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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// JSONオブジェクトを再帰的に走査し、プロパティ一覧に追加します。
|
|
/// </summary>
|
|
/// <param name="obj">対象のJSONオブジェクト</param>
|
|
/// <param name="prefix">現在のキー階層プレフィックス</param>
|
|
/// <param name="list">追加先のプロパティリスト</param>
|
|
private void FlattenJsonObject(JsonObject obj, string prefix, List<SaveDataPropertyEntry> 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
|
|
});
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// JSON配列を再帰的に走査し、プロパティ一覧に追加します。
|
|
/// </summary>
|
|
/// <param name="arr">対象のJSON配列</param>
|
|
/// <param name="prefix">現在のキー階層プレフィックス</param>
|
|
/// <param name="list">追加先のプロパティリスト</param>
|
|
private void FlattenJsonArray(JsonArray arr, string prefix, List<SaveDataPropertyEntry> 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);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// JSON展開に失敗した場合のフォールバックとしてバイナリ値を抽出します。
|
|
/// </summary>
|
|
/// <param name="bytes">ファイル全体のバイナリデータ</param>
|
|
/// <returns>バイナリ情報プロパティのリスト</returns>
|
|
private List<SaveDataPropertyEntry> ExtractBinaryPropertiesFallback(byte[] bytes)
|
|
{
|
|
var list = new List<SaveDataPropertyEntry>
|
|
{
|
|
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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 編集後のプロパティ一覧をセーブファイルへ書き戻して保存します。
|
|
/// </summary>
|
|
/// <param name="filePath">保存先セーブファイルの絶対パス</param>
|
|
/// <param name="properties">編集されたプロパティ一覧</param>
|
|
/// <param name="optionalPassword">任意の暗号化パスワード</param>
|
|
/// <returns>保存に成功した場合は true、それ以外は false</returns>
|
|
public bool SaveProperties(string filePath, List<SaveDataPropertyEntry> 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;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// キーパスに基づいてJSONノードの値を更新します。
|
|
/// </summary>
|
|
/// <param name="root">ルートのJSONノード</param>
|
|
/// <param name="path">ドット区切りのキーパス</param>
|
|
/// <param name="newValue">更新後の値文字列</param>
|
|
/// <param name="type">値の型名</param>
|
|
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 { }
|
|
}
|
|
|
|
/// <summary>
|
|
/// 文字列値と型名から対応するJSONノードを生成します。
|
|
/// </summary>
|
|
/// <param name="value">値文字列</param>
|
|
/// <param name="type">型名</param>
|
|
/// <returns>生成されたJSONノード</returns>
|
|
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);
|
|
}
|
|
|
|
/// <summary>
|
|
/// AESアルゴリズムによるセーブデータの復号を試みます。
|
|
/// </summary>
|
|
/// <param name="data">暗号化バイナリデータ</param>
|
|
/// <param name="password">復号パスワード</param>
|
|
/// <returns>復号された平文文字列。失敗時は null</returns>
|
|
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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 平文バイト配列をAESアルゴリズムで暗号化します。
|
|
/// </summary>
|
|
/// <param name="plainBytes">平文バイナリデータ</param>
|
|
/// <param name="password">暗号化パスワード</param>
|
|
/// <returns>暗号化されたバイナリデータ</returns>
|
|
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;
|
|
}
|
|
}
|
|
}
|