405 lines
13 KiB
C++
405 lines
13 KiB
C++
#pragma once
|
||
|
||
// Kleiner iCalendar-Leser für die Terminseite. Bekommt die .ics-Datei Zeile für Zeile (bereits
|
||
// entfaltet) und sammelt die Termine eines Zeitfensters.
|
||
// Versteht VEVENT mit DTSTART, DTEND oder DURATION, SUMMARY, STATUS:CANCELLED, EXDATE,
|
||
// RECURRENCE-ID (einzeln geänderte Wiederholungen) und RRULE mit FREQ=DAILY/WEEKLY/MONTHLY/YEARLY,
|
||
// INTERVAL, COUNT, UNTIL, BYDAY und BYMONTHDAY. Zeiten mit TZID gelten als Ortszeit des Geräts.
|
||
|
||
#include <stdint.h>
|
||
#include <stdio.h>
|
||
#include <stdlib.h>
|
||
#include <string.h>
|
||
#include <time.h>
|
||
|
||
#include "timeutil.h"
|
||
|
||
struct CalEvent {
|
||
time_t start;
|
||
time_t end;
|
||
bool allDay;
|
||
bool waste; // aus dem Müllkalender
|
||
char summary[48];
|
||
};
|
||
|
||
class ICalCollector {
|
||
public:
|
||
ICalCollector(time_t from, time_t to) : _from(from), _to(to) {}
|
||
|
||
// Gilt für die folgenden Zeilen: Termine stammen aus dem Müllkalender
|
||
void setWaste(bool waste) { _waste = waste; }
|
||
|
||
void line(const char* l) {
|
||
if (strncmp(l, "BEGIN:", 6) == 0) {
|
||
if (!_inEvent && strcmp(l + 6, "VEVENT") == 0) {
|
||
_inEvent = true;
|
||
_sub = 0;
|
||
_ev = Pending();
|
||
} else if (_inEvent) {
|
||
_sub++; // z. B. VALARM, dessen Felder nicht zum Termin gehören
|
||
}
|
||
return;
|
||
}
|
||
if (strncmp(l, "END:", 4) == 0) {
|
||
if (_inEvent && _sub > 0) _sub--;
|
||
else if (_inEvent && strcmp(l + 4, "VEVENT") == 0) {
|
||
_inEvent = false;
|
||
finishEvent();
|
||
}
|
||
return;
|
||
}
|
||
if (_inEvent && _sub == 0) property(l);
|
||
}
|
||
|
||
// Sortierte Termine ohne die durch RECURRENCE-ID ersetzten Wiederholungen; liefert die Anzahl
|
||
int finish(CalEvent* out, int max) {
|
||
int n = 0;
|
||
for (int i = 0; i < _count && n < max; i++) {
|
||
const Candidate& c = _cand[i];
|
||
bool replaced = false;
|
||
for (int j = 0; c.fromRule && j < _overrideCount; j++) {
|
||
replaced |= _overrides[j].uid == c.uid && _overrides[j].start == c.occurrence;
|
||
}
|
||
if (!replaced) out[n++] = c.ev;
|
||
}
|
||
return n;
|
||
}
|
||
|
||
private:
|
||
struct Civil {
|
||
int y = 0, m = 0, d = 0, hh = 0, mi = 0, ss = 0;
|
||
bool utc = false, date = false;
|
||
};
|
||
|
||
struct Pending {
|
||
uint32_t uid = 0;
|
||
char summary[48] = "";
|
||
Civil start, end;
|
||
bool hasStart = false, hasEnd = false, cancelled = false;
|
||
long duration = -1;
|
||
char rrule[160] = "";
|
||
time_t exdates[16];
|
||
int exCount = 0;
|
||
time_t recurrenceId = 0;
|
||
};
|
||
|
||
struct Candidate {
|
||
CalEvent ev;
|
||
uint32_t uid;
|
||
time_t occurrence; // ursprünglicher Beginn dieser Wiederholung
|
||
bool fromRule;
|
||
};
|
||
|
||
struct Override {
|
||
uint32_t uid;
|
||
time_t start;
|
||
};
|
||
|
||
struct Rule {
|
||
int freq = 0; // 1 täglich, 2 wöchentlich, 3 monatlich, 4 jährlich
|
||
int interval = 1, count = 0;
|
||
time_t until = 0;
|
||
int nByDay = 0, nByMonthDay = 0;
|
||
int8_t byDayOrd[7], byDayWd[7]; // Ordnung (0 = jeder) und Wochentag (0 = Sonntag)
|
||
int8_t byMonthDay[8];
|
||
};
|
||
|
||
static constexpr int MAX_CANDIDATES = 40;
|
||
static constexpr int MAX_OVERRIDES = 32;
|
||
|
||
time_t _from, _to;
|
||
bool _waste = false, _inEvent = false;
|
||
int _sub = 0;
|
||
Pending _ev;
|
||
Candidate _cand[MAX_CANDIDATES];
|
||
int _count = 0;
|
||
Override _overrides[MAX_OVERRIDES];
|
||
int _overrideCount = 0;
|
||
|
||
static uint32_t hash(const char* s) {
|
||
uint32_t h = 2166136261u;
|
||
while (*s) h = (h ^ (uint8_t)*s++) * 16777619u;
|
||
return h;
|
||
}
|
||
|
||
static bool parseCivil(const char* v, Civil& c) {
|
||
c = Civil();
|
||
if (sscanf(v, "%4d%2d%2d", &c.y, &c.m, &c.d) != 3) return false;
|
||
c.date = v[8] != 'T';
|
||
if (!c.date) {
|
||
if (sscanf(v + 9, "%2d%2d%2d", &c.hh, &c.mi, &c.ss) != 3) return false;
|
||
c.utc = v[15] == 'Z';
|
||
}
|
||
return c.m >= 1 && c.m <= 12 && c.d >= 1 && c.d <= 31;
|
||
}
|
||
|
||
static time_t toEpoch(const Civil& c) {
|
||
if (c.utc) return (time_t)daysFromCivil(c.y, c.m, c.d) * 86400 + c.hh * 3600 + c.mi * 60 + c.ss;
|
||
tm t = {};
|
||
t.tm_year = c.y - 1900;
|
||
t.tm_mon = c.m - 1;
|
||
t.tm_mday = c.d;
|
||
t.tm_hour = c.hh;
|
||
t.tm_min = c.mi;
|
||
t.tm_sec = c.ss;
|
||
t.tm_isdst = -1;
|
||
return mktime(&t);
|
||
}
|
||
|
||
// "PT1H30M", "P1D", "P2W"
|
||
static long parseDuration(const char* v) {
|
||
long total = 0, n = 0;
|
||
int sign = 1;
|
||
if (*v == '-') sign = -1, v++;
|
||
if (*v == '+') v++;
|
||
for (; *v; v++) {
|
||
if (*v >= '0' && *v <= '9') n = n * 10 + (*v - '0');
|
||
else {
|
||
static const char UNITS[] = "WDHMS";
|
||
static const long SECS[] = {604800, 86400, 3600, 60, 1};
|
||
const char* u = strchr(UNITS, *v);
|
||
if (u) total += n * SECS[u - UNITS];
|
||
n = 0;
|
||
}
|
||
}
|
||
return sign * total;
|
||
}
|
||
|
||
// Text mit \, \; \n und \\ in lesbare Form, beim Kürzen nur ganze UTF-8-Zeichen
|
||
static void unescape(const char* v, char* out, size_t len) {
|
||
size_t n = 0;
|
||
for (; *v && n + 1 < len; v++) {
|
||
char c = *v;
|
||
if (c == '\\' && v[1]) {
|
||
c = *++v;
|
||
if (c == 'n' || c == 'N') c = ' ';
|
||
}
|
||
out[n++] = c;
|
||
}
|
||
if (*v) { // gekürzt: ein angefangenes Zeichen am Ende entfernen
|
||
size_t lead = n;
|
||
while (lead > 0 && ((uint8_t)out[lead - 1] & 0xC0) == 0x80) lead--;
|
||
if (lead > 0 && (uint8_t)out[lead - 1] >= 0xC0) {
|
||
uint8_t b = out[lead - 1];
|
||
size_t need = b >= 0xF0 ? 4 : b >= 0xE0 ? 3 : 2;
|
||
if (n - (lead - 1) < need) n = lead - 1;
|
||
}
|
||
}
|
||
out[n] = 0;
|
||
}
|
||
|
||
void property(const char* l) {
|
||
// NAME;PARAM=…:WERT – der Doppelpunkt in Anführungszeichen zählt nicht
|
||
const char* value = nullptr;
|
||
bool quoted = false;
|
||
for (const char* p = l; *p; p++) {
|
||
if (*p == '"') quoted = !quoted;
|
||
else if (*p == ':' && !quoted) {
|
||
value = p + 1;
|
||
break;
|
||
}
|
||
}
|
||
if (!value) return;
|
||
size_t nameLen = strcspn(l, ";:");
|
||
auto is = [&](const char* name) { return strlen(name) == nameLen && strncmp(l, name, nameLen) == 0; };
|
||
|
||
if (is("UID")) _ev.uid = hash(value);
|
||
else if (is("SUMMARY")) unescape(value, _ev.summary, sizeof(_ev.summary));
|
||
else if (is("STATUS")) _ev.cancelled = strcmp(value, "CANCELLED") == 0;
|
||
else if (is("DTSTART")) _ev.hasStart = parseCivil(value, _ev.start);
|
||
else if (is("DTEND")) _ev.hasEnd = parseCivil(value, _ev.end);
|
||
else if (is("DURATION")) _ev.duration = parseDuration(value);
|
||
else if (is("RRULE")) strncpy(_ev.rrule, value, sizeof(_ev.rrule) - 1);
|
||
else if (is("RECURRENCE-ID")) {
|
||
Civil c;
|
||
if (parseCivil(value, c)) _ev.recurrenceId = toEpoch(c);
|
||
} else if (is("EXDATE")) {
|
||
for (const char* v = value; *v && _ev.exCount < 16;) {
|
||
Civil c;
|
||
if (parseCivil(v, c)) _ev.exdates[_ev.exCount++] = toEpoch(c);
|
||
const char* comma = strchr(v, ',');
|
||
if (!comma) break;
|
||
v = comma + 1;
|
||
}
|
||
}
|
||
}
|
||
|
||
static bool parseRule(const char* s, Rule& r) {
|
||
char buf[160];
|
||
strncpy(buf, s, sizeof(buf) - 1);
|
||
buf[sizeof(buf) - 1] = 0;
|
||
for (char* save = nullptr, *part = strtok_r(buf, ";", &save); part; part = strtok_r(nullptr, ";", &save)) {
|
||
char* eq = strchr(part, '=');
|
||
if (!eq) continue;
|
||
*eq = 0;
|
||
const char* v = eq + 1;
|
||
if (!strcmp(part, "FREQ")) {
|
||
r.freq = !strcmp(v, "DAILY") ? 1 : !strcmp(v, "WEEKLY") ? 2 : !strcmp(v, "MONTHLY") ? 3 : !strcmp(v, "YEARLY") ? 4 : 0;
|
||
} else if (!strcmp(part, "INTERVAL")) {
|
||
r.interval = atoi(v) > 0 ? atoi(v) : 1;
|
||
} else if (!strcmp(part, "COUNT")) {
|
||
r.count = atoi(v);
|
||
} else if (!strcmp(part, "UNTIL")) {
|
||
Civil c;
|
||
if (parseCivil(v, c)) {
|
||
if (c.date) c.hh = 23, c.mi = 59, c.ss = 59; // ganzer letzter Tag zählt mit
|
||
r.until = toEpoch(c);
|
||
}
|
||
} else if (!strcmp(part, "BYDAY")) {
|
||
static const char* const DAYS[] = {"SU", "MO", "TU", "WE", "TH", "FR", "SA"};
|
||
for (const char* p = v; *p && r.nByDay < 7;) {
|
||
int ord = (int)strtol(p, (char**)&p, 10);
|
||
for (int wd = 0; wd < 7; wd++) {
|
||
if (!strncmp(p, DAYS[wd], 2)) {
|
||
r.byDayOrd[r.nByDay] = ord;
|
||
r.byDayWd[r.nByDay++] = wd;
|
||
}
|
||
}
|
||
p = strchr(p, ',');
|
||
if (!p) break;
|
||
p++;
|
||
}
|
||
} else if (!strcmp(part, "BYMONTHDAY")) {
|
||
for (const char* p = v; *p && r.nByMonthDay < 8;) {
|
||
r.byMonthDay[r.nByMonthDay++] = (int8_t)atoi(p);
|
||
p = strchr(p, ',');
|
||
if (!p) break;
|
||
p++;
|
||
}
|
||
}
|
||
}
|
||
return r.freq != 0;
|
||
}
|
||
|
||
void add(const CalEvent& ev, time_t occurrence, bool fromRule) {
|
||
if (_count == MAX_CANDIDATES && ev.start >= _cand[_count - 1].ev.start) return;
|
||
int i = _count < MAX_CANDIDATES ? _count++ : _count - 1;
|
||
for (; i > 0 && _cand[i - 1].ev.start > ev.start; i--) _cand[i] = _cand[i - 1];
|
||
_cand[i] = {ev, _ev.uid, occurrence, fromRule};
|
||
}
|
||
|
||
bool excluded(time_t t) const {
|
||
for (int i = 0; i < _ev.exCount; i++) {
|
||
if (_ev.exdates[i] == t) return true;
|
||
}
|
||
return false;
|
||
}
|
||
|
||
// Ein Termin ab t; false, wenn er das Fenster schon verlassen hat
|
||
void offer(time_t t, long duration, bool fromRule) {
|
||
if (t >= _to || t + (duration > 0 ? duration : 1) <= _from) return;
|
||
if (fromRule && excluded(t)) return;
|
||
CalEvent ev;
|
||
ev.start = t;
|
||
ev.end = t + duration;
|
||
ev.allDay = _ev.start.date;
|
||
ev.waste = _waste;
|
||
strncpy(ev.summary, _ev.summary, sizeof(ev.summary));
|
||
add(ev, t, fromRule);
|
||
}
|
||
|
||
void finishEvent() {
|
||
if (!_ev.hasStart || _ev.cancelled) return;
|
||
time_t first = toEpoch(_ev.start);
|
||
long duration;
|
||
if (_ev.hasEnd) duration = (long)(toEpoch(_ev.end) - first);
|
||
else if (_ev.duration >= 0) duration = _ev.duration;
|
||
else duration = _ev.start.date ? 86400 : 0;
|
||
|
||
if (_ev.recurrenceId && _overrideCount < MAX_OVERRIDES) {
|
||
_overrides[_overrideCount++] = {_ev.uid, _ev.recurrenceId};
|
||
}
|
||
Rule r;
|
||
if (!_ev.rrule[0] || _ev.recurrenceId || !parseRule(_ev.rrule, r)) {
|
||
offer(first, duration, false);
|
||
return;
|
||
}
|
||
expand(r, duration);
|
||
}
|
||
|
||
void expand(const Rule& r, long duration) {
|
||
const Civil& s = _ev.start;
|
||
const long startDay = daysFromCivil(s.y, s.m, s.d);
|
||
const long fromDay = (long)(_from / 86400) - 2;
|
||
const long toDay = (long)(_to / 86400) + 2;
|
||
const long durDays = duration / 86400 + 1;
|
||
int made = 0; // erzeugte Wiederholungen, für COUNT
|
||
|
||
// false = Ende der Regel erreicht
|
||
auto emit = [&](long day) {
|
||
if (day < startDay) return true;
|
||
if (r.count && made >= r.count) return false;
|
||
if (r.until && (time_t)(day - 1) * 86400 > r.until) return false;
|
||
if (day > toDay) return false;
|
||
made++;
|
||
if (day + durDays < fromDay) return true; // liegt sicher vor dem Fenster
|
||
Civil c = s;
|
||
civilFromDays(day, c.y, c.m, c.d);
|
||
time_t t = toEpoch(c);
|
||
if (r.until && t > r.until) return false;
|
||
offer(t, duration, true);
|
||
return true;
|
||
};
|
||
|
||
// Ohne COUNT lässt sich bis kurz vor das Fenster springen. periodDays ist die längste
|
||
// mögliche Periode, damit der Sprung nie zu weit geht.
|
||
auto skip = [&](long periodDays) {
|
||
if (r.count || fromDay <= startDay) return 0L;
|
||
long k = (fromDay - startDay - durDays) / (periodDays * r.interval) - 1;
|
||
return k > 0 ? k : 0L;
|
||
};
|
||
|
||
if (r.freq == 1) {
|
||
for (long k = skip(1); k < 20000; k++) {
|
||
if (!emit(startDay + k * r.interval)) return;
|
||
}
|
||
} else if (r.freq == 2) {
|
||
int mask = 0;
|
||
for (int i = 0; i < r.nByDay; i++) mask |= 1 << r.byDayWd[i];
|
||
if (!mask) mask = 1 << weekdayFromDays(startDay);
|
||
long weekStart = startDay - (weekdayFromDays(startDay) + 6) % 7; // Woche beginnt montags
|
||
for (long k = skip(7); k < 5000; k++) {
|
||
long ws = weekStart + k * 7 * r.interval;
|
||
for (int i = 0; i < 7; i++) {
|
||
int wd = (i + 1) % 7; // Montag … Sonntag
|
||
if ((mask >> wd & 1) && !emit(ws + i)) return;
|
||
}
|
||
}
|
||
} else if (r.freq == 3) {
|
||
long base = s.y * 12L + s.m - 1;
|
||
for (long k = skip(31); k < 2000; k++) {
|
||
long mi = base + k * r.interval;
|
||
int y = (int)(mi / 12), m = (int)(mi % 12) + 1, dim = daysInMonth(y, m);
|
||
long first = daysFromCivil(y, m, 1);
|
||
bool hit[32] = {};
|
||
if (r.nByMonthDay) {
|
||
for (int i = 0; i < r.nByMonthDay; i++) {
|
||
int d = r.byMonthDay[i] > 0 ? r.byMonthDay[i] : dim + r.byMonthDay[i] + 1;
|
||
if (d >= 1 && d <= dim) hit[d] = true;
|
||
}
|
||
} else if (r.nByDay) {
|
||
for (int i = 0; i < r.nByDay; i++) {
|
||
int d0 = 1 + (r.byDayWd[i] - weekdayFromDays(first) + 7) % 7; // erster solcher Wochentag
|
||
int n = (dim - d0) / 7 + 1;
|
||
int ord = r.byDayOrd[i];
|
||
for (int j = 0; j < n; j++) {
|
||
if (ord == 0 || ord == j + 1 || ord == j - n) hit[d0 + j * 7] = true;
|
||
}
|
||
}
|
||
} else if (s.d <= dim) {
|
||
hit[s.d] = true;
|
||
}
|
||
for (int d = 1; d <= dim; d++) {
|
||
if (hit[d] && !emit(first + d - 1)) return;
|
||
}
|
||
}
|
||
} else if (r.freq == 4) {
|
||
for (long k = skip(366); k < 500; k++) {
|
||
int y = s.y + (int)(k * r.interval);
|
||
if (s.d > daysInMonth(y, s.m)) continue; // 29. Februar
|
||
if (!emit(daysFromCivil(y, s.m, s.d))) return;
|
||
}
|
||
}
|
||
}
|
||
};
|