#nullable enable using System; using System.IO; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using ReminderOrganizer.Models; namespace ReminderOrganizer.Services { /// /// 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. /// 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; private set; } public string DataDirectory => Path.GetDirectoryName(DataFilePath)!; /// Time stamp of our own last write – a different one means another PC (sync) changed the file. public DateTime LastWriteUtc { get; private set; } /// /// App folder (pointer file, error log): %APPDATA%\ReminderOrganizer – or REMINDER_ORGANIZER_DATA (tests/screenshots). /// public static string AppDirectory => Environment.GetEnvironmentVariable("REMINDER_ORGANIZER_DATA") is { Length: > 0 } custom ? custom : Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "ReminderOrganizer"); /// Where tasks.json lives: the folder chosen in Settings (e.g. OneDrive), otherwise the app folder. public static string DefaultDataDirectory => ReadPointer(AppDirectory) ?? AppDirectory; private const string PointerFile = "location.json"; /// Chosen data folder from location.json, or null (none / folder gone). public static string? ReadPointer(string appDirectory) { try { var file = Path.Combine(appDirectory, PointerFile); if (!File.Exists(file)) return null; using var doc = JsonDocument.Parse(File.ReadAllText(file)); var folder = doc.RootElement.TryGetProperty("DataFolder", out var p) ? p.GetString() : null; return !string.IsNullOrWhiteSpace(folder) && Directory.Exists(folder) ? folder : null; } catch { return null; } } /// Stores the data folder; null or the app folder itself removes the pointer. public static void WritePointer(string appDirectory, string? folder) { Directory.CreateDirectory(appDirectory); var file = Path.Combine(appDirectory, PointerFile); if (string.IsNullOrWhiteSpace(folder) || string.Equals(Path.GetFullPath(folder).TrimEnd('\\'), Path.GetFullPath(appDirectory).TrimEnd('\\'), StringComparison.OrdinalIgnoreCase)) { if (File.Exists(file)) File.Delete(file); return; } File.WriteAllText(file, JsonSerializer.Serialize(new { DataFolder = folder }, _jsonOptions)); } public DataService() : this(DefaultDataDirectory) { } public DataService(string dataDirectory) { Directory.CreateDirectory(dataDirectory); DataFilePath = Path.Combine(dataDirectory, "tasks.json"); } /// Use another folder from now on (after moving or adopting its tasks.json). public void SwitchTo(string dataDirectory) { StopWatching(); Directory.CreateDirectory(dataDirectory); DataFilePath = Path.Combine(dataDirectory, "tasks.json"); LastWriteUtc = File.Exists(DataFilePath) ? File.GetLastWriteTimeUtc(DataFilePath) : default; } // ---------- sync: notice changes made by another PC ---------- private FileSystemWatcher? _watcher; private Timer? _debounce; /// Calls (thread pool) when tasks.json changes and it wasn't us. public void StartWatching(Action onExternalChange) { StopWatching(); if (File.Exists(DataFilePath)) LastWriteUtc = File.GetLastWriteTimeUtc(DataFilePath); _debounce = new Timer(_ => { try { if (IsExternalChange()) onExternalChange(); } catch { /* file busy – next event */ } }); _watcher = new FileSystemWatcher(DataDirectory, "tasks.json") { NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.Size, EnableRaisingEvents = true }; FileSystemEventHandler h = (_, _) => _debounce?.Change(1000, Timeout.Infinite); // sync tools write in bursts _watcher.Changed += h; _watcher.Created += h; _watcher.Renamed += (_, _) => _debounce?.Change(1000, Timeout.Infinite); } public void StopWatching() { _watcher?.Dispose(); _watcher = null; _debounce?.Dispose(); _debounce = null; } /// True if the file on disk is newer than our own last write. public bool IsExternalChange() { if (!File.Exists(DataFilePath)) return false; var stamp = File.GetLastWriteTimeUtc(DataFilePath); if (Math.Abs((stamp - LastWriteUtc).TotalMilliseconds) < 50) return false; LastWriteUtc = stamp; return true; } /// Copies tasks.json from an old location (next to the exe) if no data exists yet. 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 LoadAsync() { if (!File.Exists(DataFilePath)) return new AppData(); try { var json = await File.ReadAllTextAsync(DataFilePath); var data = JsonSerializer.Deserialize(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); LastWriteUtc = File.GetLastWriteTimeUtc(DataFilePath); // our own write is not a "sync change" } 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(); } } } }