// AufTasks fuer Scriptable: Sperrbildschirm-/Homescreen-Widget UND Siri-Eingang in einem Skript. // Einrichtung: in der AufTasks-App oben auf das iPhone-Symbol ("Widget & Siri") tippen. // // Widget: zeigt offene Aufgaben, die heute faellig oder ueberfaellig sind. // Siri: ein Kurzbefehl uebergibt den diktierten Satz als Eingabe ("Zahnarzt morgen um // 14 Uhr fuer Studium"). Datum, Uhrzeit und Ordner erkennt der Server aus dem Satz; // das Skript antwortet mit einem Bestaetigungssatz, den Siri vorliest. // (Auch "DATUM|SATZ" wird angenommen, falls ein Kurzbefehl das Datum selbst liefert.) // Ein Widget pro Ordner: im Widget-Feld "Parameter" den Ordnernamen eintragen (z. B. Studium). // Tages-Uebersicht: eine Kurzbefehle-Automation ruft das Skript mit "#uebersicht" (morgens) // oder "#abend" auf; optional Tage ("#uebersicht 14") und "text" (keine eigene Mitteilung). // Updates: Skript in Scriptable starten -> "Skript aktualisieren". // Der persoenliche Schluessel liegt nur hier auf dem iPhone (Schluesselbund). const SB_URL = "https://tdoawgzwwuzlkwxkbuha.supabase.co"; const SB_ANON = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InRkb2F3Z3p3d3V6bGt3eGtidWhhIiwicm9sZSI6ImFub24iLCJpYXQiOjE3ODQ3MjY5NjYsImV4cCI6MjEwMDMwMjk2Nn0.S6jbd2oNl5PH8jFINyfO7dRkhRDkpDwh8c2sgiLErwI"; const APP_URL = "https://aufgaben.pages.dev"; const SCRIPT_URL = `${APP_URL}/widget/AufTasks.js`; const VERSION = "2026-11-13.1"; const KEY_NAME = "auftasks.key"; const REFRESH_MIN = 15; const fm = FileManager.local(); const KEY_FILE = fm.joinPath(fm.documentsDirectory(), ".auftasks-key"); function cacheFile(folder) { const slug = folder ? "-" + folder.toLowerCase().replace(/[^a-z0-9]+/g, "_") : ""; return fm.joinPath(fm.documentsDirectory(), `.auftasks-cache${slug}.json`); } const COLORS = { bg: new Color("#141619"), fg: new Color("#e8eaed"), muted: new Color("#9aa0a6"), warn: new Color("#ff8a80"), accent: new Color("#8ab4f8"), }; const WEEKDAYS = ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"]; // ---------- key ---------- // Keychain first; the file copy is a fallback because Scriptable doesn't document // whether widgets and Shortcuts can always read the Keychain. function readKey() { try { if (Keychain.contains(KEY_NAME)) return Keychain.get(KEY_NAME); } catch (e) {} try { if (fm.fileExists(KEY_FILE)) return fm.readString(KEY_FILE).trim(); } catch (e) {} return null; } function storeKey(key) { try { Keychain.set(KEY_NAME, key); } catch (e) {} try { fm.writeString(KEY_FILE, key); } catch (e) {} } function forgetKey() { try { if (Keychain.contains(KEY_NAME)) Keychain.remove(KEY_NAME); } catch (e) {} try { if (fm.fileExists(KEY_FILE)) fm.remove(KEY_FILE); } catch (e) {} } // ---------- server ---------- class BridgeError extends Error { constructor(kind, message) { super(message || kind); this.kind = kind; } } async function rpc(fn, body) { const req = new Request(`${SB_URL}/rest/v1/rpc/${fn}`); req.method = "POST"; req.timeoutInterval = 15; req.headers = { apikey: SB_ANON, Authorization: `Bearer ${SB_ANON}`, "Content-Type": "application/json" }; req.body = JSON.stringify(body); let data = null; try { data = await req.loadJSON(); } catch (e) { /* non-JSON body or no network */ } const status = req.response && req.response.statusCode; if (!status) throw new BridgeError("offline", "Keine Verbindung"); if (status === 401 || status === 403) throw new BridgeError("key", "Schl\u00fcssel ung\u00fcltig"); if (status === 404) throw new BridgeError("setup", "Die Br\u00fccke ist in Supabase noch nicht eingerichtet"); if (status >= 400) throw new BridgeError("server", (data && data.message) || `Fehler ${status}`); return data; } // ---------- helpers ---------- function pad(n) { return String(n).padStart(2, "0"); } function isoLocal(d) { return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`; } function shortDate(iso) { const [y, m, d] = iso.split("-").map(Number); return `${WEEKDAYS[new Date(y, m - 1, d).getDay()]} ${d}.${m}.`; } function itemLabel(item) { if (item.overdue) return "\u00fcberf\u00e4llig"; if (item.dueTime) return item.dueTime; return "heute"; } function withFolder(item, showFolder) { return showFolder && item.folder ? `${item.folder}: ${item.text}` : item.text; } function itemLine(item, showFolder) { const text = withFolder(item, showFolder); if (item.overdue) return `! ${text}`; if (item.dueTime) return `${item.dueTime} ${text}`; return `\u2022 ${text}`; } function dueCount(data) { return (data.overdueCount || 0) + (data.todayCount || 0); } function headline(data) { const n = dueCount(data); if (n === 0) return "Nichts f\u00e4llig"; const parts = []; if (data.todayCount) parts.push(`${data.todayCount} heute`); if (data.overdueCount) parts.push(`${data.overdueCount} \u00fcberf\u00e4llig`); return parts.join(" \u00b7 "); } // ---------- data with offline cache ---------- async function loadData(key, folder) { const file = cacheFile(folder); const body = { p_token: key, p_today: isoLocal(new Date()) }; if (folder) body.p_folder = folder; try { const data = await rpc("api_widget", body); try { fm.writeString(file, JSON.stringify({ at: Date.now(), data })); } catch (e) {} return { data, stale: null }; } catch (e) { if (e.kind === "offline" && fm.fileExists(file)) { const c = JSON.parse(fm.readString(file)); const t = new Date(c.at); return { data: c.data, stale: `${pad(t.getHours())}:${pad(t.getMinutes())}` }; } throw e; } } // ---------- widgets ---------- function baseWidget() { const w = new ListWidget(); w.url = APP_URL; w.refreshAfterDate = new Date(Date.now() + REFRESH_MIN * 60 * 1000); return w; } function addLine(w, text, font, color, opacity) { const t = w.addText(text); t.font = font; t.lineLimit = 1; t.minimumScaleFactor = 0.8; if (color) t.textColor = color; if (opacity != null) t.textOpacity = opacity; return t; } function messageWidget(family, title, detail) { const w = baseWidget(); if (family === "accessoryInline") { addLine(w, `AufTasks: ${title}`, Font.systemFont(12)); return w; } if (family === "accessoryCircular") { w.addAccessoryWidgetBackground = true; addLine(w, "!", Font.boldSystemFont(22)).centerAlignText(); return w; } const lock = family === "accessoryRectangular"; if (!lock) { w.backgroundColor = COLORS.bg; w.setPadding(14, 14, 14, 14); } addLine(w, "AufTasks", Font.boldSystemFont(lock ? 13 : 15), lock ? null : COLORS.fg); addLine(w, title, Font.systemFont(lock ? 12 : 13), lock ? null : COLORS.warn); if (detail) { const t = addLine(w, detail, Font.systemFont(lock ? 11 : 11), lock ? null : COLORS.muted); t.lineLimit = 2; } return w; } function inlineWidget(data, filtered) { const w = baseWidget(); const first = data.items && data.items[0]; const scope = filtered ? `${data.folder}: ` : ""; const text = first ? `${scope}${headline(data)} \u00b7 ${first.text}` : (data.next && data.next[0] ? `${scope}Nichts f\u00e4llig \u00b7 ${shortDate(data.next[0].dueDate)} ${data.next[0].text}` : `${filtered ? data.folder : "AufTasks"}: nichts f\u00e4llig`); const img = w.addImage(SFSymbol.named("checklist").image); img.imageSize = new Size(12, 12); addLine(w, text, Font.systemFont(12)); return w; } function circularWidget(data, filtered) { const w = baseWidget(); w.addAccessoryWidgetBackground = true; const n = dueCount(data); addLine(w, n === 0 ? "\u2713" : String(n), Font.boldSystemFont(n > 9 ? 18 : 22)).centerAlignText(); addLine(w, filtered ? data.folder : (n === 0 ? "frei" : "f\u00e4llig"), Font.systemFont(9)).centerAlignText(); return w; } function rectangularWidget(data, stale, filtered) { const w = baseWidget(); addLine(w, `${filtered ? data.folder : "AufTasks"} \u00b7 ${headline(data)}`, Font.boldSystemFont(13)); const items = data.items || []; if (items.length) { for (const item of items.slice(0, 2)) addLine(w, itemLine(item, !filtered), Font.systemFont(12), null, item.overdue ? 1 : 0.9); if (items.length > 2) addLine(w, `+ ${items.length - 2} weitere`, Font.systemFont(11), null, 0.7); } else if (data.next && data.next.length) { const n = data.next[0]; addLine(w, `N\u00e4chste: ${shortDate(n.dueDate)}`, Font.systemFont(12), null, 0.8); addLine(w, withFolder(n, !filtered), Font.systemFont(12), null, 0.9); } else { addLine(w, "Alles erledigt", Font.systemFont(12), null, 0.8); } if (stale) addLine(w, `offline \u00b7 Stand ${stale}`, Font.systemFont(9), null, 0.6); return w; } function homeWidget(data, stale, family, filtered) { const w = baseWidget(); w.backgroundColor = COLORS.bg; w.setPadding(14, 14, 12, 14); const max = family === "large" ? 11 : family === "medium" ? 4 : 3; const head = w.addStack(); head.layoutHorizontally(); head.centerAlignContent(); const title = head.addText(filtered ? data.folder : "AufTasks"); title.font = Font.boldSystemFont(15); title.textColor = COLORS.fg; head.addSpacer(); const count = head.addText(headline(data)); count.font = Font.mediumSystemFont(11); count.textColor = data.overdueCount ? COLORS.warn : COLORS.muted; count.lineLimit = 1; w.addSpacer(8); const items = data.items || []; const rows = items.length ? items : (data.next || []); if (!items.length) addLine(w, rows.length ? "Heute nichts f\u00e4llig. Als N\u00e4chstes:" : "Alles erledigt.", Font.systemFont(12), COLORS.muted); for (const item of rows.slice(0, max)) { const row = w.addStack(); row.layoutHorizontally(); row.spacing = 8; const label = row.addText(items.length ? itemLabel(item) : shortDate(item.dueDate)); label.font = Font.mediumSystemFont(11); label.textColor = item.overdue ? COLORS.warn : COLORS.accent; label.lineLimit = 1; const text = row.addText(item.text); text.font = Font.systemFont(13); text.textColor = COLORS.fg; text.lineLimit = 1; if (!filtered && item.folder) { row.addSpacer(); const f = row.addText(item.folder); f.font = Font.systemFont(11); f.textColor = COLORS.muted; f.lineLimit = 1; } w.addSpacer(4); } if (rows.length > max) addLine(w, `+ ${rows.length - max} weitere`, Font.systemFont(11), COLORS.muted); w.addSpacer(); if (stale) addLine(w, `offline \u00b7 Stand ${stale}`, Font.systemFont(9), COLORS.muted); return w; } async function buildWidget(family, folder) { const key = readKey(); if (!key) return messageWidget(family, "Noch nicht eingerichtet", "Skript einmal in Scriptable \u00f6ffnen"); try { const { data, stale } = await loadData(key, folder); if (data.folderNotFound) return messageWidget(family, `Ordner "${folder}" fehlt`, "Parameter im Widget pr\u00fcfen"); const filtered = !!(folder && data.folder); if (family === "accessoryInline") return inlineWidget(data, filtered); if (family === "accessoryCircular") return circularWidget(data, filtered); if (family === "accessoryRectangular") return rectangularWidget(data, stale, filtered); return homeWidget(data, stale, family || "medium", filtered); } catch (e) { const detail = e.kind === "key" ? "Neuen Schl\u00fcssel in der App erzeugen" : e.kind === "offline" ? "Keine Verbindung" : e.message; return messageWidget(family, e.kind === "key" ? "Schl\u00fcssel ung\u00fcltig" : "Nicht erreichbar", detail); } } // ---------- Siri / Kurzbefehl ---------- function parseSiriInput(param) { if (param && typeof param === "object" && !Array.isArray(param)) { return { text: String(param.text || param.Text || "").trim(), due: String(param.due || param.datum || "").trim() }; } const s = Array.isArray(param) ? param.join(" ") : String(param == null ? "" : param); const bar = s.indexOf("|"); if (bar === -1) return { text: s.trim(), due: "" }; return { due: s.slice(0, bar).trim(), text: s.slice(bar + 1).trim() }; } async function addFromSiri(param) { const { text, due } = parseSiriInput(param); if (!text) return "Ich habe keine Aufgabe verstanden."; const key = readKey(); if (!key) return "AufTasks ist auf diesem iPhone noch nicht eingerichtet. \u00d6ffne das Skript einmal in Scriptable."; try { const res = await rpc("api_add_task", { p_token: key, p_text: text, p_due: due || null, p_today: isoLocal(new Date()) }); return res.message || "Gespeichert."; } catch (e) { if (e.kind === "key") return "Der AufTasks-Schl\u00fcssel ist ung\u00fcltig. Erzeuge in der App einen neuen."; if (e.kind === "offline") return "Keine Verbindung, die Aufgabe wurde nicht gespeichert."; return `Nicht gespeichert: ${e.message}`; } } // ---------- Tages-Uebersicht als Mitteilung (D18) ---------- const DIGEST_RE = /^#\s*(\u00fcbersicht|uebersicht|digest|summary|abend|evening)\b(.*)$/i; function parseDigestParam(param) { if (typeof param !== "string") return null; const m = param.trim().match(DIGEST_RE); if (!m) return null; const rest = m[2].trim().toLowerCase().split(/\s+/).filter(Boolean); const num = rest.find(x => /^\d{1,2}$/.test(x)); return { evening: /^(abend|evening)$/i.test(m[1]), days: num ? Number(num) : 7, notify: !rest.includes("text") }; } function dayLabel(iso, todayIso) { const [y, m, d] = todayIso.split("-").map(Number); return iso === isoLocal(new Date(y, m - 1, d + 1)) ? "Morgen" : shortDate(iso); } function fmtTask(it, overdue) { const prio = it.importance === "high" ? "! " : ""; const time = it.dueTime ? `${it.dueTime} ` : ""; const extra = [it.folder, overdue && it.dueDate ? `seit ${shortDate(it.dueDate)}` : null].filter(Boolean).join(", "); return `${prio}${time}${it.text}${extra ? ` (${extra})` : ""}`; } function buildDigest(d, evening) { const list = (items, overdue) => items.map(it => fmtTask(it, overdue)).join(" \u00b7 "); const upcomingCount = d.upcoming.reduce((n, g) => n + g.items.length, 0); const lines = []; if (d.overdue.length) lines.push(`\u00dcberf\u00e4llig (${d.overdue.length}): ${list(d.overdue, true)}`); if (d.dueToday.length) lines.push(`${evening ? "Noch offen von heute" : "Heute"} (${d.dueToday.length}): ${list(d.dueToday)}`); for (const g of d.upcoming) lines.push(`${dayLabel(g.date, d.today)} (${g.items.length}): ${list(g.items)}`); if (d.undatedCount) lines.push(`Ohne Datum (${d.undatedCount}): ${list(d.undated)}${d.undatedCount > d.undated.length ? " \u2026" : ""}`); const parts = []; if (d.overdue.length) parts.push(`${d.overdue.length} \u00fcberf\u00e4llig`); if (d.dueToday.length) parts.push(`${d.dueToday.length} heute`); if (upcomingCount) parts.push(`${upcomingCount} in den n\u00e4chsten ${d.days} Tagen`); return { title: evening ? "AufTasks \u00b7 Ausblick" : "AufTasks \u00b7 Dein Tag", subtitle: parts.join(" \u00b7 ") || "Nichts f\u00e4llig", body: lines.join("\n") || `Nichts f\u00e4llig in den n\u00e4chsten ${d.days} Tagen.`, empty: d.overdue.length + d.dueToday.length + upcomingCount === 0, }; } async function postNotification(title, subtitle, body) { const n = new Notification(); n.title = title; n.subtitle = subtitle; n.body = body; n.openURL = APP_URL; n.threadIdentifier = "auftasks-digest"; n.sound = "default"; await n.schedule(); } // force: also notify when nothing is due (the in-app test) async function runDigest(opts, force) { const key = readKey(); if (!key) return "AufTasks ist auf diesem iPhone noch nicht eingerichtet. \u00d6ffne das Skript einmal in Scriptable."; let d; try { d = await rpc("api_digest", { p_token: key, p_today: isoLocal(new Date()), p_days: opts.days }); } catch (e) { const msg = e.kind === "key" ? "Schl\u00fcssel ung\u00fcltig. Erzeuge in der App einen neuen." : e.kind === "setup" ? "Die Br\u00fccke in Supabase ist veraltet: bridge.sql neu ausf\u00fchren." : e.kind === "offline" ? "Keine Verbindung, die \u00dcbersicht konnte nicht geladen werden." : e.message; if (opts.notify) { try { await postNotification("AufTasks", "\u00dcbersicht nicht verf\u00fcgbar", msg); } catch (_) {} } return `AufTasks: ${msg}`; } const dg = buildDigest(d, opts.evening); if (opts.notify && (!dg.empty || force)) await postNotification(dg.title, dg.subtitle, dg.body); return `${dg.title}\n${dg.subtitle}\n\n${dg.body}`; } // ---------- in der App: einrichten & Vorschau ---------- async function askForKey() { const a = new Alert(); a.title = "AufTasks-Schl\u00fcssel"; a.message = "F\u00fcge den Schl\u00fcssel ein, den du in AufTasks unter \"Widget & Siri\" erzeugt hast."; a.addTextField("Schl\u00fcssel", ""); a.addAction("Speichern"); a.addCancelAction("Abbrechen"); if ((await a.presentAlert()) === -1) return false; const key = a.textFieldValue(0).trim().toLowerCase(); if (!/^[0-9a-f]{64}$/.test(key)) { await notice("Das sieht nicht wie ein AufTasks-Schl\u00fcssel aus (64 Zeichen 0-9 und a-f)."); return false; } try { await rpc("api_widget", { p_token: key, p_today: isoLocal(new Date()) }); } catch (e) { await notice(e.kind === "key" ? "Dieser Schl\u00fcssel wird nicht akzeptiert. Erzeuge in der App einen neuen." : `Pr\u00fcfung fehlgeschlagen: ${e.message}`); return false; } storeKey(key); await notice("Gespeichert. F\u00fcge jetzt das Widget auf dem Sperrbildschirm hinzu und w\u00e4hle dort das Skript \"AufTasks\"."); return true; } async function notice(message) { const a = new Alert(); a.title = "AufTasks"; a.message = message; a.addAction("OK"); await a.presentAlert(); } // Downloads the current version from the app's own site and overwrites this script file. async function updateScript() { let code = null; try { const r = new Request(`${SCRIPT_URL}?v=${Date.now()}`); r.timeoutInterval = 20; code = await r.loadString(); if (!r.response || r.response.statusCode !== 200) code = null; } catch (e) { code = null; } if (!code || !code.includes("async function main()") || !code.includes(SB_URL)) { await notice("Update konnte nicht geladen werden. Pr\u00fcfe die Verbindung."); return; } const remote = (code.match(/const VERSION = "([^"]+)"/) || [])[1]; if (remote === VERSION) { await notice(`Schon aktuell (Version ${VERSION}).`); return; } let target = FileManager.local(); try { const icloud = FileManager.iCloud(); if (icloud.isFileStoredIniCloud(module.filename)) target = icloud; } catch (e) {} try { target.writeString(module.filename, code); } catch (e) { await notice("Konnte das Skript nicht \u00fcberschreiben. Bitte manuell neu kopieren."); return; } await notice(`Aktualisiert auf Version ${remote || "neu"}. Widgets nutzen sie beim n\u00e4chsten Auffrischen.`); } async function appMenu() { if (!readKey()) { if (!(await askForKey())) return; } const a = new Alert(); a.title = "AufTasks"; a.message = `Eingerichtet (Version ${VERSION}). Was m\u00f6chtest du tun?`; a.addAction("Vorschau Sperrbildschirm"); a.addAction("Vorschau Homescreen"); a.addAction("Skript aktualisieren"); a.addAction("Mitteilung testen"); a.addAction("Schl\u00fcssel ersetzen"); a.addCancelAction("Fertig"); const choice = await a.presentAlert(); if (choice === 0) await (await buildWidget("accessoryRectangular", null)).presentAccessoryRectangular(); if (choice === 1) await (await buildWidget("medium", null)).presentMedium(); if (choice === 2) await updateScript(); if (choice === 3) { await runDigest({ evening: false, days: 7, notify: true }, true); await notice("Mitteilung verschickt. Kam keine? Einstellungen \u2192 Mitteilungen \u2192 Scriptable \u2192 Mitteilungen erlauben."); } if (choice === 4) { forgetKey(); await askForKey(); } } // ---------- main ---------- async function main() { const param = args.shortcutParameter; if (!config.runsInWidget && param != null) { const digestOpts = parseDigestParam(param); Script.setShortcutOutput(digestOpts ? await runDigest(digestOpts, false) : await addFromSiri(param)); return; } if (config.runsInWidget) { const p = args.widgetParameter; const folder = typeof p === "string" && p.trim() ? p.trim() : null; Script.setWidget(await buildWidget(config.widgetFamily, folder)); return; } await appMenu(); } await main(); Script.complete();