tui-trello 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. tui_trello/__init__.py +3 -0
  2. tui_trello/__main__.py +3 -0
  3. tui_trello/agenda.py +36 -0
  4. tui_trello/auth.py +308 -0
  5. tui_trello/backend/__init__.py +107 -0
  6. tui_trello/backend/demo.py +540 -0
  7. tui_trello/backend/trello.py +276 -0
  8. tui_trello/cli.py +141 -0
  9. tui_trello/config.py +123 -0
  10. tui_trello/drafts.py +105 -0
  11. tui_trello/emoji.py +37 -0
  12. tui_trello/emoji_codes.py +1998 -0
  13. tui_trello/files.py +9 -0
  14. tui_trello/links.py +56 -0
  15. tui_trello/mentions.py +35 -0
  16. tui_trello/models.py +426 -0
  17. tui_trello/prefs.py +69 -0
  18. tui_trello/query.py +64 -0
  19. tui_trello/quote.py +54 -0
  20. tui_trello/remote.py +178 -0
  21. tui_trello/store.py +555 -0
  22. tui_trello/ui/__init__.py +0 -0
  23. tui_trello/ui/app.py +420 -0
  24. tui_trello/ui/bidi.py +312 -0
  25. tui_trello/ui/clipboard.py +41 -0
  26. tui_trello/ui/commands.py +61 -0
  27. tui_trello/ui/desktop.py +56 -0
  28. tui_trello/ui/follow.py +159 -0
  29. tui_trello/ui/keymap.py +526 -0
  30. tui_trello/ui/keys_compat.py +32 -0
  31. tui_trello/ui/markdown.py +284 -0
  32. tui_trello/ui/render.py +128 -0
  33. tui_trello/ui/screens/__init__.py +0 -0
  34. tui_trello/ui/screens/base.py +581 -0
  35. tui_trello/ui/screens/browser.py +200 -0
  36. tui_trello/ui/screens/card.py +67 -0
  37. tui_trello/ui/screens/keys.py +168 -0
  38. tui_trello/ui/screens/mywork.py +194 -0
  39. tui_trello/ui/screens/news.py +67 -0
  40. tui_trello/ui/screens/notifications.py +215 -0
  41. tui_trello/ui/screens/picker.py +791 -0
  42. tui_trello/ui/screens/preview.py +209 -0
  43. tui_trello/ui/screens/search.py +113 -0
  44. tui_trello/ui/screens/triage.py +135 -0
  45. tui_trello/ui/tips.py +40 -0
  46. tui_trello/ui/widgets/__init__.py +0 -0
  47. tui_trello/ui/widgets/bell.py +24 -0
  48. tui_trello/ui/widgets/card_view.py +340 -0
  49. tui_trello/ui/widgets/news_badge.py +27 -0
  50. tui_trello/ui/widgets/spinner.py +40 -0
  51. tui_trello-0.1.0.dist-info/METADATA +514 -0
  52. tui_trello-0.1.0.dist-info/RECORD +55 -0
  53. tui_trello-0.1.0.dist-info/WHEEL +4 -0
  54. tui_trello-0.1.0.dist-info/entry_points.txt +2 -0
  55. tui_trello-0.1.0.dist-info/licenses/LICENSE +21 -0
tui_trello/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """A keyboard-first terminal client for Trello."""
2
+
3
+ __version__ = "0.1.0"
tui_trello/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from tui_trello.cli import main
2
+
3
+ main()
tui_trello/agenda.py ADDED
@@ -0,0 +1,36 @@
1
+ """Group cards by when they're due, for the My work view."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import datetime, timedelta
6
+
7
+ from tui_trello.models import Card
8
+
9
+ GROUPS = ("Overdue", "Today", "This week", "Later", "No due date", "Done")
10
+
11
+
12
+ def group_of(card: Card, now: datetime) -> str:
13
+ if card.due_complete:
14
+ return "Done"
15
+ if card.due is None:
16
+ return "No due date"
17
+ due = card.due.astimezone(now.tzinfo).date()
18
+ today = now.date()
19
+ if card.due < now and due < today:
20
+ return "Overdue"
21
+ if due <= today:
22
+ return "Today"
23
+ if due < today + timedelta(days=7):
24
+ return "This week"
25
+ return "Later"
26
+
27
+
28
+ def agenda(cards: list[Card], now: datetime) -> list[tuple[str, list[Card]]]:
29
+ """Non-empty groups in GROUPS order, each sorted by due date, then name."""
30
+ groups: dict[str, list[Card]] = {name: [] for name in GROUPS}
31
+ for card in cards:
32
+ groups[group_of(card, now)].append(card)
33
+ return [
34
+ (name, sorted(group, key=lambda c: (c.due or now, c.name.lower())))
35
+ for name, group in groups.items() if group
36
+ ]
tui_trello/auth.py ADDED
@@ -0,0 +1,308 @@
1
+ """Trello authorisation: browser login, saved credentials, and httpx auth for API requests.
2
+
3
+ `tui-trello login` uses OAuth 2.0 with PKCE
4
+ (https://developer.atlassian.com/cloud/trello/guides/rest-api/oauth-2-getting-started/): it opens Atlassian's consent
5
+ page, which redirects to a one-shot server on 127.0.0.1 with a code; the code is swapped for an access token (1 hour)
6
+ and a refresh token (90 days, single use). `OAuth2Auth` sends the access token as a bearer token and refreshes it,
7
+ saving each new pair, so users log in once. tui-trello's OAuth client is public: no secret is involved.
8
+
9
+ The tokens are saved to `credentials.json` (mode 600) next to the config file.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import asyncio
15
+ import base64
16
+ import hashlib
17
+ import json
18
+ import os
19
+ import secrets
20
+ import tempfile
21
+ import time
22
+ import webbrowser
23
+ from collections.abc import AsyncGenerator, Callable, Generator
24
+ from dataclasses import asdict, dataclass
25
+ from pathlib import Path
26
+ from typing import Any
27
+ from urllib.parse import parse_qsl, urlencode, urlsplit
28
+
29
+ import httpx
30
+
31
+ from tui_trello.backend import BackendError
32
+ from tui_trello.config import config_path
33
+
34
+ # tui-trello's OAuth 2.0 client, on https://trello.com/power-ups/admin. Its callback URLs must include
35
+ # http://127.0.0.1:<oauth_port>/callback and its scopes must include SCOPES.
36
+ OAUTH_CLIENT_ID = "gGrXO7ZLRFrZ00UM9irqMjhBGAhIByaI"
37
+ OAUTH_AUTHORIZE_URL = "https://auth.atlassian.com/authorize"
38
+ OAUTH_TOKEN_URL = "https://auth.atlassian.com/oauth/token"
39
+ # write:member:trello is for marking notifications read: Trello refuses that with the board scopes alone, even
40
+ # through POST /cards/{id}/markAssociatedNotificationsRead, which its API reference says they cover.
41
+ SCOPES = "read:member:trello write:member:trello read:board:trello write:board:trello offline_access"
42
+
43
+ LOGIN_TIMEOUT = 300 # seconds to wait for the user to approve in the browser
44
+ REQUEST_LINE_TIMEOUT = 10 # seconds a connection to the callback server may take to send its request line
45
+ REFRESH_MARGIN = 60 # refresh this many seconds before the access token expires
46
+ DONE = "Logged in to Trello. You can close this tab and go back to the terminal."
47
+ RETIRED_LOGIN = ("Your saved Trello login used a login method tui-trello no longer supports (a pasted token). "
48
+ "Log in again in the browser: tui-trello login. Starting it now.")
49
+
50
+
51
+ class LoginError(Exception):
52
+ pass
53
+
54
+
55
+ # -- credentials -------------------------------------------------------------------------------------------------
56
+
57
+
58
+ @dataclass(frozen=True)
59
+ class OAuth2Tokens:
60
+ access_token: str
61
+ refresh_token: str
62
+ expires_at: float # unix time
63
+
64
+ @property
65
+ def expiring(self) -> bool:
66
+ return time.time() > self.expires_at - REFRESH_MARGIN
67
+
68
+ @classmethod
69
+ def from_response(cls, data: dict[str, Any], refresh_token: str = "") -> OAuth2Tokens:
70
+ """`refresh_token` is the one to keep if the response doesn't rotate it."""
71
+ return cls(data["access_token"], data.get("refresh_token") or refresh_token,
72
+ time.time() + int(data.get("expires_in", 3600)))
73
+
74
+
75
+ def credentials_path() -> Path:
76
+ return config_path().with_name("credentials.json")
77
+
78
+
79
+ def load_credentials(path: Path | None = None) -> OAuth2Tokens | None:
80
+ """The saved login, or None if there is none or the file is unreadable (the user logs in again)."""
81
+ path = path or credentials_path()
82
+ try:
83
+ data = json.loads(path.read_text())
84
+ return OAuth2Tokens(data["access_token"], data["refresh_token"], float(data["expires_at"]))
85
+ except (OSError, ValueError, KeyError, TypeError, AttributeError): # missing, corrupt, or not an OAuth login
86
+ return None
87
+
88
+
89
+ def retired_login(path: Path | None = None) -> bool:
90
+ """True if the saved file is a pasted-token login from before tui-trello logged in with OAuth only."""
91
+ path = path or credentials_path()
92
+ try:
93
+ data = json.loads(path.read_text())
94
+ return bool(data.get("token")) and "access_token" not in data
95
+ except (OSError, ValueError, AttributeError):
96
+ return False
97
+
98
+
99
+ def save_credentials(credentials: OAuth2Tokens, path: Path | None = None) -> Path:
100
+ """Write the credentials readable only by the user, atomically: a refresh token is single use, so a half-written
101
+ file would mean logging in again."""
102
+ path = path or credentials_path()
103
+ path.parent.mkdir(parents=True, exist_ok=True)
104
+ fd, temporary = tempfile.mkstemp(dir=path.parent, prefix=".credentials-") # mkstemp makes it mode 600
105
+ try:
106
+ with os.fdopen(fd, "w") as f:
107
+ json.dump(asdict(credentials), f)
108
+ f.flush()
109
+ os.fsync(f.fileno())
110
+ os.replace(temporary, path)
111
+ except BaseException:
112
+ os.unlink(temporary)
113
+ raise
114
+ return path
115
+
116
+
117
+ def delete_credentials(path: Path | None = None) -> bool:
118
+ path = path or credentials_path()
119
+ if path.exists():
120
+ path.unlink()
121
+ return True
122
+ return False
123
+
124
+
125
+ # -- request authentication --------------------------------------------------------------------------------------
126
+
127
+
128
+ class OAuth2Auth(httpx.Auth):
129
+ """Bearer token auth that refreshes the access token when it is about to expire, or is rejected.
130
+
131
+ Refresh tokens are single use and the backend sends requests concurrently, so refreshing happens under a lock,
132
+ and a request that waited for the lock re-checks whether another one has already refreshed.
133
+
134
+ Trello also answers 401 for things the user may not see (a board they were removed from), so a 401 refreshes at
135
+ most once per access token: if the fresh token is refused too, the 401 goes back to the caller.
136
+
137
+ Overriding `async_auth_flow` skips httpx's own reading of the flow's responses (`requires_response_body`), so the
138
+ token responses are read here.
139
+ """
140
+
141
+ def __init__(self, tokens: OAuth2Tokens, *, client_id: str = OAUTH_CLIENT_ID,
142
+ on_refresh: Callable[[OAuth2Tokens], object] = save_credentials) -> None:
143
+ self.tokens = tokens
144
+ self.client_id = client_id
145
+ self.on_refresh = on_refresh
146
+ self._lock = asyncio.Lock()
147
+ self._refreshed_for_401: OAuth2Tokens | None = None # the tokens a 401 last refreshed to
148
+
149
+ def sync_auth_flow(self, request: httpx.Request) -> Generator[httpx.Request, httpx.Response, None]:
150
+ raise RuntimeError("OAuth2Auth only supports httpx.AsyncClient")
151
+
152
+ async def async_auth_flow(self, request: httpx.Request) -> AsyncGenerator[httpx.Request, httpx.Response]:
153
+ if self.tokens.expiring:
154
+ async with self._lock:
155
+ if self.tokens.expiring:
156
+ await self._refreshed((yield self._refresh_request()))
157
+ used = self.tokens
158
+ request.headers["Authorization"] = f"Bearer {used.access_token}"
159
+ response = yield request
160
+ if response.status_code == 401 and used is not self._refreshed_for_401:
161
+ async with self._lock:
162
+ if self.tokens is used: # nobody refreshed while we waited for the lock
163
+ await self._refreshed((yield self._refresh_request()))
164
+ self._refreshed_for_401 = self.tokens
165
+ request.headers["Authorization"] = f"Bearer {self.tokens.access_token}"
166
+ yield request
167
+
168
+ def _refresh_request(self) -> httpx.Request:
169
+ return httpx.Request("POST", OAUTH_TOKEN_URL, json={
170
+ "grant_type": "refresh_token",
171
+ "client_id": self.client_id,
172
+ "refresh_token": self.tokens.refresh_token,
173
+ })
174
+
175
+ async def _refreshed(self, response: httpx.Response) -> None:
176
+ await response.aread()
177
+ if response.is_error:
178
+ raise BackendError("Your Trello login has expired or was revoked. Run `tui-trello login` again.")
179
+ try:
180
+ self.tokens = OAuth2Tokens.from_response(response.json(), self.tokens.refresh_token)
181
+ except (ValueError, KeyError) as exc:
182
+ raise BackendError(f"Unexpected reply when renewing the Trello login: {response.text[:200]}") from exc
183
+ self.on_refresh(self.tokens)
184
+
185
+
186
+ async def whoami(auth: httpx.Auth, transport: httpx.AsyncBaseTransport | None = None) -> str:
187
+ """Check credentials work; returns the member's name."""
188
+ from tui_trello.backend.trello import TrelloBackend
189
+
190
+ backend = TrelloBackend(auth, transport=transport)
191
+ try:
192
+ member = await backend.me()
193
+ except BackendError as exc:
194
+ raise LoginError(str(exc)) from exc
195
+ finally:
196
+ await backend.aclose()
197
+ return f"{member.full_name} (@{member.username})"
198
+
199
+
200
+ # -- OAuth 2.0 login ---------------------------------------------------------------------------------------------
201
+
202
+
203
+ def pkce_pair() -> tuple[str, str]:
204
+ verifier = secrets.token_urlsafe(64)
205
+ challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip(b"=").decode()
206
+ return verifier, challenge
207
+
208
+
209
+ async def _await_callback(port: int, state: str, open_url: Callable[[], object]) -> str:
210
+ """Serve http://127.0.0.1:port/callback until it is hit with our state; return the authorisation code."""
211
+ received: asyncio.Future[str] = asyncio.get_running_loop().create_future()
212
+
213
+ def respond(path: str, query: dict[str, str]) -> tuple[str, str]:
214
+ if path != "/callback":
215
+ return "404 Not Found", "Not found."
216
+ if received.done():
217
+ return "200 OK", DONE
218
+ if query.get("state") != state:
219
+ return "400 Bad Request", "This login link is stale; go back to the terminal and try again."
220
+ if "error" in query:
221
+ message = query.get("error_description") or query["error"]
222
+ received.set_exception(LoginError(f"Trello said: {message}"))
223
+ return "200 OK", f"Login failed: {message}. Go back to the terminal."
224
+ if "code" not in query:
225
+ return "400 Bad Request", "No authorisation code in the callback."
226
+ received.set_result(query["code"])
227
+ return "200 OK", DONE
228
+
229
+ connections: set[asyncio.StreamWriter] = set()
230
+
231
+ async def handle(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
232
+ # Browsers open spare connections that may never send a request; don't wait on those for ever.
233
+ connections.add(writer)
234
+ try:
235
+ request_line = (await asyncio.wait_for(reader.readline(), REQUEST_LINE_TIMEOUT)).decode(errors="replace")
236
+ target = urlsplit(request_line.split(" ")[1] if request_line.count(" ") >= 2 else "/")
237
+ status, body = respond(target.path, dict(parse_qsl(target.query)))
238
+ payload = body.encode()
239
+ writer.write(f"HTTP/1.1 {status}\r\nContent-Type: text/plain; charset=utf-8\r\n"
240
+ f"Content-Length: {len(payload)}\r\nConnection: close\r\n\r\n".encode() + payload)
241
+ await writer.drain()
242
+ except (TimeoutError, ConnectionError):
243
+ pass
244
+ finally:
245
+ writer.close()
246
+ connections.discard(writer)
247
+
248
+ try:
249
+ server = await asyncio.start_server(handle, "127.0.0.1", port)
250
+ except OSError as exc:
251
+ raise LoginError(f"Could not listen on port {port} for the login callback: {exc}") from exc
252
+ try:
253
+ open_url()
254
+ return await asyncio.wait_for(received, LOGIN_TIMEOUT)
255
+ except TimeoutError:
256
+ raise LoginError("Timed out waiting for you to approve in the browser. If Atlassian showed an error about the "
257
+ f"redirect URL, add http://127.0.0.1:{port}/callback to the app's callback URLs.") from None
258
+ finally:
259
+ server.close()
260
+ for writer in list(connections): # wait_closed() waits for open connections too
261
+ writer.close()
262
+ await server.wait_closed()
263
+
264
+
265
+ async def login_oauth2(
266
+ *,
267
+ port: int,
268
+ client_id: str = OAUTH_CLIENT_ID,
269
+ open_browser: Callable[[str], object] | None = None,
270
+ echo: Callable[[str], object] = print,
271
+ transport: httpx.AsyncBaseTransport | None = None,
272
+ ) -> OAuth2Tokens:
273
+ redirect_uri = f"http://127.0.0.1:{port}/callback"
274
+ verifier, challenge = pkce_pair()
275
+ state = secrets.token_urlsafe(16)
276
+ url = f"{OAUTH_AUTHORIZE_URL}?" + urlencode({
277
+ "client_id": client_id,
278
+ "scope": SCOPES,
279
+ "redirect_uri": redirect_uri,
280
+ "response_type": "code",
281
+ "prompt": "consent",
282
+ "state": state,
283
+ "code_challenge": challenge,
284
+ "code_challenge_method": "S256",
285
+ })
286
+
287
+ def open_url() -> None:
288
+ echo(f"Opening Trello in your browser. Click Accept.\nIf the browser doesn't open, visit:\n {url}\n")
289
+ (open_browser or webbrowser.open)(url) # looked up now, so tests can patch it
290
+
291
+ code = await _await_callback(port, state, open_url)
292
+ try:
293
+ async with httpx.AsyncClient(timeout=20, transport=transport) as http:
294
+ response = await http.post(OAUTH_TOKEN_URL, json={
295
+ "grant_type": "authorization_code",
296
+ "client_id": client_id,
297
+ "code": code,
298
+ "redirect_uri": redirect_uri,
299
+ "code_verifier": verifier,
300
+ })
301
+ except httpx.HTTPError as exc:
302
+ raise LoginError(f"Could not reach Atlassian to finish logging in: {exc}") from exc
303
+ if response.is_error:
304
+ raise LoginError(f"Could not exchange the code for a token ({response.status_code}): {response.text[:200]}")
305
+ try:
306
+ return OAuth2Tokens.from_response(response.json())
307
+ except (ValueError, KeyError) as exc:
308
+ raise LoginError(f"Unexpected reply from Atlassian: {response.text[:200]}") from exc
@@ -0,0 +1,107 @@
1
+ """Data backends.
2
+
3
+ A backend is anything that implements :class:`Backend`. Screens never talk to a backend directly; they go through
4
+ :class:`tui_trello.store.Store`, which caches board snapshots and broadcasts changes.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from pathlib import Path
10
+ from typing import Protocol
11
+
12
+ from tui_trello.models import (
13
+ Attachment,
14
+ Board,
15
+ BoardSnapshot,
16
+ Card,
17
+ CardPreview,
18
+ CheckItem,
19
+ Checklist,
20
+ Comment,
21
+ Label,
22
+ Member,
23
+ Notification,
24
+ Reaction,
25
+ WorkSnapshot,
26
+ )
27
+
28
+
29
+ class BackendError(Exception):
30
+ """A backend call failed; the message is fit to show the user. `unsure` if the request may have reached the
31
+ service and done its work all the same (a timeout or dropped connection after sending, a gateway error)."""
32
+
33
+ def __init__(self, message: str, *, unsure: bool = False) -> None:
34
+ super().__init__(message)
35
+ self.unsure = unsure
36
+
37
+
38
+ class Backend(Protocol):
39
+ async def me(self) -> Member: ...
40
+
41
+ async def boards(self) -> list[Board]: ...
42
+
43
+ async def board_snapshot(self, board_id: str) -> BoardSnapshot: ...
44
+
45
+ async def card(self, card_id: str) -> Card: ... # an id or a short link
46
+
47
+ async def board(self, board_id: str) -> Board: ... # likewise
48
+
49
+ async def card_preview(self, card_id: str) -> CardPreview: ... # likewise; archived cards too
50
+
51
+ async def my_work(self) -> WorkSnapshot: ...
52
+
53
+ async def comments(self, card_id: str) -> list[Comment]: ...
54
+
55
+ async def move_card(self, card: Card, list_id: str, pos: str = "top") -> Card: ...
56
+
57
+ async def create_card(self, list_id: str, name: str, desc: str = "", *, pos: str = "bottom") -> Card: ...
58
+
59
+ async def archive_card(self, card: Card) -> Card: ... # the card as Trello now has it, `closed`
60
+
61
+ async def delete_card(self, card_id: str) -> None: ... # for good
62
+
63
+ async def add_comment(self, card_id: str, text: str) -> Comment: ...
64
+
65
+ async def edit_comment(self, card_id: str, comment_id: str, text: str) -> None: ...
66
+
67
+ async def delete_comment(self, card_id: str, comment_id: str) -> None: ...
68
+
69
+ async def search_cards(self, query: str) -> list[CardPreview]: ... # open and archived cards, every board
70
+
71
+ async def set_description(self, card: Card, desc: str) -> Card: ...
72
+
73
+ async def add_reaction(self, comment_id: str, short_name: str) -> Reaction: ...
74
+
75
+ async def remove_reaction(self, comment_id: str, reaction_id: str) -> None: ...
76
+
77
+ async def labels(self, board_id: str) -> list[Label]: ...
78
+
79
+ async def members(self, board_id: str) -> list[Member]: ...
80
+
81
+ async def add_label(self, card: Card, label: Label) -> Card: ...
82
+
83
+ async def remove_label(self, card: Card, label: Label) -> Card: ...
84
+
85
+ async def create_label(self, board_id: str, name: str, color: str | None) -> Label: ...
86
+
87
+ async def checklists(self, card_id: str) -> list[Checklist]: ...
88
+
89
+ async def set_check_item(self, card_id: str, item: CheckItem, checked: bool) -> CheckItem: ...
90
+
91
+ async def add_check_item(self, checklist_id: str, name: str) -> CheckItem: ...
92
+
93
+ async def create_checklist(self, card_id: str, name: str) -> Checklist: ...
94
+
95
+ async def attachments(self, card_id: str) -> list[Attachment]: ...
96
+
97
+ async def attach_file(self, card_id: str, path: Path) -> Attachment: ...
98
+
99
+ async def attach_link(self, card_id: str, url: str, name: str = "") -> Attachment: ...
100
+
101
+ async def notifications(self) -> list[Notification]: ...
102
+
103
+ async def mark_notifications_read(self, ids: list[str]) -> None: ...
104
+
105
+ async def mark_all_notifications_read(self) -> None: ...
106
+
107
+ async def aclose(self) -> None: ...