Files

66 lines
2.1 KiB
C#

using System.IO;
using System.Text.Json;
using Futonizer.Models;
namespace Futonizer.Services;
/// <summary>
/// Persists a rolling history of previously processed files (newest first,
/// capped at <see cref="MaxEntries"/>) as a JSON file stored next to the
/// application executable.
/// </summary>
public static class HistoryService
{
private const int MaxEntries = 1000;
private static readonly string HistoryFilePath =
Path.Combine(AppContext.BaseDirectory, "history.json");
private static readonly object FileLock = new();
public static List<HistoryEntry> Load()
{
lock (FileLock)
{
try
{
if (!File.Exists(HistoryFilePath)) return new List<HistoryEntry>();
string json = File.ReadAllText(HistoryFilePath);
var list = JsonSerializer.Deserialize<List<HistoryEntry>>(json);
return list ?? new List<HistoryEntry>();
}
catch
{
return new List<HistoryEntry>();
}
}
}
/// <summary>
/// Adds a new entry at the front of the history and trims it down to
/// <see cref="MaxEntries"/> items. Safe to call concurrently from
/// multiple in-flight strip jobs.
/// </summary>
public static void Add(HistoryEntry entry)
{
lock (FileLock)
{
try
{
var list = File.Exists(HistoryFilePath)
? JsonSerializer.Deserialize<List<HistoryEntry>>(File.ReadAllText(HistoryFilePath)) ?? new List<HistoryEntry>()
: new List<HistoryEntry>();
list.Insert(0, entry);
if (list.Count > MaxEntries)
list.RemoveRange(MaxEntries, list.Count - MaxEntries);
string json = JsonSerializer.Serialize(list, new JsonSerializerOptions { WriteIndented = true });
File.WriteAllText(HistoryFilePath, json);
}
catch
{
// Best effort — history is a convenience feature, never worth failing a strip job over.
}
}
}
}