pyimouapi 1.4.4__tar.gz → 1.4.5__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.
Files changed (66) hide show
  1. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/PKG-INFO +1 -1
  2. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/pyimouapi/__init__.py +1 -1
  3. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/pyimouapi/device.py +13 -0
  4. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/pyimouapi/ha_device.py +106 -6
  5. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/pyimouapi/openapi.py +16 -4
  6. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/pyimouapi.egg-info/PKG-INFO +1 -1
  7. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/pyimouapi.egg-info/SOURCES.txt +1 -0
  8. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/pyproject.toml +1 -1
  9. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/setup.py +1 -1
  10. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/tests/test_device_stream.py +1 -1
  11. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/tests/test_get_devices.py +18 -0
  12. pyimouapi-1.4.5/tests/test_live_stream_source.py +206 -0
  13. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/tests/test_openapi_http.py +65 -3
  14. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/LICENSE +0 -0
  15. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/README.md +0 -0
  16. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/pyimouapi/alarm_mode.py +0 -0
  17. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/pyimouapi/bulb_light.py +0 -0
  18. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/pyimouapi/collection_point.py +0 -0
  19. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/pyimouapi/const.py +0 -0
  20. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/pyimouapi/dormant_retry.py +0 -0
  21. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/pyimouapi/exceptions.py +0 -0
  22. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/pyimouapi/pic_decode.py +0 -0
  23. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/pyimouapi/push.py +0 -0
  24. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/pyimouapi/py.typed +0 -0
  25. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/pyimouapi/select_option.py +0 -0
  26. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/pyimouapi/sensor.py +0 -0
  27. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/pyimouapi/siren.py +0 -0
  28. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/pyimouapi.egg-info/dependency_links.txt +0 -0
  29. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/pyimouapi.egg-info/not-zip-safe +0 -0
  30. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/pyimouapi.egg-info/requires.txt +0 -0
  31. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/pyimouapi.egg-info/top_level.txt +0 -0
  32. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/setup.cfg +0 -0
  33. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/tests/test_accessory_device_id.py +0 -0
  34. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/tests/test_alarm_control_panel.py +0 -0
  35. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/tests/test_alarm_mode.py +0 -0
  36. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/tests/test_alarm_pir_switch.py +0 -0
  37. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/tests/test_auth_failure_propagates.py +0 -0
  38. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/tests/test_bind_device.py +0 -0
  39. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/tests/test_bulb_light.py +0 -0
  40. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/tests/test_channel_id_and_api_guards.py +0 -0
  41. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/tests/test_collect_property_entities.py +0 -0
  42. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/tests/test_collection_point.py +0 -0
  43. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/tests/test_connection_pool.py +0 -0
  44. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/tests/test_device_image.py +0 -0
  45. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/tests/test_device_summaries.py +0 -0
  46. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/tests/test_dormant_write_retry.py +0 -0
  47. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/tests/test_entity_tables_golden.py +0 -0
  48. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/tests/test_event_identifier_map.py +0 -0
  49. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/tests/test_feature_switches.py +0 -0
  50. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/tests/test_lookup_property.py +0 -0
  51. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/tests/test_message_callback.py +0 -0
  52. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/tests/test_motion_detect_excepts.py +0 -0
  53. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/tests/test_packaging.py +0 -0
  54. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/tests/test_pic_decode.py +0 -0
  55. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/tests/test_product_id_guard.py +0 -0
  56. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/tests/test_push.py +0 -0
  57. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/tests/test_select_option.py +0 -0
  58. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/tests/test_sensor_normalize.py +0 -0
  59. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/tests/test_services_entities_concurrency.py +0 -0
  60. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/tests/test_set_text_value.py +0 -0
  61. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/tests/test_shared_status_reads.py +0 -0
  62. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/tests/test_siren.py +0 -0
  63. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/tests/test_status_read_concurrency.py +0 -0
  64. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/tests/test_switch_status_aggregation.py +0 -0
  65. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/tests/test_update_from_detail.py +0 -0
  66. {pyimouapi-1.4.4 → pyimouapi-1.4.5}/tests/test_write_optimistic_state.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyimouapi
3
- Version: 1.4.4
3
+ Version: 1.4.5
4
4
  Summary: A package for imou open api
5
5
  Home-page: https://github.com/Imou-OpenPlatform/Py-Imou-Open-Api
6
6
  Author: Imou-OpenPlatform
@@ -1,4 +1,4 @@
1
- __version__ = "1.4.4"
1
+ __version__ = "1.4.5"
2
2
 
3
3
  from .device import ImouChannel, ImouDevice, ImouDeviceManager
4
4
  from .exceptions import (
@@ -195,6 +195,7 @@ class ImouDevice:
195
195
  self._is_multi = False
196
196
  self._is_ipc = False
197
197
  self._access_type = "PaaS"
198
+ self._source = ""
198
199
 
199
200
  @property
200
201
  def device_id(self) -> str:
@@ -258,6 +259,14 @@ class ImouDevice:
258
259
  def access_type(self) -> str:
259
260
  return self._access_type
260
261
 
262
+ @property
263
+ def source(self) -> str:
264
+ """Device detail ``source``, such as ``bind`` or ``share``."""
265
+ return self._source
266
+
267
+ def set_source(self, source: str) -> None:
268
+ self._source = source
269
+
261
270
  def set_product_id(self, product_id: str) -> None:
262
271
  self._product_id = product_id
263
272
 
@@ -414,6 +423,10 @@ class ImouDeviceManager:
414
423
  imou_device.set_is_multi(device[PARAM_MULTI_FLAG])
415
424
  if PARAM_ACCESS_TYPE in device:
416
425
  imou_device.set_access_type(device[PARAM_ACCESS_TYPE])
426
+ raw_source = device.get("source")
427
+ imou_device.set_source(
428
+ raw_source.strip() if isinstance(raw_source, str) else ""
429
+ )
417
430
  if PARAM_CHANNEL_LIST in device:
418
431
  channel_list = device[PARAM_CHANNEL_LIST] or []
419
432
  if not isinstance(channel_list, list):
@@ -30,6 +30,8 @@ from .const import (
30
30
  BUTTON_TYPE_ABILITY,
31
31
  BUTTON_TYPE_PARAM_VALUE,
32
32
  BUTTON_TYPE_REF,
33
+ ERROR_CODE_LIVE_ALREADY_EXIST,
34
+ ERROR_CODE_LIVE_NOT_EXIST,
33
35
  ERROR_CODE_NO_STORAGE_MEDIUM,
34
36
  PARAM_ABILITY,
35
37
  PARAM_ALKELEC,
@@ -47,6 +49,7 @@ from .const import (
47
49
  PARAM_EXPRESSION,
48
50
  PARAM_FUNCTION_TYPE,
49
51
  PARAM_HD,
52
+ PARAM_HLS,
50
53
  PARAM_HUMIDITY_CURRENT,
51
54
  PARAM_INPUT_REF,
52
55
  PARAM_LITELEC,
@@ -69,6 +72,8 @@ from .const import (
69
72
  PARAM_STATE,
70
73
  PARAM_STATUS,
71
74
  PARAM_STORAGE_USED,
75
+ PARAM_STREAM_ID,
76
+ PARAM_STREAMS,
72
77
  PARAM_SUPPORTED,
73
78
  PARAM_TEMPERATURE_CURRENT,
74
79
  PARAM_TOTAL_BYTES,
@@ -95,6 +100,29 @@ from .siren import build_siren_start_iot_content
95
100
  _LOGGER: logging.Logger = logging.getLogger(__package__)
96
101
 
97
102
 
103
+ def _safe_stream_host(url: str) -> str:
104
+ """Return only a validated hostname and port for debug logging."""
105
+ if not isinstance(url, str) or any(
106
+ not character.isprintable() or character.isspace() for character in url
107
+ ):
108
+ return "***"
109
+ try:
110
+ parsed = urlparse(url)
111
+ hostname = parsed.hostname or ""
112
+ port = parsed.port
113
+ except ValueError:
114
+ return "***"
115
+ if (
116
+ parsed.scheme not in {"http", "https", "rtsp", "rtmp"}
117
+ or not hostname
118
+ or port == 0
119
+ or any(character in hostname for character in "/\\@?#%")
120
+ ):
121
+ return "***"
122
+ host = f"[{hostname}]" if ":" in hostname else hostname
123
+ return f"{host}:{port}" if port is not None else host
124
+
125
+
98
126
  def property_is_on(raw: Any) -> bool | None:
99
127
  """Return True/False for an on/off property, or None when it cannot be read.
100
128
 
@@ -335,6 +363,7 @@ class ImouHaDevice:
335
363
  self._parent_device_id: str | None = None
336
364
  self._device_ability = "unknown"
337
365
  self._channel_ability = "unknown"
366
+ self._source = ""
338
367
 
339
368
  @property
340
369
  def device_id(self) -> str:
@@ -444,11 +473,20 @@ class ImouHaDevice:
444
473
  def set_channel_ability(self, channel_ability: str) -> None:
445
474
  self._channel_ability = channel_ability
446
475
 
476
+ @property
477
+ def source(self) -> str:
478
+ """Account relationship from the device list, such as ``bind`` or ``share``."""
479
+ return self._source
480
+
481
+ def set_source(self, source: str) -> None:
482
+ self._source = source
483
+
447
484
  def apply_identity(self, other: ImouHaDevice) -> None:
448
485
  """Copy name, model, and firmware from a freshly listed device."""
449
486
  self._device_name = other.device_name
450
487
  self._model = other.model
451
488
  self._swversion = other.swversion
489
+ self._source = other.source
452
490
  if other.channel_name is not None:
453
491
  self._channel_name = other.channel_name
454
492
 
@@ -1155,13 +1193,22 @@ class ImouHaDeviceManager:
1155
1193
  async def async_get_device_stream(
1156
1194
  self, device: ImouHaDevice, live_resolution: str, live_protocol: str = ""
1157
1195
  ) -> str:
1158
- """Return a fresh cloud RTSP URL from getStreamUrl.
1196
+ """Return a live URL for this camera.
1159
1197
 
1160
- ``live_protocol`` is unused (kept so Home Assistant callers that
1161
- still pass https keep working). Shared-account viewers cannot use
1162
- HLS live addresses; getStreamUrl works for the owner and sharers.
1198
+ Owner cameras use the cloud HLS address (bindDeviceLive). Shared
1199
+ cameras and cameras with no source use getStreamUrl. Overseas regions
1200
+ often reject real-time FLV.
1163
1201
  """
1164
- del live_protocol
1202
+ if device.source == "bind":
1203
+ return await self._async_get_bind_live(
1204
+ device, live_resolution, live_protocol
1205
+ )
1206
+ return await self._async_get_rtsp_live(device, live_resolution)
1207
+
1208
+ async def _async_get_rtsp_live(
1209
+ self, device: ImouHaDevice, live_resolution: str
1210
+ ) -> str:
1211
+ """Return a fresh cloud RTSP URL from getStreamUrl."""
1165
1212
  stream_id = 0 if live_resolution == PARAM_HD else 1
1166
1213
  data = await self.delegate.async_get_rtsp_stream_url(
1167
1214
  device.device_id,
@@ -1174,7 +1221,59 @@ class ImouHaDeviceManager:
1174
1221
  raise RequestFailedException(
1175
1222
  f"device {device.device_id} answered getStreamUrl without a url"
1176
1223
  )
1177
- _LOGGER.debug("get_device_stream host=%s", urlparse(url).netloc)
1224
+ _LOGGER.debug("get_device_stream host=%s", _safe_stream_host(url))
1225
+ return url
1226
+
1227
+ @staticmethod
1228
+ def _live_code(exc: RequestFailedException, code: str) -> bool:
1229
+ """Match a platform code. 1.4.x puts it at the start of the message."""
1230
+ return code in (exc.message or "")
1231
+
1232
+ @staticmethod
1233
+ def _pick_hls_url(data: dict[str, Any], resolution: str, protocol: str) -> str:
1234
+ """Pick an exact stream id and, when supplied, an exact protocol."""
1235
+ streams = data.get(PARAM_STREAMS) if isinstance(data, dict) else None
1236
+ if not isinstance(streams, list) or not streams:
1237
+ raise RequestFailedException("live stream list is empty")
1238
+ wanted_id = 0 if resolution == PARAM_HD else 1
1239
+ for stream in streams:
1240
+ if not isinstance(stream, dict):
1241
+ continue
1242
+ hls = stream.get(PARAM_HLS)
1243
+ if not isinstance(hls, str) or not hls:
1244
+ continue
1245
+ if stream.get(PARAM_STREAM_ID) != wanted_id:
1246
+ continue
1247
+ if protocol and not hls.startswith(f"{protocol}:"):
1248
+ continue
1249
+ return hls
1250
+ raise RequestFailedException(
1251
+ f"live stream not found for resolution {resolution}"
1252
+ f" and protocol {protocol or 'any'}"
1253
+ )
1254
+
1255
+ async def _async_get_bind_live(
1256
+ self, device: ImouHaDevice, resolution: str, protocol: str
1257
+ ) -> str:
1258
+ try:
1259
+ data = await self.delegate.async_get_stream_url(
1260
+ device.device_id, device.channel_id
1261
+ )
1262
+ except RequestFailedException as exc:
1263
+ if not self._live_code(exc, ERROR_CODE_LIVE_NOT_EXIST):
1264
+ raise
1265
+ try:
1266
+ data = await self.delegate.async_create_stream_url(
1267
+ device.device_id, device.channel_id
1268
+ )
1269
+ except RequestFailedException as created:
1270
+ if not self._live_code(created, ERROR_CODE_LIVE_ALREADY_EXIST):
1271
+ raise
1272
+ data = await self.delegate.async_get_stream_url(
1273
+ device.device_id, device.channel_id
1274
+ )
1275
+ url = self._pick_hls_url(data, resolution, protocol)
1276
+ _LOGGER.debug("get_device_stream host=%s", _safe_stream_host(url))
1178
1277
  return url
1179
1278
 
1180
1279
  async def async_get_device_image(
@@ -1286,6 +1385,7 @@ class ImouHaDeviceManager:
1286
1385
  imou_ha_device.set_parent_device_id(device.parent_device_id)
1287
1386
  imou_ha_device.set_is_ipc(device.is_ipc)
1288
1387
  imou_ha_device.set_device_ability(device.device_ability)
1388
+ imou_ha_device.set_source(device.source)
1289
1389
  return imou_ha_device
1290
1390
 
1291
1391
  async def async_press_button(
@@ -139,10 +139,22 @@ class ImouOpenApiClient:
139
139
  f"request failed,status code {response.status}"
140
140
  )
141
141
  reader = getattr(response, "content", None)
142
- if reader is not None and hasattr(reader, "read"):
143
- body = await reader.read(DOWNLOAD_MAX_BYTES + 1)
144
- else:
145
- body = await response.read()
142
+ if reader is not None and hasattr(reader, "readany"):
143
+ # StreamReader.read(n) returns only the bytes already
144
+ # buffered, not the rest of the body. One call leaves a
145
+ # snapshot JPEG cut off, and the picture shows the top only.
146
+ chunks: list[bytes] = []
147
+ total = 0
148
+ while True:
149
+ block = await reader.readany()
150
+ if not block:
151
+ break
152
+ total += len(block)
153
+ if total > DOWNLOAD_MAX_BYTES:
154
+ raise RequestFailedException("download exceeded size limit")
155
+ chunks.append(block)
156
+ return b"".join(chunks)
157
+ body = await response.read()
146
158
  if len(body) > DOWNLOAD_MAX_BYTES:
147
159
  raise RequestFailedException("download exceeded size limit")
148
160
  return body
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyimouapi
3
- Version: 1.4.4
3
+ Version: 1.4.5
4
4
  Summary: A package for imou open api
5
5
  Home-page: https://github.com/Imou-OpenPlatform/Py-Imou-Open-Api
6
6
  Author: Imou-OpenPlatform
@@ -43,6 +43,7 @@ tests/test_entity_tables_golden.py
43
43
  tests/test_event_identifier_map.py
44
44
  tests/test_feature_switches.py
45
45
  tests/test_get_devices.py
46
+ tests/test_live_stream_source.py
46
47
  tests/test_lookup_property.py
47
48
  tests/test_message_callback.py
48
49
  tests/test_motion_detect_excepts.py
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "pyimouapi"
7
- version = "1.4.4"
7
+ version = "1.4.5"
8
8
  description = "A package for imou open api"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
@@ -4,7 +4,7 @@ from setuptools import find_packages, setup
4
4
 
5
5
  setup(
6
6
  name="pyimouapi",
7
- version="1.4.4",
7
+ version="1.4.5",
8
8
  packages=find_packages(),
9
9
  package_data={"pyimouapi": ["py.typed"]},
10
10
  zip_safe=False,
@@ -68,7 +68,7 @@ async def test_rtsp_request_sends_product_id_for_iot_devices() -> None:
68
68
 
69
69
  @pytest.mark.asyncio
70
70
  async def test_live_stream_uses_get_stream_url_only() -> None:
71
- """Live view fetches getStreamUrl; it does not look up or create HLS."""
71
+ """A camera that is not an owner binding keeps getStreamUrl."""
72
72
  delegate = MagicMock()
73
73
  delegate.async_get_stream_url = AsyncMock()
74
74
  delegate.async_create_stream_url = AsyncMock()
@@ -196,3 +196,21 @@ async def test_fetch_ability_refs_set_only_queries_named_devices() -> None:
196
196
  assert result[0].device_ability_refs == "unknown"
197
197
  assert result[1].device_ability_refs == "1,2,3"
198
198
  assert result[2].device_ability_refs == "unknown"
199
+
200
+
201
+ @pytest.mark.asyncio
202
+ async def test_device_list_keeps_source() -> None:
203
+ """Live selection needs bind versus share from the device list."""
204
+ owned = make_device("owned")
205
+ owned["source"] = " bind "
206
+ shared = make_device("shared")
207
+ shared["source"] = "share"
208
+ blank = make_device("blank")
209
+ blank["source"] = None
210
+ manager, _tracker = make_manager(
211
+ {1: {PARAM_COUNT: 3, PARAM_DEVICE_LIST: [owned, shared, blank]}}
212
+ )
213
+
214
+ result = await manager.async_get_devices(fetch_ability_refs=False)
215
+
216
+ assert [device.source for device in result] == ["bind", "share", ""]
@@ -0,0 +1,206 @@
1
+ """Owner cameras use cloud HLS; shared cameras keep getStreamUrl."""
2
+
3
+ import logging
4
+ from unittest.mock import AsyncMock, MagicMock
5
+
6
+ import pytest
7
+ from pyimouapi.const import (
8
+ ERROR_CODE_LIVE_ALREADY_EXIST,
9
+ ERROR_CODE_LIVE_NOT_EXIST,
10
+ PARAM_HD,
11
+ )
12
+ from pyimouapi.exceptions import RequestFailedException
13
+ from pyimouapi.ha_device import ImouHaDevice, ImouHaDeviceManager
14
+
15
+
16
+ def _camera(source: str) -> ImouHaDevice:
17
+ device = ImouHaDevice("IPC1", "Cam", "Imou", "IPC", "1.0")
18
+ device.set_channel_id("0")
19
+ device.set_source(source)
20
+ return device
21
+
22
+
23
+ def _streams() -> dict:
24
+ return {
25
+ "streams": [
26
+ {"streamId": 1, "hls": "http://cdn.example/sd.m3u8"},
27
+ {"streamId": 0, "hls": "http://cdn.example/hd.m3u8"},
28
+ ]
29
+ }
30
+
31
+
32
+ def _manager() -> ImouHaDeviceManager:
33
+ return ImouHaDeviceManager(MagicMock())
34
+
35
+
36
+ @pytest.mark.asyncio
37
+ async def test_bind_uses_cloud_hls() -> None:
38
+ device = _camera("bind")
39
+ manager = _manager()
40
+ manager.delegate.async_get_stream_url = AsyncMock(return_value=_streams())
41
+ manager.delegate.async_get_rtsp_stream_url = AsyncMock()
42
+
43
+ url = await manager.async_get_device_stream(device, "HD", "http")
44
+
45
+ assert url == "http://cdn.example/hd.m3u8"
46
+ manager.delegate.async_get_stream_url.assert_awaited_once_with("IPC1", "0")
47
+ manager.delegate.async_get_rtsp_stream_url.assert_not_awaited()
48
+
49
+
50
+ @pytest.mark.parametrize(
51
+ ("resolution", "protocol", "expected"),
52
+ [
53
+ ("HD", "http", "http://cdn.example/hd.m3u8"),
54
+ ("HD", "https", "https://cdn.example/hd.m3u8"),
55
+ ("SD", "http", "http://cdn.example/sd.m3u8"),
56
+ ("SD", "https", "https://cdn.example/sd.m3u8"),
57
+ ("HD", "", "https://cdn.example/hd.m3u8"),
58
+ ("SD", "", "https://cdn.example/sd.m3u8"),
59
+ ],
60
+ )
61
+ def test_pick_hls_url_matches_resolution_and_protocol(
62
+ resolution: str, protocol: str, expected: str
63
+ ) -> None:
64
+ data = {
65
+ "streams": [
66
+ {"streamId": 0, "hls": "https://cdn.example/hd.m3u8"},
67
+ {"streamId": 1, "hls": "https://cdn.example/sd.m3u8"},
68
+ {"streamId": 0, "hls": "http://cdn.example/hd.m3u8"},
69
+ {"streamId": 1, "hls": "http://cdn.example/sd.m3u8"},
70
+ ]
71
+ }
72
+
73
+ assert ImouHaDeviceManager._pick_hls_url(data, resolution, protocol) == expected
74
+
75
+
76
+ @pytest.mark.parametrize(
77
+ ("resolution", "protocol"),
78
+ [("HD", "https"), ("SD", "https"), ("HD", "rtmp")],
79
+ )
80
+ def test_pick_hls_url_does_not_fall_back_on_protocol_mismatch(
81
+ resolution: str, protocol: str
82
+ ) -> None:
83
+ with pytest.raises(RequestFailedException, match="live stream not found"):
84
+ ImouHaDeviceManager._pick_hls_url(_streams(), resolution, protocol)
85
+
86
+
87
+ @pytest.mark.parametrize(("resolution", "stream_id"), [("HD", 1), ("SD", 0)])
88
+ def test_pick_hls_url_does_not_fall_back_on_resolution_mismatch(
89
+ resolution: str, stream_id: int
90
+ ) -> None:
91
+ data = {"streams": [{"streamId": stream_id, "hls": "http://cdn.example/a.m3u8"}]}
92
+
93
+ with pytest.raises(RequestFailedException, match="live stream not found"):
94
+ ImouHaDeviceManager._pick_hls_url(data, resolution, "")
95
+
96
+
97
+ @pytest.mark.asyncio
98
+ async def test_bind_protocol_defaults_to_any_matching_stream() -> None:
99
+ device = _camera("bind")
100
+ manager = _manager()
101
+ manager.delegate.async_get_stream_url = AsyncMock(return_value=_streams())
102
+
103
+ assert await manager.async_get_device_stream(device, PARAM_HD) == (
104
+ "http://cdn.example/hd.m3u8"
105
+ )
106
+
107
+
108
+ @pytest.mark.asyncio
109
+ @pytest.mark.parametrize(
110
+ ("source", "url", "safe_host"),
111
+ [
112
+ (
113
+ "bind",
114
+ "https://user:password@cdn.example:8443/hd/path-secret"
115
+ "?token=query-secret#fragment-secret",
116
+ "cdn.example:8443",
117
+ ),
118
+ (
119
+ "share",
120
+ "rtsp://user:password@cdn.example:554/path-secret"
121
+ "?token=query-secret#fragment-secret",
122
+ "cdn.example:554",
123
+ ),
124
+ ],
125
+ )
126
+ async def test_stream_debug_log_keeps_only_safe_host(
127
+ caplog: pytest.LogCaptureFixture,
128
+ source: str,
129
+ url: str,
130
+ safe_host: str,
131
+ ) -> None:
132
+ device = _camera(source)
133
+ manager = _manager()
134
+ if source == "bind":
135
+ manager.delegate.async_get_stream_url = AsyncMock(
136
+ return_value={"streams": [{"streamId": 0, "hls": url}]}
137
+ )
138
+ else:
139
+ manager.delegate.async_get_rtsp_stream_url = AsyncMock(
140
+ return_value={"url": url}
141
+ )
142
+
143
+ with caplog.at_level(logging.DEBUG, logger="pyimouapi"):
144
+ result = await manager.async_get_device_stream(
145
+ device, "HD", "https" if source == "bind" else ""
146
+ )
147
+
148
+ assert result == url
149
+ assert safe_host in caplog.text
150
+ for secret in ("user:password", "path-secret", "query-secret", "fragment-secret"):
151
+ assert secret not in caplog.text
152
+
153
+
154
+ @pytest.mark.asyncio
155
+ async def test_bind_creates_hls_when_live_missing() -> None:
156
+ device = _camera("bind")
157
+ manager = _manager()
158
+ manager.delegate.async_get_stream_url = AsyncMock(
159
+ side_effect=RequestFailedException(f"{ERROR_CODE_LIVE_NOT_EXIST}:missing")
160
+ )
161
+ manager.delegate.async_create_stream_url = AsyncMock(return_value=_streams())
162
+ manager.delegate.async_get_rtsp_stream_url = AsyncMock()
163
+
164
+ url = await manager.async_get_device_stream(device, "HD", "http")
165
+
166
+ assert url == "http://cdn.example/hd.m3u8"
167
+ manager.delegate.async_get_rtsp_stream_url.assert_not_awaited()
168
+ manager.delegate.async_create_stream_url.assert_awaited_once_with("IPC1", "0")
169
+
170
+
171
+ @pytest.mark.asyncio
172
+ async def test_bind_reuses_hls_when_create_says_it_exists() -> None:
173
+ device = _camera("bind")
174
+ manager = _manager()
175
+ manager.delegate.async_get_stream_url = AsyncMock(
176
+ side_effect=[
177
+ RequestFailedException(f"{ERROR_CODE_LIVE_NOT_EXIST}:missing"),
178
+ _streams(),
179
+ ]
180
+ )
181
+ manager.delegate.async_create_stream_url = AsyncMock(
182
+ side_effect=RequestFailedException(f"{ERROR_CODE_LIVE_ALREADY_EXIST}:exists")
183
+ )
184
+
185
+ url = await manager.async_get_device_stream(device, "SD", "http")
186
+
187
+ assert url == "http://cdn.example/sd.m3u8"
188
+ assert manager.delegate.async_get_stream_url.await_count == 2
189
+
190
+
191
+ @pytest.mark.asyncio
192
+ @pytest.mark.parametrize("source", ["share", ""])
193
+ async def test_non_bind_uses_get_stream_url(source: str) -> None:
194
+ device = _camera(source)
195
+ manager = _manager()
196
+ manager.delegate.async_get_rtsp_stream_url = AsyncMock(
197
+ return_value={"url": "rtsp://cdn.example/live"}
198
+ )
199
+ manager.delegate.async_get_stream_url = AsyncMock()
200
+ manager.delegate.async_create_stream_url = AsyncMock()
201
+
202
+ url = await manager.async_get_device_stream(device, "HD", "http")
203
+
204
+ assert url == "rtsp://cdn.example/live"
205
+ manager.delegate.async_get_stream_url.assert_not_awaited()
206
+ manager.delegate.async_create_stream_url.assert_not_awaited()
@@ -19,7 +19,7 @@ from pyimouapi.exceptions import (
19
19
  InvalidAppIdOrSecretException,
20
20
  RequestFailedException,
21
21
  )
22
- from pyimouapi.openapi import CONNECTION_LIMIT, ImouOpenApiClient
22
+ from pyimouapi.openapi import CONNECTION_LIMIT, DOWNLOAD_MAX_BYTES, ImouOpenApiClient
23
23
 
24
24
  ENDPOINT = "/openapi/deviceBaseList"
25
25
 
@@ -91,13 +91,40 @@ class FakeResponse:
91
91
  return response
92
92
 
93
93
 
94
+ class _ChunkedBody:
95
+ """Body that arrives in several reads, like aiohttp's StreamReader."""
96
+
97
+ def __init__(self, chunks: list[bytes]) -> None:
98
+ """Initialize with the chunks a single read(n) would split across."""
99
+ self._chunks = list(chunks)
100
+
101
+ async def read(self, n: int = -1) -> bytes:
102
+ """Return one buffered chunk, matching StreamReader.read(n) for n > 0."""
103
+ if not self._chunks:
104
+ return b""
105
+ if n < 0:
106
+ data = b"".join(self._chunks)
107
+ self._chunks.clear()
108
+ return data
109
+ return self._chunks.pop(0)
110
+
111
+ async def readany(self) -> bytes:
112
+ """Return the next chunk, or empty once the body is finished."""
113
+ if not self._chunks:
114
+ return b""
115
+ return self._chunks.pop(0)
116
+
117
+
94
118
  class FakeBinaryResponse:
95
119
  """Minimal aiohttp response stand-in for binary downloads."""
96
120
 
97
- def __init__(self, status: int, payload: bytes) -> None:
121
+ def __init__(
122
+ self, status: int, payload: bytes, *, content: _ChunkedBody | None = None
123
+ ) -> None:
98
124
  """Initialize the response."""
99
125
  self.status = status
100
126
  self._payload = payload
127
+ self.content = content
101
128
  self.released = False
102
129
 
103
130
  async def __aenter__(self) -> "FakeBinaryResponse":
@@ -123,6 +150,7 @@ class FakeSession:
123
150
  delay: float = 0,
124
151
  download_status: int = 200,
125
152
  download_payload: bytes = b"jpeg-bytes",
153
+ download_content: _ChunkedBody | None = None,
126
154
  text_error: Exception | None = None,
127
155
  ) -> None:
128
156
  """Initialize with a queue of responses or exceptions to raise."""
@@ -130,6 +158,7 @@ class FakeSession:
130
158
  self._delay = delay
131
159
  self._download_status = download_status
132
160
  self._download_payload = download_payload
161
+ self._download_content = download_content
133
162
  self._text_error = text_error
134
163
  self.closed = False
135
164
  self.requests: list[tuple[str, dict[str, Any]]] = []
@@ -142,7 +171,9 @@ class FakeSession:
142
171
  """Return the configured binary payload as a response context manager."""
143
172
  self.downloads.append(url)
144
173
  self.last_download = FakeBinaryResponse(
145
- self._download_status, self._download_payload
174
+ self._download_status,
175
+ self._download_payload,
176
+ content=self._download_content,
146
177
  )
147
178
  return self.last_download
148
179
 
@@ -353,6 +384,37 @@ async def test_download_uses_the_shared_session(client: ImouOpenApiClient) -> No
353
384
  assert await client._async_get_session() is session
354
385
 
355
386
 
387
+ @pytest.mark.asyncio
388
+ async def test_download_reads_every_chunk(client: ImouOpenApiClient) -> None:
389
+ """A snapshot split across reads is kept whole, not cut after the first chunk."""
390
+ install_session(
391
+ client,
392
+ [],
393
+ download_content=_ChunkedBody([b"jpeg-", b"bytes", b"-rest"]),
394
+ )
395
+
396
+ assert await client.async_download("https://cdn.example.com/snap.jpg") == (
397
+ b"jpeg-bytes-rest"
398
+ )
399
+
400
+
401
+ @pytest.mark.asyncio
402
+ async def test_download_rejects_a_body_over_the_size_cap(
403
+ client: ImouOpenApiClient,
404
+ ) -> None:
405
+ """The size cap still applies when the body arrives in more than one read."""
406
+ install_session(
407
+ client,
408
+ [],
409
+ download_content=_ChunkedBody(
410
+ [b"a" * DOWNLOAD_MAX_BYTES, b"b"],
411
+ ),
412
+ )
413
+
414
+ with pytest.raises(RequestFailedException, match="size limit"):
415
+ await client.async_download("https://cdn.example.com/huge.jpg")
416
+
417
+
356
418
  @pytest.mark.asyncio
357
419
  async def test_download_raises_on_error_status(client: ImouOpenApiClient) -> None:
358
420
  """A non-200 download surfaces as RequestFailedException."""
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes