Files
ReminderOrganizer/Services/IcsImport.cs
Michi 33459bdec7 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>
2026-11-29 20:37:20 +01:00

190 lines
9.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.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);
}
}