python-gopro 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.
- pygopro/__init__.py +67 -0
- pygopro/__main__.py +3 -0
- pygopro/ble.py +451 -0
- pygopro/cli.py +144 -0
- pygopro/const.py +235 -0
- pygopro/exceptions.py +38 -0
- pygopro/firmware.py +60 -0
- pygopro/http.py +373 -0
- pygopro/models.py +228 -0
- pygopro/protocol.py +189 -0
- pygopro/schema.py +163 -0
- python_gopro-0.1.0.dist-info/METADATA +103 -0
- python_gopro-0.1.0.dist-info/RECORD +16 -0
- python_gopro-0.1.0.dist-info/WHEEL +4 -0
- python_gopro-0.1.0.dist-info/entry_points.txt +2 -0
- python_gopro-0.1.0.dist-info/licenses/LICENSE +21 -0
pygopro/http.py
ADDED
|
@@ -0,0 +1,373 @@
|
|
|
1
|
+
"""Async HTTP client (Open GoPro ``/gopro/*`` + legacy ``/gp/gpControl/*``).
|
|
2
|
+
|
|
3
|
+
Works over Camera-on-Home-Network (HTTPS :443, basic auth, camera root CA) and also over the
|
|
4
|
+
camera's own AP / USB network (plain HTTP :8080, no auth) by passing ``ssl=False``.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import asyncio
|
|
10
|
+
import json
|
|
11
|
+
import re
|
|
12
|
+
import ssl as ssl_mod
|
|
13
|
+
from collections.abc import AsyncIterator
|
|
14
|
+
from datetime import datetime
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
import aiohttp
|
|
18
|
+
|
|
19
|
+
from .const import CONTROLLER_UNAVAILABLE_MARKER, DANGEROUS_PATHS
|
|
20
|
+
from .exceptions import (
|
|
21
|
+
GoProAuthError,
|
|
22
|
+
GoProCommandError,
|
|
23
|
+
GoProConnectionError,
|
|
24
|
+
GoProControllerUnavailableError,
|
|
25
|
+
)
|
|
26
|
+
from .models import (
|
|
27
|
+
CameraInfo,
|
|
28
|
+
CameraState,
|
|
29
|
+
CohnStatus,
|
|
30
|
+
MediaFile,
|
|
31
|
+
Preset,
|
|
32
|
+
parse_media_list,
|
|
33
|
+
parse_presets,
|
|
34
|
+
)
|
|
35
|
+
from .schema import Schema
|
|
36
|
+
|
|
37
|
+
DEFAULT_TIMEOUT = 10
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def build_ssl_context(certificate: str) -> ssl_mod.SSLContext:
|
|
41
|
+
"""Trust only the camera's own root CA.
|
|
42
|
+
|
|
43
|
+
Hostname checking is off: the server certificate is re-issued for the current IP by
|
|
44
|
+
``gpCertMgr`` and we may connect through a different address (mDNS name, old IP).
|
|
45
|
+
Strict X.509 checks (default since Python 3.13) are relaxed: the camera-made certificates have
|
|
46
|
+
no Authority Key Identifier, which strict mode rejects although the chain is valid.
|
|
47
|
+
"""
|
|
48
|
+
ctx = ssl_mod.create_default_context(cadata=certificate)
|
|
49
|
+
ctx.check_hostname = False
|
|
50
|
+
ctx.verify_mode = ssl_mod.CERT_REQUIRED
|
|
51
|
+
ctx.verify_flags &= ~getattr(ssl_mod, "VERIFY_X509_STRICT", 0)
|
|
52
|
+
return ctx
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class GoProHttp:
|
|
56
|
+
"""Thin async wrapper around the camera web server."""
|
|
57
|
+
|
|
58
|
+
def __init__(
|
|
59
|
+
self,
|
|
60
|
+
host: str,
|
|
61
|
+
*,
|
|
62
|
+
username: str | None = None,
|
|
63
|
+
password: str | None = None,
|
|
64
|
+
certificate: str | None = None,
|
|
65
|
+
session: aiohttp.ClientSession | None = None,
|
|
66
|
+
port: int | None = None,
|
|
67
|
+
ssl: bool | None = None,
|
|
68
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
69
|
+
) -> None:
|
|
70
|
+
self.host = host
|
|
71
|
+
self._use_ssl = bool(certificate) if ssl is None else ssl
|
|
72
|
+
self.port = port or (443 if self._use_ssl else 8080)
|
|
73
|
+
self._auth = aiohttp.BasicAuth(username, password) if username and password else None
|
|
74
|
+
self._ssl: ssl_mod.SSLContext | bool = build_ssl_context(certificate) if self._use_ssl and certificate else self._use_ssl
|
|
75
|
+
self._session = session
|
|
76
|
+
self._own_session = session is None
|
|
77
|
+
self._timeout = aiohttp.ClientTimeout(total=timeout)
|
|
78
|
+
self._lock = asyncio.Lock()
|
|
79
|
+
|
|
80
|
+
# -- plumbing ------------------------------------------------------------------------------------
|
|
81
|
+
|
|
82
|
+
@property
|
|
83
|
+
def base_url(self) -> str:
|
|
84
|
+
scheme = "https" if self._use_ssl else "http"
|
|
85
|
+
default = 443 if self._use_ssl else 80
|
|
86
|
+
port = "" if self.port == default else f":{self.port}"
|
|
87
|
+
return f"{scheme}://{self.host}{port}"
|
|
88
|
+
|
|
89
|
+
def url(self, path: str) -> str:
|
|
90
|
+
return f"{self.base_url}{path if path.startswith('/') else '/' + path}"
|
|
91
|
+
|
|
92
|
+
@property
|
|
93
|
+
def auth(self) -> aiohttp.BasicAuth | None:
|
|
94
|
+
return self._auth
|
|
95
|
+
|
|
96
|
+
@property
|
|
97
|
+
def ssl_context(self) -> ssl_mod.SSLContext | bool:
|
|
98
|
+
return self._ssl
|
|
99
|
+
|
|
100
|
+
async def _get_session(self) -> aiohttp.ClientSession:
|
|
101
|
+
if self._session is None or self._session.closed:
|
|
102
|
+
self._session = aiohttp.ClientSession()
|
|
103
|
+
self._own_session = True
|
|
104
|
+
return self._session
|
|
105
|
+
|
|
106
|
+
async def close(self) -> None:
|
|
107
|
+
if self._own_session and self._session and not self._session.closed:
|
|
108
|
+
await self._session.close()
|
|
109
|
+
|
|
110
|
+
async def __aenter__(self) -> GoProHttp:
|
|
111
|
+
return self
|
|
112
|
+
|
|
113
|
+
async def __aexit__(self, *exc: object) -> None:
|
|
114
|
+
await self.close()
|
|
115
|
+
|
|
116
|
+
async def request(
|
|
117
|
+
self,
|
|
118
|
+
path: str,
|
|
119
|
+
params: dict[str, Any] | None = None,
|
|
120
|
+
*,
|
|
121
|
+
method: str = "GET",
|
|
122
|
+
json_body: Any = None,
|
|
123
|
+
raw: bool = False,
|
|
124
|
+
timeout: float | None = None,
|
|
125
|
+
) -> Any:
|
|
126
|
+
"""Perform a request and decode JSON (or return bytes with ``raw=True``)."""
|
|
127
|
+
if any(path.startswith(p) for p in DANGEROUS_PATHS):
|
|
128
|
+
raise GoProCommandError(f"{path} is blocked: it wedges the camera's control channel")
|
|
129
|
+
session = await self._get_session()
|
|
130
|
+
to = aiohttp.ClientTimeout(total=timeout) if timeout else self._timeout
|
|
131
|
+
try:
|
|
132
|
+
async with session.request(
|
|
133
|
+
method, self.url(path), params=params, json=json_body, auth=self._auth, ssl=self._ssl, timeout=to
|
|
134
|
+
) as resp:
|
|
135
|
+
body = await resp.read()
|
|
136
|
+
if resp.status == 401:
|
|
137
|
+
raise GoProAuthError("credentials rejected")
|
|
138
|
+
if resp.status == 503 and CONTROLLER_UNAVAILABLE_MARKER.encode() in body:
|
|
139
|
+
raise GoProControllerUnavailableError(
|
|
140
|
+
"camera web server cannot reach its settings controller (remove the battery to recover)"
|
|
141
|
+
)
|
|
142
|
+
if resp.status >= 400:
|
|
143
|
+
raise GoProCommandError(
|
|
144
|
+
f"{method} {path} -> HTTP {resp.status}", resp.status, body.decode(errors="replace")[:500]
|
|
145
|
+
)
|
|
146
|
+
if raw:
|
|
147
|
+
return body
|
|
148
|
+
if not body.strip():
|
|
149
|
+
return {}
|
|
150
|
+
try:
|
|
151
|
+
return json.loads(body)
|
|
152
|
+
except ValueError:
|
|
153
|
+
return body.decode(errors="replace")
|
|
154
|
+
except aiohttp.ServerDisconnectedError as err:
|
|
155
|
+
# COHN closes the socket without an answer when basic auth is missing/invalid.
|
|
156
|
+
raise GoProAuthError("server closed the connection (missing or invalid credentials?)") from err
|
|
157
|
+
except (aiohttp.ClientConnectorError, aiohttp.ClientOSError, TimeoutError) as err:
|
|
158
|
+
raise GoProConnectionError(f"{self.host}: {err!s}") from err
|
|
159
|
+
except aiohttp.ClientResponseError as err:
|
|
160
|
+
raise GoProCommandError(str(err), err.status) from err
|
|
161
|
+
except aiohttp.ClientError as err:
|
|
162
|
+
raise GoProConnectionError(f"{self.host}: {err!s}") from err
|
|
163
|
+
|
|
164
|
+
async def stream(self, path: str, chunk_size: int = 1 << 16, headers: dict[str, str] | None = None) -> AsyncIterator[bytes]:
|
|
165
|
+
"""Stream a file (media download) chunk by chunk."""
|
|
166
|
+
session = await self._get_session()
|
|
167
|
+
try:
|
|
168
|
+
async with session.get(
|
|
169
|
+
self.url(path),
|
|
170
|
+
auth=self._auth,
|
|
171
|
+
ssl=self._ssl,
|
|
172
|
+
headers=headers,
|
|
173
|
+
timeout=aiohttp.ClientTimeout(total=None, sock_read=60),
|
|
174
|
+
) as resp:
|
|
175
|
+
if resp.status >= 400:
|
|
176
|
+
raise GoProCommandError(f"GET {path} -> HTTP {resp.status}", resp.status)
|
|
177
|
+
async for chunk in resp.content.iter_chunked(chunk_size):
|
|
178
|
+
yield chunk
|
|
179
|
+
except aiohttp.ClientError as err:
|
|
180
|
+
raise GoProConnectionError(str(err)) from err
|
|
181
|
+
|
|
182
|
+
# -- reads ---------------------------------------------------------------------------------------
|
|
183
|
+
|
|
184
|
+
async def get_version(self) -> str:
|
|
185
|
+
return str((await self.request("/gopro/version")).get("version", ""))
|
|
186
|
+
|
|
187
|
+
async def get_info(self) -> CameraInfo:
|
|
188
|
+
return CameraInfo.from_json(await self.request("/gopro/camera/info"))
|
|
189
|
+
|
|
190
|
+
async def get_state(self) -> CameraState:
|
|
191
|
+
return CameraState.from_json(await self.request("/gopro/camera/state"))
|
|
192
|
+
|
|
193
|
+
async def get_legacy_status(self) -> CameraState:
|
|
194
|
+
"""Same data as ``get_state`` through the legacy route (still works when /gopro/* is 503)."""
|
|
195
|
+
return CameraState.from_json(await self.request("/gp/gpControl/status"))
|
|
196
|
+
|
|
197
|
+
async def get_schema(self) -> Schema:
|
|
198
|
+
return Schema.from_json(await self.request("/gp/gpControl", timeout=30))
|
|
199
|
+
|
|
200
|
+
async def get_presets(self) -> list[Preset]:
|
|
201
|
+
return parse_presets(await self.request("/gopro/camera/presets/get"))
|
|
202
|
+
|
|
203
|
+
async def get_presets_raw(self) -> dict[str, Any]:
|
|
204
|
+
return await self.request("/gopro/camera/presets/get")
|
|
205
|
+
|
|
206
|
+
async def get_media_list(self) -> list[MediaFile]:
|
|
207
|
+
return parse_media_list(await self.request("/gp/gpMediaList", timeout=30))
|
|
208
|
+
|
|
209
|
+
async def get_last_captured(self) -> str | None:
|
|
210
|
+
data = await self.request("/gopro/media/last_captured")
|
|
211
|
+
if not data or not data.get("file"):
|
|
212
|
+
return None
|
|
213
|
+
return f"{data.get('folder', '')}/{data['file']}"
|
|
214
|
+
|
|
215
|
+
async def get_media_info(self, path: str) -> dict[str, Any]:
|
|
216
|
+
return await self.request("/gopro/media/info", {"path": path})
|
|
217
|
+
|
|
218
|
+
async def get_date_time(self) -> dict[str, Any]:
|
|
219
|
+
return await self.request("/gopro/camera/get_date_time")
|
|
220
|
+
|
|
221
|
+
async def get_camera_name(self) -> str:
|
|
222
|
+
return str((await self.request("/gopro/camera/name")).get("value", ""))
|
|
223
|
+
|
|
224
|
+
async def get_cohn_status(self) -> CohnStatus:
|
|
225
|
+
d = await self.request("/gopro/cohn/status")
|
|
226
|
+
return CohnStatus(
|
|
227
|
+
provisioned=d.get("status") == "COHN_PROVISIONED",
|
|
228
|
+
state=re.sub(r"(?<!^)(?=[A-Z])", "_", str(d.get("state", "")).removeprefix("COHN_STATE_")).upper(),
|
|
229
|
+
username=d.get("username", ""),
|
|
230
|
+
password=d.get("password", ""),
|
|
231
|
+
ip_address=d.get("ipaddress", ""),
|
|
232
|
+
enabled=bool(d.get("enabled")),
|
|
233
|
+
ssid=d.get("ssid", ""),
|
|
234
|
+
mac_address=d.get("macaddress", ""),
|
|
235
|
+
)
|
|
236
|
+
|
|
237
|
+
async def get_mobile_offload_state(self) -> dict[str, Any]:
|
|
238
|
+
return await self.request("/gp/gpControl/command/mobile_offload/get_state")
|
|
239
|
+
|
|
240
|
+
async def get_beacon(self) -> dict[str, Any]:
|
|
241
|
+
return await self.request("/gp/gpControl/command/system/get_beacon")
|
|
242
|
+
|
|
243
|
+
async def get_analytics(self) -> bytes:
|
|
244
|
+
return await self.request("/gopro/camera/analytics/get", raw=True)
|
|
245
|
+
|
|
246
|
+
async def get_file_access_log(self) -> str:
|
|
247
|
+
"""``/fa_log``: recent file reads ("[R] 100GOPRO/GS010001.LRV")."""
|
|
248
|
+
body = await self.request("/fa_log", raw=True)
|
|
249
|
+
return body.decode(errors="replace")
|
|
250
|
+
|
|
251
|
+
async def get_root_ca(self) -> str:
|
|
252
|
+
return (await self.request("/GoProRootCA.crt", raw=True)).decode()
|
|
253
|
+
|
|
254
|
+
async def get_webcam_status(self) -> dict[str, Any]:
|
|
255
|
+
return await self.request("/gopro/webcam/status")
|
|
256
|
+
|
|
257
|
+
# -- media ---------------------------------------------------------------------------------------
|
|
258
|
+
|
|
259
|
+
@staticmethod
|
|
260
|
+
def media_path(path: str) -> str:
|
|
261
|
+
return f"/videos/DCIM/{path.lstrip('/')}"
|
|
262
|
+
|
|
263
|
+
async def get_thumbnail(self, path: str) -> bytes:
|
|
264
|
+
return await self.request("/gopro/media/thumbnail", {"path": path}, raw=True, timeout=30)
|
|
265
|
+
|
|
266
|
+
async def get_screennail(self, path: str) -> bytes:
|
|
267
|
+
return await self.request("/gopro/media/screennail", {"path": path}, raw=True, timeout=30)
|
|
268
|
+
|
|
269
|
+
async def get_gpmf(self, path: str) -> bytes:
|
|
270
|
+
return await self.request("/gopro/media/gpmf", {"path": path}, raw=True, timeout=60)
|
|
271
|
+
|
|
272
|
+
async def get_telemetry(self, path: str) -> bytes:
|
|
273
|
+
return await self.request("/gopro/media/telemetry", {"path": path}, raw=True, timeout=60)
|
|
274
|
+
|
|
275
|
+
async def download(self, path: str) -> AsyncIterator[bytes]:
|
|
276
|
+
async for chunk in self.stream(self.media_path(path)):
|
|
277
|
+
yield chunk
|
|
278
|
+
|
|
279
|
+
async def delete_file(self, path: str) -> None:
|
|
280
|
+
await self.request("/gopro/media/delete/file", {"path": path})
|
|
281
|
+
|
|
282
|
+
async def delete_last(self) -> None:
|
|
283
|
+
await self.request("/gp/gpControl/command/storage/delete/last")
|
|
284
|
+
|
|
285
|
+
async def delete_all(self) -> None:
|
|
286
|
+
await self.request("/gp/gpControl/command/storage/delete/all", timeout=120)
|
|
287
|
+
|
|
288
|
+
async def hilight_file(self, path: str, ms: int | None = None) -> None:
|
|
289
|
+
params: dict[str, Any] = {"path": path}
|
|
290
|
+
if ms is not None:
|
|
291
|
+
params["ms"] = ms
|
|
292
|
+
await self.request("/gopro/media/hilight/file", params)
|
|
293
|
+
|
|
294
|
+
async def hilight_remove(self, path: str, ms: int | None = None) -> None:
|
|
295
|
+
params: dict[str, Any] = {"path": path}
|
|
296
|
+
if ms is not None:
|
|
297
|
+
params["ms"] = ms
|
|
298
|
+
await self.request("/gopro/media/hilight/remove", params)
|
|
299
|
+
|
|
300
|
+
async def set_turbo_transfer(self, enabled: bool) -> None:
|
|
301
|
+
await self.request("/gopro/media/turbo_transfer", {"p": int(enabled)})
|
|
302
|
+
|
|
303
|
+
# -- control -------------------------------------------------------------------------------------
|
|
304
|
+
|
|
305
|
+
async def keep_alive(self) -> None:
|
|
306
|
+
await self.request("/gopro/camera/keep_alive")
|
|
307
|
+
|
|
308
|
+
async def shutter(self, start: bool) -> None:
|
|
309
|
+
await self.request(f"/gopro/camera/shutter/{'start' if start else 'stop'}")
|
|
310
|
+
|
|
311
|
+
async def set_setting(self, setting_id: int, option_id: int) -> None:
|
|
312
|
+
await self.request("/gopro/camera/setting", {"setting": setting_id, "option": option_id})
|
|
313
|
+
|
|
314
|
+
async def load_preset(self, preset_id: int) -> None:
|
|
315
|
+
await self.request("/gopro/camera/presets/load", {"id": preset_id})
|
|
316
|
+
|
|
317
|
+
async def load_preset_group(self, group_id: int) -> None:
|
|
318
|
+
await self.request("/gopro/camera/presets/set_group", {"id": group_id})
|
|
319
|
+
|
|
320
|
+
async def set_date_time(self, when: datetime, tz_offset_minutes: int | None = None, dst: bool = False) -> None:
|
|
321
|
+
params: dict[str, Any] = {
|
|
322
|
+
"date": f"{when.year}_{when.month}_{when.day}",
|
|
323
|
+
"time": f"{when.hour}_{when.minute}_{when.second}",
|
|
324
|
+
}
|
|
325
|
+
if tz_offset_minutes is not None:
|
|
326
|
+
params["tzone"] = tz_offset_minutes
|
|
327
|
+
params["dst"] = int(dst)
|
|
328
|
+
await self.request("/gopro/camera/set_date_time", params)
|
|
329
|
+
|
|
330
|
+
async def set_digital_zoom(self, percent: int) -> None:
|
|
331
|
+
await self.request("/gopro/camera/digital_zoom", {"percent": max(0, min(100, int(percent)))})
|
|
332
|
+
|
|
333
|
+
async def set_client_info(self) -> None:
|
|
334
|
+
"""Tell the camera a third-party client is in control (Open GoPro analytics)."""
|
|
335
|
+
await self.request("/gopro/camera/analytics/set_client_info")
|
|
336
|
+
|
|
337
|
+
async def set_camera_control(self, external: bool) -> None:
|
|
338
|
+
"""Claim (``True``) / release the UI so the camera shows "external control"."""
|
|
339
|
+
await self.request("/gopro/camera/control/set_ui_controller", {"p": 2 if external else 0})
|
|
340
|
+
|
|
341
|
+
async def start_preview(self, port: int | None = None) -> None:
|
|
342
|
+
params = {"port": port} if port else None
|
|
343
|
+
await self.request("/gopro/camera/stream/start", params)
|
|
344
|
+
|
|
345
|
+
async def stop_preview(self) -> None:
|
|
346
|
+
await self.request("/gopro/camera/stream/stop")
|
|
347
|
+
|
|
348
|
+
# legacy commands (found in gpHttpServer's command_handler_table) --------------------------------
|
|
349
|
+
|
|
350
|
+
async def legacy(self, command: str, **params: Any) -> Any:
|
|
351
|
+
"""``/gp/gpControl/command/<command>`` with ``p=`` style parameters."""
|
|
352
|
+
return await self.request(f"/gp/gpControl/command/{command.strip('/')}", params or None)
|
|
353
|
+
|
|
354
|
+
async def locate(self, on: bool) -> None:
|
|
355
|
+
"""Make the camera beep/blink so it can be found."""
|
|
356
|
+
await self.legacy("system/locate", p=int(on))
|
|
357
|
+
|
|
358
|
+
async def sleep(self) -> None:
|
|
359
|
+
"""Put the camera to sleep (BLE stays up so it can be woken)."""
|
|
360
|
+
await self.legacy("system/sleep")
|
|
361
|
+
|
|
362
|
+
async def tag_moment(self) -> None:
|
|
363
|
+
"""Add a HiLight to the current recording."""
|
|
364
|
+
await self.legacy("storage/tag_moment")
|
|
365
|
+
|
|
366
|
+
async def protune_reset(self) -> None:
|
|
367
|
+
await self.legacy("protune/reset")
|
|
368
|
+
|
|
369
|
+
async def set_photo_timer(self, seconds: int) -> None:
|
|
370
|
+
await self.legacy("photo_timer", p=seconds)
|
|
371
|
+
|
|
372
|
+
async def clear_new_media_flag(self) -> None:
|
|
373
|
+
await self.legacy("mobile_offload/clear_new_media_flag")
|
pygopro/models.py
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
"""Typed results."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from datetime import UTC, datetime
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass(frozen=True)
|
|
11
|
+
class CameraInfo:
|
|
12
|
+
model_number: int
|
|
13
|
+
model_name: str
|
|
14
|
+
firmware_version: str
|
|
15
|
+
serial_number: str
|
|
16
|
+
ap_ssid: str = ""
|
|
17
|
+
ap_mac: str = ""
|
|
18
|
+
board_type: str = ""
|
|
19
|
+
lens_count: int | None = None
|
|
20
|
+
git_sha1: str = ""
|
|
21
|
+
|
|
22
|
+
@classmethod
|
|
23
|
+
def from_json(cls, data: dict[str, Any]) -> CameraInfo:
|
|
24
|
+
data = data.get("info", data)
|
|
25
|
+
lens = data.get("lens_count")
|
|
26
|
+
return cls(
|
|
27
|
+
model_number=int(data.get("model_number") or 0),
|
|
28
|
+
model_name=str(data.get("model_name") or "GoPro"),
|
|
29
|
+
firmware_version=str(data.get("firmware_version") or ""),
|
|
30
|
+
serial_number=str(data.get("serial_number") or ""),
|
|
31
|
+
ap_ssid=str(data.get("ap_ssid") or ""),
|
|
32
|
+
ap_mac=str(data.get("ap_mac_addr") or data.get("ap_mac") or ""),
|
|
33
|
+
board_type=str(data.get("board_type") or ""),
|
|
34
|
+
lens_count=int(lens) if lens not in (None, "") else None,
|
|
35
|
+
git_sha1=str(data.get("git_sha1") or ""),
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass(frozen=True)
|
|
40
|
+
class CohnCredentials:
|
|
41
|
+
"""Everything needed to reach a camera over its home network."""
|
|
42
|
+
|
|
43
|
+
host: str
|
|
44
|
+
username: str
|
|
45
|
+
password: str
|
|
46
|
+
certificate: str # PEM of the camera's root CA ("GoPro Camera Root")
|
|
47
|
+
mac_address: str = ""
|
|
48
|
+
ssid: str = ""
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass(frozen=True)
|
|
52
|
+
class CohnStatus:
|
|
53
|
+
provisioned: bool
|
|
54
|
+
state: str
|
|
55
|
+
username: str = ""
|
|
56
|
+
password: str = ""
|
|
57
|
+
ip_address: str = ""
|
|
58
|
+
enabled: bool = False
|
|
59
|
+
ssid: str = ""
|
|
60
|
+
mac_address: str = ""
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@dataclass(frozen=True)
|
|
64
|
+
class CameraState:
|
|
65
|
+
status: dict[int, Any]
|
|
66
|
+
settings: dict[int, int]
|
|
67
|
+
|
|
68
|
+
@classmethod
|
|
69
|
+
def from_json(cls, data: dict[str, Any]) -> CameraState:
|
|
70
|
+
return cls(
|
|
71
|
+
status={int(k): v for k, v in (data.get("status") or {}).items()},
|
|
72
|
+
settings={int(k): int(v) for k, v in (data.get("settings") or {}).items() if _is_int(v)},
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _is_int(v: Any) -> bool:
|
|
77
|
+
try:
|
|
78
|
+
int(v)
|
|
79
|
+
except (TypeError, ValueError):
|
|
80
|
+
return False
|
|
81
|
+
return True
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@dataclass(frozen=True)
|
|
85
|
+
class MediaFile:
|
|
86
|
+
folder: str
|
|
87
|
+
name: str
|
|
88
|
+
size: int
|
|
89
|
+
created: datetime | None
|
|
90
|
+
modified: datetime | None
|
|
91
|
+
low_res_size: int | None = None
|
|
92
|
+
group_id: str | None = None
|
|
93
|
+
raw: dict[str, Any] = field(default_factory=dict, compare=False, repr=False)
|
|
94
|
+
|
|
95
|
+
@property
|
|
96
|
+
def path(self) -> str:
|
|
97
|
+
return f"{self.folder}/{self.name}"
|
|
98
|
+
|
|
99
|
+
@property
|
|
100
|
+
def extension(self) -> str:
|
|
101
|
+
return self.name.rsplit(".", 1)[-1].upper() if "." in self.name else ""
|
|
102
|
+
|
|
103
|
+
@property
|
|
104
|
+
def is_video(self) -> bool:
|
|
105
|
+
return self.extension in {"MP4", "360", "LRV"}
|
|
106
|
+
|
|
107
|
+
@property
|
|
108
|
+
def is_photo(self) -> bool:
|
|
109
|
+
return self.extension in {"JPG", "36P", "GPR"}
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def parse_media_list(data: dict[str, Any]) -> list[MediaFile]:
|
|
113
|
+
out: list[MediaFile] = []
|
|
114
|
+
for folder in data.get("media") or []:
|
|
115
|
+
d = folder.get("d", "")
|
|
116
|
+
for f in folder.get("fs") or []:
|
|
117
|
+
out.append(
|
|
118
|
+
MediaFile(
|
|
119
|
+
folder=d,
|
|
120
|
+
name=f.get("n", ""),
|
|
121
|
+
size=int(f.get("s") or 0),
|
|
122
|
+
created=_ts(f.get("cre")),
|
|
123
|
+
modified=_ts(f.get("mod")),
|
|
124
|
+
low_res_size=int(f["ls"]) if str(f.get("ls", "")).lstrip("-").isdigit() and int(f["ls"]) >= 0 else None,
|
|
125
|
+
group_id=str(f["g"]) if "g" in f else None,
|
|
126
|
+
raw=f,
|
|
127
|
+
)
|
|
128
|
+
)
|
|
129
|
+
out.sort(key=lambda m: (m.created or datetime.min, m.path))
|
|
130
|
+
return out
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _ts(v: Any) -> datetime | None:
|
|
134
|
+
# The camera stores local wall-clock time as if it were UTC seconds.
|
|
135
|
+
try:
|
|
136
|
+
return datetime.fromtimestamp(int(v), UTC).replace(tzinfo=None) if v not in (None, "") else None
|
|
137
|
+
except (TypeError, ValueError, OverflowError):
|
|
138
|
+
return None
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
PRESET_GROUP_IDS = {"PRESET_GROUP_ID_VIDEO": 1000, "PRESET_GROUP_ID_PHOTO": 1001, "PRESET_GROUP_ID_TIMELAPSE": 1002}
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
@dataclass(frozen=True)
|
|
145
|
+
class Preset:
|
|
146
|
+
id: int
|
|
147
|
+
group_id: int
|
|
148
|
+
group: str
|
|
149
|
+
mode: str
|
|
150
|
+
title_id: str
|
|
151
|
+
custom_title: str
|
|
152
|
+
is_modified: bool
|
|
153
|
+
is_visible: bool
|
|
154
|
+
user_defined: bool
|
|
155
|
+
settings: dict[int, int]
|
|
156
|
+
|
|
157
|
+
@property
|
|
158
|
+
def title(self) -> str:
|
|
159
|
+
"""Readable title ("PRESET_TITLE_TIME_WARP" -> "Time Warp")."""
|
|
160
|
+
if self.custom_title:
|
|
161
|
+
return self.custom_title
|
|
162
|
+
t = self.title_id.removeprefix("PRESET_TITLE_").replace("_", " ").strip()
|
|
163
|
+
return t.title() if t else str(self.id)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def parse_presets(data: dict[str, Any]) -> list[Preset]:
|
|
167
|
+
out: list[Preset] = []
|
|
168
|
+
for g in data.get("presetGroupArray") or []:
|
|
169
|
+
gid = str(g.get("id", ""))
|
|
170
|
+
for p in g.get("presetArray") or []:
|
|
171
|
+
out.append(
|
|
172
|
+
Preset(
|
|
173
|
+
id=int(p.get("id", 0)),
|
|
174
|
+
group_id=PRESET_GROUP_IDS.get(gid, 0),
|
|
175
|
+
group=gid.removeprefix("PRESET_GROUP_ID_").lower(),
|
|
176
|
+
mode=str(p.get("mode", "")),
|
|
177
|
+
title_id=str(p.get("titleId", "")),
|
|
178
|
+
custom_title=str(p.get("customName", "") or ""),
|
|
179
|
+
is_modified=bool(p.get("isModified")),
|
|
180
|
+
is_visible=bool(p.get("isVisible", True)),
|
|
181
|
+
user_defined=bool(p.get("userDefined")),
|
|
182
|
+
settings={int(s["id"]): int(s["value"]) for s in p.get("settingArray") or [] if "id" in s},
|
|
183
|
+
)
|
|
184
|
+
)
|
|
185
|
+
return out
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
@dataclass(frozen=True)
|
|
189
|
+
class AccessPoint:
|
|
190
|
+
ssid: str
|
|
191
|
+
signal_bars: int
|
|
192
|
+
frequency_mhz: int
|
|
193
|
+
flags: int
|
|
194
|
+
|
|
195
|
+
@property
|
|
196
|
+
def configured(self) -> bool:
|
|
197
|
+
return bool(self.flags & 0x02)
|
|
198
|
+
|
|
199
|
+
@property
|
|
200
|
+
def open(self) -> bool:
|
|
201
|
+
return not self.flags & 0x01
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
@dataclass(frozen=True)
|
|
205
|
+
class HardwareInfo:
|
|
206
|
+
model_number: int
|
|
207
|
+
model_name: str
|
|
208
|
+
firmware_version: str
|
|
209
|
+
serial_number: str
|
|
210
|
+
ap_ssid: str
|
|
211
|
+
ap_mac: str
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
@dataclass(frozen=True)
|
|
215
|
+
class FirmwareRelease:
|
|
216
|
+
model_number: int
|
|
217
|
+
model_string: str
|
|
218
|
+
name: str
|
|
219
|
+
version: str
|
|
220
|
+
url: str
|
|
221
|
+
release_date: str
|
|
222
|
+
sha1: str
|
|
223
|
+
release_html: str = ""
|
|
224
|
+
|
|
225
|
+
@property
|
|
226
|
+
def full_version(self) -> str:
|
|
227
|
+
"""Same shape as ``firmware_version`` reported by the camera (e.g. H24.02.01.34.00)."""
|
|
228
|
+
return f"{self.model_string}.{self.version}"
|