using System.IO; using System.Security.Cryptography; using System.Text; using System.Text.Json; using YukkuriMovieMaker.Commons; namespace UndoTree; internal sealed class UndoTreeRecordStore(string directory) { const string Extension = ".json"; const string TemporaryExtension = ".tmp"; const int NameLength = 32; public const long BytesPerKilobyte = 1024; public const long BytesPerMegabyte = BytesPerKilobyte * BytesPerKilobyte; static readonly Lazy DefaultStore = new(() => new UndoTreeRecordStore(Path.Combine(AppDirectories.UserResourceDirectory, "cache", "UndoTree"))); static readonly JsonSerializerOptions Options = new() { WriteIndented = false }; readonly object gate = new(); public static UndoTreeRecordStore Default => DefaultStore.Value; public string Directory { get; } = directory; public string FileOf(string projectPath) { var normalized = Path.GetFullPath(projectPath).ToUpperInvariant(); var hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(normalized))); return Path.Combine(Directory, hash[..NameLength] + Extension); } public bool Exists(string projectPath) { try { return File.Exists(FileOf(projectPath)); } catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException) { return false; } } public UndoTreeRecordFile? Load(string projectPath) { lock (gate) { try { var file = FileOf(projectPath); if (!File.Exists(file)) return null; var loaded = JsonSerializer.Deserialize(File.ReadAllText(file, Encoding.UTF8), Options); return loaded is { Version: UndoTreeRecordFile.CurrentVersion } ? loaded : null; } catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or JsonException or ArgumentException or NotSupportedException) { return null; } } } public bool Save(string projectPath, UndoTreeRecordFile record) { lock (gate) { try { System.IO.Directory.CreateDirectory(Directory); var file = FileOf(projectPath); var temporary = file + TemporaryExtension; File.WriteAllText(temporary, JsonSerializer.Serialize(record, Options), new UTF8Encoding(false)); File.Move(temporary, file, overwrite: true); return true; } catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException) { return false; } } } public UndoTreeRecordUsage Usage() { lock (gate) { var files = RecordFiles(); return new UndoTreeRecordUsage(files.Count, files.Sum(file => file.Length)); } } public int Clear() { lock (gate) { var removed = 0; foreach (var file in RecordFiles()) { if (TryDelete(file)) removed++; } return removed; } } public int Prune(int retentionDays, long maxBytes, DateTime now) { lock (gate) { var removed = 0; var files = RecordFiles().OrderByDescending(file => file.LastWriteTime).ToList(); foreach (var file in files.Where(file => now - file.LastWriteTime > TimeSpan.FromDays(retentionDays)).ToArray()) { if (TryDelete(file)) removed++; files.Remove(file); } var total = 0L; foreach (var file in files) { total += file.Length; if (total > maxBytes && TryDelete(file)) removed++; } return removed; } } List RecordFiles() { try { return System.IO.Directory.Exists(Directory) ? new DirectoryInfo(Directory).GetFiles("*" + Extension).ToList() : []; } catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) { return []; } } static bool TryDelete(FileInfo file) { try { file.Delete(); return true; } catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) { return false; } } }