aboutsummaryrefslogtreecommitdiffstats
path: root/examples
diff options
context:
space:
mode:
authorDanilo M. <danix@danix.xyz>2026-11-25 10:06:56 +0100
committerDanilo M. <danix@danix.xyz>2026-11-25 10:06:56 +0100
commita0c19ff5cff2b40e7335cafccd53708c897bb7cc (patch)
treefb343433551a5015d0f8d8debc79296b0e6713be /examples
parent8c8c8965bf6952c1cc461978993c99aa2c54ee8b (diff)
downloaddesktop-assistant-a0c19ff5cff2b40e7335cafccd53708c897bb7cc.tar.gz
desktop-assistant-a0c19ff5cff2b40e7335cafccd53708c897bb7cc.zip
tools: vikunja, date, project and line helpers
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'examples')
-rwxr-xr-xexamples/tools/vikunja.py152
1 files changed, 152 insertions, 0 deletions
diff --git a/examples/tools/vikunja.py b/examples/tools/vikunja.py
new file mode 100755
index 0000000..21ed451
--- /dev/null
+++ b/examples/tools/vikunja.py
@@ -0,0 +1,152 @@
+#!/usr/bin/env python3
+# desktop-assistant tool: the user's Vikunja tasks, through Vikunja's MCP server.
+# Copyright (C) 2026 Danilo M. <danix@danix.xyz>
+#
+# This program is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License version 2 as published
+# by the Free Software Foundation.
+#
+# This program is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
+# Public License for more details.
+#
+# You should have received a copy of the GNU General Public License along
+# with this program; if not, write to the Free Software Foundation, Inc.,
+# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+"""vikunja.py ACTION ARGS...: the user's Vikunja tasks.
+
+ list QUERY PROJECT DUE_BEFORE ALL ID
+ add TITLE DESCRIPTION DUE PROJECT
+ edit ID TITLE DESCRIPTION DUE PROJECT DONE
+ delete ID
+
+Every argument is present and empty means not given. Dates are local
+time, YYYY-MM-DD (23:59 that day) or YYYY-MM-DD HH:MM; "none" clears a
+due date in edit. VIKUNJA_MCP_URL is the MCP endpoint, VIKUNJA_TOKEN_CMD
+prints the bearer token on its first line (run without a shell).
+--test runs the self-check.
+"""
+
+import functools
+import json
+import os
+import shlex
+import subprocess
+import sys
+import time
+import urllib.error
+import urllib.request
+from datetime import datetime, timezone
+
+NO_DATE = "0001-01-01T00:00:00Z" # Vikunja's "no due date"
+FIELDS = ["id", "title", "done", "due_date", "project_id"]
+
+
+def parse_due(s):
+ # Local "YYYY-MM-DD" (23:59 that day) or "YYYY-MM-DD HH:MM" to UTC ISO;
+ # "none" to None.
+ s = s.strip()
+ if s.lower() == "none":
+ return None
+ for fmt in ("%Y-%m-%d %H:%M", "%Y-%m-%d"):
+ try:
+ d = datetime.strptime(s, fmt)
+ except ValueError:
+ continue
+ if fmt == "%Y-%m-%d":
+ d = d.replace(hour=23, minute=59)
+ return d.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
+ raise ValueError(f"bad date {s!r}: use YYYY-MM-DD or YYYY-MM-DD HH:MM")
+
+
+def when(iso):
+ # Vikunja date to an aware datetime, None for "no date".
+ if not iso or iso.startswith("0001-"):
+ return None
+ return datetime.fromisoformat(iso.replace("Z", "+00:00"))
+
+
+def show_due(iso):
+ # Local time with the weekday: the model gets weekdays wrong from dates.
+ d = when(iso)
+ return d.astimezone().strftime("%a %d %b %Y %H:%M") if d else ""
+
+
+def paths(projects):
+ # id -> "parent/title", so nested projects read unambiguously.
+ by = {p["id"]: p for p in projects}
+
+ def path(p):
+ parent = by.get(p.get("parent_project_id"))
+ return f"{path(parent)}/{p['title']}" if parent else p["title"]
+ return {i: path(p) for i, p in by.items()}
+
+
+def find_project(name, ps):
+ # By full path or by own title, case-insensitive; exactly one match.
+ n = name.strip().lower()
+ hits = [i for i, p in ps.items() if n in (p.lower(), p.rsplit("/", 1)[-1].lower())]
+ if len(hits) == 1:
+ return hits[0]
+ raise ValueError(f"{'ambiguous' if hits else 'no'} project {name.strip()!r}; "
+ "projects: " + ", ".join(sorted(ps.values())))
+
+
+def line(t, ps):
+ s = f"#{t['id']} [{ps.get(t['project_id'], '?')}] {t['title']}"
+ if d := show_due(t.get("due_date")):
+ s += f", due {d}"
+ return s + (" (done)" if t.get("done") else "")
+
+
+def task_id(s):
+ try:
+ return int(str(s).strip().lstrip("#"))
+ except ValueError:
+ raise ValueError(f"bad task id {s!r}") from None
+
+
+def test():
+ os.environ["TZ"] = "Europe/Rome"
+ time.tzset()
+ assert parse_due("2026-11-28") == "2026-11-28T22:59:00Z"
+ assert parse_due("2026-07-01 09:30") == "2026-07-01T07:30:00Z" # summer time
+ assert parse_due(" None ") is None
+ for bad in ("28/11/2026", "2026-11-28 25:00", "tomorrow", ""):
+ try:
+ parse_due(bad)
+ except ValueError:
+ continue
+ raise AssertionError(bad)
+ assert show_due("2026-11-28T22:59:00Z") == "Sat 28 Nov 2026 23:59"
+ assert show_due("2026-11-28T23:59:00+01:00") == "Sat 28 Nov 2026 23:59"
+ assert show_due(NO_DATE) == "" and show_due(None) == ""
+ ps = paths([{"id": 1, "title": "Inbox", "parent_project_id": 0},
+ {"id": 9, "title": "dev", "parent_project_id": 0},
+ {"id": 12, "title": "quickshell", "parent_project_id": 9}])
+ assert ps == {1: "Inbox", 9: "dev", 12: "dev/quickshell"}
+ assert find_project("QuickShell", ps) == 12 == find_project("dev/quickshell", ps)
+ try:
+ find_project("nope", ps)
+ raise AssertionError("unknown project")
+ except ValueError as e:
+ assert "dev/quickshell" in str(e)
+ assert line({"id": 42, "title": "Fix lamp", "done": False, "project_id": 12,
+ "due_date": "2026-11-28T23:59:00+01:00"}, ps) \
+ == "#42 [dev/quickshell] Fix lamp, due Sat 28 Nov 2026 23:59"
+ assert line({"id": 7, "title": "x", "done": True, "project_id": 1,
+ "due_date": NO_DATE}, ps) == "#7 [Inbox] x (done)"
+ assert task_id("#42") == 42 == task_id(" 42 ")
+ try:
+ task_id("forty")
+ raise AssertionError("bad id")
+ except ValueError:
+ pass
+ print("ok")
+
+
+if __name__ == "__main__":
+ if sys.argv[1:] == ["--test"]:
+ test()
+ sys.exit()