Files
ReminderOrganizer/Services/DataService.cs

132 lines
4.3 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#nullable enable
using System;
using System.IO;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using ReminderOrganizer.Models;
namespace ReminderOrganizer.Services
{
/// <summary>
/// Stores tasks in %APPDATA%\ReminderOrganizer\tasks.json.
/// Writes are serialized and atomic (temp file + replace), a corrupt file is
/// backed up instead of being overwritten.
/// </summary>
public class DataService : IDataService
{
private static readonly JsonSerializerOptions _jsonOptions = new()
{
WriteIndented = true,
PropertyNameCaseInsensitive = true
};
private readonly SemaphoreSlim _writeLock = new(1, 1);
public string DataFilePath { get; }
/// <summary>%APPDATA%\ReminderOrganizer – or REMINDER_ORGANIZER_DATA (for tests/screenshots).</summary>
public static string DefaultDataDirectory =>
Environment.GetEnvironmentVariable("REMINDER_ORGANIZER_DATA") is { Length: > 0 } custom
? custom
: Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "ReminderOrganizer");
public DataService() : this(DefaultDataDirectory) { }
public DataService(string dataDirectory)
{
Directory.CreateDirectory(dataDirectory);
DataFilePath = Path.Combine(dataDirectory, "tasks.json");
}
/// <summary>Copies tasks.json from an old location (next to the exe) if no data exists yet.</summary>
public void MigrateFrom(string? legacyDirectory)
{
if (string.IsNullOrEmpty(legacyDirectory) || File.Exists(DataFilePath)) return;
var legacy = Path.Combine(legacyDirectory, "tasks.json");
try
{
if (File.Exists(legacy) && !string.Equals(Path.GetFullPath(legacy), Path.GetFullPath(DataFilePath), StringComparison.OrdinalIgnoreCase))
File.Copy(legacy, DataFilePath);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"[DataService] Migration failed: {ex.Message}");
}
}
public async Task<AppData> LoadAsync()
{
if (!File.Exists(DataFilePath))
return new AppData();
try
{
var json = await File.ReadAllTextAsync(DataFilePath);
var data = JsonSerializer.Deserialize<AppData>(json, _jsonOptions);
return data ?? new AppData();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"[DataService] Load failed: {ex.Message}");
BackupCorruptFile();
return new AppData();
}
}
private void BackupCorruptFile()
{
try
{
var backup = DataFilePath + $".corrupt-{DateTime.Now:yyyyMMdd-HHmmss}";
File.Copy(DataFilePath, backup, overwrite: true);
}
catch { }
}
public void Save(AppData data)
{
_writeLock.Wait();
try
{
var tmp = DataFilePath + ".tmp";
File.WriteAllText(tmp, JsonSerializer.Serialize(data, _jsonOptions));
Commit(tmp);
}
finally
{
_writeLock.Release();
}
}
private void Commit(string tmp)
{
if (File.Exists(DataFilePath))
File.Replace(tmp, DataFilePath, DataFilePath + ".bak");
else
File.Move(tmp, DataFilePath);
}
public async Task SaveAsync(AppData data)
{
await _writeLock.WaitAsync();
try
{
var json = JsonSerializer.Serialize(data, _jsonOptions);
var tmp = DataFilePath + ".tmp";
await File.WriteAllTextAsync(tmp, json);
Commit(tmp);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"[DataService] Save failed: {ex.Message}");
throw;
}
finally
{
_writeLock.Release();
}
}
}
}