Luigit
repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by admin

quickshell/nuguland/features/clock/CalDav.qml

Raw
pragma ComponentBehavior: Bound
import QtQuick
import Quickshell
import Quickshell.Io
import "caldav.js" as Ical

Item {
    id: root

    // Writable so the cadence test points it at a private file.
    property string configPath: Quickshell.statePath("caldav.json")
    // Non-secret settings: loadConfig() reads them, persistConfig() writes them.
    property alias config: cfgAdapter
    property var events: []
    property bool stale: false
    // Epoch ms of the last successful fetch; 0 until one succeeds.
    property double lastSyncMs: 0
    // "idle" until the first fetch: nothing fetches at startup or while closed.
    property string status: "idle"
    // Set by the registry entry while the clock popup is open; it fetches on
    // every opening and gates the periodic refresh.
    property bool popupOpen: false
    property int refreshMs: 15 * 60 * 1000

    readonly property string host: root.hostOf(root.config.url)

    // scheme+host only; PROPFIND hrefs are absolute from the host root, so the
    // dav path must NOT be prepended again when building fetch URLs.
    readonly property string origin: {
        const m = /^(https?:\/\/[^\/]+)/.exec(root.config.url);
        return m ? m[1] : "";
    }

    function hostOf(url: string): string {
        const m = /^https?:\/\/([^\/:]+)/.exec(url);
        return m ? m[1] : "";
    }

    function stateJson() {
        return JSON.stringify({
            backend: "CalDav.qml",
            status: status,
            stale: stale,
            lastSyncMs: lastSyncMs,
            secretError: secretError,
            host: host,
            username: config.username,
            setupDraftUrl: setupUrlDraft,
            setupDraftUsername: setupUsernameDraft,
            setupDraftHasPassword: setupPasswordDraft.length > 0,
            calendarCount: config.calendars.length,
            eventCount: events.length
        });
    }

    function loadConfig() {
        let data = {};
        try {
            data = JSON.parse(cfgFile.text() || "{}");
        } catch (error) {
            data = {};
        }
        root.config.url = String(data.url || "");
        root.config.username = String(data.username || "");
        root.config.calendars = data.calendars || [];
        if (!root.setupUrlDraft)
            root.setupUrlDraft = root.config.url;
        if (!root.setupUsernameDraft)
            root.setupUsernameDraft = root.config.username;
    }

    function persistConfig() {
        cfgFile.setText(JSON.stringify({
            "url": root.config.url,
            "username": root.config.username,
            "calendars": root.config.calendars || []
        }, null, 2));
    }

    function discoverAndFetch() {
        if (!root.host || !root.config.username) {
            root.status = "needs-setup";
            return;
        }
        root.status = "loading";
        discoverProc.exec({
            command: ["sh", "-c", root.discoverScript()],
            environment: {
                CALDAV_HOST: root.host,
                CALDAV_USER: String(root.config.username),
                CALDAV_URL: String(root.config.url).replace(/\/+$/, "") + "/calendars/" + encodeURIComponent(String(root.config.username)) + "/"
            }
        });
    }

    function discoverScript() {
        // password read here, fed to curl via -K - on stdin; never in argv
        return 'PW="$(secret-tool lookup service caldav host "$CALDAV_HOST" 2>/dev/null)";' + 'if [ -z "$PW" ]; then echo __NO_SECRET__; exit 0; fi;' + 'curl -sS -X PROPFIND -H "Depth: 1" -H "Content-Type: application/xml" ' + '--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>\' ' + '-K - "$CALDAV_URL" <<EOF\nuser = "$CALDAV_USER:$PW"\nEOF';
    }

    function applyDiscovery(text) {
        const t = String(text || "");
        if (t.indexOf("__NO_SECRET__") >= 0) {
            root.status = "needs-setup";
            return;
        }
        const cals = Ical.parseCalendars(t);
        if (!cals.length) {
            root.status = "offline";
            root.stale = true;
            return;
        }
        root.config.calendars = cals;
        root.persistConfig();
        root.refresh();
    }

    function refresh() {
        if (!root.host || !root.config.username) {
            root.status = "needs-setup";
            return;
        }
        if (!root.config.calendars || !root.config.calendars.length) {
            root.discoverAndFetch();
            return;
        }
        root.status = "loading";
        const w = Ical.windowUtc(Ical.gridStart(new Date()));
        const lines = [];
        const cals = root.config.calendars.filter(c => c.enabled !== false);
        for (let i = 0; i < cals.length; i++) {
            const isTask = (cals[i].components || []).indexOf("VTODO") >= 0 && (cals[i].components || []).indexOf("VEVENT") < 0;
            lines.push([cals[i].href, cals[i].color, isTask ? "VTODO" : "VEVENT"].join("\t"));
        }
        fetchProc.exec({
            command: ["sh", "-c", root.fetchScript()],
            environment: {
                CALDAV_HOST: root.host,
                CALDAV_USER: String(root.config.username),
                CALDAV_BASE: root.origin,
                CALDAV_WIN_START: w.start,
                CALDAV_WIN_END: w.end,
                CALDAV_CALS: lines.join("\n")
            }
        });
    }

    function fetchScript() {
        // For each "href\tcolor\tkind" line: print delimiter, then curl REPORT.
        // The trailing newline lets read return the last calendar's line too.
        // VEVENT uses <c:expand>; VTODO must NOT (Nextcloud #45333 drops tasks).
        return 'PW="$(secret-tool lookup service caldav host "$CALDAV_HOST" 2>/dev/null)";' + 'if [ -z "$PW" ]; then echo __NO_SECRET__; exit 0; fi;' + 'printf "%s\\n" "$CALDAV_CALS" | while IFS="\t" read -r HREF COLOR KIND; do ' + '[ -z "$HREF" ] && continue;' + 'printf "@@CAL %s\\t%s\\t%s\\n" "$HREF" "$COLOR" "$KIND";' + 'if [ "$KIND" = "VTODO" ]; then ' + '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>";' + 'else ' + '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>";' + 'fi;' + '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' + 'printf "\\n";' + 'done';
    }

    function applyFetch(text) {
        const t = String(text || "");
        if (t.indexOf("__NO_SECRET__") >= 0) {
            root.status = "needs-setup";
            return;
        }
        // a successful REPORT is a 207 <d:multistatus>; its absence means a
        // transport/auth failure (curl prints @@CAL headers but no data), so
        // t is non-empty yet useless: keep last-good events and flag stale.
        // (an empty month still returns multistatus, so this won't false-trip.)
        // Every calendar must answer: one success never hides another's failure.
        const reports = t.split("@@CAL ").slice(1);
        if (reports.length === 0 || reports.some(report => report.indexOf("multistatus") < 0)) {
            root.status = "offline";
            root.stale = true;
            return;
        }
        let parsed = [];
        try {
            parsed = Ical.parseIcs(t);
        } catch (e) {
            parsed = [];
        }
        // client-side window filter for tasks (VTODO has no server time-range)
        const winStart = Ical.gridStart(new Date()), winEnd = Ical.addDays(winStart, Ical.GRID_DAYS);
        root.events = parsed.filter(function (ev) {
            if (ev.kind !== "task")
                return true;
            return ev.date && ev.date >= winStart && ev.date < winEnd;
        });
        root.status = "ok";
        root.stale = false;
        root.lastSyncMs = Date.now();
    }

    // non-empty when the last keyring write failed; shown in the setup form
    property string secretError: ""
    property string setupUrlDraft: ""
    property string setupUsernameDraft: ""
    property string setupPasswordDraft: ""
    property bool setupBusy: false
    property int passwordRevision: 0
    property int submittedPasswordRevision: -1
    onSetupPasswordDraftChanged: passwordRevision++

    function editSetupUrl(value: string): void {
        if (!setupBusy)
            setupUrlDraft = value;
    }
    function editSetupUsername(value: string): void {
        if (!setupBusy)
            setupUsernameDraft = value;
    }
    function editSetupPassword(value: string): void {
        if (!setupBusy)
            setupPasswordDraft = value;
    }

    // Persist url+username, store the password in gnome-keyring, then discover.
    // Password reaches secret-tool via stdin (printf is a shell builtin, so it
    // never appears in argv/ps); it travels QML->sh only as a transient env var.
    function saveSetup(url, username, password) {
        if (root.setupBusy)
            return;
        root.secretError = "";
        root.setupUrlDraft = String(url || "");
        root.setupUsernameDraft = String(username || "");
        root.setupPasswordDraft = String(password || "");
        const u = String(url || "").trim().replace(/\/+$/, "");
        const user = String(username || "").trim();
        if (!u || !user || !password) {
            root.secretError = "fill in url, username and password";
            return;
        }
        const h = root.hostOf(u);
        if (!h) {
            root.secretError = "enter a full https:// url";
            return;
        }
        root.setupUrlDraft = u;
        root.setupUsernameDraft = user;
        root.config.url = u;
        root.config.username = user;
        root.config.calendars = [];
        root.persistConfig();
        root.setupBusy = true;
        root.submittedPasswordRevision = root.passwordRevision;
        storeProc.exec({
            command: ["sh", "-c", root.storeScript()],
            environment: {
                CALDAV_HOST: h,
                CALDAV_USER: user,
                CALDAV_NEWPW: String(password)
            }
        });
    }

    function storeScript() {
        return 'printf %s "$CALDAV_NEWPW" | secret-tool store --label="nuguland caldav" service caldav host "$CALDAV_HOST" account "$CALDAV_USER"';
    }

    Process {
        id: discoverProc
        stdout: StdioCollector {
            waitForEnd: true
            onStreamFinished: root.applyDiscovery(this.text)
        }
        stderr: StdioCollector {
            waitForEnd: true
            onStreamFinished: if (this.text.trim())
                root.stale = true
        }
    }

    Process {
        id: fetchProc
        stdout: StdioCollector {
            waitForEnd: true
            onStreamFinished: root.applyFetch(this.text)
        }
        stderr: StdioCollector {
            waitForEnd: true
            onStreamFinished: if (this.text.trim()) {
                root.stale = true;
                if (root.status === "loading")
                    root.status = "offline";
            }
        }
    }

    Process {
        id: storeProc
        onRunningChanged: if (!running)
            Qt.callLater(() => {
                if (root.setupBusy && !storeProc.running) {
                    storeProc.environment = {};
                    root.setupBusy = false;
                    root.status = "needs-setup";
                    root.secretError = "keyring storage interrupted; save again";
                }
            })
        onExited: code => {
            environment = {};
            root.setupBusy = false;
            if (code === 0) {
                root.secretError = "";
                if (root.passwordRevision === root.submittedPasswordRevision)
                    root.setupPasswordDraft = "";
                root.status = "idle";
                if (root.popupOpen)
                    root.discoverAndFetch();
            } else {
                root.status = "needs-setup";
                root.secretError = "unlock keyring and save again";
            }
        }
    }

    Timer {
        interval: root.refreshMs
        running: root.popupOpen
        repeat: true
        onTriggered: root.refresh()
    }

    QtObject {
        id: cfgAdapter

        property string url: ""
        property string username: ""
        property var calendars: []
    }

    FileView {
        id: cfgFile
        path: root.configPath
        // A missing file is the first run; only other read failures are warnings.
        printErrors: false
        // Config is read async; a popup opened before it landed fetches now,
        // otherwise the next opening does.
        onLoaded: {
            root.loadConfig();
            if (!root.host || !root.config.username)
                root.status = "needs-setup";
            else if (root.popupOpen)
                root.refresh();
        }
        onLoadFailed: error => {
            root.status = "needs-setup";
            if (error !== FileViewError.FileNotFound)
                console.warn("caldav settings could not be read");
        }
    }
}