Snooze notifications, morning summary, ICS import, data folder sync

- Windows toast notifications with snooze (10 min / 1 h / tomorrow) and
  done buttons; balloon fallback; works when Windows starts the app
- Recurring entries snooze via SnoozedUntil without moving their date;
  lead reminders keep the real date
- Morning summary once a day from a chosen hour (pure DailySummary)
- iCalendar import incl. Google birthday calendar, folded lines, UTC,
  alarms, own export round trip, duplicates skipped by UID, undo
- Data folder selectable (location.json pointer), file watcher reloads
  changes from another PC (own writes ignored)
- Themed date picker calendar, WPF tray menu, arrow/Home/End/Space keys
- 90 tests

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-29 20:37:20 +01:00
parent 7486eebd67
commit 33459bdec7
18 changed files with 1300 additions and 61 deletions

View File

@@ -23,14 +23,56 @@ namespace ReminderOrganizer.Services
private readonly SemaphoreSlim _writeLock = new(1, 1);
public string DataFilePath { get; }
public string DataFilePath { get; private set; }
public string DataDirectory => Path.GetDirectoryName(DataFilePath)!;
/// <summary>%APPDATA%\ReminderOrganizer – or REMINDER_ORGANIZER_DATA (for tests/screenshots).</summary>
public static string DefaultDataDirectory =>
/// <summary>Time stamp of our own last write – a different one means another PC (sync) changed the file.</summary>
public DateTime LastWriteUtc { get; private set; }
/// <summary>
/// App folder (pointer file, error log): %APPDATA%\ReminderOrganizer – or REMINDER_ORGANIZER_DATA (tests/screenshots).
/// </summary>
public static string AppDirectory =>
Environment.GetEnvironmentVariable("REMINDER_ORGANIZER_DATA") is { Length: > 0 } custom
? custom
: Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "ReminderOrganizer");
/// <summary>Where tasks.json lives: the folder chosen in Settings (e.g. OneDrive), otherwise the app folder.</summary>
public static string DefaultDataDirectory => ReadPointer(AppDirectory) ?? AppDirectory;
private const string PointerFile = "location.json";
/// <summary>Chosen data folder from location.json, or null (none / folder gone).</summary>
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;
}
}
/// <summary>Stores the data folder; null or the app folder itself removes the pointer.</summary>
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)
@@ -39,6 +81,62 @@ namespace ReminderOrganizer.Services
DataFilePath = Path.Combine(dataDirectory, "tasks.json");
}
/// <summary>Use another folder from now on (after moving or adopting its tasks.json).</summary>
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;
/// <summary>Calls <paramref name="onExternalChange"/> (thread pool) when tasks.json changes and it wasn't us.</summary>
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;
}
/// <summary>True if the file on disk is newer than our own last write.</summary>
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;
}
/// <summary>Copies tasks.json from an old location (next to the exe) if no data exists yet.</summary>
public void MigrateFrom(string? legacyDirectory)
{
@@ -105,6 +203,7 @@ namespace ReminderOrganizer.Services
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)

189
Services/IcsImport.cs Normal file
View File

@@ -0,0 +1,189 @@
#nullable enable
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using ReminderOrganizer.Models;
namespace ReminderOrganizer.Services
{
/// <summary>
/// iCalendar (.ics) import – counterpart of <see cref="IcsExport"/>. Reads Outlook, Google (incl. the birthday
/// calendar) and Apple exports. All-day yearly events become anniversaries.
/// </summary>
public static class IcsImport
{
public sealed record Result(List<ReminderTask> Tasks, int Skipped);
/// <param name="existingIds">Ids already in the app – events with the same UID are skipped (safe re-import).</param>
public static Result Parse(string ics, ISet<string> existingIds, DateTime now)
{
var tasks = new List<ReminderTask>();
int skipped = 0;
Dictionary<string, (string Params, string Value)>? ev = null;
bool inAlarm = false;
string? trigger = null;
foreach (var line in Unfold(ics))
{
if (line.Equals("BEGIN:VEVENT", StringComparison.OrdinalIgnoreCase)) { ev = new(StringComparer.OrdinalIgnoreCase); trigger = null; continue; }
if (ev == null) continue;
if (line.Equals("BEGIN:VALARM", StringComparison.OrdinalIgnoreCase)) { inAlarm = true; continue; }
if (line.Equals("END:VALARM", StringComparison.OrdinalIgnoreCase)) { inAlarm = false; continue; }
if (line.Equals("END:VEVENT", StringComparison.OrdinalIgnoreCase))
{
var task = ToTask(ev, trigger, existingIds, now);
if (task == null) skipped++;
else { tasks.Add(task); existingIds.Add(task.Id); }
ev = null;
continue;
}
int colon = line.IndexOf(':');
if (colon <= 0) continue;
var head = line[..colon];
var value = line[(colon + 1)..];
int semi = head.IndexOf(';');
var name = semi < 0 ? head : head[..semi];
var parameters = semi < 0 ? "" : head[(semi + 1)..];
if (inAlarm)
{
if (name.Equals("TRIGGER", StringComparison.OrdinalIgnoreCase)) trigger ??= value;
continue;
}
ev.TryAdd(name, (parameters, value));
}
return new Result(tasks, skipped);
}
private static ReminderTask? ToTask(Dictionary<string, (string Params, string Value)> ev, string? trigger,
ISet<string> existingIds, DateTime now)
{
if (!ev.TryGetValue("SUMMARY", out var summary) || string.IsNullOrWhiteSpace(summary.Value)) return null;
if (!ev.TryGetValue("DTSTART", out var start) || !TryParseDate(start.Params, start.Value, out var date, out bool allDay)) return null;
var uid = ev.TryGetValue("UID", out var u) && !string.IsNullOrWhiteSpace(u.Value) ? u.Value.Trim() : null;
if (uid != null && existingIds.Contains(uid)) return null;
var freq = ev.TryGetValue("RRULE", out var rrule) ? Regex.Match(rrule.Value, @"FREQ=(\w+)", RegexOptions.IgnoreCase).Groups[1].Value.ToUpperInvariant() : "";
var name = Unescape(summary.Value).Trim();
var description = ev.TryGetValue("DESCRIPTION", out var d) ? Unescape(d.Value).Trim() : "";
var task = new ReminderTask { Name = name, Description = description };
if (uid != null) task.Id = uid;
task.LeadDays = LeadDaysFrom(trigger, allDay);
if (allDay && freq == "YEARLY")
{
// anniversary: birthday, wedding, …
task.IsAnniversary = true;
task.IsRecurring = true;
task.RecurrenceType = RecurrenceType.Yearly;
task.CategoryId = GuessCategory(name + " " + description);
if (date.Year < now.Year && date.Year >= 1900) task.BirthYear = date.Year;
// our own export writes "Oma (86)" with the date of the next occurrence → year = date year − age
var age = Regex.Match(name, @"\s*\((\d{1,3})\)\s*$");
if (age.Success)
{
int y = date.Year - int.Parse(age.Groups[1].Value, CultureInfo.InvariantCulture);
if (y >= 1900 && y <= now.Year) task.BirthYear = y;
name = name[..age.Index];
}
task.ReminderDate = ReminderTask.NextBirthday(date.Day, date.Month, now.Date);
task.Name = StripCategoryWords(name);
return task;
}
if (allDay) date = date.Date.AddHours(ReminderTask.BirthdayHour);
task.ReminderDate = date;
if (freq is "DAILY" or "WEEKLY" or "MONTHLY" or "YEARLY")
{
task.IsRecurring = true;
task.RecurrenceType = freq switch
{
"DAILY" => RecurrenceType.Daily,
"WEEKLY" => RecurrenceType.Weekly,
"MONTHLY" => RecurrenceType.Monthly,
_ => RecurrenceType.Yearly
};
if (task.ReminderDate <= now) task.ReminderDate = task.GetNextOccurrence(now);
}
else if (date <= now)
{
return null; // past one-off events are not imported
}
return task;
}
/// <summary>Google's birthday calendar writes "Anna's birthday" / "Geburtstag von Anna" – keep just the name.</summary>
private static string StripCategoryWords(string name)
{
var n = Regex.Replace(name, @"^(Geburtstag von|Geburtstag:)\s*", "", RegexOptions.IgnoreCase);
n = Regex.Replace(n, @"(['’]s)?\s+(birthday|Geburtstag)$", "", RegexOptions.IgnoreCase);
return string.IsNullOrWhiteSpace(n) ? name : n.Trim();
}
public static string GuessCategory(string text)
{
var t = text.ToLowerInvariant();
if (t.Contains("hochzeit") || t.Contains("wedding") || t.Contains("anniversary") || t.Contains("jahrestag")) return Category.WeddingId;
if (t.Contains("jubiläum") || t.Contains("jubilaeum") || t.Contains("jubilee")) return Category.JubileeId;
if (t.Contains("todestag") || t.Contains("gedenk") || t.Contains("memorial")) return Category.MemorialId;
return Category.BirthdayId;
}
/// <summary>
/// "-P2D", "-PT24H", "-P1W" → days before (0 when none or after the start). All-day events start at
/// midnight, so "-PT15H" means "the day before at 09:00" → rounded up; timed events round down.
/// </summary>
public static int LeadDaysFrom(string? trigger, bool allDay = false)
{
if (string.IsNullOrWhiteSpace(trigger) || !trigger.TrimStart().StartsWith("-")) return 0;
var m = Regex.Match(trigger, @"P(?:(\d+)W)?(?:(\d+)D)?(?:T(?:(\d+)H)?)?", RegexOptions.IgnoreCase);
if (!m.Success) return 0;
int Val(int g) => m.Groups[g].Success ? int.Parse(m.Groups[g].Value, CultureInfo.InvariantCulture) : 0;
int hours = (Val(1) * 7 + Val(2)) * 24 + Val(3);
int days = allDay ? (hours + 23) / 24 : hours / 24;
return days switch { <= 0 => 0, 1 => 1, 2 => 2, <= 4 => 3, _ => 7 }; // nearest option of the app
}
public static bool TryParseDate(string parameters, string value, out DateTime date, out bool allDay)
{
value = value.Trim();
allDay = parameters.Contains("VALUE=DATE", StringComparison.OrdinalIgnoreCase) && !parameters.Contains("VALUE=DATE-TIME", StringComparison.OrdinalIgnoreCase)
|| value.Length == 8;
if (allDay)
return DateTime.TryParseExact(value[..Math.Min(8, value.Length)], "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out date);
bool utc = value.EndsWith("Z", StringComparison.OrdinalIgnoreCase);
if (!DateTime.TryParseExact(value.TrimEnd('Z', 'z'), new[] { "yyyyMMdd'T'HHmmss", "yyyyMMdd'T'HHmm" },
CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
return false;
if (utc) date = DateTime.SpecifyKind(date, DateTimeKind.Utc).ToLocalTime();
date = DateTime.SpecifyKind(date, DateTimeKind.Unspecified); // TZID / floating: treat as local time
return true;
}
public static IEnumerable<string> Unfold(string ics)
{
var sb = new StringBuilder();
foreach (var raw in ics.Replace("\r\n", "\n").Split('\n'))
{
if (raw.Length > 0 && (raw[0] == ' ' || raw[0] == '\t'))
{
sb.Append(raw, 1, raw.Length - 1);
continue;
}
if (sb.Length > 0) yield return sb.ToString();
sb.Clear().Append(raw.TrimEnd('\r'));
}
if (sb.Length > 0) yield return sb.ToString();
}
public static string Unescape(string s) =>
Regex.Replace(s, @"\\([\\;,nN])", m => m.Groups[1].Value is "n" or "N" ? "\n" : m.Groups[1].Value);
}
}

View File

@@ -1,4 +1,4 @@
#nullable enable
#nullable enable
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
@@ -12,11 +12,17 @@ namespace ReminderOrganizer.Services
Task SaveAsync(AppData data);
void Save(AppData data);
string DataFilePath { get; }
string DataDirectory { get; }
void SwitchTo(string dataDirectory);
void StartWatching(Action onExternalChange);
void StopWatching();
}
public interface INotificationService
{
void ShowNotification(string title, string message);
/// <summary>Reminder with snooze/done buttons for one task.</summary>
void ShowReminder(string title, string message, string taskId, bool isLead);
}
public interface ILocalizationService

View File

@@ -1,51 +1,117 @@
#nullable enable
using System;
using System.IO;
using System.Windows;
using System.Windows.Forms;
using Microsoft.Toolkit.Uwp.Notifications;
namespace ReminderOrganizer.Services
{
/// <summary>
/// Windows toast notifications (Action Center) with snooze buttons. Falls back to the tray balloon if toasts
/// are not available (e.g. notifications turned off or an old Windows build).
/// </summary>
public class NotificationService : INotificationService
{
private readonly object _lock = new();
private readonly ILocalizationService _loc;
private string? _logoPath;
public static NotifyIcon? SharedTrayIcon { get; set; }
public NotificationService(ILocalizationService localizationService)
{
_loc = localizationService;
}
public void ShowNotification(string title, string message)
{
try
{
System.Diagnostics.Debug.WriteLine($"[NotificationService] ShowNotification: {title} - {message}");
System.Diagnostics.Debug.WriteLine($"[NotificationService] SharedTrayIcon is null: {SharedTrayIcon == null}");
ShowBalloonTip(title, message);
Builder(title, message).AddArgument("action", "open").Show();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"[NotificationService] Error: {ex.Message}");
System.Diagnostics.Debug.WriteLine($"[Toast] {ex.Message}");
ShowBalloon(title, message);
}
}
private void ShowBalloonTip(string title, string message)
public void ShowReminder(string title, string message, string taskId, bool isLead)
{
lock (_lock)
try
{
if (SharedTrayIcon != null)
{
// ShowBalloonTip throws on empty text – tasks without description would never notify.
SharedTrayIcon.BalloonTipTitle = string.IsNullOrWhiteSpace(title) ? "Reminder Organizer" : title;
SharedTrayIcon.BalloonTipText = string.IsNullOrWhiteSpace(message) ? " " : message;
SharedTrayIcon.BalloonTipIcon = ToolTipIcon.Info;
SharedTrayIcon.ShowBalloonTip(5000);
System.Diagnostics.Debug.WriteLine("[NotificationService] BalloonTip shown!");
}
else
{
System.Diagnostics.Debug.WriteLine("[NotificationService] SharedTrayIcon is null, cannot show balloon tip!");
}
string lead = isLead ? "1" : "0";
ToastButton Snooze(string label, string minutes) => new ToastButton()
.SetContent(label)
.AddArgument("action", "snooze").AddArgument("min", minutes)
.AddArgument("id", taskId).AddArgument("lead", lead)
.SetBackgroundActivation();
Builder(title, message)
.AddArgument("action", "open").AddArgument("id", taskId)
.AddButton(Snooze(_loc.GetString("Snooze10"), "10"))
.AddButton(Snooze(_loc.GetString("Snooze60"), "60"))
.AddButton(Snooze(_loc.GetString("SnoozeTomorrow"), "tomorrow"))
.AddButton(new ToastButton()
.SetContent(_loc.GetString("ToastDone"))
.AddArgument("action", "done").AddArgument("id", taskId).AddArgument("lead", lead)
.SetBackgroundActivation())
.Show();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"[Toast] {ex.Message}");
ShowBalloon(title, message);
}
}
public void Dispose()
private ToastContentBuilder Builder(string title, string message)
{
var b = new ToastContentBuilder()
.AddText(string.IsNullOrWhiteSpace(title) ? "Reminder Organizer" : title);
if (!string.IsNullOrWhiteSpace(message)) b.AddText(message);
if (LogoPath() is { } logo) b.AddAppLogoOverride(new Uri(logo), ToastGenericAppLogoCrop.Default);
return b;
}
/// <summary>Toasts need the logo as a file – extract it once to the app folder.</summary>
private string? LogoPath()
{
if (_logoPath != null) return _logoPath;
try
{
var path = Path.Combine(DataService.AppDirectory, "toast-logo.png");
if (!File.Exists(path))
{
var res = System.Windows.Application.GetResourceStream(new Uri("pack://application:,,,/Assets/app.png"));
if (res == null) return null;
Directory.CreateDirectory(DataService.AppDirectory);
using var fs = File.Create(path);
res.Stream.CopyTo(fs);
}
return _logoPath = path;
}
catch
{
return null;
}
}
private static void ShowBalloon(string title, string message)
{
try
{
if (SharedTrayIcon == null) return;
// ShowBalloonTip throws on empty text – tasks without description would never notify.
SharedTrayIcon.BalloonTipTitle = string.IsNullOrWhiteSpace(title) ? "Reminder Organizer" : title;
SharedTrayIcon.BalloonTipText = string.IsNullOrWhiteSpace(message) ? " " : message;
SharedTrayIcon.BalloonTipIcon = ToolTipIcon.Info;
SharedTrayIcon.ShowBalloonTip(5000);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"[Balloon] {ex.Message}");
}
}
}
}