glimsy 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.
- glimsy/__init__.py +90 -0
- glimsy/_api/__init__.py +1 -0
- glimsy/_api/calls.py +235 -0
- glimsy/_api/change_calls.py +37 -0
- glimsy/_api/media_files.py +84 -0
- glimsy/_api/parse.py +175 -0
- glimsy/_auth/__init__.py +6 -0
- glimsy/_auth/api_key.py +54 -0
- glimsy/_auth/sources.py +63 -0
- glimsy/_client.py +213 -0
- glimsy/_error_mapping.py +168 -0
- glimsy/_transport/__init__.py +17 -0
- glimsy/_transport/async_transport.py +113 -0
- glimsy/_transport/base_url.py +64 -0
- glimsy/_transport/core.py +112 -0
- glimsy/_transport/cycle.py +77 -0
- glimsy/_transport/rate_limit.py +85 -0
- glimsy/_transport/retry.py +115 -0
- glimsy/_transport/settings.py +74 -0
- glimsy/_transport/sync_transport.py +112 -0
- glimsy/_transport/throttle.py +64 -0
- glimsy/errors.py +212 -0
- glimsy/local/__init__.py +1 -0
- glimsy/local/hebrew.py +35 -0
- glimsy/local/html_fields.py +91 -0
- glimsy/local/query/__init__.py +15 -0
- glimsy/local/query/fields.py +61 -0
- glimsy/local/query/lookups.py +95 -0
- glimsy/local/query/q.py +78 -0
- glimsy/local/query/values.py +29 -0
- glimsy/local/read_only_sql.py +43 -0
- glimsy/local/schema.py +88 -0
- glimsy/local/sqlite_functions.py +64 -0
- glimsy/local/store.py +133 -0
- glimsy/models/__init__.py +31 -0
- glimsy/models/card.py +106 -0
- glimsy/models/changes.py +81 -0
- glimsy/models/inputs.py +48 -0
- glimsy/models/results.py +146 -0
- glimsy/py.typed +0 -0
- glimsy/resources/__init__.py +16 -0
- glimsy/resources/aio.py +262 -0
- glimsy/resources/changes.py +113 -0
- glimsy/resources/sync.py +259 -0
- glimsy-0.1.0.dist-info/METADATA +231 -0
- glimsy-0.1.0.dist-info/RECORD +48 -0
- glimsy-0.1.0.dist-info/WHEEL +4 -0
- glimsy-0.1.0.dist-info/licenses/LICENSE +202 -0
glimsy/__init__.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""Official Python library for managing your own Glimsy flashcards."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import version as _version
|
|
4
|
+
|
|
5
|
+
from glimsy._client import AsyncClient, Client
|
|
6
|
+
from glimsy._transport import RetryPolicy
|
|
7
|
+
from glimsy.errors import (
|
|
8
|
+
ApiBlockedError,
|
|
9
|
+
APIError,
|
|
10
|
+
AuthenticationError,
|
|
11
|
+
ConfigurationError,
|
|
12
|
+
ConflictError,
|
|
13
|
+
DailyLimitError,
|
|
14
|
+
EditsUnavailableError,
|
|
15
|
+
GlimsyError,
|
|
16
|
+
InvalidApiKeyError,
|
|
17
|
+
KeyExpiredError,
|
|
18
|
+
KeyRevokedError,
|
|
19
|
+
MissingApiKeyError,
|
|
20
|
+
NetworkError,
|
|
21
|
+
NotFoundError,
|
|
22
|
+
PartialBatchError,
|
|
23
|
+
PermissionDeniedError,
|
|
24
|
+
PlanLimitError,
|
|
25
|
+
RateLimitError,
|
|
26
|
+
ServerError,
|
|
27
|
+
ValidationError,
|
|
28
|
+
)
|
|
29
|
+
from glimsy.models import (
|
|
30
|
+
Account,
|
|
31
|
+
BatchRestore,
|
|
32
|
+
Candidate,
|
|
33
|
+
Card,
|
|
34
|
+
Change,
|
|
35
|
+
ChangeRestore,
|
|
36
|
+
Deck,
|
|
37
|
+
DeckTheme,
|
|
38
|
+
Direction,
|
|
39
|
+
ItemError,
|
|
40
|
+
ItemResult,
|
|
41
|
+
Match,
|
|
42
|
+
MediaRef,
|
|
43
|
+
RestoreItem,
|
|
44
|
+
)
|
|
45
|
+
from glimsy.models.inputs import CardEdit, NewCard
|
|
46
|
+
|
|
47
|
+
__version__ = _version("glimsy")
|
|
48
|
+
|
|
49
|
+
__all__ = [
|
|
50
|
+
"APIError",
|
|
51
|
+
"Account",
|
|
52
|
+
"ApiBlockedError",
|
|
53
|
+
"AsyncClient",
|
|
54
|
+
"AuthenticationError",
|
|
55
|
+
"BatchRestore",
|
|
56
|
+
"Candidate",
|
|
57
|
+
"Card",
|
|
58
|
+
"CardEdit",
|
|
59
|
+
"Change",
|
|
60
|
+
"ChangeRestore",
|
|
61
|
+
"Client",
|
|
62
|
+
"ConfigurationError",
|
|
63
|
+
"ConflictError",
|
|
64
|
+
"DailyLimitError",
|
|
65
|
+
"Deck",
|
|
66
|
+
"DeckTheme",
|
|
67
|
+
"Direction",
|
|
68
|
+
"EditsUnavailableError",
|
|
69
|
+
"GlimsyError",
|
|
70
|
+
"InvalidApiKeyError",
|
|
71
|
+
"ItemError",
|
|
72
|
+
"ItemResult",
|
|
73
|
+
"KeyExpiredError",
|
|
74
|
+
"KeyRevokedError",
|
|
75
|
+
"Match",
|
|
76
|
+
"MediaRef",
|
|
77
|
+
"MissingApiKeyError",
|
|
78
|
+
"NetworkError",
|
|
79
|
+
"NewCard",
|
|
80
|
+
"NotFoundError",
|
|
81
|
+
"PartialBatchError",
|
|
82
|
+
"PermissionDeniedError",
|
|
83
|
+
"PlanLimitError",
|
|
84
|
+
"RateLimitError",
|
|
85
|
+
"RestoreItem",
|
|
86
|
+
"RetryPolicy",
|
|
87
|
+
"ServerError",
|
|
88
|
+
"ValidationError",
|
|
89
|
+
"__version__",
|
|
90
|
+
]
|
glimsy/_api/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""API calls as plain data (internal): built once, sent by the sync or the async client."""
|
glimsy/_api/calls.py
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
"""Builders of every API call (no I/O), shared by the sync and async resources.
|
|
2
|
+
|
|
3
|
+
Ids are checked before they become part of a path, so a crafted id can never point a request
|
|
4
|
+
at another endpoint. Batch sizes follow the contract; larger inputs are split by the caller.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
import uuid
|
|
11
|
+
from collections.abc import Iterable, Sequence
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
from glimsy.errors import GlimsyError, PartialBatchError
|
|
16
|
+
from glimsy.models.card import WIRE_DIRECTION
|
|
17
|
+
from glimsy.models.inputs import CardEdit, NewCard
|
|
18
|
+
from glimsy.models.results import Deck
|
|
19
|
+
|
|
20
|
+
MAX_BATCH = 100
|
|
21
|
+
MAX_MATCH_ITEMS = 200
|
|
22
|
+
MAX_MEDIA_CHECK = 200
|
|
23
|
+
MAX_PAGE_SIZE = 500
|
|
24
|
+
_ID = re.compile(r"[A-Za-z0-9_-]{1,128}")
|
|
25
|
+
# The server accepts [A-Za-z0-9_.:-]{8,128}; "." and the last 8 characters are reserved for
|
|
26
|
+
# the chunk suffix (".100", ".200", ...) added to one logical batch's key.
|
|
27
|
+
_IDEMPOTENCY_KEY = re.compile(r"[A-Za-z0-9_-]{8,120}")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True, slots=True)
|
|
31
|
+
class Call:
|
|
32
|
+
"""One HTTP call to the API.
|
|
33
|
+
|
|
34
|
+
``replay_safe`` marks a call that repeating can never apply twice: a read sent as POST
|
|
35
|
+
(match, search, media check) or a write the server deduplicates by ``Idempotency-Key``.
|
|
36
|
+
``None`` leaves the transport's default (reads yes, writes no).
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
method: str
|
|
40
|
+
path: str
|
|
41
|
+
json: Any = None
|
|
42
|
+
params: dict[str, str] | None = None
|
|
43
|
+
content: bytes | None = None
|
|
44
|
+
headers: dict[str, str] | None = None
|
|
45
|
+
idempotency_key: str | None = None
|
|
46
|
+
replay_safe: bool | None = None
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def path_id(value: Deck | str, what: str = "id") -> str:
|
|
50
|
+
"""Return a safe path segment for a deck or card id.
|
|
51
|
+
|
|
52
|
+
Raises:
|
|
53
|
+
ValueError: The id has characters no Glimsy id has.
|
|
54
|
+
"""
|
|
55
|
+
raw = value.id if isinstance(value, Deck) else value
|
|
56
|
+
if not isinstance(raw, str) or _ID.fullmatch(raw) is None:
|
|
57
|
+
msg = f"Not a valid Glimsy {what}: {str(raw)[:40]!r}"
|
|
58
|
+
raise ValueError(msg)
|
|
59
|
+
return raw
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def checked_key(value: str | None) -> str | None:
|
|
63
|
+
"""Return a key the server will accept (or ``None``).
|
|
64
|
+
|
|
65
|
+
Raises:
|
|
66
|
+
ValueError: The key is not 8-120 letters, digits, ``_`` or ``-``.
|
|
67
|
+
"""
|
|
68
|
+
if value is not None and _IDEMPOTENCY_KEY.fullmatch(value) is None:
|
|
69
|
+
msg = "idempotency_key must be 8-120 characters: letters, digits, '_' or '-'"
|
|
70
|
+
raise ValueError(msg)
|
|
71
|
+
return value
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def batch_key(value: str | None) -> str:
|
|
75
|
+
"""The key of one logical batch: yours, or a fresh one so a retry can resume it."""
|
|
76
|
+
return checked_key(value) or uuid.uuid4().hex
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def me() -> Call:
|
|
80
|
+
"""``GET /v1/me``."""
|
|
81
|
+
return Call("GET", "/v1/me")
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def list_decks() -> Call:
|
|
85
|
+
"""``GET /v1/decks``."""
|
|
86
|
+
return Call("GET", "/v1/decks")
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def create_deck(name: str, idempotency_key: str | None) -> Call:
|
|
90
|
+
"""``POST /v1/decks``."""
|
|
91
|
+
key = checked_key(idempotency_key)
|
|
92
|
+
return Call("POST", "/v1/decks", json={"name": name}, idempotency_key=key, replay_safe=True)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def rename_deck(deck: Deck | str, name: str) -> Call:
|
|
96
|
+
"""``PATCH /v1/decks/{id}``."""
|
|
97
|
+
return Call("PATCH", f"/v1/decks/{path_id(deck, 'deck id')}", json={"name": name})
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def get_theme(deck: Deck | str) -> Call:
|
|
101
|
+
"""``GET /v1/decks/{id}/theme``."""
|
|
102
|
+
return Call("GET", f"/v1/decks/{path_id(deck, 'deck id')}/theme")
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def set_theme_css(deck: Deck | str, css: str) -> Call:
|
|
106
|
+
"""``PUT /v1/decks/{id}/theme`` with your own stylesheet (the server checks it)."""
|
|
107
|
+
if not isinstance(css, str):
|
|
108
|
+
msg = "css must be a string"
|
|
109
|
+
raise TypeError(msg)
|
|
110
|
+
return Call("PUT", f"/v1/decks/{path_id(deck, 'deck id')}/theme", json={"css": css})
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def clear_theme(deck: Deck | str) -> Call:
|
|
114
|
+
"""``DELETE /v1/decks/{id}/theme``."""
|
|
115
|
+
return Call("DELETE", f"/v1/decks/{path_id(deck, 'deck id')}/theme")
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def list_cards(deck: Deck | str, page_size: int, page_token: str | None) -> Call:
|
|
119
|
+
"""``GET /v1/decks/{id}/cards`` (one page)."""
|
|
120
|
+
if not 1 <= page_size <= MAX_PAGE_SIZE:
|
|
121
|
+
msg = f"page_size must be between 1 and {MAX_PAGE_SIZE}"
|
|
122
|
+
raise ValueError(msg)
|
|
123
|
+
params = {"page_size": str(page_size)}
|
|
124
|
+
if page_token:
|
|
125
|
+
params["page_token"] = page_token
|
|
126
|
+
return Call("GET", f"/v1/decks/{path_id(deck, 'deck id')}/cards", params=params)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def batch_create(deck: Deck | str, items: Sequence[NewCard], idempotency_key: str | None) -> Call:
|
|
130
|
+
"""``POST /v1/decks/{id}/cards:batchCreate`` (at most ``MAX_BATCH`` items)."""
|
|
131
|
+
_check_size(items, MAX_BATCH)
|
|
132
|
+
body = {
|
|
133
|
+
"items": [
|
|
134
|
+
{"front": i.front, "back": i.back, "direction": WIRE_DIRECTION[i.direction]}
|
|
135
|
+
for i in items
|
|
136
|
+
]
|
|
137
|
+
}
|
|
138
|
+
path = f"/v1/decks/{path_id(deck, 'deck id')}/cards:batchCreate"
|
|
139
|
+
return Call("POST", path, json=body, idempotency_key=idempotency_key, replay_safe=True)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def batch_update(items: Sequence[CardEdit]) -> Call:
|
|
143
|
+
"""``POST /v1/cards:batchUpdate`` (at most ``MAX_BATCH`` items)."""
|
|
144
|
+
_check_size(items, MAX_BATCH)
|
|
145
|
+
body = {
|
|
146
|
+
"items": [
|
|
147
|
+
{
|
|
148
|
+
"deck_id": path_id(i.deck_id, "deck id"),
|
|
149
|
+
"card_id": path_id(i.card_id, "card id"),
|
|
150
|
+
"front": i.front,
|
|
151
|
+
"back": i.back,
|
|
152
|
+
}
|
|
153
|
+
for i in items
|
|
154
|
+
]
|
|
155
|
+
}
|
|
156
|
+
return Call("POST", "/v1/cards:batchUpdate", json=body)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def match(
|
|
160
|
+
items: Sequence[tuple[str, str]], deck_ids: Iterable[Deck | str] | None, limit: int
|
|
161
|
+
) -> Call:
|
|
162
|
+
"""``POST /v1/cards:match`` (at most ``MAX_MATCH_ITEMS`` items)."""
|
|
163
|
+
_check_size(items, MAX_MATCH_ITEMS)
|
|
164
|
+
body: dict[str, Any] = {"items": [{"front": f, "back": b} for f, b in items], "limit": limit}
|
|
165
|
+
if deck_ids is not None:
|
|
166
|
+
body["deck_ids"] = [path_id(d, "deck id") for d in deck_ids]
|
|
167
|
+
return Call("POST", "/v1/cards:match", json=body, replay_safe=True)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def search(query: str, deck_ids: Iterable[Deck | str] | None, limit: int) -> Call:
|
|
171
|
+
"""``POST /v1/cards:search``."""
|
|
172
|
+
body: dict[str, Any] = {"query": query, "limit": limit}
|
|
173
|
+
if deck_ids is not None:
|
|
174
|
+
body["deck_ids"] = [path_id(d, "deck id") for d in deck_ids]
|
|
175
|
+
return Call("POST", "/v1/cards:search", json=body, replay_safe=True)
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def media_check(hashes: Sequence[str]) -> Call:
|
|
179
|
+
"""``POST /v1/media:check`` (at most ``MAX_MEDIA_CHECK`` hashes)."""
|
|
180
|
+
_check_size(hashes, MAX_MEDIA_CHECK)
|
|
181
|
+
return Call("POST", "/v1/media:check", json={"hashes": list(hashes)}, replay_safe=True)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def media_upload(data: bytes, content_type: str, sha256: str) -> Call:
|
|
185
|
+
"""``POST /v1/media`` with the raw bytes."""
|
|
186
|
+
headers = {"Content-Type": content_type, "X-Glimsy-Sha256": sha256}
|
|
187
|
+
return Call("POST", "/v1/media", content=data, headers=headers)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def chunks(items: Sequence[Any], size: int) -> Iterable[tuple[int, Sequence[Any]]]:
|
|
191
|
+
"""Yield ``(offset, chunk)`` pairs of at most ``size`` items."""
|
|
192
|
+
for start in range(0, len(items), size):
|
|
193
|
+
yield start, items[start : start + size]
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def chunk_key(idempotency_key: str | None, offset: int) -> str | None:
|
|
197
|
+
"""A distinct, repeatable idempotency key for each chunk of one logical batch."""
|
|
198
|
+
if idempotency_key is None:
|
|
199
|
+
return None
|
|
200
|
+
checked_key(idempotency_key)
|
|
201
|
+
return idempotency_key if offset == 0 else f"{idempotency_key}.{offset}"
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def with_key(error: GlimsyError, key: str | None) -> GlimsyError:
|
|
205
|
+
"""Return ``error`` carrying the idempotency key of the failed write, so it can be resumed."""
|
|
206
|
+
error.idempotency_key = key
|
|
207
|
+
return error
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def partial(error: GlimsyError, completed: list[Any], key: str | None) -> GlimsyError:
|
|
211
|
+
"""The error to raise when a chunk fails, already chained to its cause.
|
|
212
|
+
|
|
213
|
+
When nothing was applied yet it is ``error`` itself, carrying ``key``; otherwise a
|
|
214
|
+
:class:`PartialBatchError` caused by ``error``. Raise it without ``from``: re-raising
|
|
215
|
+
``error`` with ``from error`` would replace its own cause (the network failure) by itself.
|
|
216
|
+
"""
|
|
217
|
+
if not completed:
|
|
218
|
+
return with_key(error, key)
|
|
219
|
+
done = len(completed)
|
|
220
|
+
message = (
|
|
221
|
+
f"The batch failed after {done} items were applied ({error}). Call again with the same "
|
|
222
|
+
"items and idempotency_key to resume."
|
|
223
|
+
if key
|
|
224
|
+
else f"The batch failed after {done} items were applied ({error})."
|
|
225
|
+
)
|
|
226
|
+
partial_error = PartialBatchError(message, completed=completed, idempotency_key=key)
|
|
227
|
+
partial_error.__cause__ = error
|
|
228
|
+
partial_error.__suppress_context__ = True
|
|
229
|
+
return partial_error
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _check_size(items: Sequence[Any], limit: int) -> None:
|
|
233
|
+
if not 1 <= len(items) <= limit:
|
|
234
|
+
msg = f"expected 1 to {limit} items, got {len(items)}"
|
|
235
|
+
raise ValueError(msg)
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Builders of the undo calls (no I/O): list changes, restore one, restore a whole request.
|
|
2
|
+
|
|
3
|
+
Restores are writes the server does not deduplicate (each restore is itself kept for undo), so
|
|
4
|
+
they are never marked replay-safe: the transport repeats them only after refusals made before
|
|
5
|
+
processing (HTTP 429, 503 ``rate_limiter_unavailable``).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from glimsy._api.calls import Call, path_id
|
|
11
|
+
from glimsy.models.changes import Change
|
|
12
|
+
|
|
13
|
+
MAX_CHANGES_PAGE = 200
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def list_changes(page_size: int, page_token: str | None) -> Call:
|
|
17
|
+
"""``GET /v1/changes`` (one page, newest first)."""
|
|
18
|
+
if not 1 <= page_size <= MAX_CHANGES_PAGE:
|
|
19
|
+
msg = f"page_size must be between 1 and {MAX_CHANGES_PAGE}"
|
|
20
|
+
raise ValueError(msg)
|
|
21
|
+
params = {"page_size": str(page_size)}
|
|
22
|
+
if page_token:
|
|
23
|
+
params["page_token"] = page_token
|
|
24
|
+
return Call("GET", "/v1/changes", params=params)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def restore(change: Change | str) -> Call:
|
|
28
|
+
"""``POST /v1/changes/{id}:restore`` (no body)."""
|
|
29
|
+
change_id = change.id if isinstance(change, Change) else change
|
|
30
|
+
return Call("POST", f"/v1/changes/{path_id(change_id, 'change id')}:restore")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def restore_batch(batch_id: str) -> Call:
|
|
34
|
+
"""``POST /v1/changes:restoreBatch``."""
|
|
35
|
+
return Call(
|
|
36
|
+
"POST", "/v1/changes:restoreBatch", json={"batch_id": path_id(batch_id, "batch id")}
|
|
37
|
+
)
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""Media files before upload: type from the file signature, SHA-256 and size limits.
|
|
2
|
+
|
|
3
|
+
The server checks the same things; checking here first saves an upload that would be refused.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import hashlib
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Literal
|
|
12
|
+
|
|
13
|
+
MAX_IMAGE_BYTES = 10 * 1024 * 1024
|
|
14
|
+
MAX_AUDIO_BYTES = 15 * 1024 * 1024
|
|
15
|
+
_RIFF_TYPE = slice(8, 12)
|
|
16
|
+
_FTYP = slice(4, 8)
|
|
17
|
+
_BRAND = slice(8, 12)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True, slots=True)
|
|
21
|
+
class MediaFile:
|
|
22
|
+
"""Bytes ready to upload."""
|
|
23
|
+
|
|
24
|
+
data: bytes
|
|
25
|
+
content_type: str
|
|
26
|
+
kind: Literal["image", "audio"]
|
|
27
|
+
sha256: str
|
|
28
|
+
|
|
29
|
+
@property
|
|
30
|
+
def src(self) -> str:
|
|
31
|
+
"""The address to put into card HTML."""
|
|
32
|
+
return f"glimsy://{self.kind}/{self.sha256}"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
_PREFIXES: tuple[tuple[bytes, str], ...] = (
|
|
36
|
+
(b"\x89PNG\r\n\x1a\n", "image/png"),
|
|
37
|
+
(b"\xff\xd8\xff", "image/jpeg"),
|
|
38
|
+
(b"GIF87a", "image/gif"),
|
|
39
|
+
(b"GIF89a", "image/gif"),
|
|
40
|
+
(b"OggS", "audio/ogg"),
|
|
41
|
+
(b"ID3", "audio/mpeg"),
|
|
42
|
+
)
|
|
43
|
+
_RIFF_KINDS = {b"WEBP": "image/webp", b"WAVE": "audio/wav"}
|
|
44
|
+
# ISO media "major brands" of audio files; HEIC photos and videos share the ftyp box.
|
|
45
|
+
_AUDIO_BRANDS = frozenset({b"M4A ", b"M4B ", b"mp42", b"isom", b"mp41", b"dash"})
|
|
46
|
+
_SYNC_BYTE = 0xFF
|
|
47
|
+
_FRAME_SYNC = 0xE0
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def sniff_content_type(data: bytes) -> str | None:
|
|
51
|
+
"""Return the media type the file signature shows, or ``None`` when unsupported."""
|
|
52
|
+
for prefix, mime in _PREFIXES:
|
|
53
|
+
if data.startswith(prefix):
|
|
54
|
+
return mime
|
|
55
|
+
if len(data) > 1 and data[0] == _SYNC_BYTE and data[1] & _FRAME_SYNC == _FRAME_SYNC:
|
|
56
|
+
return "audio/mpeg" # an MPEG audio frame: 11 sync bits
|
|
57
|
+
if data.startswith(b"RIFF"):
|
|
58
|
+
return _RIFF_KINDS.get(data[_RIFF_TYPE])
|
|
59
|
+
if data[_FTYP] == b"ftyp" and data[_BRAND] in _AUDIO_BRANDS:
|
|
60
|
+
return "audio/mp4"
|
|
61
|
+
return None
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def prepare_media(source: bytes | str | Path, content_type: str | None = None) -> MediaFile:
|
|
65
|
+
"""Read and check one file.
|
|
66
|
+
|
|
67
|
+
Raises:
|
|
68
|
+
ValueError: Unsupported type, or the file is larger than the API accepts.
|
|
69
|
+
"""
|
|
70
|
+
data = source if isinstance(source, bytes) else Path(source).read_bytes()
|
|
71
|
+
detected = sniff_content_type(data)
|
|
72
|
+
mime = content_type or detected
|
|
73
|
+
if mime is None or detected is None:
|
|
74
|
+
msg = "Unsupported media: use JPEG, PNG, GIF, WebP, MP3, M4A, OGG or WAV."
|
|
75
|
+
raise ValueError(msg)
|
|
76
|
+
if mime != detected:
|
|
77
|
+
msg = f"The file is {detected}, not {mime}; the server would refuse it."
|
|
78
|
+
raise ValueError(msg)
|
|
79
|
+
kind: Literal["image", "audio"] = "image" if mime.startswith("image/") else "audio"
|
|
80
|
+
limit = MAX_IMAGE_BYTES if kind == "image" else MAX_AUDIO_BYTES
|
|
81
|
+
if len(data) > limit:
|
|
82
|
+
msg = f"The file has {len(data)} bytes; the limit for {kind} is {limit}."
|
|
83
|
+
raise ValueError(msg)
|
|
84
|
+
return MediaFile(data, mime, kind, hashlib.sha256(data).hexdigest())
|
glimsy/_api/parse.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
"""Turning API responses into models (no I/O)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import functools
|
|
6
|
+
from collections.abc import Callable
|
|
7
|
+
from typing import Any, ParamSpec, TypeVar
|
|
8
|
+
|
|
9
|
+
from pydantic import ValidationError as _ShapeError
|
|
10
|
+
|
|
11
|
+
from glimsy._api.media_files import MediaFile
|
|
12
|
+
from glimsy._error_mapping import error_from_response
|
|
13
|
+
from glimsy.errors import APIError, NotFoundError
|
|
14
|
+
from glimsy.models.card import Card
|
|
15
|
+
from glimsy.models.changes import BatchRestore, Change, ChangeRestore
|
|
16
|
+
from glimsy.models.results import (
|
|
17
|
+
Account,
|
|
18
|
+
Candidate,
|
|
19
|
+
Deck,
|
|
20
|
+
DeckTheme,
|
|
21
|
+
ItemResult,
|
|
22
|
+
Match,
|
|
23
|
+
MediaRef,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
_ITEM_STATUS = 422
|
|
27
|
+
_STATUS_BY_ITEM_CODE = {"not_found": 404, "conflict": 409, "already_created": 409}
|
|
28
|
+
_BAD_GATEWAY = 502
|
|
29
|
+
|
|
30
|
+
_P = ParamSpec("_P")
|
|
31
|
+
_R = TypeVar("_R")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _shaped(parse: Callable[_P, _R]) -> Callable[_P, _R]:
|
|
35
|
+
"""Report an answer of an unexpected shape as an ``APIError``, never a raw KeyError."""
|
|
36
|
+
|
|
37
|
+
@functools.wraps(parse)
|
|
38
|
+
def checked(*args: _P.args, **kwargs: _P.kwargs) -> _R:
|
|
39
|
+
try:
|
|
40
|
+
return parse(*args, **kwargs)
|
|
41
|
+
except (KeyError, TypeError, IndexError, AttributeError, _ShapeError) as error:
|
|
42
|
+
raise APIError(
|
|
43
|
+
status=_BAD_GATEWAY,
|
|
44
|
+
code="unexpected_response",
|
|
45
|
+
detail="The Glimsy API answered in an unexpected format; update the glimsy "
|
|
46
|
+
"package, or report this with the request id",
|
|
47
|
+
) from error
|
|
48
|
+
|
|
49
|
+
return checked
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@_shaped
|
|
53
|
+
def account(data: Any) -> Account:
|
|
54
|
+
"""``/v1/me``."""
|
|
55
|
+
return Account.model_validate(data)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@_shaped
|
|
59
|
+
def decks(data: Any) -> list[Deck]:
|
|
60
|
+
"""``{"decks": [...]}``."""
|
|
61
|
+
return [Deck.model_validate(d) for d in data["decks"]]
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@_shaped
|
|
65
|
+
def deck(data: Any) -> Deck:
|
|
66
|
+
"""One deck."""
|
|
67
|
+
return Deck.model_validate(data)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@_shaped
|
|
71
|
+
def deck_theme(data: Any) -> DeckTheme:
|
|
72
|
+
"""A deck's stylesheet."""
|
|
73
|
+
return DeckTheme.model_validate(data)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@_shaped
|
|
77
|
+
def card_page(data: Any) -> tuple[list[Card], str | None]:
|
|
78
|
+
"""One page of cards and the next page token."""
|
|
79
|
+
return [Card.model_validate(c) for c in data["cards"]], data.get("next_page_token")
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@_shaped
|
|
83
|
+
def item_results(data: Any, offset: int = 0) -> list[ItemResult]:
|
|
84
|
+
"""Batch results in input order, indexes shifted by ``offset`` (position in your input)."""
|
|
85
|
+
results = sorted((ItemResult.model_validate(r) for r in data["results"]), key=_by_index)
|
|
86
|
+
undo = data.get("undo_batch_id")
|
|
87
|
+
return [
|
|
88
|
+
r.model_copy(update={"index": r.index + offset, "undo_batch_id": undo if r.ok else None})
|
|
89
|
+
for r in results
|
|
90
|
+
]
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@_shaped
|
|
94
|
+
def matches(data: Any, offset: int = 0) -> list[Match]:
|
|
95
|
+
"""Match results in input order, with indexes shifted by ``offset``."""
|
|
96
|
+
found = sorted((Match.model_validate(r) for r in data["results"]), key=_by_index)
|
|
97
|
+
return [m.model_copy(update={"index": m.index + offset}) for m in found]
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _by_index(result: ItemResult | Match) -> int:
|
|
101
|
+
return result.index
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
@_shaped
|
|
105
|
+
def candidates(data: Any) -> list[Candidate]:
|
|
106
|
+
"""Search results, best first."""
|
|
107
|
+
return [Candidate.model_validate(c) for c in data["results"]]
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
@_shaped
|
|
111
|
+
def missing(data: Any) -> list[str]:
|
|
112
|
+
"""Hashes the server does not have yet."""
|
|
113
|
+
return [str(h) for h in data["missing"]]
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
@_shaped
|
|
117
|
+
def media_ref(data: Any) -> MediaRef:
|
|
118
|
+
"""An uploaded file."""
|
|
119
|
+
return MediaRef.model_validate(data)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def pick_deck(decks: list[Deck], name_or_id: str) -> Deck:
|
|
123
|
+
"""The deck with this id, or else the one with this exact name.
|
|
124
|
+
|
|
125
|
+
Raises:
|
|
126
|
+
NotFoundError: No such deck.
|
|
127
|
+
"""
|
|
128
|
+
for deck in decks:
|
|
129
|
+
if deck.id == name_or_id:
|
|
130
|
+
return deck
|
|
131
|
+
for deck in decks:
|
|
132
|
+
if deck.name == name_or_id:
|
|
133
|
+
return deck
|
|
134
|
+
raise NotFoundError(status=404, code="not_found", detail=f"No deck {name_or_id!r}.")
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def ref_of(file: MediaFile) -> MediaRef:
|
|
138
|
+
"""The reference of a file the library already has (no upload needed)."""
|
|
139
|
+
return MediaRef(hash=file.sha256, kind=file.kind, src=file.src)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def only_card(results: list[ItemResult]) -> Card:
|
|
143
|
+
"""The card of a one-item batch, or the item's error raised as an exception.
|
|
144
|
+
|
|
145
|
+
Raises:
|
|
146
|
+
APIError: The item was refused (``ValidationError`` for invalid content).
|
|
147
|
+
"""
|
|
148
|
+
[result] = results
|
|
149
|
+
if result.card is not None:
|
|
150
|
+
return result.card
|
|
151
|
+
error = result.error
|
|
152
|
+
raise _item_error(error.code if error else "item_failed", error.detail if error else "")
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _item_error(code: str, detail: str) -> APIError:
|
|
156
|
+
status = _STATUS_BY_ITEM_CODE.get(code, _ITEM_STATUS)
|
|
157
|
+
return error_from_response(status, {"code": code, "detail": detail}, headers={})
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
@_shaped
|
|
161
|
+
def change_page(data: Any) -> tuple[list[Change], str | None]:
|
|
162
|
+
"""One page of undoable changes and the next page token."""
|
|
163
|
+
return [Change.model_validate(c) for c in data["changes"]], data.get("next_page_token")
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
@_shaped
|
|
167
|
+
def change_restore(data: Any) -> ChangeRestore:
|
|
168
|
+
"""The result of restoring one change."""
|
|
169
|
+
return ChangeRestore.model_validate(data)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
@_shaped
|
|
173
|
+
def batch_restore(data: Any) -> BatchRestore:
|
|
174
|
+
"""The result of restoring a whole request."""
|
|
175
|
+
return BatchRestore.model_validate(data)
|
glimsy/_auth/__init__.py
ADDED
glimsy/_auth/api_key.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""Glimsy API key: format check and safe representation.
|
|
2
|
+
|
|
3
|
+
Format: ``glimsy_`` (production) or ``glimsy_dev_`` (development), followed by a 12-character
|
|
4
|
+
key id, a 43-character secret and an 8-character tag, all base62. Only the format is checked
|
|
5
|
+
here; the tag and the secret can be verified by the server alone.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import re
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from typing import Literal
|
|
13
|
+
|
|
14
|
+
from glimsy.errors import InvalidApiKeyError
|
|
15
|
+
|
|
16
|
+
Environment = Literal["prod", "dev"]
|
|
17
|
+
|
|
18
|
+
_KEY_ID_LEN = 12
|
|
19
|
+
_PATTERN = re.compile(r"glimsy_(?P<dev>dev_)?(?P<body>[0-9A-Za-z]{63})")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True, slots=True)
|
|
23
|
+
class ApiKey:
|
|
24
|
+
"""A syntactically valid API key whose secret is never shown in ``repr`` or ``str``."""
|
|
25
|
+
|
|
26
|
+
environment: Environment
|
|
27
|
+
key_id: str
|
|
28
|
+
_raw: str = field(repr=False)
|
|
29
|
+
|
|
30
|
+
@classmethod
|
|
31
|
+
def parse(cls, raw: str) -> ApiKey:
|
|
32
|
+
"""Validate the key format and return the key.
|
|
33
|
+
|
|
34
|
+
Raises:
|
|
35
|
+
InvalidApiKeyError: The text is not a complete Glimsy key. The message never repeats it.
|
|
36
|
+
"""
|
|
37
|
+
match = _PATTERN.fullmatch(raw.strip())
|
|
38
|
+
if match is None:
|
|
39
|
+
msg = (
|
|
40
|
+
"This does not look like a complete Glimsy API key. Keys start with 'glimsy_' and "
|
|
41
|
+
"are 70 characters long (74 for development keys); copy the whole key again."
|
|
42
|
+
)
|
|
43
|
+
raise InvalidApiKeyError(msg)
|
|
44
|
+
environment: Environment = "dev" if match["dev"] else "prod"
|
|
45
|
+
return cls(environment=environment, key_id=match["body"][:_KEY_ID_LEN], _raw=match[0])
|
|
46
|
+
|
|
47
|
+
def authorization_header(self) -> str:
|
|
48
|
+
"""Return the value of the ``Authorization`` header for this key."""
|
|
49
|
+
return f"Bearer {self._raw}"
|
|
50
|
+
|
|
51
|
+
def __str__(self) -> str:
|
|
52
|
+
"""Show the key id only, so keys can be logged and compared safely."""
|
|
53
|
+
prefix = "glimsy_dev_" if self.environment == "dev" else "glimsy_"
|
|
54
|
+
return f"{prefix}{self.key_id}…"
|