using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Text.Json; using GameLauncher.Helpers; namespace GameLauncher.Services.Codecs.Es3 { /// /// ES3 のパスワード特定結果を「ゲーム単位」で永続化する学習キャッシュ。 /// /// 一度解決したパスワードを保存しておくことで、次回以降は自動適用できます。 /// 保存先は exe 直下の es3-passwords.json で、キャッシュ破棄やブックマークとは独立に管理します。 /// public sealed class Es3PasswordStore { /// 永続化ファイル名。 private const string FileName = "es3-passwords.json"; /// 既定のシングルトンインスタンス。 public static Es3PasswordStore Instance { get; } = new(); private readonly object _syncRoot = new(); private readonly string _filePath; private Dictionary? _entries; /// /// exe 直下の既定パスを用いて を初期化します。 /// public Es3PasswordStore() : this(Path.Combine(AppPathHelper.GetExeDirectory(), FileName)) { } /// /// 任意のファイルパスを指定して を初期化します(テスト用途を含む)。 /// /// 永続化ファイルの絶対パス public Es3PasswordStore(string filePath) { this._filePath = filePath; } /// /// 永続化ファイルのパスを取得します。 /// public string FilePath => this._filePath; /// /// 指定キーに対応する学習済みパスワードを取得します。 /// /// ゲーム単位のキー(通常はゲームのルートディレクトリ) /// 保存済みパスワード。未登録の場合は null public string? TryGet(string key) { if (string.IsNullOrWhiteSpace(key)) { return null; } lock (this._syncRoot) { var entries = this.LoadEntries(); return entries.TryGetValue(Normalize(key), out var password) ? password : null; } } /// /// 学習済みパスワードを保存します。 /// /// ゲーム単位のキー /// 保存するパスワード(空文字も有効な値として保存します) public void Set(string key, string password) { if (string.IsNullOrWhiteSpace(key)) { return; } lock (this._syncRoot) { var entries = this.LoadEntries(); entries[Normalize(key)] = password ?? string.Empty; this.SaveEntries(entries); } } /// /// 指定キーの学習済みパスワードを削除します。 /// /// ゲーム単位のキー /// 削除できた場合 true public bool Remove(string key) { if (string.IsNullOrWhiteSpace(key)) { return false; } lock (this._syncRoot) { var entries = this.LoadEntries(); if (!entries.Remove(Normalize(key))) { return false; } this.SaveEntries(entries); return true; } } /// /// 保存済みエントリのスナップショットを取得します(表示・診断用)。 /// /// キーとパスワードの読み取り専用ディクショナリ public IReadOnlyDictionary Snapshot() { lock (this._syncRoot) { return new Dictionary(this.LoadEntries(), StringComparer.OrdinalIgnoreCase); } } /// /// 永続化ファイルを読み込みます。壊れている場合は空のディクショナリを返します。 /// /// 読み込んだエントリ private Dictionary LoadEntries() { if (this._entries != null) { return this._entries; } var result = new Dictionary(StringComparer.OrdinalIgnoreCase); try { if (File.Exists(this._filePath)) { var json = File.ReadAllText(this._filePath, Encoding.UTF8); if (!string.IsNullOrWhiteSpace(json)) { var loaded = JsonSerializer.Deserialize>(json); if (loaded != null) { foreach (var kvp in loaded) { if (!string.IsNullOrWhiteSpace(kvp.Key)) { result[Normalize(kvp.Key)] = kvp.Value ?? string.Empty; } } } } } } catch { // 破損ファイルは無視し、空の状態から再構築する result = new Dictionary(StringComparer.OrdinalIgnoreCase); } this._entries = result; return this._entries; } /// /// エントリを永続化ファイルへ書き出します。 /// /// 書き出すエントリ private void SaveEntries(Dictionary entries) { try { var directory = Path.GetDirectoryName(this._filePath); if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory)) { Directory.CreateDirectory(directory); } var options = new JsonSerializerOptions { WriteIndented = true }; var json = JsonSerializer.Serialize(entries, options); // BOM なし UTF-8 で保存する File.WriteAllText(this._filePath, json, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); } catch { // 保存失敗は致命的ではないため握りつぶす(次回再度解決を試みる) } } /// /// キーを比較用に正規化します(パス区切りと大文字小文字の揺れを吸収)。 /// /// 元のキー /// 正規化済みキー private static string Normalize(string key) { var trimmed = key.Trim(); try { return Path.GetFullPath(trimmed).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); } catch { return trimmed; } } } }