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
zapy/_client/media.py ADDED
@@ -0,0 +1,829 @@
1
+ """Client media helpers (mirrors ``src/client/media.ts``).
2
+
3
+ The media transfer client (``src/media``) belongs to another worker, so this
4
+ module works against the structural :class:`WaClientMediaTransfer` protocol.
5
+ ``download_media_message`` returns the decrypted bytes (the oracle returns a
6
+ live ``Readable``); pass ``stream=True``-style callers should use the transfer
7
+ client directly.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import asyncio
13
+ import base64
14
+ import hashlib
15
+ import json
16
+ import logging
17
+ import os
18
+ import random
19
+ import tempfile
20
+ import urllib.parse
21
+ import weakref
22
+ from collections.abc import Awaitable, Callable
23
+ from dataclasses import dataclass
24
+ from typing import Any, BinaryIO, Protocol, cast
25
+
26
+ from zapy._infra.log import Logger
27
+ from zapy._message.encode.content import MessageDict
28
+ from zapy._message.encode.media_payload import resolve_media_payload
29
+ from zapy._util.primitives import to_error
30
+
31
+ _logger = logging.getLogger("zapy._client.media")
32
+
33
+ IMAGE_THUMB_MAX_EDGE: int = 100
34
+ VIDEO_THUMB_MAX_EDGE: int = 100
35
+ STICKER_THUMB_MAX_EDGE: int = 100
36
+
37
+ MEDIA_UPLOAD_ID_MAX: int = 281_474_976_710_655
38
+
39
+
40
+ @dataclass(frozen=True, slots=True)
41
+ class ProcessedMediaFields:
42
+ """Derived media fields (mirrors ``ProcessedMediaFields``)."""
43
+
44
+ jpeg_thumbnail: bytes | None = None
45
+ png_thumbnail: bytes | None = None
46
+ width: int | None = None
47
+ height: int | None = None
48
+ seconds: int | None = None
49
+ waveform: bytes | None = None
50
+ is_animated: bool | None = None
51
+ first_frame_length: int | None = None
52
+
53
+
54
+ @dataclass(frozen=True, slots=True)
55
+ class WebpAnimInfo:
56
+ """WebP animation probe result."""
57
+
58
+ is_animated: bool = True
59
+ first_frame_length: int = 0
60
+
61
+
62
+ @dataclass(frozen=True, slots=True)
63
+ class StreamFileMetrics:
64
+ """SHA-256 + length of an uploaded stream."""
65
+
66
+ file_sha256: bytes
67
+ byte_length: int
68
+
69
+
70
+ @dataclass(frozen=True, slots=True)
71
+ class WaMediaProcessorCallContext:
72
+ """Per-call processor context (mirrors ``WaMediaProcessorCallContext``)."""
73
+
74
+ logger: Any = None
75
+
76
+
77
+ class WaMediaProcessor(Protocol):
78
+ """Structural media processor (mirrors ``WaMediaProcessor``)."""
79
+
80
+ async def generate_image_thumbnail(
81
+ self, input: Any, max_edge: int, ctx: Any = None
82
+ ) -> Any | None: ...
83
+ async def generate_video_thumbnail(
84
+ self, input: Any, max_edge: int, ctx: Any = None
85
+ ) -> Any | None: ...
86
+ async def probe_media(self, input: Any, ctx: Any = None) -> Any | None: ...
87
+ async def compute_waveform(self, input: Any, ctx: Any = None) -> Any | None: ...
88
+ async def generate_sticker_thumbnail(
89
+ self, input: Any, max_edge: int, ctx: Any = None
90
+ ) -> Any | None: ...
91
+ async def normalize_voice_note(self, input: Any, ctx: Any = None) -> Any | None: ...
92
+ async def detect_mimetype(self, input: Any, ctx: Any = None) -> str | None: ...
93
+
94
+
95
+ @dataclass(frozen=True, slots=True)
96
+ class WaMediaOptions:
97
+ """Media handling tuning (mirrors ``WaMediaOptions``)."""
98
+
99
+ processor: WaMediaProcessor | None = None
100
+ generate_thumbnail: bool | None = None
101
+ generate_probe: bool | None = None
102
+ generate_waveform: bool | None = None
103
+ generate_sticker_thumbnail: bool | None = None
104
+ normalize_voice_note: bool | None = None
105
+
106
+
107
+ @dataclass(frozen=True, slots=True)
108
+ class WaDownloadMediaOptions:
109
+ """Download tuning (mirrors ``WaDownloadMediaOptions``)."""
110
+
111
+ max_bytes: int | None = None
112
+ timeout_ms: int | None = None
113
+ signal: Any | None = None
114
+ transfer: Any | None = None
115
+ proxy: Any | None = None
116
+
117
+
118
+ class WaClientMediaTransfer(Protocol):
119
+ """Transfer leg used by the client media helpers."""
120
+
121
+ async def upload_stream(
122
+ self,
123
+ *,
124
+ url: str,
125
+ body: Any,
126
+ content_length: int,
127
+ content_type: str | None = None,
128
+ ) -> Any: ...
129
+
130
+ async def read_response_bytes(self, response: Any) -> bytes: ...
131
+
132
+ async def download_and_decrypt(
133
+ self,
134
+ *,
135
+ direct_path: str,
136
+ media_type: str,
137
+ media_key: bytes,
138
+ file_sha256: bytes | None = None,
139
+ file_enc_sha256: bytes | None = None,
140
+ timeout_ms: int | None = None,
141
+ max_bytes: int | None = None,
142
+ ) -> bytes: ...
143
+
144
+
145
+ async def read_file_head(file_path: str, byte_count: int) -> bytes:
146
+ """Read the first ``byte_count`` bytes of ``file_path``."""
147
+
148
+ def _read() -> bytes:
149
+ with open(file_path, "rb") as handle:
150
+ return handle.read(byte_count)
151
+
152
+ return await asyncio.to_thread(_read)
153
+
154
+
155
+ def parse_webp_animation(data: bytes | bytearray) -> WebpAnimInfo | None:
156
+ """Detect an animated WebP and the length of its first frame."""
157
+ raw = bytes(data)
158
+ RIFF_HEADER_SIZE = 12
159
+ CHUNK_HEADER_SIZE = 8
160
+ if len(raw) < RIFF_HEADER_SIZE + CHUNK_HEADER_SIZE:
161
+ return None
162
+ offset = RIFF_HEADER_SIZE
163
+ if raw[offset : offset + 4] != b"VP8X":
164
+ return None
165
+ offset += CHUNK_HEADER_SIZE + 10
166
+
167
+ while offset + CHUNK_HEADER_SIZE <= len(raw):
168
+ is_anmf = raw[offset : offset + 4] == b"ANMF"
169
+ size_offset = offset + 4
170
+ if size_offset + 4 > len(raw):
171
+ return None
172
+ chunk_size = int.from_bytes(raw[size_offset : size_offset + 4], "little")
173
+ if chunk_size % 2 != 0:
174
+ chunk_size += 1
175
+ next_offset = offset + CHUNK_HEADER_SIZE + chunk_size
176
+ if next_offset <= offset or next_offset > len(raw):
177
+ return None
178
+ if is_anmf:
179
+ return WebpAnimInfo(is_animated=True, first_frame_length=next_offset)
180
+ offset = next_offset
181
+ return None
182
+
183
+
184
+ def is_readable_stream(value: Any) -> bool:
185
+ """Return whether ``value`` behaves like a binary read stream."""
186
+ return hasattr(value, "read") and callable(value.read)
187
+
188
+
189
+ async def stream_to_temp_file(source: BinaryIO) -> str:
190
+ """Spill ``source`` to a temp file; returns its path."""
191
+
192
+ def _spill() -> str:
193
+ fd, path = tempfile.mkstemp(prefix="zapy-media-")
194
+ try:
195
+ with os.fdopen(fd, "wb") as handle:
196
+ while True:
197
+ chunk = source.read(65536)
198
+ if not chunk:
199
+ break
200
+ handle.write(chunk)
201
+ except BaseException:
202
+ try:
203
+ os.unlink(path)
204
+ except OSError:
205
+ pass
206
+ raise
207
+ return path
208
+
209
+ return await asyncio.to_thread(_spill)
210
+
211
+
212
+ async def cleanup_temp_file(file_path: str) -> None:
213
+ """Remove a temp file, ignoring missing paths."""
214
+ try:
215
+ await asyncio.to_thread(os.unlink, file_path)
216
+ except OSError:
217
+ pass
218
+
219
+
220
+ def _close_quietly(handle: BinaryIO) -> None:
221
+ try:
222
+ handle.close()
223
+ except OSError:
224
+ pass
225
+
226
+
227
+ def _sha256_size(body: bytes) -> StreamFileMetrics:
228
+ return StreamFileMetrics(
229
+ file_sha256=hashlib.sha256(body).digest(), byte_length=len(body)
230
+ )
231
+
232
+
233
+ async def stream_to_temp_file_with_sha256(
234
+ source: BinaryIO,
235
+ ) -> tuple[str, StreamFileMetrics]:
236
+ """Spill ``source`` to a temp file while hashing it."""
237
+
238
+ def _spill() -> tuple[str, StreamFileMetrics]:
239
+ digest = hashlib.sha256()
240
+ byte_length = 0
241
+ fd, path = tempfile.mkstemp(prefix="zapy-media-")
242
+ try:
243
+ with os.fdopen(fd, "wb") as handle:
244
+ while True:
245
+ chunk = source.read(65536)
246
+ if not chunk:
247
+ break
248
+ digest.update(bytes(chunk))
249
+ byte_length += len(chunk)
250
+ handle.write(chunk)
251
+ except BaseException:
252
+ try:
253
+ os.unlink(path)
254
+ except OSError:
255
+ pass
256
+ raise
257
+ return path, StreamFileMetrics(
258
+ file_sha256=digest.digest(), byte_length=byte_length
259
+ )
260
+
261
+ return await asyncio.to_thread(_spill)
262
+
263
+
264
+ WaUploadMediaSource = bytes | str | BinaryIO
265
+
266
+
267
+ def _host_name(host: Any) -> str | None:
268
+ name = (
269
+ host.get("hostname")
270
+ if isinstance(host, dict)
271
+ else getattr(host, "hostname", None)
272
+ )
273
+ return name if isinstance(name, str) else None
274
+
275
+
276
+ def _host_fallback(host: Any) -> bool:
277
+ if isinstance(host, dict):
278
+ return bool(host.get("is_fallback", False))
279
+ return bool(getattr(host, "is_fallback", False))
280
+
281
+
282
+ def select_media_upload_host(media_conn: Any) -> str:
283
+ """Pick the first non-fallback upload host (mirrors the TS helper)."""
284
+ hosts = getattr(media_conn, "hosts", [])
285
+ for host in hosts:
286
+ hostname = _host_name(host)
287
+ if hostname and not _host_fallback(host):
288
+ return hostname
289
+ if hosts:
290
+ hostname = _host_name(hosts[0])
291
+ if hostname:
292
+ return hostname
293
+ raise ValueError("media conn has no upload hosts")
294
+
295
+
296
+ def build_media_upload_url(
297
+ host: str,
298
+ path: str,
299
+ auth: str,
300
+ file_sha256: bytes,
301
+ media_id: str | None = None,
302
+ ) -> str:
303
+ """Build the plaintext upload URL (mirrors ``buildMediaUploadUrl``)."""
304
+ hash_token = base64.urlsafe_b64encode(bytes(file_sha256)).decode("ascii")
305
+ base = (
306
+ f"https://{host}{path}/{hash_token}"
307
+ f"?auth={urllib.parse.quote(auth, safe='')}"
308
+ f"&token={urllib.parse.quote(hash_token, safe='')}"
309
+ )
310
+ return base if media_id is None else f"{base}&media_id={media_id}"
311
+
312
+
313
+ def assert_media_upload_status(status: int, label: str) -> None:
314
+ """Throw unless the upload status is 2xx (mirrors the TS helper)."""
315
+ if status < 200 or status >= 300:
316
+ raise ValueError(f"{label} failed with status {status}")
317
+
318
+
319
+ def parse_media_upload_json_body(body: bytes, label: str) -> Any:
320
+ """Parse an upload JSON body (mirrors ``parseMediaUploadJsonBody``)."""
321
+ try:
322
+ return json.loads(bytes(body).decode("utf-8"))
323
+ except (ValueError, UnicodeDecodeError) as error:
324
+ raise ValueError(f"{label} returned invalid json: {to_error(error)}") from error
325
+
326
+
327
+ async def perform_plaintext_media_upload(
328
+ media_transfer: WaClientMediaTransfer,
329
+ media_conn: Any,
330
+ source: WaUploadMediaSource,
331
+ path: str,
332
+ mimetype: str | None = None,
333
+ log_label: str = "sending media upload",
334
+ logger: Any = None,
335
+ ) -> dict[str, Any]:
336
+ """Upload plaintext media; returns response bytes plus file metrics."""
337
+ metrics: StreamFileMetrics | None = None
338
+ body: bytes | BinaryIO
339
+ cleanup: Callable[[], Awaitable[None]] | None = None
340
+ if isinstance(source, (bytes, bytearray)):
341
+ raw = bytes(source)
342
+ metrics = _sha256_size(raw)
343
+ body = raw
344
+ elif isinstance(source, str):
345
+ await assert_readable_file(source)
346
+ handle = open(source, "rb")
347
+ temp_path, metrics = await stream_to_temp_file_with_sha256(handle)
348
+ handle.close()
349
+
350
+ def _open_temp() -> BinaryIO:
351
+ return open(temp_path, "rb")
352
+
353
+ temp_handle: BinaryIO = await asyncio.to_thread(_open_temp)
354
+ body = temp_handle
355
+
356
+ async def _cleanup_temp() -> None:
357
+ _close_quietly(temp_handle)
358
+ await cleanup_temp_file(temp_path)
359
+
360
+ cleanup = _cleanup_temp
361
+ elif is_readable_stream(source):
362
+ temp_path, metrics = await stream_to_temp_file_with_sha256(source)
363
+ stream_handle: BinaryIO = await asyncio.to_thread(open, temp_path, "rb")
364
+ body = stream_handle
365
+
366
+ async def _cleanup_stream() -> None:
367
+ _close_quietly(stream_handle)
368
+ await cleanup_temp_file(temp_path)
369
+
370
+ cleanup = _cleanup_stream
371
+ else:
372
+ raise ValueError("media upload received unsupported source type")
373
+ try:
374
+ assert metrics is not None
375
+ host = select_media_upload_host(media_conn)
376
+ media_id = str(random.randint(0, MEDIA_UPLOAD_ID_MAX))
377
+ raw_auth = (
378
+ media_conn.get("auth")
379
+ if isinstance(media_conn, dict)
380
+ else getattr(media_conn, "auth", "")
381
+ )
382
+ auth = raw_auth if isinstance(raw_auth, str) else ""
383
+ url = build_media_upload_url(host, path, auth, metrics.file_sha256, media_id)
384
+ if logger is None:
385
+ _logger.debug("%s to %s (%d bytes)", log_label, host, metrics.byte_length)
386
+ else:
387
+ _log_debug(
388
+ logger,
389
+ log_label,
390
+ {"host": host, "path": path, "size": metrics.byte_length},
391
+ )
392
+ response = await media_transfer.upload_stream(
393
+ url=url,
394
+ body=body,
395
+ content_length=metrics.byte_length,
396
+ content_type=mimetype,
397
+ )
398
+ response_bytes = await media_transfer.read_response_bytes(response)
399
+ return {
400
+ "response_bytes": response_bytes,
401
+ "status": getattr(response, "status", 200),
402
+ "file_sha256": metrics.file_sha256,
403
+ "byte_length": metrics.byte_length,
404
+ "media_id": media_id,
405
+ }
406
+ finally:
407
+ if cleanup is not None:
408
+ await cleanup()
409
+
410
+
411
+ def _log_debug(logger: Any, message: str, context: dict[str, Any]) -> None:
412
+ debug = getattr(logger, "debug", None)
413
+ if callable(debug):
414
+ try:
415
+ debug(message, context)
416
+ return
417
+ except TypeError:
418
+ pass
419
+ _logger.debug("%s %s", message, context)
420
+
421
+
422
+ async def assert_readable_file(file_path: str) -> None:
423
+ """Throw unless ``file_path`` is a readable regular file."""
424
+
425
+ def _check() -> None:
426
+ if not os.path.isfile(file_path):
427
+ if not os.path.exists(file_path):
428
+ raise ValueError(f"media file not found: {file_path}")
429
+ raise ValueError(f"media path is not a regular file: {file_path}")
430
+
431
+ await asyncio.to_thread(_check)
432
+
433
+
434
+ async def resolve_media_inputs(
435
+ should_process: bool, raw: bytes | BinaryIO | str
436
+ ) -> dict[str, Any]:
437
+ """Resolve upload/processor inputs (mirrors ``resolveMediaInputs``)."""
438
+ if isinstance(raw, str):
439
+ await assert_readable_file(raw)
440
+
441
+ def _open() -> BinaryIO:
442
+ return open(raw, "rb")
443
+
444
+ return {
445
+ "processor_input": raw,
446
+ "upload_media": await asyncio.to_thread(_open),
447
+ }
448
+ if isinstance(raw, (bytes, bytearray)):
449
+ raw_bytes = bytes(raw)
450
+ return {"processor_input": raw_bytes, "upload_media": raw_bytes}
451
+ if is_readable_stream(raw):
452
+ stream = raw
453
+ if should_process:
454
+ temp_file_path = await stream_to_temp_file(stream)
455
+
456
+ def _open_temp() -> BinaryIO:
457
+ return open(temp_file_path, "rb")
458
+
459
+ return {
460
+ "processor_input": temp_file_path,
461
+ "upload_media": await asyncio.to_thread(_open_temp),
462
+ "temp_file_path": temp_file_path,
463
+ }
464
+ return {"upload_media": stream}
465
+ raise ValueError("media resolve received unsupported source type")
466
+
467
+
468
+ def _content_type(content: Any) -> str | None:
469
+ raw = (
470
+ content.get("type")
471
+ if isinstance(content, dict)
472
+ else getattr(content, "type", None)
473
+ )
474
+ return raw if isinstance(raw, str) else None
475
+
476
+
477
+ def _processor_fn(
478
+ processor: WaMediaProcessor, name: str
479
+ ) -> Callable[..., Awaitable[Any]] | None:
480
+ """Fetch an optional processor hook as a typed callable."""
481
+ fn = getattr(processor, name, None)
482
+ if callable(fn):
483
+ return cast(Callable[..., Awaitable[Any]], fn)
484
+ return None
485
+
486
+
487
+ def _read_field(source: Any, name: str) -> Any:
488
+ """Read a result field off a dict or an object (calling zero-arg methods)."""
489
+ raw = source.get(name) if isinstance(source, dict) else getattr(source, name, None)
490
+ if callable(raw):
491
+ return cast(Callable[[], Any], raw)()
492
+ return raw
493
+
494
+
495
+ def _content_field(content: Any, name: str) -> Any:
496
+ if isinstance(content, dict):
497
+ return content.get(name)
498
+ return getattr(content, name, None)
499
+
500
+
501
+ def should_generate_thumbnail(media: WaMediaOptions | None, content: Any) -> bool:
502
+ """Mirror the TS ``shouldGenerateThumbnail`` predicate."""
503
+ if media is None or media.processor is None or media.generate_thumbnail is False:
504
+ return False
505
+ content_type = _content_type(content)
506
+ processor = media.processor
507
+ if content_type == "image":
508
+ return (
509
+ _content_field(content, "jpeg_thumbnail") is None
510
+ and _processor_fn(processor, "generate_image_thumbnail") is not None
511
+ )
512
+ if content_type in ("video", "ptv"):
513
+ return (
514
+ _content_field(content, "jpeg_thumbnail") is None
515
+ and _processor_fn(processor, "generate_video_thumbnail") is not None
516
+ )
517
+ if content_type == "document":
518
+ return _processor_fn(processor, "generate_image_thumbnail") is not None
519
+ return False
520
+
521
+
522
+ def should_probe_media(media: WaMediaOptions | None, content: Any) -> bool:
523
+ """Mirror the TS ``shouldProbeMedia`` predicate."""
524
+ if media is None or media.processor is None or media.generate_probe is False:
525
+ return False
526
+ processor = media.processor
527
+ if _processor_fn(processor, "probe_media") is None:
528
+ return False
529
+ content_type = _content_type(content)
530
+ if content_type in ("video", "ptv"):
531
+ return (
532
+ _content_field(content, "seconds") is None
533
+ or _content_field(content, "width") is None
534
+ or _content_field(content, "height") is None
535
+ )
536
+ if content_type == "audio":
537
+ return _content_field(content, "seconds") is None
538
+ return False
539
+
540
+
541
+ def should_generate_waveform(media: WaMediaOptions | None, content: Any) -> bool:
542
+ """Mirror the TS ``shouldGenerateWaveform`` predicate."""
543
+ if media is None or media.processor is None or media.generate_waveform is False:
544
+ return False
545
+ return (
546
+ _processor_fn(media.processor, "compute_waveform") is not None
547
+ and _content_type(content) == "audio"
548
+ and _content_field(content, "waveform") is None
549
+ )
550
+
551
+
552
+ def should_normalize_voice_note(media: WaMediaOptions | None, content: Any) -> bool:
553
+ """Mirror the TS ``shouldNormalizeVoiceNote`` guard."""
554
+ return (
555
+ media is not None
556
+ and media.processor is not None
557
+ and _processor_fn(media.processor, "normalize_voice_note") is not None
558
+ and media.normalize_voice_note is True
559
+ and _content_type(content) == "audio"
560
+ and _content_field(content, "ptt") is True
561
+ )
562
+
563
+
564
+ def should_generate_sticker_thumbnail(
565
+ media: WaMediaOptions | None, content: Any
566
+ ) -> bool:
567
+ """Mirror the TS sticker-thumbnail predicate."""
568
+ if media is None or media.processor is None:
569
+ return False
570
+ if media.generate_sticker_thumbnail is False:
571
+ return False
572
+ return (
573
+ _content_type(content) == "sticker"
574
+ and _content_field(content, "png_thumbnail") is None
575
+ and _processor_fn(media.processor, "generate_sticker_thumbnail") is not None
576
+ )
577
+
578
+
579
+ def has_media_processing_tasks(media: WaMediaOptions | None, content: Any) -> bool:
580
+ """Return whether any processor step applies (mirrors the TS helper)."""
581
+ return (
582
+ should_generate_thumbnail(media, content)
583
+ or should_probe_media(media, content)
584
+ or should_generate_waveform(media, content)
585
+ or should_generate_sticker_thumbnail(media, content)
586
+ )
587
+
588
+
589
+ _scoped_media_logger_cache: weakref.WeakKeyDictionary[Any, Logger] = (
590
+ weakref.WeakKeyDictionary()
591
+ )
592
+
593
+
594
+ def get_scoped_media_logger(parent: Logger) -> Logger:
595
+ """Return the cached ``scope=media-utils`` child logger for ``parent``."""
596
+ cached = _scoped_media_logger_cache.get(parent)
597
+ if cached is not None:
598
+ return cached
599
+ scoped = parent.child({"scope": "media-utils"})
600
+ _scoped_media_logger_cache[parent] = scoped
601
+ return scoped
602
+
603
+
604
+ async def _run_processor_step(
605
+ step: str, content: Any, logger: Logger, fn: Callable[[], Awaitable[Any]]
606
+ ) -> Any | None:
607
+ try:
608
+ return await fn()
609
+ except Exception as error:
610
+ logger.error(
611
+ "media processor step failed, skipping step",
612
+ {
613
+ "type": _content_type(content),
614
+ "step": step,
615
+ "message": str(to_error(error)),
616
+ },
617
+ )
618
+ return None
619
+
620
+
621
+ async def run_media_processor(
622
+ media: WaMediaOptions | None,
623
+ input: bytes | str | None,
624
+ content: Any,
625
+ logger: Logger,
626
+ ) -> ProcessedMediaFields:
627
+ """Run thumbnail/probe/waveform/sticker steps (mirrors ``runMediaProcessor``)."""
628
+ processor = media.processor if media is not None else None
629
+ if (
630
+ processor is None
631
+ or not has_media_processing_tasks(media, content)
632
+ or input is None
633
+ ):
634
+ return ProcessedMediaFields()
635
+
636
+ result: dict[str, Any] = {
637
+ "jpeg_thumbnail": None,
638
+ "png_thumbnail": None,
639
+ "width": None,
640
+ "height": None,
641
+ "seconds": None,
642
+ "waveform": None,
643
+ "is_animated": None,
644
+ "first_frame_length": None,
645
+ }
646
+ ctx = WaMediaProcessorCallContext(logger=get_scoped_media_logger(logger))
647
+
648
+ content_type = _content_type(content)
649
+ is_video = content_type in ("video", "ptv")
650
+ thumb_max_edge = VIDEO_THUMB_MAX_EDGE if is_video else IMAGE_THUMB_MAX_EDGE
651
+ thumb_fn = _processor_fn(
652
+ processor,
653
+ "generate_video_thumbnail" if is_video else "generate_image_thumbnail",
654
+ )
655
+
656
+ async def _run_thumb() -> Any | None:
657
+ assert thumb_fn is not None
658
+ return await thumb_fn(input, thumb_max_edge, ctx)
659
+
660
+ async def _run_probe() -> Any | None:
661
+ assert probe_fn is not None
662
+ return await probe_fn(input, ctx)
663
+
664
+ thumb_task = (
665
+ _run_processor_step("thumbnail", content, logger, _run_thumb)
666
+ if should_generate_thumbnail(media, content) and thumb_fn is not None
667
+ else None
668
+ )
669
+ probe_fn = _processor_fn(processor, "probe_media")
670
+ probe_task = (
671
+ _run_processor_step("probe", content, logger, _run_probe)
672
+ if should_probe_media(media, content) and probe_fn is not None
673
+ else None
674
+ )
675
+
676
+ thumb, probe = None, None
677
+ if thumb_task is not None or probe_task is not None:
678
+ thumb, probe = await asyncio.gather(
679
+ thumb_task or asyncio.sleep(0, result=None),
680
+ probe_task or asyncio.sleep(0, result=None),
681
+ )
682
+
683
+ if thumb:
684
+ result["jpeg_thumbnail"] = _read_field(thumb, "jpeg_thumbnail")
685
+ if not is_video and not probe:
686
+ result["width"] = _read_field(thumb, "width")
687
+ result["height"] = _read_field(thumb, "height")
688
+
689
+ if probe:
690
+ duration = _read_field(probe, "duration_seconds") or _read_field(
691
+ probe, "durationSeconds"
692
+ )
693
+ if duration is not None and _content_field(content, "seconds") is None:
694
+ result["seconds"] = int(duration)
695
+ if _content_field(content, "width") is None:
696
+ width = _read_field(probe, "width")
697
+ if width is not None:
698
+ result["width"] = width
699
+ if _content_field(content, "height") is None:
700
+ height = _read_field(probe, "height")
701
+ if height is not None:
702
+ result["height"] = height
703
+
704
+ if should_generate_waveform(media, content):
705
+ waveform_fn = _processor_fn(processor, "compute_waveform")
706
+
707
+ async def _run_waveform() -> Any | None:
708
+ assert waveform_fn is not None
709
+ return await waveform_fn(input, ctx)
710
+
711
+ waveform_result = (
712
+ await _run_processor_step("waveform", content, logger, _run_waveform)
713
+ if waveform_fn is not None
714
+ else None
715
+ )
716
+ if waveform_result:
717
+ result["waveform"] = _read_field(waveform_result, "waveform")
718
+ duration = _read_field(waveform_result, "duration_seconds") or _read_field(
719
+ waveform_result, "durationSeconds"
720
+ )
721
+ if (
722
+ result["seconds"] is None
723
+ and _content_field(content, "seconds") is None
724
+ and duration is not None
725
+ ):
726
+ result["seconds"] = int(duration)
727
+
728
+ if content_type == "sticker":
729
+ if should_generate_sticker_thumbnail(media, content):
730
+ sticker_fn = _processor_fn(processor, "generate_sticker_thumbnail")
731
+
732
+ async def _run_sticker_thumb() -> Any | None:
733
+ assert sticker_fn is not None
734
+ return await sticker_fn(input, STICKER_THUMB_MAX_EDGE, ctx)
735
+
736
+ sticker_thumb = (
737
+ await _run_processor_step(
738
+ "stickerThumbnail", content, logger, _run_sticker_thumb
739
+ )
740
+ if sticker_fn is not None
741
+ else None
742
+ )
743
+ if sticker_thumb:
744
+ result["png_thumbnail"] = _read_field(sticker_thumb, "png_thumbnail")
745
+ result["width"] = _read_field(sticker_thumb, "width")
746
+ result["height"] = _read_field(sticker_thumb, "height")
747
+ if _content_field(content, "is_animated") is None:
748
+ header = (
749
+ await read_file_head(input, 100) if isinstance(input, str) else input
750
+ )
751
+ anim = parse_webp_animation(header)
752
+ if anim is not None:
753
+ result["is_animated"] = True
754
+ result["first_frame_length"] = anim.first_frame_length
755
+ else:
756
+ result["is_animated"] = False
757
+
758
+ return ProcessedMediaFields(**result)
759
+
760
+
761
+ async def download_media_message(
762
+ source: MessageDict | dict[str, Any],
763
+ options: WaDownloadMediaOptions | None = None,
764
+ transfer: WaClientMediaTransfer | None = None,
765
+ ) -> bytes:
766
+ """Download and decrypt message media (mirrors ``downloadMediaMessage``).
767
+
768
+ Returns the decrypted bytes; ``options.transfer`` (or ``transfer``)
769
+ supplies the transfer leg.
770
+ """
771
+ opts = options or WaDownloadMediaOptions()
772
+ if isinstance(source, dict):
773
+ message: MessageDict | None = source
774
+ else:
775
+ message = getattr(source, "message", None)
776
+ payload = resolve_media_payload(message)
777
+ if payload is None:
778
+ raise ValueError("message has no downloadable media")
779
+ active = transfer or opts.transfer
780
+ if active is None:
781
+ raise ValueError("download_media_message requires a transfer client")
782
+ return await active.download_and_decrypt(
783
+ direct_path=payload.direct_path,
784
+ media_type=str(payload.media_type),
785
+ media_key=bytes(payload.media_key),
786
+ file_sha256=payload.file_sha256,
787
+ file_enc_sha256=payload.file_enc_sha256,
788
+ timeout_ms=opts.timeout_ms,
789
+ max_bytes=opts.max_bytes,
790
+ )
791
+
792
+
793
+ __all__: list[str] = [
794
+ "IMAGE_THUMB_MAX_EDGE",
795
+ "MEDIA_UPLOAD_ID_MAX",
796
+ "STICKER_THUMB_MAX_EDGE",
797
+ "VIDEO_THUMB_MAX_EDGE",
798
+ "ProcessedMediaFields",
799
+ "StreamFileMetrics",
800
+ "WaClientMediaTransfer",
801
+ "WaDownloadMediaOptions",
802
+ "WaMediaOptions",
803
+ "WaMediaProcessor",
804
+ "WaMediaProcessorCallContext",
805
+ "WaUploadMediaSource",
806
+ "WebpAnimInfo",
807
+ "assert_media_upload_status",
808
+ "assert_readable_file",
809
+ "build_media_upload_url",
810
+ "cleanup_temp_file",
811
+ "download_media_message",
812
+ "get_scoped_media_logger",
813
+ "has_media_processing_tasks",
814
+ "is_readable_stream",
815
+ "parse_media_upload_json_body",
816
+ "parse_webp_animation",
817
+ "perform_plaintext_media_upload",
818
+ "read_file_head",
819
+ "resolve_media_inputs",
820
+ "run_media_processor",
821
+ "select_media_upload_host",
822
+ "should_generate_sticker_thumbnail",
823
+ "should_generate_thumbnail",
824
+ "should_generate_waveform",
825
+ "should_normalize_voice_note",
826
+ "should_probe_media",
827
+ "stream_to_temp_file",
828
+ "stream_to_temp_file_with_sha256",
829
+ ]