shellzapy 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.
Files changed (345) hide show
  1. shellzapy-0.1.0.dist-info/METADATA +112 -0
  2. shellzapy-0.1.0.dist-info/RECORD +345 -0
  3. shellzapy-0.1.0.dist-info/WHEEL +4 -0
  4. shellzapy-0.1.0.dist-info/licenses/LICENSE +21 -0
  5. shellzapy-0.1.0.dist-info/licenses/NOTICE +9 -0
  6. zapy/__init__.py +58 -0
  7. zapy/_appstate/__init__.py +59 -0
  8. zapy/_appstate/constants.py +82 -0
  9. zapy/_appstate/crypto/__init__.py +17 -0
  10. zapy/_appstate/crypto/app_state_crypto.py +401 -0
  11. zapy/_appstate/parsers/__init__.py +23 -0
  12. zapy/_appstate/parsers/encoding.py +157 -0
  13. zapy/_appstate/parsers/response_parser.py +135 -0
  14. zapy/_appstate/sync/__init__.py +11 -0
  15. zapy/_appstate/sync/sync_client.py +1559 -0
  16. zapy/_appstate/types.py +137 -0
  17. zapy/_appstate/utils.py +100 -0
  18. zapy/_auth/__init__.py +3 -0
  19. zapy/_auth/auth_client.py +618 -0
  20. zapy/_auth/credentials_flow.py +290 -0
  21. zapy/_auth/pairing/__init__.py +3 -0
  22. zapy/_auth/pairing/companion_host.py +239 -0
  23. zapy/_auth/pairing/flow.py +808 -0
  24. zapy/_auth/pairing/pairing_code_crypto.py +143 -0
  25. zapy/_auth/pairing/qr_flow.py +123 -0
  26. zapy/_auth/pairing/shortcake_crypto.py +122 -0
  27. zapy/_auth/pairing/shortcake_flow.py +393 -0
  28. zapy/_auth/types.py +110 -0
  29. zapy/_client/__init__.py +26 -0
  30. zapy/_client/client.py +972 -0
  31. zapy/_client/connection/__init__.py +6 -0
  32. zapy/_client/connection/manager.py +525 -0
  33. zapy/_client/connection/receipt_queue.py +74 -0
  34. zapy/_client/coordinators/__init__.py +81 -0
  35. zapy/_client/coordinators/ab_props.py +260 -0
  36. zapy/_client/coordinators/app_state_mutation.py +2538 -0
  37. zapy/_client/coordinators/bot.py +830 -0
  38. zapy/_client/coordinators/broadcast_list.py +101 -0
  39. zapy/_client/coordinators/business.py +247 -0
  40. zapy/_client/coordinators/email.py +158 -0
  41. zapy/_client/coordinators/group.py +1478 -0
  42. zapy/_client/coordinators/incoming_node.py +758 -0
  43. zapy/_client/coordinators/low_level.py +119 -0
  44. zapy/_client/coordinators/message.py +1153 -0
  45. zapy/_client/coordinators/message_dispatch.py +1637 -0
  46. zapy/_client/coordinators/newsletter.py +110 -0
  47. zapy/_client/coordinators/offline_resume.py +271 -0
  48. zapy/_client/coordinators/passive_tasks.py +447 -0
  49. zapy/_client/coordinators/presence.py +103 -0
  50. zapy/_client/coordinators/privacy.py +623 -0
  51. zapy/_client/coordinators/profile.py +1024 -0
  52. zapy/_client/coordinators/retry.py +1878 -0
  53. zapy/_client/coordinators/status.py +132 -0
  54. zapy/_client/coordinators/stream_control.py +260 -0
  55. zapy/_client/coordinators/trusted_contact_token.py +417 -0
  56. zapy/_client/events/__init__.py +266 -0
  57. zapy/_client/events/abprops.py +58 -0
  58. zapy/_client/events/appstate_mutation.py +248 -0
  59. zapy/_client/events/business.py +565 -0
  60. zapy/_client/events/call.py +144 -0
  61. zapy/_client/events/chatstate.py +41 -0
  62. zapy/_client/events/devices.py +122 -0
  63. zapy/_client/events/dirty.py +384 -0
  64. zapy/_client/events/group.py +655 -0
  65. zapy/_client/events/identity.py +40 -0
  66. zapy/_client/events/incoming.py +1079 -0
  67. zapy/_client/events/mex_notification.py +317 -0
  68. zapy/_client/events/offline.py +123 -0
  69. zapy/_client/events/picture.py +67 -0
  70. zapy/_client/events/presence.py +74 -0
  71. zapy/_client/events/privacy.py +187 -0
  72. zapy/_client/events/privacy_token.py +72 -0
  73. zapy/_client/events/receipt.py +109 -0
  74. zapy/_client/events/registration.py +70 -0
  75. zapy/_client/events/username.py +76 -0
  76. zapy/_client/factory.py +2020 -0
  77. zapy/_client/media.py +829 -0
  78. zapy/_client/newsletter/__init__.py +90 -0
  79. zapy/_client/newsletter/admin.py +323 -0
  80. zapy/_client/newsletter/content.py +499 -0
  81. zapy/_client/newsletter/discovery.py +233 -0
  82. zapy/_client/newsletter/messaging.py +396 -0
  83. zapy/_client/newsletter/mex.py +99 -0
  84. zapy/_client/newsletter/parse.py +406 -0
  85. zapy/_client/newsletter/types.py +393 -0
  86. zapy/_client/persistence/__init__.py +89 -0
  87. zapy/_client/persistence/companion_host.py +133 -0
  88. zapy/_client/persistence/ephemeral_setting.py +245 -0
  89. zapy/_client/persistence/group_history.py +361 -0
  90. zapy/_client/persistence/history_blob.py +169 -0
  91. zapy/_client/persistence/history_sync.py +646 -0
  92. zapy/_client/persistence/mailbox.py +232 -0
  93. zapy/_client/persistence/write_behind_persistence.py +368 -0
  94. zapy/_client/plugins/__init__.py +23 -0
  95. zapy/_client/plugins/define.py +44 -0
  96. zapy/_client/plugins/install.py +254 -0
  97. zapy/_client/plugins/types.py +64 -0
  98. zapy/_client/tokens/__init__.py +21 -0
  99. zapy/_client/tokens/cs_token.py +47 -0
  100. zapy/_client/tokens/tc_token.py +43 -0
  101. zapy/_client/types.py +988 -0
  102. zapy/_crypto/__init__.py +65 -0
  103. zapy/_crypto/core/__init__.py +62 -0
  104. zapy/_crypto/core/hkdf.py +41 -0
  105. zapy/_crypto/core/keys.py +51 -0
  106. zapy/_crypto/core/nonce.py +25 -0
  107. zapy/_crypto/core/primitives.py +179 -0
  108. zapy/_crypto/core/random.py +32 -0
  109. zapy/_crypto/core/xeddsa.py +72 -0
  110. zapy/_crypto/curves/__init__.py +3 -0
  111. zapy/_crypto/curves/constants.py +10 -0
  112. zapy/_crypto/curves/ed25519.py +61 -0
  113. zapy/_crypto/curves/types.py +18 -0
  114. zapy/_crypto/curves/x25519.py +117 -0
  115. zapy/_crypto/math/__init__.py +3 -0
  116. zapy/_crypto/math/constants.py +35 -0
  117. zapy/_crypto/math/edwards.py +174 -0
  118. zapy/_crypto/math/fe.py +120 -0
  119. zapy/_crypto/math/le.py +13 -0
  120. zapy/_crypto/math/mod.py +15 -0
  121. zapy/_crypto/math/prime.py +11 -0
  122. zapy/_crypto/math/types.py +25 -0
  123. zapy/_crypto/native_backend.py +40 -0
  124. zapy/_infra/__init__.py +3 -0
  125. zapy/_infra/log.py +142 -0
  126. zapy/_infra/perf.py +77 -0
  127. zapy/_media/__init__.py +64 -0
  128. zapy/_media/constants.py +133 -0
  129. zapy/_media/container.py +110 -0
  130. zapy/_media/crypto/__init__.py +19 -0
  131. zapy/_media/crypto/crypto.py +633 -0
  132. zapy/_media/crypto/media_retry.py +107 -0
  133. zapy/_media/processor.py +100 -0
  134. zapy/_media/sticker/__init__.py +8 -0
  135. zapy/_media/sticker/pack.py +188 -0
  136. zapy/_media/transfer/__init__.py +15 -0
  137. zapy/_media/transfer/client.py +635 -0
  138. zapy/_media/transfer/conn.py +48 -0
  139. zapy/_media/types.py +169 -0
  140. zapy/_message/__init__.py +121 -0
  141. zapy/_message/addons/__init__.py +5 -0
  142. zapy/_message/addons/link_preview/__init__.py +54 -0
  143. zapy/_message/addons/link_preview/builder.py +56 -0
  144. zapy/_message/addons/link_preview/detect.py +72 -0
  145. zapy/_message/addons/link_preview/fetcher.py +553 -0
  146. zapy/_message/addons/link_preview/types.py +100 -0
  147. zapy/_message/client.py +486 -0
  148. zapy/_message/context_info.py +424 -0
  149. zapy/_message/crypto/__init__.py +71 -0
  150. zapy/_message/crypto/addon_crypto.py +656 -0
  151. zapy/_message/crypto/icdc.py +138 -0
  152. zapy/_message/crypto/phash.py +87 -0
  153. zapy/_message/crypto/reporting_token.py +498 -0
  154. zapy/_message/crypto/use_case_secret.py +113 -0
  155. zapy/_message/encode/__init__.py +84 -0
  156. zapy/_message/encode/content.py +636 -0
  157. zapy/_message/encode/device_sent.py +88 -0
  158. zapy/_message/encode/media_payload.py +122 -0
  159. zapy/_message/encode/padding.py +27 -0
  160. zapy/_message/kinds/__init__.py +1 -0
  161. zapy/_message/kinds/bot.py +179 -0
  162. zapy/_message/kinds/group_history.py +206 -0
  163. zapy/_message/kinds/newsletter.py +388 -0
  164. zapy/_message/kinds/sticker_pack.py +74 -0
  165. zapy/_message/messaging/__init__.py +336 -0
  166. zapy/_message/messaging/companion_host.py +117 -0
  167. zapy/_message/messaging/fanout.py +311 -0
  168. zapy/_message/messaging/group_metadata.py +444 -0
  169. zapy/_message/messaging/ignore_key.py +264 -0
  170. zapy/_message/messaging/key_protocol.py +217 -0
  171. zapy/_message/messaging/link_preview.py +448 -0
  172. zapy/_message/messaging/messages.py +1429 -0
  173. zapy/_message/primitives/__init__.py +1 -0
  174. zapy/_message/primitives/ack.py +232 -0
  175. zapy/_message/primitives/incoming.py +1141 -0
  176. zapy/_message/primitives/media_retry.py +451 -0
  177. zapy/_message/primitives/peer_data_operation.py +271 -0
  178. zapy/_message/types.py +434 -0
  179. zapy/_proto/WAProto_pb2.py +2584 -0
  180. zapy/_proto/__init__.py +1 -0
  181. zapy/_protocol/__init__.py +3 -0
  182. zapy/_protocol/abprops_spec.py +6216 -0
  183. zapy/_protocol/auth.py +17 -0
  184. zapy/_protocol/browser.py +57 -0
  185. zapy/_protocol/defaults.py +38 -0
  186. zapy/_protocol/device_identity.py +54 -0
  187. zapy/_protocol/jid.py +241 -0
  188. zapy/_protocol/message.py +127 -0
  189. zapy/_protocol/nodes.py +144 -0
  190. zapy/_protocol/notification.py +18 -0
  191. zapy/_retry/__init__.py +77 -0
  192. zapy/_retry/codec.py +209 -0
  193. zapy/_retry/constants.py +28 -0
  194. zapy/_retry/parse.py +132 -0
  195. zapy/_retry/reason.py +65 -0
  196. zapy/_retry/replay.py +483 -0
  197. zapy/_retry/tracker.py +161 -0
  198. zapy/_retry/types.py +122 -0
  199. zapy/_signal/__init__.py +171 -0
  200. zapy/_signal/api/__init__.py +133 -0
  201. zapy/_signal/api/codec.py +164 -0
  202. zapy/_signal/api/constants.py +14 -0
  203. zapy/_signal/api/device_sync.py +915 -0
  204. zapy/_signal/api/digest_sync.py +363 -0
  205. zapy/_signal/api/identity_sync.py +250 -0
  206. zapy/_signal/api/missing_pre_keys_sync.py +267 -0
  207. zapy/_signal/api/prekeys.py +191 -0
  208. zapy/_signal/api/result_map.py +40 -0
  209. zapy/_signal/api/rotate_key.py +111 -0
  210. zapy/_signal/api/session_sync.py +297 -0
  211. zapy/_signal/attestation.py +145 -0
  212. zapy/_signal/constants.py +22 -0
  213. zapy/_signal/encoding.py +78 -0
  214. zapy/_signal/group/__init__.py +35 -0
  215. zapy/_signal/group/chain.py +139 -0
  216. zapy/_signal/group/codec.py +78 -0
  217. zapy/_signal/group/encoding.py +166 -0
  218. zapy/_signal/group/manager.py +361 -0
  219. zapy/_signal/registration/__init__.py +44 -0
  220. zapy/_signal/registration/keygen.py +46 -0
  221. zapy/_signal/registration/reg_encoding.py +66 -0
  222. zapy/_signal/registration/reg_utils.py +52 -0
  223. zapy/_signal/session/__init__.py +114 -0
  224. zapy/_signal/session/encoding.py +385 -0
  225. zapy/_signal/session/protocol.py +590 -0
  226. zapy/_signal/session/ratchet.py +381 -0
  227. zapy/_signal/session/resolver.py +630 -0
  228. zapy/_signal/session/serializer.py +96 -0
  229. zapy/_signal/session/session.py +272 -0
  230. zapy/_signal/types.py +214 -0
  231. zapy/_store/__init__.py +118 -0
  232. zapy/_store/cache/__init__.py +166 -0
  233. zapy/_store/cache/identity.py +130 -0
  234. zapy/_store/cache/privacy_token.py +116 -0
  235. zapy/_store/cache/sender_key.py +168 -0
  236. zapy/_store/cache/session.py +142 -0
  237. zapy/_store/contracts/__init__.py +84 -0
  238. zapy/_store/contracts/appstate.py +82 -0
  239. zapy/_store/contracts/auth.py +16 -0
  240. zapy/_store/contracts/chat_metadata.py +29 -0
  241. zapy/_store/contracts/contact.py +31 -0
  242. zapy/_store/contracts/device_list.py +35 -0
  243. zapy/_store/contracts/group_metadata.py +33 -0
  244. zapy/_store/contracts/identity.py +18 -0
  245. zapy/_store/contracts/message.py +36 -0
  246. zapy/_store/contracts/message_secret.py +41 -0
  247. zapy/_store/contracts/pre_key.py +32 -0
  248. zapy/_store/contracts/privacy_token.py +32 -0
  249. zapy/_store/contracts/retry.py +47 -0
  250. zapy/_store/contracts/sender_key.py +37 -0
  251. zapy/_store/contracts/session.py +21 -0
  252. zapy/_store/contracts/signal.py +23 -0
  253. zapy/_store/contracts/thread.py +35 -0
  254. zapy/_store/create_store.py +890 -0
  255. zapy/_store/locks.py +1154 -0
  256. zapy/_store/memory/__init__.py +40 -0
  257. zapy/_store/memory/appstate.py +200 -0
  258. zapy/_store/memory/auth.py +24 -0
  259. zapy/_store/memory/chat_metadata.py +124 -0
  260. zapy/_store/memory/contact.py +125 -0
  261. zapy/_store/memory/device_list.py +161 -0
  262. zapy/_store/memory/group_metadata.py +125 -0
  263. zapy/_store/memory/identity.py +86 -0
  264. zapy/_store/memory/message.py +85 -0
  265. zapy/_store/memory/message_secret.py +145 -0
  266. zapy/_store/memory/pre_key.py +112 -0
  267. zapy/_store/memory/privacy_token.py +103 -0
  268. zapy/_store/memory/retry.py +250 -0
  269. zapy/_store/memory/sender_key.py +162 -0
  270. zapy/_store/memory/session.py +111 -0
  271. zapy/_store/memory/signal.py +45 -0
  272. zapy/_store/memory/thread.py +66 -0
  273. zapy/_store/noop.py +279 -0
  274. zapy/_transport/__init__.py +3 -0
  275. zapy/_transport/binary/__init__.py +77 -0
  276. zapy/_transport/binary/constants.py +80 -0
  277. zapy/_transport/binary/decoder.py +260 -0
  278. zapy/_transport/binary/encoder.py +279 -0
  279. zapy/_transport/binary/tokens.py +1289 -0
  280. zapy/_transport/comms.py +759 -0
  281. zapy/_transport/keepalive/__init__.py +3 -0
  282. zapy/_transport/keepalive/keep_alive.py +252 -0
  283. zapy/_transport/node/__init__.py +3 -0
  284. zapy/_transport/node/builders/__init__.py +9 -0
  285. zapy/_transport/node/builders/abprops.py +33 -0
  286. zapy/_transport/node/builders/account_sync.py +120 -0
  287. zapy/_transport/node/builders/bot.py +56 -0
  288. zapy/_transport/node/builders/business.py +261 -0
  289. zapy/_transport/node/builders/chatstate.py +74 -0
  290. zapy/_transport/node/builders/community.py +116 -0
  291. zapy/_transport/node/builders/device.py +30 -0
  292. zapy/_transport/node/builders/email.py +181 -0
  293. zapy/_transport/node/builders/global_.py +74 -0
  294. zapy/_transport/node/builders/group.py +279 -0
  295. zapy/_transport/node/builders/media.py +21 -0
  296. zapy/_transport/node/builders/message.py +436 -0
  297. zapy/_transport/node/builders/mobile.py +227 -0
  298. zapy/_transport/node/builders/newsletter.py +293 -0
  299. zapy/_transport/node/builders/offline.py +20 -0
  300. zapy/_transport/node/builders/pairing.py +130 -0
  301. zapy/_transport/node/builders/passive.py +28 -0
  302. zapy/_transport/node/builders/prekeys.py +215 -0
  303. zapy/_transport/node/builders/presence.py +100 -0
  304. zapy/_transport/node/builders/privacy.py +243 -0
  305. zapy/_transport/node/builders/privacy_token.py +94 -0
  306. zapy/_transport/node/builders/profile.py +176 -0
  307. zapy/_transport/node/builders/retry.py +156 -0
  308. zapy/_transport/node/builders/shortcake.py +87 -0
  309. zapy/_transport/node/builders/tos.py +92 -0
  310. zapy/_transport/node/builders/usync.py +185 -0
  311. zapy/_transport/node/helpers.py +201 -0
  312. zapy/_transport/node/orchestrator.py +210 -0
  313. zapy/_transport/node/query.py +82 -0
  314. zapy/_transport/node/transport.py +105 -0
  315. zapy/_transport/node/usync.py +33 -0
  316. zapy/_transport/node/xml.py +38 -0
  317. zapy/_transport/noise/__init__.py +7 -0
  318. zapy/_transport/noise/cert.py +85 -0
  319. zapy/_transport/noise/client_payload.py +344 -0
  320. zapy/_transport/noise/constants.py +12 -0
  321. zapy/_transport/noise/frame_codec.py +120 -0
  322. zapy/_transport/noise/handshake.py +92 -0
  323. zapy/_transport/noise/session.py +493 -0
  324. zapy/_transport/noise/socket.py +45 -0
  325. zapy/_transport/noise/types.py +66 -0
  326. zapy/_transport/noise/version.json +3 -0
  327. zapy/_transport/proxy.py +35 -0
  328. zapy/_transport/types.py +19 -0
  329. zapy/_transport/wa_version_fetcher.py +159 -0
  330. zapy/_transport/web_socket.py +602 -0
  331. zapy/_util/__init__.py +3 -0
  332. zapy/_util/bytes.py +131 -0
  333. zapy/_util/coercion.py +29 -0
  334. zapy/_util/collections.py +45 -0
  335. zapy/_util/primitives.py +49 -0
  336. zapy/client.py +840 -0
  337. zapy/errors.py +148 -0
  338. zapy/events.py +564 -0
  339. zapy/jid.py +140 -0
  340. zapy/py.typed +0 -0
  341. zapy/stores/__init__.py +50 -0
  342. zapy/stores/base.py +1627 -0
  343. zapy/stores/json_file.py +359 -0
  344. zapy/stores/memory.py +322 -0
  345. zapy/stores/sqlite.py +343 -0
@@ -0,0 +1,635 @@
1
+ """Streaming media uploader/downloader (mirrors ``transfer/``).
2
+
3
+ Handles host failover, encryption (:class:`WaMediaCrypto`), and MAC
4
+ verification. Bodies are delivered whole (bounded by ``max_bytes``) rather
5
+ than as live sockets: callers in this codebase always consume the full
6
+ payload, and the stdlib ``http.client`` transport below runs in a worker
7
+ thread. Upload bodies may be ``bytes`` or binary streams; the latter are
8
+ sent chunked without buffering the whole payload.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import asyncio
14
+ import http.client
15
+ import ssl
16
+ import urllib.parse
17
+ from collections.abc import AsyncIterator, Mapping
18
+ from dataclasses import dataclass
19
+ from typing import Any, BinaryIO
20
+
21
+ from zapy._infra.log import Logger
22
+ from zapy._media.constants import DEFAULT_MEDIA_HOSTS
23
+ from zapy._media.crypto.crypto import WaMediaCrypto
24
+ from zapy._media.types import (
25
+ WaMediaReadableDecryptionResult,
26
+ WaMediaReadableDecryptionResultMetadata,
27
+ WaMediaTransferClientOptions,
28
+ )
29
+ from zapy._util.primitives import to_error
30
+
31
+ # Verbatim ``WA_DEFAULTS.MEDIA_TIMEOUT_MS`` (the full defaults table lands
32
+ # with the protocol layer).
33
+ _DEFAULT_TIMEOUT_MS: int = 30_000
34
+
35
+ _EMPTY_BYTES: bytes = b""
36
+
37
+
38
+ def _normalize_headers(
39
+ headers: Mapping[str, str] | None,
40
+ ) -> dict[str, str]:
41
+ if not headers:
42
+ return {}
43
+ return {str(key).lower(): headers[key] for key in headers}
44
+
45
+
46
+ def _read_body_capped(
47
+ response: http.client.HTTPResponse, max_bytes: int | None
48
+ ) -> bytes:
49
+ if max_bytes is not None and (
50
+ not isinstance(max_bytes, int) or isinstance(max_bytes, bool) or max_bytes < 0
51
+ ):
52
+ raise ValueError(f"invalid max bytes limit: {max_bytes}")
53
+ chunks: list[bytes] = []
54
+ total = 0
55
+ while True:
56
+ piece = response.read(65_536)
57
+ if not piece:
58
+ break
59
+ chunks.append(piece)
60
+ total += len(piece)
61
+ if max_bytes is not None and total > max_bytes:
62
+ raise ValueError(f"stream exceeded max bytes limit ({max_bytes})")
63
+ return b"".join(chunks)
64
+
65
+
66
+ @dataclass(frozen=True, slots=True)
67
+ class StreamTransferResponse:
68
+ """One completed transfer leg: URL, status, headers, whole body."""
69
+
70
+ url: str = ""
71
+ status: int = 0
72
+ ok: bool = False
73
+ headers: dict[str, str] | None = None
74
+ body: bytes | None = None
75
+
76
+
77
+ @dataclass(frozen=True, slots=True)
78
+ class EncryptedUploadResult:
79
+ """Upload receipt plus the key/hashes for the message stanza."""
80
+
81
+ transfer: StreamTransferResponse | None = None
82
+ media_key: bytes = b""
83
+ file_sha256: bytes = b""
84
+ file_enc_sha256: bytes = b""
85
+ plaintext_length: int = 0
86
+
87
+
88
+ async def _as_chunk_stream(
89
+ source: AsyncIterator[bytes] | BinaryIO,
90
+ ) -> AsyncIterator[bytes]:
91
+ """Yield chunks from an async iterator (callers filter streams first)."""
92
+ if isinstance(source, AsyncIterator):
93
+ async for piece in source:
94
+ yield bytes(piece)
95
+ return
96
+ raise ValueError("media transfer received unsupported source type")
97
+
98
+
99
+ async def _aiter_to_bytes(source: AsyncIterator[bytes] | BinaryIO) -> bytes:
100
+ if callable(getattr(source, "read", None)):
101
+ read = getattr(source, "read")
102
+
103
+ def _read_all() -> bytes:
104
+ parts: list[bytes] = []
105
+ while True:
106
+ piece = read(65_536)
107
+ if not piece:
108
+ break
109
+ parts.append(bytes(piece))
110
+ return b"".join(parts)
111
+
112
+ return await asyncio.to_thread(_read_all)
113
+ parts = [bytes(piece) async for piece in _as_chunk_stream(source)]
114
+ return b"".join(parts)
115
+
116
+
117
+ class WaMediaTransferClient:
118
+ """Media uploader/downloader with host failover and crypto (mirrors TS)."""
119
+
120
+ def __init__(self, options: WaMediaTransferClientOptions | None = None) -> None:
121
+ opts = options or WaMediaTransferClientOptions()
122
+ self._logger = opts.logger
123
+ self._default_hosts = (
124
+ tuple(opts.default_hosts) if opts.default_hosts else DEFAULT_MEDIA_HOSTS
125
+ )
126
+ self._default_timeout_ms = (
127
+ opts.default_timeout_ms
128
+ if opts.default_timeout_ms is not None
129
+ else _DEFAULT_TIMEOUT_MS
130
+ )
131
+ self._default_max_read_bytes = opts.default_max_read_bytes
132
+ self._default_headers = _normalize_headers(opts.default_headers)
133
+ self._skip_mac_verification = opts.skip_mac_verification is True
134
+
135
+ def _log_debug(self, message: str, context: dict[str, Any]) -> None:
136
+ logger: Logger | None = self._logger
137
+ if logger is not None:
138
+ logger.debug(message, context)
139
+
140
+ def _log_info(self, message: str, context: dict[str, Any]) -> None:
141
+ logger: Logger | None = self._logger
142
+ if logger is not None:
143
+ logger.info(message, context)
144
+
145
+ def _log_warn(self, message: str, context: dict[str, Any]) -> None:
146
+ logger: Logger | None = self._logger
147
+ if logger is not None:
148
+ logger.warn(message, context)
149
+
150
+ def _resolve_urls(
151
+ self,
152
+ url: str | None,
153
+ direct_path: str | None,
154
+ hosts: list[str] | tuple[str, ...] | None,
155
+ ) -> list[str]:
156
+ resolved: list[str] = []
157
+ if url and url not in resolved:
158
+ resolved.append(url)
159
+ if direct_path:
160
+ if direct_path.startswith("https://") or direct_path.startswith("http://"):
161
+ if direct_path not in resolved:
162
+ resolved.append(direct_path)
163
+ else:
164
+ normalized = (
165
+ direct_path if direct_path.startswith("/") else f"/{direct_path}"
166
+ )
167
+ for host in hosts or self._default_hosts:
168
+ # Hosts may carry an explicit scheme (tests use loopback
169
+ # http); bare CDN hostnames default to https.
170
+ if "://" in host:
171
+ candidate = f"{host.rstrip('/')}{normalized}"
172
+ else:
173
+ candidate = f"https://{host}{normalized}"
174
+ if candidate not in resolved:
175
+ resolved.append(candidate)
176
+ if len(resolved) == 0:
177
+ raise ValueError("missing transfer url/directPath")
178
+ return resolved
179
+
180
+ def _resolve_request(
181
+ self,
182
+ url: str | None,
183
+ direct_path: str | None,
184
+ hosts: list[str] | tuple[str, ...] | None,
185
+ headers: Mapping[str, str] | None,
186
+ timeout_ms: int | None,
187
+ extra_headers: Mapping[str, str | None] | None = None,
188
+ ) -> tuple[list[str], dict[str, str], int]:
189
+ merged = dict(self._default_headers)
190
+ merged.update(_normalize_headers(headers))
191
+ if extra_headers:
192
+ for key in extra_headers:
193
+ value = extra_headers[key]
194
+ if value is not None:
195
+ merged[str(key).lower()] = value
196
+ return (
197
+ self._resolve_urls(url, direct_path, hosts),
198
+ merged,
199
+ timeout_ms if timeout_ms is not None else self._default_timeout_ms,
200
+ )
201
+
202
+ @staticmethod
203
+ def _check_signal(signal: Any) -> None:
204
+ if signal is None:
205
+ return
206
+ aborted = getattr(signal, "aborted", None)
207
+ if aborted is True:
208
+ raise ValueError("transfer aborted")
209
+ if callable(aborted) and aborted():
210
+ raise ValueError("transfer aborted")
211
+ is_set = getattr(signal, "is_set", None)
212
+ if callable(is_set) and is_set():
213
+ raise ValueError("transfer aborted")
214
+
215
+ def _request_once(
216
+ self,
217
+ url: str,
218
+ method: str,
219
+ headers: dict[str, str],
220
+ body: bytes | BinaryIO | None,
221
+ content_length: int | None,
222
+ timeout_ms: int,
223
+ ) -> StreamTransferResponse:
224
+ parsed = urllib.parse.urlsplit(url)
225
+ if parsed.scheme == "https":
226
+ connection: http.client.HTTPConnection = http.client.HTTPSConnection(
227
+ parsed.hostname or "",
228
+ parsed.port or 443,
229
+ timeout=timeout_ms / 1_000,
230
+ context=ssl.create_default_context(),
231
+ )
232
+ elif parsed.scheme == "http":
233
+ connection = http.client.HTTPConnection(
234
+ parsed.hostname or "",
235
+ parsed.port or 80,
236
+ timeout=timeout_ms / 1_000,
237
+ )
238
+ else:
239
+ raise ValueError(f"unsupported transfer url scheme: {parsed.scheme}")
240
+ path = parsed.path or "/"
241
+ if parsed.query:
242
+ path = f"{path}?{parsed.query}"
243
+ try:
244
+ send_headers = dict(headers)
245
+ if content_length is not None:
246
+ send_headers["content-length"] = str(content_length)
247
+ if isinstance(body, (bytes, bytearray)):
248
+ connection.request(method, path, body=bytes(body), headers=send_headers)
249
+ elif body is None:
250
+ connection.request(method, path, headers=send_headers)
251
+ else:
252
+ connection.putrequest(
253
+ method, path, skip_host=False, skip_accept_encoding=True
254
+ )
255
+ for key, value in send_headers.items():
256
+ connection.putheader(key, value)
257
+ connection.endheaders()
258
+ while True:
259
+ piece = body.read(65_536)
260
+ if not piece:
261
+ break
262
+ connection.send(bytes(piece))
263
+ response = connection.getresponse()
264
+ status = response.status
265
+ response_headers: dict[str, str] = {}
266
+ for key, value in response.getheaders():
267
+ name = str(key).lower()
268
+ response_headers[name] = (
269
+ f"{response_headers[name]}, {value}"
270
+ if name in response_headers
271
+ else str(value)
272
+ )
273
+ body_bytes = _read_body_capped(response, self._default_max_read_bytes)
274
+ return StreamTransferResponse(
275
+ url=url,
276
+ status=status,
277
+ ok=200 <= status < 300,
278
+ headers=response_headers,
279
+ body=body_bytes,
280
+ )
281
+ finally:
282
+ connection.close()
283
+
284
+ async def _fetch_with_fallback(
285
+ self,
286
+ urls: list[str],
287
+ method: str,
288
+ headers: dict[str, str],
289
+ body: bytes | BinaryIO | None,
290
+ content_length: int | None,
291
+ timeout_ms: int,
292
+ signal: Any,
293
+ ) -> StreamTransferResponse:
294
+ self._check_signal(signal)
295
+ last_error: BaseException | None = None
296
+ for index, url in enumerate(urls):
297
+ try:
298
+ response = await asyncio.to_thread(
299
+ self._request_once,
300
+ url,
301
+ method,
302
+ headers,
303
+ body,
304
+ content_length,
305
+ timeout_ms,
306
+ )
307
+ except BaseException as error: # noqa: BLE001 - failover tries the next host
308
+ last_error = error
309
+ if index == len(urls) - 1:
310
+ raise
311
+ self._log_warn(
312
+ "transfer host failed, trying next host",
313
+ {"url": url, "message": str(to_error(error))},
314
+ )
315
+ continue
316
+ if response.status < 500 or index == len(urls) - 1:
317
+ return response
318
+ self._log_warn(
319
+ "transfer fallback to next host",
320
+ {"url": url, "status": response.status},
321
+ )
322
+ if last_error is not None:
323
+ raise last_error
324
+ raise ValueError("transfer failed")
325
+
326
+ async def download_stream(
327
+ self,
328
+ url: str | None = None,
329
+ direct_path: str | None = None,
330
+ hosts: list[str] | tuple[str, ...] | None = None,
331
+ headers: Mapping[str, str] | None = None,
332
+ agent: Any | None = None,
333
+ timeout_ms: int | None = None,
334
+ signal: Any | None = None,
335
+ max_bytes: int | None = None,
336
+ ) -> StreamTransferResponse:
337
+ """Fetch an encrypted payload from the first responsive media host."""
338
+ del agent
339
+ urls, merged, resolved_timeout = self._resolve_request(
340
+ url, direct_path, hosts, headers, timeout_ms
341
+ )
342
+ self._log_debug(
343
+ "media download stream start",
344
+ {"urls": len(urls), "timeoutMs": resolved_timeout},
345
+ )
346
+ result = await self._fetch_with_fallback(
347
+ urls, "GET", merged, None, None, resolved_timeout, signal
348
+ )
349
+ if (
350
+ max_bytes is not None
351
+ and result.body is not None
352
+ and len(result.body) > max_bytes
353
+ ):
354
+ raise ValueError(f"stream exceeded max bytes limit ({max_bytes})")
355
+ self._log_debug(
356
+ "media download stream response",
357
+ {"url": result.url, "status": result.status},
358
+ )
359
+ return result
360
+
361
+ async def download_bytes(
362
+ self,
363
+ url: str | None = None,
364
+ direct_path: str | None = None,
365
+ hosts: list[str] | tuple[str, ...] | None = None,
366
+ headers: Mapping[str, str] | None = None,
367
+ agent: Any | None = None,
368
+ timeout_ms: int | None = None,
369
+ signal: Any | None = None,
370
+ max_bytes: int | None = None,
371
+ ) -> bytes:
372
+ """Download the encrypted body and return it as bytes."""
373
+ response = await self.download_stream(
374
+ url=url,
375
+ direct_path=direct_path,
376
+ hosts=hosts,
377
+ headers=headers,
378
+ agent=agent,
379
+ timeout_ms=timeout_ms,
380
+ signal=signal,
381
+ max_bytes=max_bytes or self._default_max_read_bytes,
382
+ )
383
+ await self._assert_successful_response(response)
384
+ if response.body is None:
385
+ return _EMPTY_BYTES
386
+ return bytes(response.body)
387
+
388
+ async def upload_stream(
389
+ self,
390
+ url: str | None = None,
391
+ direct_path: str | None = None,
392
+ hosts: list[str] | tuple[str, ...] | None = None,
393
+ headers: Mapping[str, str] | None = None,
394
+ agent: Any | None = None,
395
+ timeout_ms: int | None = None,
396
+ signal: Any | None = None,
397
+ method: str = "POST",
398
+ body: bytes | bytearray | BinaryIO | AsyncIterator[bytes] | None = None,
399
+ content_length: int | None = None,
400
+ content_type: str | None = None,
401
+ ) -> StreamTransferResponse:
402
+ """Upload a raw (already-encrypted or plaintext) body to a media URL."""
403
+ del agent
404
+ upload_body: bytes | BinaryIO | None
405
+ if isinstance(body, AsyncIterator) or (
406
+ body is not None
407
+ and not isinstance(body, (bytes, bytearray))
408
+ and not callable(getattr(body, "read", None))
409
+ ):
410
+ upload_body = await _aiter_to_bytes(body)
411
+ elif isinstance(body, (bytes, bytearray)):
412
+ upload_body = bytes(body)
413
+ else:
414
+ upload_body = body
415
+ urls, merged, resolved_timeout = self._resolve_request(
416
+ url,
417
+ direct_path,
418
+ hosts,
419
+ headers,
420
+ timeout_ms,
421
+ {
422
+ "content-type": content_type,
423
+ "content-length": (
424
+ str(content_length) if content_length is not None else None
425
+ ),
426
+ },
427
+ )
428
+ upload_urls = list(urls)
429
+ if not isinstance(upload_body, (bytes, bytearray)) and len(upload_urls) > 1:
430
+ self._log_warn(
431
+ "upload stream fallback disabled for non-replayable body",
432
+ {"attemptedHosts": len(upload_urls)},
433
+ )
434
+ upload_urls = upload_urls[:1]
435
+ self._log_debug(
436
+ "media upload stream start",
437
+ {"urls": len(upload_urls), "timeoutMs": resolved_timeout, "method": method},
438
+ )
439
+ result = await self._fetch_with_fallback(
440
+ upload_urls,
441
+ method,
442
+ merged,
443
+ upload_body,
444
+ content_length
445
+ if content_length is not None
446
+ else (len(upload_body) if isinstance(upload_body, bytes) else None),
447
+ resolved_timeout,
448
+ signal,
449
+ )
450
+ self._log_debug(
451
+ "media upload stream response",
452
+ {"url": result.url, "status": result.status},
453
+ )
454
+ return result
455
+
456
+ async def upload_encrypted(
457
+ self,
458
+ media_type: str,
459
+ plaintext: bytes | bytearray | BinaryIO | AsyncIterator[bytes],
460
+ url: str | None = None,
461
+ direct_path: str | None = None,
462
+ hosts: list[str] | tuple[str, ...] | None = None,
463
+ headers: Mapping[str, str] | None = None,
464
+ agent: Any | None = None,
465
+ timeout_ms: int | None = None,
466
+ signal: Any | None = None,
467
+ method: str = "POST",
468
+ media_key: bytes | bytearray | None = None,
469
+ content_length: int | None = None,
470
+ content_type: str | None = None,
471
+ ) -> EncryptedUploadResult:
472
+ """Encrypt the plaintext body and upload it; returns key/hashes/receipt."""
473
+ self._log_info("media encrypted upload start", {"mediaType": media_type})
474
+ key = (
475
+ bytes(media_key)
476
+ if media_key is not None
477
+ else WaMediaCrypto.generate_media_key()
478
+ )
479
+ if isinstance(plaintext, (bytes, bytearray)):
480
+ raw = bytes(plaintext)
481
+ encrypted = WaMediaCrypto.encrypt_bytes(media_type, key, raw)
482
+ ciphertext = encrypted.ciphertext_hmac
483
+ file_sha256 = encrypted.file_sha256
484
+ file_enc_sha256 = encrypted.file_enc_sha256
485
+ plaintext_length = len(raw)
486
+ else:
487
+ prepared = await WaMediaCrypto.encrypt_readable(
488
+ media_type,
489
+ key,
490
+ plaintext,
491
+ expected_file_size=content_length,
492
+ )
493
+ ciphertext = b"".join([piece async for piece in prepared.encrypted])
494
+ metadata = await prepared.metadata
495
+ file_sha256 = metadata.file_sha256
496
+ file_enc_sha256 = metadata.file_enc_sha256
497
+ plaintext_length = metadata.plaintext_length
498
+ transfer = await self.upload_stream(
499
+ url=url,
500
+ direct_path=direct_path,
501
+ hosts=hosts,
502
+ headers=headers,
503
+ agent=agent,
504
+ timeout_ms=timeout_ms,
505
+ signal=signal,
506
+ method=method,
507
+ body=ciphertext,
508
+ content_length=len(ciphertext),
509
+ content_type=content_type,
510
+ )
511
+ self._log_info("media encrypted upload completed", {"status": transfer.status})
512
+ return EncryptedUploadResult(
513
+ transfer=transfer,
514
+ media_key=key,
515
+ file_sha256=file_sha256,
516
+ file_enc_sha256=file_enc_sha256,
517
+ plaintext_length=plaintext_length,
518
+ )
519
+
520
+ async def download_and_decrypt(
521
+ self,
522
+ request: Mapping[str, Any] | None = None,
523
+ **kwargs: Any,
524
+ ) -> bytes:
525
+ """Download an encrypted payload, decrypt it, and verify MAC + hashes."""
526
+ fields: dict[str, Any] = dict(request) if request is not None else {}
527
+ fields.update(kwargs)
528
+ media_type = fields.get("mediaType") or fields.get("media_type") or ""
529
+ raw_key = fields.get("mediaKey") or fields.get("media_key") or b""
530
+ raw_sha = fields.get("fileSha256") or fields.get("file_sha256")
531
+ raw_enc_sha = fields.get("fileEncSha256") or fields.get("file_enc_sha256")
532
+ self._log_info("media encrypted download start", {"mediaType": media_type})
533
+ decrypted = await self.download_and_decrypt_stream(
534
+ url=fields.get("url"),
535
+ direct_path=fields.get("directPath") or fields.get("direct_path"),
536
+ hosts=fields.get("hosts"),
537
+ headers=fields.get("headers"),
538
+ agent=fields.get("agent"),
539
+ timeout_ms=fields.get("timeoutMs") or fields.get("timeout_ms"),
540
+ signal=fields.get("signal"),
541
+ max_bytes=fields.get("maxBytes") or fields.get("max_bytes"),
542
+ media_type=str(media_type),
543
+ media_key=bytes(raw_key),
544
+ file_sha256=bytes(raw_sha) if raw_sha is not None else None,
545
+ file_enc_sha256=bytes(raw_enc_sha) if raw_enc_sha is not None else None,
546
+ )
547
+ plaintext = b"".join([piece async for piece in decrypted.plaintext])
548
+ metadata = await decrypted.metadata
549
+ _ = metadata
550
+ self._log_info(
551
+ "media encrypted download completed", {"byteLength": len(plaintext)}
552
+ )
553
+ return plaintext
554
+
555
+ async def download_and_decrypt_stream(
556
+ self,
557
+ url: str | None = None,
558
+ direct_path: str | None = None,
559
+ hosts: list[str] | tuple[str, ...] | None = None,
560
+ headers: Mapping[str, str] | None = None,
561
+ agent: Any | None = None,
562
+ timeout_ms: int | None = None,
563
+ signal: Any | None = None,
564
+ max_bytes: int | None = None,
565
+ media_type: str = "",
566
+ media_key: bytes | bytearray = b"",
567
+ file_sha256: bytes | bytearray | None = None,
568
+ file_enc_sha256: bytes | bytearray | None = None,
569
+ ) -> WaMediaReadableDecryptionResult:
570
+ """Download, decrypt, and verify; resolves with plaintext bytes + metadata."""
571
+ response = await self.download_stream(
572
+ url=url,
573
+ direct_path=direct_path,
574
+ hosts=hosts,
575
+ headers=headers,
576
+ agent=agent,
577
+ timeout_ms=timeout_ms,
578
+ signal=signal,
579
+ max_bytes=max_bytes,
580
+ )
581
+ await self._assert_successful_response(response)
582
+ if response.body is None:
583
+ raise ValueError(f"download response body is empty for {response.url}")
584
+ decrypted = WaMediaCrypto.decrypt_bytes(
585
+ media_type,
586
+ bytes(media_key),
587
+ bytes(response.body),
588
+ bytes(file_sha256) if file_sha256 is not None else None,
589
+ bytes(file_enc_sha256) if file_enc_sha256 is not None else None,
590
+ self._skip_mac_verification,
591
+ )
592
+ self._log_debug(
593
+ "media encrypted download stream ready", {"mediaType": media_type}
594
+ )
595
+
596
+ async def _plaintext() -> AsyncIterator[bytes]:
597
+ yield decrypted.plaintext
598
+
599
+ async def _metadata() -> WaMediaReadableDecryptionResultMetadata:
600
+ return WaMediaReadableDecryptionResultMetadata(
601
+ file_sha256=decrypted.file_sha256,
602
+ file_enc_sha256=decrypted.file_enc_sha256,
603
+ )
604
+
605
+ return WaMediaReadableDecryptionResult(
606
+ plaintext=_plaintext(), metadata=_metadata()
607
+ )
608
+
609
+ async def read_response_bytes(
610
+ self, response: StreamTransferResponse, max_bytes: int | None = None
611
+ ) -> bytes:
612
+ """Return a response body as bytes (respects ``max_bytes``)."""
613
+ if response.body is None:
614
+ return _EMPTY_BYTES
615
+ body = bytes(response.body)
616
+ limit = max_bytes if max_bytes is not None else self._default_max_read_bytes
617
+ if limit is not None and len(body) > limit:
618
+ raise ValueError(f"stream exceeded max bytes limit ({limit})")
619
+ return body
620
+
621
+ async def _assert_successful_response(
622
+ self, response: StreamTransferResponse
623
+ ) -> None:
624
+ if response.ok:
625
+ return
626
+ raise ValueError(
627
+ f"download failed with status {response.status} for {response.url}"
628
+ )
629
+
630
+
631
+ __all__ = [
632
+ "EncryptedUploadResult",
633
+ "StreamTransferResponse",
634
+ "WaMediaTransferClient",
635
+ ]
@@ -0,0 +1,48 @@
1
+ """``media_conn`` IQ response parser (mirrors ``src/media/transfer/conn.ts``)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from zapy._media.types import WaMediaConn, WaMediaConnHost
6
+ from zapy._protocol.nodes import WA_NODE_TAGS
7
+ from zapy._transport.node.helpers import (
8
+ find_node_child,
9
+ get_node_children_by_tag,
10
+ )
11
+ from zapy._transport.node.query import assert_iq_result
12
+ from zapy._transport.types import BinaryNode
13
+ from zapy._util.primitives import parse_optional_int
14
+
15
+
16
+ def parse_media_conn_response(node: BinaryNode, now_ms: int) -> WaMediaConn:
17
+ """Parse a ``media_conn`` IQ response into auth token, expiry, and hosts."""
18
+ assert_iq_result(node, "media_conn")
19
+
20
+ media_conn_node = find_node_child(node, WA_NODE_TAGS["MEDIA_CONN"])
21
+ if media_conn_node is None:
22
+ raise ValueError("media_conn response is missing media_conn node")
23
+
24
+ auth = media_conn_node.attrs.get("auth")
25
+ if not auth:
26
+ raise ValueError("media_conn response is missing auth")
27
+ ttl = parse_optional_int(media_conn_node.attrs.get("ttl")) or 0
28
+ if ttl <= 0:
29
+ raise ValueError("media_conn response has invalid ttl")
30
+
31
+ expires_at_ms = ttl * 1_000 if ttl >= 1_000_000_000 else now_ms + ttl * 1_000
32
+ hosts: list[WaMediaConnHost] = []
33
+ for host in get_node_children_by_tag(media_conn_node, WA_NODE_TAGS["HOST"]):
34
+ hostname = host.attrs.get("hostname")
35
+ if hostname:
36
+ hosts.append(
37
+ WaMediaConnHost(
38
+ hostname=hostname,
39
+ is_fallback=host.attrs.get("type") == "fallback",
40
+ )
41
+ )
42
+ if len(hosts) == 0:
43
+ raise ValueError("media_conn response contains no hosts")
44
+
45
+ return WaMediaConn(auth=auth, expires_at_ms=expires_at_ms, hosts=tuple(hosts))
46
+
47
+
48
+ __all__ = ["parse_media_conn_response"]