aboutsummaryrefslogtreecommitdiffstats
path: root/deckit/modules/todo.py
blob: 8ce673d26f06b0738a171ba3b45b16a5353bcd8b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# 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 pass, entry [todo] pass, read
once and kept in memory until Vikunja refuses it.
"""

import http.client
import json
import subprocess
import threading
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime, timedelta, timezone

from ..module import Module, ModuleError

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 _pass(entry):
    """The first line of a pass entry. gpg may ask for the PIN the first time."""
    try:
        out = subprocess.run(["pass", "show", entry], capture_output=True, text=True, timeout=120)
    except subprocess.TimeoutExpired:
        raise OSError("pass timed out") from None
    if out.returncode:
        raise OSError(f"pass show {entry} failed")
    return out.stdout.partition("\n")[0].strip()


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):
        tcfg = cfg.get("todo", {})
        self.url = tcfg.get("url", "").rstrip("/")
        self.entry = tcfg.get("pass", "")
        self.http = cfg.get("http", _http)
        self.popen = cfg.get("popen", _popen)
        self.pass_ = cfg.get("pass", _pass)
        self.token = None
        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):
        if not self.entry:
            raise OSError("no [todo] pass entry for the token")
        if self.token is None:
            self.token = self.pass_(self.entry)
        try:
            return self.http(method, self.url + path, self.token, data)
        except OSError as e:
            if str(e) == "HTTP 401":
                self.token = None   # revoked or replaced: read pass again next time
            raise

    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)