unstrap 0.1.0__tar.gz

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,19 @@
1
+ # Real watch captures contain personal data (GPS, health). Never commit.
2
+ fixtures/capture-*/
3
+ data/
4
+
5
+ # Build / tooling
6
+ node_modules/
7
+ .venv/
8
+ .wrangler/
9
+ dist/
10
+ target/
11
+ __pycache__/
12
+ *.egg-info/
13
+ .pytest_cache/
14
+ .mypy_cache/
15
+ .ruff_cache/
16
+ .DS_Store
17
+ .claude/settings.local.json
18
+ .tools/
19
+ .dev.vars
unstrap-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 SweatStack
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
unstrap-0.1.0/Makefile ADDED
@@ -0,0 +1,15 @@
1
+ # Client (Python). `check` runs on the oldest and newest supported Python.
2
+ PYTHONS ?= 3.10 3.14
3
+ export UV_PYTHON_PREFERENCE := only-managed
4
+ .PHONY: check lint test
5
+
6
+ check: lint
7
+ @for py in $(PYTHONS); do \
8
+ echo "== pytest on Python $$py"; \
9
+ uv run --python $$py --isolated --group dev pytest || exit 1; \
10
+ done
11
+
12
+ lint:
13
+ uv run --group dev ruff check .
14
+ uv run --group dev ruff format --check .
15
+ uv run --group dev mypy
unstrap-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,24 @@
1
+ Metadata-Version: 2.4
2
+ Name: unstrap
3
+ Version: 0.1.0
4
+ Summary: Your watch data, set free. Copies everything your Garmin watch records, straight off the watch over USB.
5
+ Author: SweatStack
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Classifier: Environment :: Console
9
+ Classifier: Operating System :: MacOS
10
+ Classifier: Operating System :: POSIX :: Linux
11
+ Classifier: Programming Language :: Python :: 3
12
+ Requires-Python: >=3.10
13
+ Requires-Dist: httpx<1,>=0.28
14
+ Description-Content-Type: text/markdown
15
+
16
+ # unstrap
17
+
18
+ Your watch data, set free. Plug in your Garmin watch and run:
19
+
20
+ ```sh
21
+ uvx unstrap
22
+ ```
23
+
24
+ See the project README for how it works.
@@ -0,0 +1,9 @@
1
+ # unstrap
2
+
3
+ Your watch data, set free. Plug in your Garmin watch and run:
4
+
5
+ ```sh
6
+ uvx unstrap
7
+ ```
8
+
9
+ See the project README for how it works.
@@ -0,0 +1,57 @@
1
+ [project]
2
+ name = "unstrap"
3
+ version = "0.1.0"
4
+ description = "Your watch data, set free. Copies everything your Garmin watch records, straight off the watch over USB."
5
+ readme = "README.md"
6
+ requires-python = ">=3.10"
7
+ license = "MIT"
8
+ license-files = ["LICENSE"]
9
+ authors = [{ name = "SweatStack" }]
10
+ classifiers = [
11
+ "Environment :: Console",
12
+ "Operating System :: MacOS",
13
+ "Operating System :: POSIX :: Linux",
14
+ "Programming Language :: Python :: 3",
15
+ ]
16
+ dependencies = ["httpx>=0.28,<1"]
17
+
18
+ [project.scripts]
19
+ unstrap = "unstrap.cli:main"
20
+
21
+ [build-system]
22
+ # <1.32: hatchling 1.32 writes Metadata-Version 2.5, which the PyPI publish action's twine rejects.
23
+ requires = ["hatchling>=1.27,<1.32"]
24
+ build-backend = "hatchling.build"
25
+
26
+ [dependency-groups]
27
+ dev = ["pytest>=8", "ruff>=0.13", "mypy>=1.18", "unstrap-synth", "jsonschema>=4.23", "types-jsonschema"]
28
+
29
+ [tool.uv.sources]
30
+ unstrap-synth = { path = "../fixtures/synth", editable = true }
31
+
32
+ [tool.ruff]
33
+ line-length = 100
34
+ target-version = "py310"
35
+
36
+ [tool.ruff.lint]
37
+ select = ["E", "F", "W", "I", "B", "UP", "SIM", "RUF", "PL", "PT"]
38
+ ignore = ["PLR2004"]
39
+
40
+ [tool.ruff.lint.per-file-ignores]
41
+ # A test double that mirrors a CLI's whole command surface in one dispatcher.
42
+ "tests/fake_mtp_rs.py" = ["PLR0912", "PLR0915"]
43
+ "tests/fake_server.py" = ["PLR0911", "PLR0912"]
44
+
45
+ [tool.ruff.lint.pylint]
46
+ # Keyword-only parameters and early-return error mapping read fine at these sizes.
47
+ max-args = 8
48
+ max-returns = 10
49
+
50
+ [tool.mypy]
51
+ strict = true
52
+ python_version = "3.10"
53
+ files = ["src", "tests"]
54
+
55
+ [tool.pytest.ini_options]
56
+ testpaths = ["tests"]
57
+ addopts = "-q"
@@ -0,0 +1,112 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://unstrap.sweatstack.no/schema/report.json",
4
+ "title": "unstrap sync --json report",
5
+ "description": "Machine-readable result of one sync (consumed by e.g. the Raspberry Pi box). Additive changes only.",
6
+ "type": "object",
7
+ "required": [
8
+ "unit_id",
9
+ "usb_serial",
10
+ "listed",
11
+ "read",
12
+ "uploaded",
13
+ "uploaded_bytes",
14
+ "store",
15
+ "status",
16
+ "store_status",
17
+ "unrecorded",
18
+ "errors",
19
+ "seconds",
20
+ "changed"
21
+ ],
22
+ "properties": {
23
+ "unit_id": {
24
+ "type": "string",
25
+ "pattern": "^[0-9]{1,10}$"
26
+ },
27
+ "usb_serial": {
28
+ "type": "string",
29
+ "pattern": "^[0-9a-f]{12}$"
30
+ },
31
+ "product": {
32
+ "type": [
33
+ "string",
34
+ "null"
35
+ ]
36
+ },
37
+ "listed": {
38
+ "type": "integer",
39
+ "minimum": 0
40
+ },
41
+ "read": {
42
+ "type": "integer",
43
+ "minimum": 0
44
+ },
45
+ "uploaded": {
46
+ "type": "integer",
47
+ "minimum": 0
48
+ },
49
+ "uploaded_bytes": {
50
+ "type": "integer",
51
+ "minimum": 0
52
+ },
53
+ "store": {
54
+ "enum": [
55
+ "new",
56
+ "existing"
57
+ ]
58
+ },
59
+ "status": {
60
+ "enum": [
61
+ "ok",
62
+ "partial"
63
+ ]
64
+ },
65
+ "store_status": {
66
+ "enum": [
67
+ "claimed",
68
+ "unclaimed"
69
+ ]
70
+ },
71
+ "owner_hint": {
72
+ "type": [
73
+ "string",
74
+ "null"
75
+ ]
76
+ },
77
+ "retention_days": {
78
+ "type": [
79
+ "integer",
80
+ "null"
81
+ ]
82
+ },
83
+ "unrecorded": {
84
+ "type": "array",
85
+ "items": {
86
+ "type": "string"
87
+ }
88
+ },
89
+ "errors": {
90
+ "type": "array",
91
+ "items": {
92
+ "type": "string"
93
+ }
94
+ },
95
+ "saved": {
96
+ "type": "integer",
97
+ "minimum": 0
98
+ },
99
+ "seconds": {
100
+ "type": "number",
101
+ "minimum": 0
102
+ },
103
+ "changed": {
104
+ "type": "array",
105
+ "items": {
106
+ "type": "string"
107
+ },
108
+ "description": "Mutable files rewritten on the watch during the sync; included next time."
109
+ }
110
+ },
111
+ "additionalProperties": false
112
+ }
@@ -0,0 +1,3 @@
1
+ """Unstrap: copy Garmin watch data off the watch over USB (MTP) and upload it."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,186 @@
1
+ """HTTP client for the Unstrap sync API (plan §4). Retries only what is safe to retry."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import platform
6
+ import random
7
+ import time
8
+ from collections.abc import Callable, Sequence
9
+ from dataclasses import dataclass
10
+ from typing import Any
11
+ from urllib.parse import quote
12
+
13
+ import httpx
14
+
15
+ from unstrap import __version__
16
+ from unstrap.transport import DeviceInfo, RemoteFile
17
+
18
+ DEFAULT_SERVER = "https://unstrap.sweatstack.no"
19
+ MAX_ATTEMPTS = 5
20
+
21
+
22
+ class ApiError(Exception):
23
+ """The server said no. `message` is meant for people and is printed as-is."""
24
+
25
+ def __init__(self, status: int, code: str, message: str) -> None:
26
+ super().__init__(message)
27
+ self.status = status
28
+ self.code = code
29
+ self.message = message
30
+
31
+
32
+ class ClientTooOld(ApiError):
33
+ pass
34
+
35
+
36
+ class ServerUnreachable(Exception):
37
+ pass
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class HashedFile:
42
+ path: str
43
+ size: int
44
+ sha256: str
45
+
46
+ def as_json(self) -> dict[str, Any]:
47
+ return {"path": self.path, "size": self.size, "sha256": self.sha256}
48
+
49
+
50
+ def user_agent(mtp_rs_version: str | None) -> str:
51
+ system = f"{platform.system()} {platform.machine()}".strip()
52
+ return f"unstrap/{__version__} ({system}; mtp-rs/{mtp_rs_version or 'none'})"
53
+
54
+
55
+ class Api:
56
+ def __init__(
57
+ self,
58
+ base_url: str = DEFAULT_SERVER,
59
+ *,
60
+ agent: str | None = None,
61
+ client: httpx.Client | None = None,
62
+ sleep: Callable[[float], None] = time.sleep,
63
+ ) -> None:
64
+ self.base_url = base_url.rstrip("/")
65
+ self._client = client or httpx.Client(timeout=httpx.Timeout(60.0, connect=15.0))
66
+ self._agent = agent or user_agent(None)
67
+ self._sleep = sleep
68
+
69
+ def close(self) -> None:
70
+ self._client.close()
71
+
72
+ # -- plumbing ---------------------------------------------------------------------------------
73
+
74
+ def _request(
75
+ self,
76
+ method: str,
77
+ path: str,
78
+ *,
79
+ token: str | None = None,
80
+ json: Any = None,
81
+ content: bytes | None = None,
82
+ headers: dict[str, str] | None = None,
83
+ ) -> dict[str, Any]:
84
+ h = {"user-agent": self._agent, **(headers or {})}
85
+ if token:
86
+ h["authorization"] = f"Bearer {token}"
87
+ url = f"{self.base_url}/api/v1{path}"
88
+ last: Exception | None = None
89
+ for attempt in range(MAX_ATTEMPTS):
90
+ try:
91
+ res = self._client.request(method, url, json=json, content=content, headers=h)
92
+ except httpx.TransportError as e:
93
+ last = e
94
+ self._backoff(attempt, None)
95
+ continue
96
+ if res.status_code == 429 or res.status_code >= 500:
97
+ last = ApiError(res.status_code, *_error(res))
98
+ self._backoff(attempt, res.headers.get("retry-after"))
99
+ continue
100
+ if res.status_code >= 400:
101
+ code, message = _error(res)
102
+ if res.status_code == 426:
103
+ raise ClientTooOld(426, code, message)
104
+ raise ApiError(res.status_code, code, message)
105
+ try:
106
+ data: dict[str, Any] = res.json()
107
+ except ValueError as e:
108
+ # E.g. a captive portal or proxy answering in HTML (review M3).
109
+ raise ServerUnreachable(
110
+ f"Unexpected answer from {self.base_url} (a Wi-Fi login page or proxy?)"
111
+ ) from e
112
+ return data
113
+ if isinstance(last, ApiError):
114
+ raise last
115
+ raise ServerUnreachable(f"Can't reach {self.base_url}: {last}")
116
+
117
+ def _backoff(self, attempt: int, retry_after: str | None) -> None:
118
+ if attempt + 1 >= MAX_ATTEMPTS:
119
+ return
120
+ if retry_after and retry_after.isdigit():
121
+ delay = min(float(retry_after), 60.0)
122
+ else:
123
+ delay = min(2.0**attempt, 30.0) * (0.5 + random.random() / 2)
124
+ self._sleep(delay)
125
+
126
+ # -- endpoints --------------------------------------------------------------------------------
127
+
128
+ def healthz(self) -> bool:
129
+ try:
130
+ res = self._client.get(f"{self.base_url}/healthz", headers={"user-agent": self._agent})
131
+ except httpx.TransportError:
132
+ return False
133
+ return res.status_code == 200
134
+
135
+ def start(self, device: DeviceInfo, listing: Sequence[RemoteFile]) -> dict[str, Any]:
136
+ dev: dict[str, Any] = {"usb_serial": device.usb_serial, "unit_id": device.unit_id}
137
+ if device.product:
138
+ dev["product"] = device.product[:100]
139
+ if device.firmware:
140
+ dev["firmware"] = device.firmware[:32]
141
+ body = {"device": dev, "listing": [{"path": f.path, "size": f.size} for f in listing]}
142
+ return self._request("POST", "/syncs", json=body)
143
+
144
+ def prove(
145
+ self, sync_id: int, token: str, nonce: str, proofs: list[dict[str, str]]
146
+ ) -> dict[str, Any]:
147
+ body = {"nonce": nonce, "proofs": proofs}
148
+ return self._request("POST", f"/syncs/{sync_id}/prove", token=token, json=body)
149
+
150
+ def check(self, sync_id: int, token: str, files: Sequence[HashedFile]) -> list[str]:
151
+ body = {"files": [f.as_json() for f in files]}
152
+ res = self._request("POST", f"/syncs/{sync_id}/check", token=token, json=body)
153
+ return list(res["missing"])
154
+
155
+ def put_blob(self, sync_id: int, token: str, file: HashedFile, data: bytes) -> bool:
156
+ headers = {
157
+ "unstrap-path": quote(file.path, safe=""),
158
+ "content-type": "application/octet-stream",
159
+ }
160
+ res = self._request(
161
+ "PUT",
162
+ f"/syncs/{sync_id}/blobs/{file.sha256}",
163
+ token=token,
164
+ content=data,
165
+ headers=headers,
166
+ )
167
+ return bool(res.get("stored"))
168
+
169
+ def finish(
170
+ self,
171
+ sync_id: int,
172
+ token: str,
173
+ files: Sequence[HashedFile],
174
+ stats: dict[str, int | str | bool],
175
+ errors: list[str],
176
+ ) -> dict[str, Any]:
177
+ body = {"files": [f.as_json() for f in files], "stats": stats, "errors": errors[:100]}
178
+ return self._request("POST", f"/syncs/{sync_id}/finish", token=token, json=body)
179
+
180
+
181
+ def _error(res: httpx.Response) -> tuple[str, str]:
182
+ try:
183
+ err = res.json()["error"]
184
+ return str(err["code"]), str(err["message"])
185
+ except (ValueError, KeyError, TypeError):
186
+ return "http_error", f"Server returned HTTP {res.status_code}."