python-gopro 0.1.0__tar.gz → 0.1.1__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: python-gopro
3
- Version: 0.1.0
3
+ Version: 0.1.1
4
4
  Summary: Async local client for GoPro cameras (HTTPS over Camera-on-Home-Network + BLE), built from reverse engineering the MAX2 firmware
5
5
  Project-URL: Homepage, https://github.com/hudsonbrendon/python-gopro
6
6
  Project-URL: Repository, https://github.com/hudsonbrendon/python-gopro
@@ -24,7 +24,7 @@ from .models import (
24
24
  )
25
25
  from .schema import Schema, Setting, SettingOption, StatusField
26
26
 
27
- __version__ = "0.1.0"
27
+ __version__ = "0.1.1"
28
28
 
29
29
  __all__ = [
30
30
  "GOPRO_MANUFACTURER_ID",
@@ -290,8 +290,19 @@ class GoProBle:
290
290
  async def set_setting(self, setting_id: int, value: int, size: int = 1) -> None:
291
291
  await self.tlv(UUID_SETTINGS, UUID_SETTINGS_RESP, setting_id, value.to_bytes(size, "big"))
292
292
 
293
- async def keep_alive(self) -> None:
294
- await self.set_setting(KEEP_ALIVE_SETTING, KEEP_ALIVE_VALUE)
293
+ async def keep_alive(self) -> bool:
294
+ """Poke the camera so it stays (or wakes) up.
295
+
296
+ While it is still booting the camera may answer status 1; the link itself is what wakes it,
297
+ so that is reported as ``False`` instead of raising.
298
+ """
299
+ try:
300
+ await self.set_setting(KEEP_ALIVE_SETTING, KEEP_ALIVE_VALUE)
301
+ except GoProBleError as err:
302
+ if "failed with status" not in str(err):
303
+ raise
304
+ return False
305
+ return True
295
306
 
296
307
  async def get_statuses(self, *status_ids: int) -> dict[int, bytes]:
297
308
  async with self._lock:
@@ -65,13 +65,21 @@ class GoProHttp:
65
65
  session: aiohttp.ClientSession | None = None,
66
66
  port: int | None = None,
67
67
  ssl: bool | None = None,
68
+ ssl_context: ssl_mod.SSLContext | None = None,
68
69
  timeout: float = DEFAULT_TIMEOUT,
69
70
  ) -> None:
71
+ """``ssl_context`` lets callers build the context off the event loop (loading a CA blocks)."""
70
72
  self.host = host
71
- self._use_ssl = bool(certificate) if ssl is None else ssl
73
+ self._use_ssl = bool(certificate or ssl_context) if ssl is None else ssl
72
74
  self.port = port or (443 if self._use_ssl else 8080)
73
75
  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
76
+ self._ssl: ssl_mod.SSLContext | bool
77
+ if ssl_context is not None:
78
+ self._ssl = ssl_context
79
+ elif self._use_ssl and certificate:
80
+ self._ssl = build_ssl_context(certificate)
81
+ else:
82
+ self._ssl = self._use_ssl
75
83
  self._session = session
76
84
  self._own_session = session is None
77
85
  self._timeout = aiohttp.ClientTimeout(total=timeout)
@@ -123,14 +131,42 @@ class GoProHttp:
123
131
  raw: bool = False,
124
132
  timeout: float | None = None,
125
133
  ) -> Any:
126
- """Perform a request and decode JSON (or return bytes with ``raw=True``)."""
134
+ """Perform a request and decode JSON (or return bytes with ``raw=True``).
135
+
136
+ Every request uses ``Connection: close``: the camera's civetweb drops idle connections
137
+ after 1 s (``keep_alive_timeout_ms=1000``), so a pooled connection is usually dead and
138
+ would surface as a bogus disconnect.
139
+ """
127
140
  if any(path.startswith(p) for p in DANGEROUS_PATHS):
128
141
  raise GoProCommandError(f"{path} is blocked: it wedges the camera's control channel")
142
+ for attempt in (1, 2):
143
+ try:
144
+ return await self._request_once(path, params, method, json_body, raw, timeout)
145
+ except aiohttp.ServerDisconnectedError as err:
146
+ if attempt == 2:
147
+ # A fresh connection closed without an answer: COHN does that for bad basic auth.
148
+ raise GoProAuthError("server closed the connection (missing or invalid credentials?)") from err
149
+ except aiohttp.ClientOSError as err:
150
+ if attempt == 2:
151
+ raise GoProConnectionError(f"{self.host}: {err!s}") from err
152
+ await asyncio.sleep(0.3)
153
+ raise GoProConnectionError(self.host) # pragma: no cover
154
+
155
+ async def _request_once(
156
+ self, path: str, params: dict[str, Any] | None, method: str, json_body: Any, raw: bool, timeout: float | None
157
+ ) -> Any:
129
158
  session = await self._get_session()
130
159
  to = aiohttp.ClientTimeout(total=timeout) if timeout else self._timeout
131
160
  try:
132
161
  async with session.request(
133
- method, self.url(path), params=params, json=json_body, auth=self._auth, ssl=self._ssl, timeout=to
162
+ method,
163
+ self.url(path),
164
+ params=params,
165
+ json=json_body,
166
+ auth=self._auth,
167
+ ssl=self._ssl,
168
+ timeout=to,
169
+ headers={"Connection": "close"},
134
170
  ) as resp:
135
171
  body = await resp.read()
136
172
  if resp.status == 401:
@@ -151,10 +187,9 @@ class GoProHttp:
151
187
  return json.loads(body)
152
188
  except ValueError:
153
189
  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:
190
+ except (aiohttp.ServerDisconnectedError, aiohttp.ClientOSError):
191
+ raise
192
+ except (aiohttp.ClientConnectorError, TimeoutError) as err:
158
193
  raise GoProConnectionError(f"{self.host}: {err!s}") from err
159
194
  except aiohttp.ClientResponseError as err:
160
195
  raise GoProCommandError(str(err), err.status) from err
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "python-gopro"
7
- version = "0.1.0"
7
+ version = "0.1.1"
8
8
  description = "Async local client for GoPro cameras (HTTPS over Camera-on-Home-Network + BLE), built from reverse engineering the MAX2 firmware"
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -103,3 +103,35 @@ async def test_unreachable():
103
103
  with pytest.raises(GoProConnectionError):
104
104
  await cam.get_info()
105
105
  await cam.close()
106
+
107
+
108
+ async def test_retries_once_after_disconnect():
109
+ hits = {"n": 0}
110
+
111
+ async def handler(request: web.Request) -> web.StreamResponse:
112
+ hits["n"] += 1
113
+ if hits["n"] == 1:
114
+ request.transport.close() # what a stale keep-alive connection looks like
115
+ return web.Response()
116
+ assert request.headers.get("Connection") == "close"
117
+ return web.json_response(INFO)
118
+
119
+ app = web.Application()
120
+ app.router.add_get("/gopro/camera/info", handler)
121
+ server = TestServer(app)
122
+ await server.start_server()
123
+ cam = GoProHttp("127.0.0.1", port=server.port, ssl=False)
124
+ try:
125
+ assert (await cam.get_info()).model_name == "MAX2"
126
+ assert hits["n"] == 2
127
+ finally:
128
+ await cam.close()
129
+ await server.close()
130
+
131
+
132
+ async def test_ssl_context_injection():
133
+ import ssl
134
+
135
+ ctx = ssl.create_default_context()
136
+ cam = GoProHttp("10.0.0.1", ssl_context=ctx)
137
+ assert cam.ssl_context is ctx and cam.base_url == "https://10.0.0.1"
File without changes
File without changes
File without changes