Repository navigation
Expand file tree
/
Copy pathHistoryService.cs
More file actions
74 lines (63 loc) · 2.06 KB
/
Copy pathHistoryService.cs
File metadata and controls
74 lines (63 loc) · 2.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
using System.IO;
using System.Text.Json;
namespace WhisperTyper
{
public class HistoryEntry
{
public Guid Id { get; set; } = Guid.NewGuid();
public DateTimeOffset Timestamp { get; set; } = DateTimeOffset.Now;
public string Text { get; set; } = "";
public string ModelName { get; set; } = "";
public int DurationMs { get; set; }
public string Language { get; set; } = "";
}
public class HistoryService
{
private static readonly string _path = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"WhisperTyper", "history.json");
private const int MaxEntries = 500;
public List<HistoryEntry> Entries { get; private set; } = [];
public event Action? Changed;
public HistoryService() => Load();
public void Add(HistoryEntry entry)
{
Entries.Insert(0, entry);
if (Entries.Count > MaxEntries)
Entries.RemoveRange(MaxEntries, Entries.Count - MaxEntries);
Save();
Changed?.Invoke();
}
public void Delete(Guid id)
{
Entries.RemoveAll(e => e.Id == id);
Save();
Changed?.Invoke();
}
public void Clear()
{
Entries.Clear();
Save();
Changed?.Invoke();
}
private void Load()
{
try
{
if (File.Exists(_path))
Entries = JsonSerializer.Deserialize<List<HistoryEntry>>(File.ReadAllText(_path)) ?? [];
}
catch { Entries = []; }
}
private void Save()
{
try
{
Directory.CreateDirectory(Path.GetDirectoryName(_path)!);
File.WriteAllText(_path, JsonSerializer.Serialize(Entries,
new JsonSerializerOptions { WriteIndented = true }));
}
catch { }
}
}
}