grist-backup 1.0.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.
@@ -0,0 +1 @@
1
+ __version__ = "1.0.0"
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from grist_backup.cli import main
4
+
5
+ sys.exit(main())
grist_backup/api.py ADDED
@@ -0,0 +1,275 @@
1
+ """Grist API client for downloading documents and fetching metadata."""
2
+
3
+ import contextlib
4
+ import json
5
+ import logging
6
+ import lzma
7
+ import os
8
+ import shutil
9
+ import tempfile
10
+ import urllib.error
11
+ import urllib.request
12
+ from contextlib import ExitStack
13
+ from dataclasses import dataclass
14
+ from pathlib import Path
15
+
16
+ from grist_backup.config import DiscoverEntry, DocRef
17
+
18
+ logger = logging.getLogger(__name__)
19
+
20
+ CHUNK_SIZE = 8192
21
+ TIMEOUT = 60
22
+ METADATA_TIMEOUT = 15
23
+
24
+
25
+ @dataclass
26
+ class DocMetadata:
27
+ """Metadata about a Grist document fetched from the API.
28
+
29
+ Any field may be None if the metadata could not be retrieved.
30
+ """
31
+
32
+ name: str | None = None
33
+ workspace_name: str | None = None
34
+ team_name: str | None = None
35
+
36
+
37
+ class DownloadError(Exception):
38
+ """Raised when a document download fails."""
39
+
40
+ def __init__(self, message: str, status: int | None = None):
41
+ super().__init__(message)
42
+ self.status = status
43
+
44
+
45
+ class DiscoveryError(Exception):
46
+ """Raised when listing documents via the API fails."""
47
+
48
+
49
+ def fetch_doc_metadata(server: str, api_key: str, doc_id: str) -> DocMetadata:
50
+ """Fetch document metadata via GET /api/docs/{docId}.
51
+
52
+ Returns a DocMetadata with all-None fields on any failure.
53
+ Never raises — logs a warning on error.
54
+ """
55
+ url = f"{server}/api/docs/{doc_id}"
56
+ request = urllib.request.Request(
57
+ url, headers={"Authorization": f"Bearer {api_key}"}
58
+ )
59
+ try:
60
+ with urllib.request.urlopen(request, timeout=METADATA_TIMEOUT) as response:
61
+ if response.status != 200:
62
+ logger.warning(
63
+ "Metadata fetch for %s returned HTTP %d", doc_id, response.status
64
+ )
65
+ return DocMetadata()
66
+ payload = response.read()
67
+ except urllib.error.HTTPError as exc:
68
+ logger.warning("Metadata fetch for %s failed: HTTP %d", doc_id, exc.code)
69
+ return DocMetadata()
70
+ except urllib.error.URLError as exc:
71
+ logger.warning("Metadata fetch for %s failed: %s", doc_id, exc.reason)
72
+ return DocMetadata()
73
+
74
+ try:
75
+ data = json.loads(payload)
76
+ except json.JSONDecodeError as exc:
77
+ logger.warning("Metadata for %s: invalid JSON (%s)", doc_id, exc)
78
+ return DocMetadata()
79
+
80
+ workspace = data.get("workspace") or {}
81
+ org = workspace.get("org") or {}
82
+ return DocMetadata(
83
+ name=data.get("name"),
84
+ workspace_name=workspace.get("name"),
85
+ team_name=org.get("name"),
86
+ )
87
+
88
+
89
+ def _get_json(server: str, api_key: str, path: str) -> object:
90
+ """Internal helper for GET requests returning JSON. Raises DiscoveryError."""
91
+ url = f"{server}{path}"
92
+ request = urllib.request.Request(
93
+ url, headers={"Authorization": f"Bearer {api_key}"}
94
+ )
95
+ try:
96
+ with urllib.request.urlopen(request, timeout=METADATA_TIMEOUT) as response:
97
+ if response.status != 200:
98
+ msg = f"HTTP {response.status} from {url}"
99
+ raise DiscoveryError(msg)
100
+ payload = response.read()
101
+ except urllib.error.HTTPError as exc:
102
+ body = exc.read(512).decode("utf-8", errors="replace")
103
+ msg = f"HTTP {exc.code} from {url}: {body}"
104
+ raise DiscoveryError(msg) from exc
105
+ except urllib.error.URLError as exc:
106
+ msg = f"Connection error for {url}: {exc.reason}"
107
+ raise DiscoveryError(msg) from exc
108
+
109
+ try:
110
+ return json.loads(payload)
111
+ except json.JSONDecodeError as exc:
112
+ msg = f"Invalid JSON from {url}: {exc}"
113
+ raise DiscoveryError(msg) from exc
114
+
115
+
116
+ def fetch_account_docs(
117
+ server: str,
118
+ api_key: str,
119
+ scope: list[DiscoverEntry] | None = None,
120
+ ) -> list[tuple[DocRef, DocMetadata]]:
121
+ """List all documents accessible to the API key, with metadata hints.
122
+
123
+ Enumerates orgs (teams) via GET /api/orgs, then their workspaces via
124
+ GET /api/orgs/{orgId}/workspaces. When `scope` is None, returns every
125
+ accessible doc. When `scope` is provided, each entry restricts results
126
+ to the given team (and optionally to specific workspaces within it).
127
+
128
+ Returns a list of (DocRef, DocMetadata) pairs; metadata is pre-populated
129
+ with team_name, workspace_name, and name from the API — allowing callers
130
+ to skip per-doc metadata fetches. Raises DiscoveryError on failure.
131
+ """
132
+ orgs_raw = _get_json(server, api_key, "/api/orgs")
133
+ if not isinstance(orgs_raw, list):
134
+ msg = "Unexpected response shape from /api/orgs: not a list"
135
+ raise DiscoveryError(msg)
136
+
137
+ # Map team name (case-sensitive) to list of workspace filters (or None
138
+ # meaning whole team). If scope is None, every team included.
139
+ if scope is None:
140
+ team_filter: dict[str, list[str] | None] | None = None
141
+ else:
142
+ team_filter = {entry.team: entry.workspaces for entry in scope}
143
+
144
+ results: list[tuple[DocRef, DocMetadata]] = []
145
+ for org in orgs_raw:
146
+ org_id = org.get("id")
147
+ org_name = org.get("name")
148
+ if org_id is None:
149
+ continue
150
+ if team_filter is not None and org_name not in team_filter:
151
+ continue
152
+
153
+ ws_filter: list[str] | None = (
154
+ team_filter[org_name] if team_filter is not None else None
155
+ )
156
+ ws_filter_set = set(ws_filter) if ws_filter is not None else None
157
+
158
+ ws_raw = _get_json(server, api_key, f"/api/orgs/{org_id}/workspaces")
159
+ if not isinstance(ws_raw, list):
160
+ msg = (
161
+ f"Unexpected response shape from /api/orgs/{org_id}/workspaces:"
162
+ " not a list"
163
+ )
164
+ raise DiscoveryError(msg)
165
+
166
+ for ws in ws_raw:
167
+ ws_name = ws.get("name")
168
+ if ws_filter_set is not None and ws_name not in ws_filter_set:
169
+ continue
170
+ for doc in ws.get("docs", []):
171
+ doc_id = doc.get("id")
172
+ if not doc_id:
173
+ continue
174
+ doc_name = doc.get("name")
175
+ results.append(
176
+ (
177
+ DocRef(id=doc_id, name=None),
178
+ DocMetadata(
179
+ name=doc_name,
180
+ workspace_name=ws_name,
181
+ team_name=org_name,
182
+ ),
183
+ )
184
+ )
185
+ return results
186
+
187
+
188
+ def download_document(
189
+ server: str,
190
+ api_key: str,
191
+ doc_id: str,
192
+ output_path: Path,
193
+ *,
194
+ no_history: bool = False,
195
+ compress: bool = True,
196
+ ) -> None:
197
+ """Download a Grist document as a .grist SQLite file.
198
+
199
+ Streams the response to disk. When `compress` is True, pipes the stream
200
+ through lzma (xz) compression on the fly. Writes to a temporary file
201
+ first, then renames on success. Cleans up partial files on failure.
202
+ """
203
+ url = f"{server}/api/docs/{doc_id}/download"
204
+ if no_history:
205
+ url += "?nohistory=true"
206
+
207
+ request = urllib.request.Request(
208
+ url, headers={"Authorization": f"Bearer {api_key}"}
209
+ )
210
+
211
+ output_dir = output_path.parent
212
+ output_dir.mkdir(parents=True, exist_ok=True)
213
+
214
+ tmp_fd, tmp_path_str = tempfile.mkstemp(
215
+ suffix=output_path.suffix + ".tmp", dir=output_dir
216
+ )
217
+ tmp_path = Path(tmp_path_str)
218
+
219
+ try:
220
+ with urllib.request.urlopen(request, timeout=TIMEOUT) as response:
221
+ status = response.status
222
+ if status != 200:
223
+ body = response.read(512).decode("utf-8", errors="replace")
224
+ msg = f"HTTP {status} from {url}: {body}"
225
+ raise DownloadError(msg, status=status)
226
+
227
+ total_in = 0
228
+ with ExitStack() as stack:
229
+ raw_out = stack.enter_context(os.fdopen(tmp_fd, "wb"))
230
+ out = (
231
+ stack.enter_context(lzma.open(raw_out, "wb"))
232
+ if compress
233
+ else raw_out
234
+ )
235
+ while True:
236
+ chunk = response.read(CHUNK_SIZE)
237
+ if not chunk:
238
+ break
239
+ out.write(chunk)
240
+ total_in += len(chunk)
241
+
242
+ shutil.move(str(tmp_path), str(output_path))
243
+ size = output_path.stat().st_size
244
+ if compress:
245
+ ratio = (1 - size / total_in) * 100 if total_in else 0
246
+ logger.info(
247
+ "Downloaded %s (%d -> %d bytes, %.1f%% saved)",
248
+ output_path.name,
249
+ total_in,
250
+ size,
251
+ ratio,
252
+ )
253
+ else:
254
+ logger.info("Downloaded %s (%d bytes)", output_path.name, size)
255
+
256
+ except urllib.error.HTTPError as exc:
257
+ body = exc.read(512).decode("utf-8", errors="replace")
258
+ _cleanup(tmp_path)
259
+ msg = f"HTTP {exc.code} from {url}: {body}"
260
+ raise DownloadError(msg, status=exc.code) from exc
261
+
262
+ except urllib.error.URLError as exc:
263
+ _cleanup(tmp_path)
264
+ msg = f"Connection error for {url}: {exc.reason}"
265
+ raise DownloadError(msg) from exc
266
+
267
+ except Exception:
268
+ _cleanup(tmp_path)
269
+ raise
270
+
271
+
272
+ def _cleanup(path: Path) -> None:
273
+ """Remove a temporary file, ignoring errors."""
274
+ with contextlib.suppress(OSError):
275
+ path.unlink(missing_ok=True)