feat: 初回コミット (GameLauncher)

This commit is contained in:
armonica committed 2026-10-01 09:42:02 +09:00
commit 7ac4dbc825
45 files changed
+9779

No files matched your search

+447
View File
@@ -0,0 +1,447 @@
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.Models;
namespace GameLauncher.Services.Codecs
{
/// <summary>
/// Easy Save 3 (ES3) 形式のセーブデータ(.sd, .es3, .save, .dat)用コーデック
/// </summary>
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;
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<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;
_wasEncrypted = false;
_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 = TryDecryptAes(fileBytes, pwd);
if (!string.IsNullOrEmpty(decrypted))
{
jsonText = decrypted;
_wasEncrypted = true;
_usedPassword = pwd;
break;
}
}
}
if (string.IsNullOrEmpty(jsonText))
{
// JSON展開ができなかった場合、バイナリキー・バリュー形式として先頭・重要オフセットを抽出
return ExtractBinaryPropertiesFallback(fileBytes);
}
// JSON からプロパティを再帰的に展開
try
{
_cachedRootNode = JsonNode.Parse(jsonText);
if (_cachedRootNode is JsonObject rootObj)
{
FlattenJsonObject(rootObj, "", list);
}
else if (_cachedRootNode is JsonArray rootArr)
{
FlattenJsonArray(rootArr, "Array", list);
}
}
catch
{
return ExtractBinaryPropertiesFallback(fileBytes);
}
return list;
}
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
{
FlattenJsonObject(childObj, key, list);
}
}
else if (node is JsonArray childArr)
{
if (childArr.Count <= 20)
{
FlattenJsonArray(childArr, key, list);
}
else
{
list.Add(new SaveDataPropertyEntry
{
Key = key,
Category = prefix,
Type = $"配列[{childArr.Count}]",
EditValue = childArr.ToJsonString(),
Description = "要素数が多いためJSON形式で直接編集できます",
RawData = key
});
}
}
}
}
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)
{
FlattenJsonObject(childObj, key, list);
}
}
}
private List<SaveDataPropertyEntry> ExtractBinaryPropertiesFallback(byte[] bytes)
{
var list = new List<SaveDataPropertyEntry>();
list.Add(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;
}
public bool SaveProperties(string filePath, List<SaveDataPropertyEntry> properties, string? optionalPassword = null)
{
try
{
if (_cachedRootNode != null)
{
// JSON の値を更新
foreach (var prop in properties)
{
if (prop.RawData is string keyPath)
{
UpdateJsonNodeByPath(_cachedRootNode, keyPath, prop.EditValue, prop.Type);
}
}
var options = new JsonSerializerOptions
{
WriteIndented = true,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
};
string updatedJson = _cachedRootNode.ToJsonString(options);
byte[] outputBytes = Encoding.UTF8.GetBytes(updatedJson);
// もともと暗号化されていた場合は再暗号化
if (_wasEncrypted)
{
string pwd = !string.IsNullOrEmpty(optionalPassword) ? optionalPassword : (_usedPassword ?? "Moodkie");
outputBytes = 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;
}
}
private void UpdateJsonNodeByPath(JsonNode root, string path, string newValue, string type)
{
try
{
// ドットと角括弧でパスを分割
var parts = path.Split(new[] { '.', '[', ']' }, 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] = ParseJsonValue(newValue, type);
}
else if (current is JsonArray finalArr && int.TryParse(lastKey, out int finalIdx) && finalIdx < finalArr.Count)
{
finalArr[finalIdx] = ParseJsonValue(newValue, type);
}
}
catch { }
}
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);
}
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;
}
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;
}
}
}