repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

feat(nuguland): CalDav service — discovery, fetch, DI, lifecycle

accfe044f7c0ff5f1ccee168afc6b86062db9ed9

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

PROPFIND discovery + REPORT fetch (expand for events, no-expand for tasks)
via curl Process; password from keyring on stdin, never argv. Config in
statePath JSON; refresh on file-load/15min. Injected shell->Bar->PopoutHost.
selfTest 6/6; live: 4 calendars, 155 events, no password leak.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

Changed files (4)

quickshell/nuguland/Bar.qml

Modified
25 25 required property QtObject lockService
26 26 required property QtObject surfaces
27 27 required property QtObject usageService
28 + required property QtObject caldavService
28 29 required property QtObject formatService
29 30 required property string orientation
418 419 surfaces: root.surfaces
419 420 niriService: root.niriService
420 421 timeService: root.timeService
422 + caldavService: root.caldavService
421 423 resourceService: root.resourceService
422 424 notificationService: root.notificationService
423 425 trayService: root.trayService

quickshell/nuguland/CalDav.qml

Added
new file mode 100644
1 +import QtQuick
2 +import Quickshell
3 +import Quickshell.Io
4 +import "caldav.js" as Ical
6 +Item {
7 + id: root
9 + readonly property string configPath: Quickshell.statePath("caldav.json")
10 + // config is the JsonAdapter below (auto-loads + auto-persists, like Usage.qml).
11 + property alias config: cfgAdapter
12 + property var events: []
13 + property bool stale: false
14 + // needs-setup until config has url+username AND a fetch has succeeded/failed
15 + property string status: (cfgAdapter.url && cfgAdapter.username) ? "loading" : "needs-setup"
17 + readonly property string host: {
18 + const u = cfgAdapter.url ? String(cfgAdapter.url) : "";
19 + const m = /^https?:\/\/([^\/:]+)/.exec(u);
20 + return m ? m[1] : "";
21 + }
23 + // scheme+host only; PROPFIND hrefs are absolute from the host root, so the
24 + // dav path must NOT be prepended again when building fetch URLs.
25 + readonly property string origin: {
26 + const u = cfgAdapter.url ? String(cfgAdapter.url) : "";
27 + const m = /^(https?:\/\/[^\/]+)/.exec(u);
28 + return m ? m[1] : "";
29 + }
31 + function stateJson() {
32 + return JSON.stringify({
33 + backend: "CalDav.qml",
34 + status: status,
35 + stale: stale,
36 + host: host,
37 + username: config ? config.username : "",
38 + calendarCount: config && config.calendars ? config.calendars.length : 0,
39 + eventCount: events ? events.length : 0
40 + });
41 + }
43 + function selfTest() {
44 + const cases = [];
45 + function ok(name, cond) { cases.push({ name: name, pass: !!cond }); }
46 + try {
47 + ok("unescape-adjacent", Ical.unescapeText("lit\\\\nslash") === "lit\\nslash");
48 + ok("entity-decode", Ical.decodeXmlEntities("a&quot;b") === 'a"b');
49 + const ev = Ical.parseIcs('@@CAL /p/\t#5b8cff\tVEVENT\n<c:calendar-data>BEGIN:VEVENT\nUID:u\nSUMMARY:X\nDTSTART:20260601T090000Z\nEND:VEVENT</c:calendar-data>')[0];
50 + ok("parse-timed", ev && ev.summary === "X" && ev.allDay === false);
51 + const seg = Ical.buildSegments([{ allDay: true, date: "2026-06-10", endDate: "2026-06-13", color: "#fff", summary: "U" }], "2026-06-08");
52 + ok("segments", seg.segments.length === 1 && seg.segments[0].colStart === 2 && seg.segments[0].colEnd === 4);
53 + const propfind = '<d:multistatus xmlns:d="DAV:" xmlns:cal="urn:ietf:params:xml:ns:caldav" xmlns:ic="http://apple.com/ns/ical/"><d:response><d:href>/p/personal/</d:href><d:propstat><d:prop><d:displayname>Mine</d:displayname><ic:calendar-color>#5b8cff</ic:calendar-color><d:resourcetype><cal:calendar/></d:resourcetype><cal:supported-calendar-component-set><cal:comp name="VEVENT"/></cal:supported-calendar-component-set></d:prop></d:propstat></d:response></d:multistatus>';
54 + const cals = root.parseCalendars(propfind);
55 + ok("discover", cals.length === 1 && cals[0].displayName === "Mine" && cals[0].color === "#5b8cff" && cals[0].components.indexOf("VEVENT") >= 0);
56 + const w = root.windowUtc("2026-06-08"); // Monday grid start
57 + const shape = /^\d{8}T\d{6}Z$/;
58 + const back = new Date(Date.UTC(+w.start.slice(0,4), +w.start.slice(4,6)-1, +w.start.slice(6,8), +w.start.slice(9,11), +w.start.slice(11,13), +w.start.slice(13,15)));
59 + const spanDays = (Date.UTC(+w.end.slice(0,4), +w.end.slice(4,6)-1, +w.end.slice(6,8), +w.end.slice(9,11)) - Date.UTC(+w.start.slice(0,4), +w.start.slice(4,6)-1, +w.start.slice(6,8), +w.start.slice(9,11))) / 86400000;
60 + ok("window", shape.test(w.start) && shape.test(w.end)
61 + && back.getFullYear() === 2026 && back.getMonth() === 5 && back.getDate() === 8 && back.getHours() === 0
62 + && spanDays === 42); // local-midnight round-trip + 42-day span, timezone-independent
63 + } catch (e) {
64 + ok("threw:" + e, false);
65 + }
66 + const fail = cases.filter(c => !c.pass).length;
67 + return JSON.stringify({ pass: cases.length - fail, fail: fail, cases: cases });
68 + }
70 + // write the adapter back to disk (also fires automatically on property change)
71 + function persistConfig() { cfgFile.writeAdapter(); }
73 + // --- discovery: parse a PROPFIND multistatus into calendar descriptors ---
74 + function parseCalendars(xml) {
75 + const out = [];
76 + const text = String(xml || "");
77 + const respRe = /<[^>]*:?response[^>]*>([\s\S]*?)<\/[^>]*:?response>/g;
78 + let m;
79 + while ((m = respRe.exec(text)) !== null) {
80 + const body = m[1];
81 + const href = (/<[^>]*:?href[^>]*>([\s\S]*?)<\/[^>]*:?href>/.exec(body) || [])[1];
82 + const name = (/<[^>]*:?displayname[^>]*>([\s\S]*?)<\/[^>]*:?displayname>/.exec(body) || [])[1];
83 + const color = (/<[^>]*calendar-color[^>]*>([\s\S]*?)<\/[^>]*calendar-color>/.exec(body) || [])[1];
84 + const isCal = /<[^>]*:?calendar\b[^>]*\/?>/.test(body);
85 + if (!href || !name || !isCal) continue; // skip inbox/outbox/trashbin (no displayname) + non-calendars
86 + const comps = [];
87 + const compRe = /<[^>]*:?comp[^>]*name="([^"]+)"/g;
88 + let cm;
89 + while ((cm = compRe.exec(body)) !== null) comps.push(cm[1]);
90 + out.push({
91 + href: Ical.decodeXmlEntities(href).trim(),
92 + displayName: Ical.decodeXmlEntities(name).trim(),
93 + color: (color ? String(color).trim().slice(0, 7) : "#888888"),
94 + components: comps,
95 + enabled: true
96 + });
97 + }
98 + return out;
99 + }
101 + function discoverAndFetch() {
102 + if (!root.host || !root.config.username) { root.status = "needs-setup"; return; }
103 + root.status = "loading";
104 + discoverProc.exec({
105 + command: ["sh", "-c", root.discoverScript()],
106 + environment: {
107 + CALDAV_HOST: root.host,
108 + CALDAV_USER: String(root.config.username),
109 + CALDAV_URL: String(root.config.url).replace(/\/+$/, "") + "/calendars/" + encodeURIComponent(String(root.config.username)) + "/"
111 + });
114 + function discoverScript() {
115 + // password read here, fed to curl via -K - on stdin; never in argv
116 + return 'PW="$(secret-tool lookup service caldav host "$CALDAV_HOST" 2>/dev/null)";' +
117 + 'if [ -z "$PW" ]; then echo __NO_SECRET__; exit 0; fi;' +
118 + 'curl -sS -X PROPFIND -H "Depth: 1" -H "Content-Type: application/xml" ' +
119 + '--data \'<d:propfind xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav" xmlns:i="http://apple.com/ns/ical/"><d:prop><d:resourcetype/><d:displayname/><i:calendar-color/><c:supported-calendar-component-set/></d:prop></d:propfind>\' ' +
120 + '-K - "$CALDAV_URL" <<EOF\nuser = "$CALDAV_USER:$PW"\nEOF';
123 + function applyDiscovery(text) {
124 + const t = String(text || "");
125 + if (t.indexOf("__NO_SECRET__") >= 0) { root.status = "needs-setup"; return; }
126 + const cals = root.parseCalendars(t);
127 + if (!cals.length) { root.status = "offline"; root.stale = true; return; }
128 + root.config.calendars = cals;
129 + root.persistConfig();
130 + root.refresh();
133 + // --- fetch window math ---
134 + // Monday on-or-before the 1st of the currently displayed month, as "YYYY-MM-DD"
135 + function gridStartDate() {
136 + const now = new Date();
137 + const first = new Date(now.getFullYear(), now.getMonth(), 1);
138 + const dow = (first.getDay() + 6) % 7; // 0=Mon
139 + first.setDate(first.getDate() - dow);
140 + function p(n){ return (n<10?"0":"")+n; }
141 + return first.getFullYear() + "-" + p(first.getMonth()+1) + "-" + p(first.getDate());
144 + // window from a "YYYY-MM-DD" local grid start: [start, start+42d] as UTC ICAL stamps
145 + function windowUtc(gridStart) {
146 + const p = gridStart.split("-");
147 + const s = new Date(+p[0], +p[1]-1, +p[2], 0, 0, 0); // local midnight
148 + const e = new Date(s.getTime()); e.setDate(e.getDate() + 42);
149 + function fmt(d){
150 + function z(n){ return (n<10?"0":"")+n; }
151 + return d.getUTCFullYear()+z(d.getUTCMonth()+1)+z(d.getUTCDate())+"T"+z(d.getUTCHours())+z(d.getUTCMinutes())+z(d.getUTCSeconds())+"Z";
153 + return { start: fmt(s), end: fmt(e) };
156 + function refresh() {
157 + if (!root.host || !root.config.username) { root.status = "needs-setup"; return; }
158 + if (!root.config.calendars || !root.config.calendars.length) { root.discoverAndFetch(); return; }
159 + root.status = "loading";
160 + const gs = root.gridStartDate();
161 + const w = root.windowUtc(gs);
162 + const lines = [];
163 + const cals = root.config.calendars.filter(c => c.enabled !== false);
164 + for (let i = 0; i < cals.length; i++) {
165 + const isTask = (cals[i].components || []).indexOf("VTODO") >= 0 && (cals[i].components || []).indexOf("VEVENT") < 0;
166 + lines.push([cals[i].href, cals[i].color, isTask ? "VTODO" : "VEVENT"].join("\t"));
168 + fetchProc.exec({
169 + command: ["sh", "-c", root.fetchScript()],
170 + environment: {
171 + CALDAV_HOST: root.host,
172 + CALDAV_USER: String(root.config.username),
173 + CALDAV_BASE: root.origin,
174 + CALDAV_WIN_START: w.start,
175 + CALDAV_WIN_END: w.end,
176 + CALDAV_CALS: lines.join("\n")
178 + });
181 + function fetchScript() {
182 + // For each "href\tcolor\tkind" line: print delimiter, then curl REPORT.
183 + // VEVENT uses <c:expand>; VTODO must NOT (Nextcloud #45333 drops tasks).
184 + return 'PW="$(secret-tool lookup service caldav host "$CALDAV_HOST" 2>/dev/null)";' +
185 + 'if [ -z "$PW" ]; then echo __NO_SECRET__; exit 0; fi;' +
186 + 'printf %s "$CALDAV_CALS" | while IFS="\t" read -r HREF COLOR KIND; do ' +
187 + '[ -z "$HREF" ] && continue;' +
188 + 'printf "@@CAL %s\\t%s\\t%s\\n" "$HREF" "$COLOR" "$KIND";' +
189 + 'if [ "$KIND" = "VTODO" ]; then ' +
190 + 'BODY="<c:calendar-query xmlns:d=\\"DAV:\\" xmlns:c=\\"urn:ietf:params:xml:ns:caldav\\"><d:prop><c:calendar-data/></d:prop><c:filter><c:comp-filter name=\\"VCALENDAR\\"><c:comp-filter name=\\"VTODO\\"/></c:comp-filter></c:filter></c:calendar-query>";' +
191 + 'else ' +
192 + 'BODY="<c:calendar-query xmlns:d=\\"DAV:\\" xmlns:c=\\"urn:ietf:params:xml:ns:caldav\\"><d:prop><c:calendar-data><c:expand start=\\"$CALDAV_WIN_START\\" end=\\"$CALDAV_WIN_END\\"/></c:calendar-data></d:prop><c:filter><c:comp-filter name=\\"VCALENDAR\\"><c:comp-filter name=\\"VEVENT\\"><c:time-range start=\\"$CALDAV_WIN_START\\" end=\\"$CALDAV_WIN_END\\"/></c:comp-filter></c:comp-filter></c:filter></c:calendar-query>";' +
193 + 'fi;' +
194 + 'curl -sS -X REPORT -H "Depth: 1" -H "Content-Type: application/xml" --data "$BODY" -K - "$CALDAV_BASE$HREF" <<EOF\nuser = "$CALDAV_USER:$PW"\nEOF\n' +
195 + 'printf "\\n";' +
196 + 'done';
199 + function applyFetch(text) {
200 + const t = String(text || "");
201 + if (t.indexOf("__NO_SECRET__") >= 0) { root.status = "needs-setup"; return; }
202 + let parsed = [];
203 + try { parsed = Ical.parseIcs(t); } catch (e) { parsed = []; }
204 + if (!t.trim()) { root.status = "offline"; root.stale = true; return; } // keep last-good events
205 + // client-side window filter for tasks (VTODO has no server time-range)
206 + const gs = root.gridStartDate();
207 + const winStart = gs, winEnd = Ical.addDays(gs, 42);
208 + root.events = parsed.filter(function (ev) {
209 + if (ev.kind !== "task") return true;
210 + return ev.date && ev.date >= winStart && ev.date < winEnd;
211 + });
212 + root.status = "ok";
213 + root.stale = false;
216 + function saveSetup(url, username, password) {}
218 + Process {
219 + id: discoverProc
220 + stdout: StdioCollector { waitForEnd: true; onStreamFinished: root.applyDiscovery(this.text) }
221 + stderr: StdioCollector { waitForEnd: true; onStreamFinished: if (this.text.trim()) root.stale = true }
224 + Process {
225 + id: fetchProc
226 + stdout: StdioCollector { waitForEnd: true; onStreamFinished: root.applyFetch(this.text) }
227 + stderr: StdioCollector { waitForEnd: true; onStreamFinished: if (this.text.trim()) { root.stale = true; if (root.status === "loading") root.status = "offline"; } }
230 + Timer {
231 + interval: 15 * 60 * 1000
232 + running: true
233 + repeat: true
234 + onTriggered: root.refresh()
237 + FileView {
238 + id: cfgFile
239 + path: root.configPath
240 + onAdapterUpdated: writeAdapter()
241 + // config is read async; refresh only once url/username are populated
242 + onLoaded: Qt.callLater(root.refresh)
243 + onLoadFailed: root.status = "needs-setup"
245 + JsonAdapter {
246 + id: cfgAdapter
247 + property string url: ""
248 + property string username: ""
249 + property var calendars: []

quickshell/nuguland/PopoutHost.qml

Modified
10 10 required property QtObject surfaces
11 11 required property QtObject niriService
12 12 required property QtObject timeService
13 + property QtObject caldavService
13 14 required property QtObject resourceService
14 15 required property QtObject notificationService
15 16 required property QtObject trayService

quickshell/nuguland/shell.qml

Modified
54 54 id: time
57 + CalDav {
58 + id: caldav
59 + }
57 61 Niri {
58 62 id: niri
525 529 lockService: lock
526 530 surfaces: surfaceManager
527 531 usageService: usage
532 + caldavService: caldav
528 533 formatService: format
529 534 orientation: shell.orientation
613 618 target: "usage"
621 + IpcHandler {
622 + target: "caldav"
623 + function state() : string { return caldav.stateJson(); }
624 + function selfTest() : string { return caldav.selfTest(); }
625 + function refresh() : string { caldav.refresh(); return caldav.stateJson(); }
616 628 IpcHandler {
617 629 function ping() : string {
618 630 return "nuguland";