aboutsummaryrefslogtreecommitdiffstats
path: root/deckit/modules/todo.py
diff options
context:
space:
mode:
Diffstat (limited to 'deckit/modules/todo.py')
-rw-r--r--deckit/modules/todo.py166
1 files changed, 166 insertions, 0 deletions
diff --git a/deckit/modules/todo.py b/deckit/modules/todo.py
new file mode 100644
index 0000000..8abbd23
--- /dev/null
+++ b/deckit/modules/todo.py
@@ -0,0 +1,166 @@
+# deck-it - todo module
+# 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 tasks that need doing now, for the Dashboard.
+
+Open tasks due today or overdue, or whose reminder has passed; one with a
+reminder still ahead is hidden, which is how a snooze works. The token is a
+Vikunja API token (read and update tasks) in ~/.config/deck-it/vikunja-token.
+"""
+
+import http.client
+import json
+import os
+import subprocess
+import threading
+import urllib.error
+import urllib.parse
+import urllib.request
+from datetime import datetime, timedelta, timezone
+from pathlib import Path
+
+from ..module import Module, ModuleError
+
+TOKEN = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / "deck-it" / "vikunja-token"
+POLL = 60
+SNOOZE = timedelta(minutes=30)
+FILTER = "done = false && (due_date < now/d+1d || reminders < now)"
+
+
+def _http(method, url, token, data=None):
+ h = {"Accept": "application/json"}
+ if token:
+ h["Authorization"] = f"Bearer {token}"
+ body = None
+ if data is not None:
+ body, h["Content-Type"] = json.dumps(data).encode(), "application/merge-patch+json"
+ try:
+ with urllib.request.urlopen(urllib.request.Request(url, body, h, method=method), timeout=10) as r:
+ raw = r.read()
+ except urllib.error.HTTPError as e:
+ raise OSError(f"HTTP {e.code}") from None
+ except http.client.HTTPException as e:
+ raise OSError(str(e) or type(e).__name__) from None
+ return json.loads(raw) if raw else {}
+
+
+def _popen(cmd):
+ subprocess.Popen(cmd, start_new_session=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+
+
+def _time(s):
+ """A Vikunja time, or None for its year-one 'unset'."""
+ if not s or s.startswith("0001-"):
+ return None
+ return datetime.fromisoformat(s.replace("Z", "+00:00"))
+
+
+def _iso(t):
+ return t.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def pick(tasks, now):
+ """The tasks to show, overdue first, then by due date, reminder-only last."""
+ out = []
+ for t in tasks:
+ if any((r := _time(x.get("reminder"))) and r > now for x in t.get("reminders") or []):
+ continue # snoozed, or reminded later on purpose
+ due = _time(t.get("due_date"))
+ out.append((due is None, due or now, {"id": t["id"], "title": t.get("title", ""),
+ "due": _iso(due) if due else None}))
+ out.sort(key=lambda x: x[:2])
+ return [x[2] for x in out]
+
+
+class Todo:
+ def __init__(self, cfg: dict):
+ self.url = cfg.get("todo", {}).get("url", "").rstrip("/")
+ self.http = cfg.get("http", _http)
+ self.popen = cfg.get("popen", _popen)
+ self.token_path = Path(cfg.get("token", TOKEN))
+ self.now = cfg.get("now", lambda: datetime.now(timezone.utc))
+ self.front = None
+ self.st = {"tasks": [], "error": None}
+ self.wake, self.stopping = threading.Event(), False
+ self.actions = {"open": self._open, "done": self._done, "snooze": self._snooze} if self.url else {}
+
+ def _call(self, method, path, data=None):
+ token = self.token_path.read_text().strip()
+ return self.http(method, self.url + path, token, data)
+
+ def refresh(self):
+ try:
+ if self.front is None:
+ self.front = self.http("GET", self.url + "/api/v1/info", "").get("frontend_url", "")
+ items = self._call("GET", "/api/v2/tasks?" + urllib.parse.urlencode(
+ {"filter": FILTER, "per_page": 50})).get("items") or []
+ self.st = {"tasks": pick(items, self.now()), "error": None}
+ except (OSError, ValueError) as e:
+ self.st = {"tasks": [], "error": str(e) or type(e).__name__}
+
+ def state(self):
+ return self.st
+
+ def _id(self, body):
+ i = body.get("id")
+ if not any(t["id"] == i for t in self.st["tasks"]):
+ raise ModuleError("not a listed task")
+ return i
+
+ def _write(self, fn):
+ try:
+ fn()
+ except (OSError, ValueError) as e:
+ raise ModuleError(str(e) or type(e).__name__) from e
+
+ def _open(self, body):
+ i = self._id(body)
+ base = (self.front or self.url).rstrip("/")
+ self._write(lambda: self.popen(["xdg-open", f"{base}/tasks/{i}"]))
+
+ def _done(self, body):
+ i = self._id(body)
+ self._write(lambda: self._call("PATCH", f"/api/v2/tasks/{i}", {"done": True}))
+ self.refresh() # the page reads the new list as soon as the action answers
+
+ def _snooze(self, body):
+ i = self._id(body)
+
+ def go():
+ old = self._call("GET", f"/api/v2/tasks/{i}").get("reminders") or []
+ self._call("PATCH", f"/api/v2/tasks/{i}",
+ {"reminders": old + [{"reminder": _iso(self.now() + SNOOZE)}]})
+ self._write(go)
+ self.refresh()
+
+ def run(self):
+ while not self.stopping:
+ self.refresh()
+ self.wake.wait(POLL)
+ self.wake.clear()
+
+ def start(self):
+ if self.url:
+ threading.Thread(target=self.run, daemon=True).start()
+
+ def stop(self):
+ self.stopping = True
+ self.wake.set()
+
+
+def make(cfg: dict) -> Module:
+ t = Todo(cfg)
+ return Module(name="todo", title="Todo", state=t.state, actions=t.actions, start=t.start, stop=t.stop)