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,1429 @@
1
+ """Outgoing message builders (mirrors ``src/client/messaging/messages.ts``).
2
+
3
+ Media sends (image/video/ptv/audio/document/sticker/sticker-pack) encrypt
4
+ through :mod:`zapy._media` and the processor/upload helpers in
5
+ :mod:`zapy._client.media` (imported lazily: that module pulls the client
6
+ package, which in turn imports this one).
7
+
8
+ TEMPORARY (sibling layers not yet ported): :func:`create_use_case_secret`,
9
+ :func:`build_addon_additional_data` and
10
+ ``WA_USE_CASE_SECRET_MODIFICATION_TYPES`` are verbatim ports of
11
+ ``src/message/crypto/use-case-secret.ts`` / ``addon-crypto.ts``;
12
+ :func:`build_extended_text_with_preview` is a verbatim implementation of
13
+ ``src/message/addons/link-preview/builder.ts``. They move to
14
+ ``zapy._message.crypto`` / ``zapy._message.addons`` once those land.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import asyncio
20
+ import time
21
+ from collections.abc import Awaitable, Callable, Mapping
22
+ from dataclasses import dataclass, field
23
+ from typing import Any, BinaryIO
24
+
25
+ from zapy._crypto.core.hkdf import hkdf
26
+ from zapy._crypto.core.primitives import aes_gcm_encrypt, sha256
27
+ from zapy._crypto.core.random import random_bytes
28
+ from zapy._infra.log import Logger
29
+ from zapy._media.constants import MEDIA_CONN_CACHE_GRACE_MS, MEDIA_UPLOAD_PATHS
30
+ from zapy._media.crypto.crypto import WaMediaCrypto
31
+ from zapy._media.sticker.pack import (
32
+ StickerPackZipEntry as MediaStickerPackZipEntry,
33
+ )
34
+ from zapy._media.sticker.pack import (
35
+ create_sticker_pack_zip_stream,
36
+ )
37
+ from zapy._media.transfer.conn import parse_media_conn_response
38
+ from zapy._message.encode.content import (
39
+ MessageDict,
40
+ is_send_event_message,
41
+ is_send_event_response_message,
42
+ is_send_keep_message,
43
+ is_send_media_message,
44
+ is_send_pin_message,
45
+ is_send_poll_message,
46
+ is_send_poll_vote_message,
47
+ is_send_reaction_message,
48
+ is_send_revoke_message,
49
+ is_send_text_message,
50
+ is_send_typed_message,
51
+ resolve_message_target,
52
+ )
53
+ from zapy._message.kinds.sticker_pack import (
54
+ to_sticker_pack_proto_stickers,
55
+ to_sticker_pack_zip_entries,
56
+ validate_sticker_pack_input,
57
+ )
58
+ from zapy._message.messaging import (
59
+ ServerClock,
60
+ is_broadcast_jid,
61
+ is_group_jid,
62
+ to_user_jid,
63
+ )
64
+ from zapy._message.messaging.link_preview import ResolvedLinkPreviewResult
65
+ from zapy._message.types import (
66
+ WaMessageUploadInfo,
67
+ WaSendStickerPackMessage,
68
+ WaSendStickerPackStickerInput,
69
+ WaSendStickerPackTrayIcon,
70
+ )
71
+ from zapy._proto import WAProto_pb2
72
+ from zapy._protocol.defaults import IQ_TIMEOUT_MS
73
+ from zapy._transport.node.builders.media import build_media_conn_iq
74
+ from zapy._transport.types import BinaryNode
75
+ from zapy._util.bytes import bytes_to_base64
76
+ from zapy._util.primitives import to_error
77
+
78
+
79
+ def _client_media() -> Any:
80
+ """Lazily load :mod:`zapy._client.media` (breaks the client import cycle)."""
81
+ from zapy._client import media as client_media
82
+
83
+ return client_media
84
+
85
+
86
+ # Verbatim ``src/message/crypto/use-case-secret.ts``.
87
+ WA_MESSAGE_SECRET_BYTES: int = 32
88
+
89
+ # Verbatim ``src/message/crypto/use-case-secret.ts``.
90
+ WA_USE_CASE_SECRET_MODIFICATION_TYPES: dict[str, str] = {
91
+ "POLL_VOTE": "Poll Vote",
92
+ "ENC_REACTION": "Enc Reaction",
93
+ "ENC_COMMENT": "Enc Comment",
94
+ "REPORT_TOKEN": "Report Token",
95
+ "EVENT_RESPONSE": "Event Response",
96
+ "EVENT_EDIT_ENCRYPTED": "Event Edit",
97
+ "MESSAGE_EDIT": "Message Edit",
98
+ "POLL_EDIT_ENCRYPTED": "Poll Edit",
99
+ "POLL_ADD_OPTION": "Poll Add Option",
100
+ }
101
+
102
+ # wa-web default pin expiry preset (24h); receivers drop pins without one.
103
+ WA_PIN_DEFAULT_DURATION_SECS: int = 86_400
104
+
105
+
106
+ def assert_message_secret(
107
+ message_secret: bytes | bytearray, context: str = "message secret"
108
+ ) -> bytes:
109
+ """Validate a 32-byte message secret, mirroring ``assertMessageSecret``."""
110
+ secret = bytes(message_secret)
111
+ if len(secret) != WA_MESSAGE_SECRET_BYTES:
112
+ raise ValueError(
113
+ f"{context} must be {WA_MESSAGE_SECRET_BYTES} bytes (got {len(secret)})"
114
+ )
115
+ return secret
116
+
117
+
118
+ def create_use_case_secret(
119
+ *,
120
+ message_secret: bytes | bytearray,
121
+ stanza_id: str,
122
+ parent_msg_original_sender: str,
123
+ modification_sender: str,
124
+ modification_type: str,
125
+ ) -> bytes:
126
+ """Derive a per-use-case secret (poll vote, reaction, edit, ...) via HKDF."""
127
+ if not stanza_id.strip():
128
+ raise ValueError("stanza id must be a non-empty string")
129
+ if not parent_msg_original_sender.strip():
130
+ raise ValueError("parent message original sender must be a non-empty string")
131
+ if not modification_sender.strip():
132
+ raise ValueError("modification sender must be a non-empty string")
133
+ secret_info = (
134
+ stanza_id + parent_msg_original_sender + modification_sender + modification_type
135
+ ).encode("utf-8")
136
+ return hkdf(
137
+ assert_message_secret(message_secret),
138
+ None,
139
+ secret_info,
140
+ WA_MESSAGE_SECRET_BYTES,
141
+ )
142
+
143
+
144
+ def should_use_addon_additional_data(modification_type: str) -> bool:
145
+ """Whether an addon kind binds ``additionalData`` (vote and event-response)."""
146
+ return modification_type in (
147
+ WA_USE_CASE_SECRET_MODIFICATION_TYPES["POLL_VOTE"],
148
+ WA_USE_CASE_SECRET_MODIFICATION_TYPES["EVENT_RESPONSE"],
149
+ )
150
+
151
+
152
+ def build_addon_additional_data(stanza_id: str, add_on_sender_jid: str) -> bytes:
153
+ """Build canonical AES-GCM ``additionalData`` (stanza id + NUL + sender)."""
154
+ if not stanza_id.strip():
155
+ raise ValueError("stanza id must be a non-empty string")
156
+ if not add_on_sender_jid.strip():
157
+ raise ValueError("addon sender jid must be a non-empty string")
158
+ return f"{stanza_id}\x00{add_on_sender_jid}".encode("utf-8")
159
+
160
+
161
+ def build_extended_text_with_preview(
162
+ text: str,
163
+ resolved: Mapping[str, Any],
164
+ thumbnail_fields: Mapping[str, Any],
165
+ ) -> MessageDict:
166
+ """Merge fetched preview fields into an ``extendedTextMessage`` (verbatim)."""
167
+ extended: dict[str, Any] = {
168
+ "text": text,
169
+ "matchedText": resolved.get("matchedText"),
170
+ "previewType": resolved.get("previewType"),
171
+ }
172
+ if resolved.get("title") is not None:
173
+ extended["title"] = resolved.get("title")
174
+ if resolved.get("description") is not None:
175
+ extended["description"] = resolved.get("description")
176
+ for key in (
177
+ "jpegThumbnail",
178
+ "thumbnailDirectPath",
179
+ "thumbnailSha256",
180
+ "thumbnailEncSha256",
181
+ "mediaKey",
182
+ "mediaKeyTimestamp",
183
+ "thumbnailWidth",
184
+ "thumbnailHeight",
185
+ ):
186
+ if thumbnail_fields.get(key) is not None:
187
+ extended[key] = thumbnail_fields.get(key)
188
+ return {"extendedTextMessage": extended}
189
+
190
+
191
+ @dataclass(frozen=True, slots=True)
192
+ class WaBuildMessageContext:
193
+ """Recipient plus the addon-crypto send context for one message build."""
194
+
195
+ to: str = ""
196
+ outgoing_stanza_id: str | None = None
197
+ me_jid: str | None = None
198
+
199
+
200
+ @dataclass(frozen=True, slots=True)
201
+ class WaMessageBuildResult:
202
+ """Built proto message plus the media-upload receipt, when applicable."""
203
+
204
+ message: MessageDict = field(default_factory=dict)
205
+ upload: WaMessageUploadInfo | MessageDict | None = None
206
+
207
+
208
+ @dataclass(frozen=True, slots=True)
209
+ class WaMediaMessageOptions:
210
+ """Hooks the media send path needs (transfer/media-conn are ``Any``)."""
211
+
212
+ logger: Logger
213
+ media_transfer: Any = None
214
+ iq_timeout_ms: float | None = None
215
+ query_with_context: Callable[..., Awaitable[BinaryNode]] | None = None
216
+ get_media_conn_cache: Callable[[], Any] | None = None
217
+ set_media_conn_cache: Callable[[Any], None] | None = None
218
+ server_clock: ServerClock | None = None
219
+ media: Any = None
220
+ link_preview_resolver: (
221
+ Callable[[MessageDict], Awaitable[ResolvedLinkPreviewResult | None]] | None
222
+ ) = None
223
+
224
+
225
+ _CTX_FIELD_DISPLAY_NAMES: dict[str, str] = {
226
+ "outgoing_stanza_id": "outgoingStanzaId",
227
+ "me_jid": "meJid",
228
+ }
229
+
230
+
231
+ def _require_ctx_field(ctx: WaBuildMessageContext | None, attr: str, kind: str) -> str:
232
+ value = getattr(ctx, attr, None) if ctx is not None else None
233
+ if not isinstance(value, str) or len(value) == 0:
234
+ display = _CTX_FIELD_DISPLAY_NAMES.get(attr, attr)
235
+ raise ValueError(f"{kind} message requires {display} in build context")
236
+ return value
237
+
238
+
239
+ def _build_message_key(
240
+ remote_jid: str, from_me: bool, id: str, participant: str | None = None
241
+ ) -> MessageDict:
242
+ key: MessageDict = {"remoteJid": remote_jid, "fromMe": from_me, "id": id}
243
+ if participant is not None:
244
+ key["participant"] = participant
245
+ return key
246
+
247
+
248
+ def _target_message_key(remote_jid: str, key: MessageDict) -> MessageDict:
249
+ in_group = is_group_jid(remote_jid) or is_broadcast_jid(remote_jid)
250
+ return _build_message_key(
251
+ remote_jid,
252
+ bool(key.get("fromMe", False)),
253
+ str(key.get("id", "")),
254
+ key.get("participant") if in_group else None,
255
+ )
256
+
257
+
258
+ def _build_reaction_message(
259
+ content: MessageDict, server_clock: ServerClock, ctx: WaBuildMessageContext | None
260
+ ) -> MessageDict:
261
+ to = _require_ctx_field(ctx, "to", "reaction")
262
+ sender_ms = content.get("senderTimestampMs")
263
+ return {
264
+ "reactionMessage": {
265
+ "key": _target_message_key(to, resolve_message_target(content["target"])),
266
+ "text": content.get("emoji"),
267
+ "senderTimestampMs": int(sender_ms)
268
+ if sender_ms is not None
269
+ else server_clock.now_ms(),
270
+ }
271
+ }
272
+
273
+
274
+ def _build_revoke_message(
275
+ content: MessageDict, ctx: WaBuildMessageContext | None
276
+ ) -> MessageDict:
277
+ to = _require_ctx_field(ctx, "to", "revoke")
278
+ return {
279
+ "protocolMessage": {
280
+ "type": WAProto_pb2.Message.ProtocolMessage.Type.Value("REVOKE"),
281
+ "key": _target_message_key(to, resolve_message_target(content["target"])),
282
+ }
283
+ }
284
+
285
+
286
+ def _build_pin_message(
287
+ content: MessageDict, server_clock: ServerClock, ctx: WaBuildMessageContext | None
288
+ ) -> MessageDict:
289
+ to = _require_ctx_field(ctx, "to", str(content.get("type", "pin")))
290
+ is_pin = content.get("type") == "pin"
291
+ sender_ms = content.get("senderTimestampMs")
292
+ pin_type = WAProto_pb2.Message.PinInChatMessage.Type.Value(
293
+ "PIN_FOR_ALL" if is_pin else "UNPIN_FOR_ALL"
294
+ )
295
+ duration = content.get("durationSecs")
296
+ return {
297
+ "pinInChatMessage": {
298
+ "key": _target_message_key(to, resolve_message_target(content["target"])),
299
+ "type": pin_type,
300
+ "senderTimestampMs": int(sender_ms)
301
+ if sender_ms is not None
302
+ else server_clock.now_ms(),
303
+ },
304
+ "messageContextInfo": {
305
+ "messageAddOnDurationInSecs": int(duration)
306
+ if is_pin and duration is not None
307
+ else (WA_PIN_DEFAULT_DURATION_SECS if is_pin else 0)
308
+ },
309
+ }
310
+
311
+
312
+ def _build_keep_message(
313
+ content: MessageDict, server_clock: ServerClock, ctx: WaBuildMessageContext | None
314
+ ) -> MessageDict:
315
+ to = _require_ctx_field(ctx, "to", str(content.get("type", "keep")))
316
+ timestamp_ms = content.get("timestampMs")
317
+ keep_type = WAProto_pb2.KeepType.Value(
318
+ "KEEP_FOR_ALL" if content.get("type") == "keep" else "UNDO_KEEP_FOR_ALL"
319
+ )
320
+ return {
321
+ "keepInChatMessage": {
322
+ "key": _target_message_key(to, resolve_message_target(content["target"])),
323
+ "keepType": keep_type,
324
+ "timestampMs": int(timestamp_ms)
325
+ if timestamp_ms is not None
326
+ else server_clock.now_ms(),
327
+ }
328
+ }
329
+
330
+
331
+ def _build_poll_creation_message(content: MessageDict) -> MessageDict:
332
+ options = content.get("options", [])
333
+ if len(options) == 0:
334
+ raise ValueError("poll message requires at least one option")
335
+ proto_options = [
336
+ {"optionName": opt if isinstance(opt, str) else opt.get("name")}
337
+ for opt in options
338
+ ]
339
+ selectable_count = content.get("selectableCount", 1)
340
+ allow_add_option = content.get("allowAddOption") is True
341
+ hide_participant_name = content.get("hideParticipantName") is True
342
+ poll_body: MessageDict = {
343
+ "name": content.get("name"),
344
+ "options": proto_options,
345
+ "selectableOptionsCount": selectable_count,
346
+ }
347
+ if allow_add_option:
348
+ poll_body["allowAddOption"] = True
349
+ if hide_participant_name:
350
+ poll_body["hideParticipantName"] = True
351
+ if allow_add_option or hide_participant_name:
352
+ return {"pollCreationMessageV6": poll_body}
353
+ if selectable_count == 1:
354
+ return {"pollCreationMessageV3": poll_body}
355
+ return {"pollCreationMessage": poll_body}
356
+
357
+
358
+ def _build_event_message(content: MessageDict) -> MessageDict:
359
+ event_message: MessageDict = {
360
+ "name": content.get("name"),
361
+ "startTime": content.get("startTime"),
362
+ "isCanceled": content.get("isCanceled")
363
+ if content.get("isCanceled") is not None
364
+ else False,
365
+ }
366
+ if content.get("description") is not None:
367
+ event_message["description"] = content.get("description")
368
+ if content.get("endTime") is not None:
369
+ event_message["endTime"] = content.get("endTime")
370
+ if content.get("joinLink") is not None:
371
+ event_message["joinLink"] = content.get("joinLink")
372
+ if content.get("extraGuestsAllowed") is not None:
373
+ event_message["extraGuestsAllowed"] = content.get("extraGuestsAllowed")
374
+ if content.get("isScheduleCall") is not None:
375
+ event_message["isScheduleCall"] = content.get("isScheduleCall")
376
+ if content.get("hasReminder") is not None:
377
+ event_message["hasReminder"] = content.get("hasReminder")
378
+ if content.get("reminderOffsetSec") is not None:
379
+ event_message["reminderOffsetSec"] = content.get("reminderOffsetSec")
380
+ location = content.get("location")
381
+ if location is not None:
382
+ location_message: MessageDict = {
383
+ "degreesLatitude": location.get("latitude"),
384
+ "degreesLongitude": location.get("longitude"),
385
+ }
386
+ if location.get("name") is not None:
387
+ location_message["name"] = location.get("name")
388
+ if location.get("address") is not None:
389
+ location_message["address"] = location.get("address")
390
+ event_message["location"] = location_message
391
+ return {"eventMessage": event_message}
392
+
393
+
394
+ _EVENT_RESPONSE_ENUM: dict[str, int] = {
395
+ "going": WAProto_pb2.Message.EventResponseMessage.EventResponseType.Value("GOING"),
396
+ "not_going": WAProto_pb2.Message.EventResponseMessage.EventResponseType.Value(
397
+ "NOT_GOING"
398
+ ),
399
+ "maybe": WAProto_pb2.Message.EventResponseMessage.EventResponseType.Value("MAYBE"),
400
+ }
401
+
402
+
403
+ def _encrypt_addon_for_outgoing(
404
+ *,
405
+ message_secret: bytes,
406
+ parent_stanza_id: str,
407
+ parent_msg_original_sender: str,
408
+ modification_sender: str,
409
+ modification_type: str,
410
+ payload: bytes,
411
+ ) -> dict[str, bytes]:
412
+ secret = create_use_case_secret(
413
+ message_secret=message_secret,
414
+ stanza_id=parent_stanza_id,
415
+ parent_msg_original_sender=parent_msg_original_sender,
416
+ modification_sender=modification_sender,
417
+ modification_type=modification_type,
418
+ )
419
+ iv = random_bytes(12)
420
+ additional_data = (
421
+ build_addon_additional_data(parent_stanza_id, modification_sender)
422
+ if should_use_addon_additional_data(modification_type)
423
+ else None
424
+ )
425
+ enc_payload = aes_gcm_encrypt(
426
+ secret, iv, payload, additional_data if additional_data is not None else b""
427
+ )
428
+ return {"encPayload": enc_payload, "encIv": iv}
429
+
430
+
431
+ def _build_poll_vote_message(
432
+ content: MessageDict, server_clock: ServerClock, ctx: WaBuildMessageContext | None
433
+ ) -> MessageDict:
434
+ to = _require_ctx_field(ctx, "to", "poll-vote")
435
+ _require_ctx_field(ctx, "outgoing_stanza_id", "poll-vote")
436
+ me_jid = _require_ctx_field(ctx, "me_jid", "poll-vote")
437
+ poll = content.get("poll", {})
438
+ selected = content.get("selectedOptionNames", [])
439
+ if len(selected) == 0:
440
+ raise ValueError("poll-vote requires at least one selected option")
441
+ selected_options = [sha256(str(name).encode("utf-8")) for name in selected]
442
+ vote_proto = WAProto_pb2.Message.PollVoteMessage()
443
+ vote_proto.selectedOptions.extend(selected_options)
444
+ payload = vote_proto.SerializeToString()
445
+ encrypted = _encrypt_addon_for_outgoing(
446
+ message_secret=bytes(poll.get("messageSecret", b"")),
447
+ parent_stanza_id=str(poll.get("id", "")),
448
+ parent_msg_original_sender=to_user_jid(str(poll.get("authorJid", ""))),
449
+ modification_sender=to_user_jid(me_jid),
450
+ modification_type=WA_USE_CASE_SECRET_MODIFICATION_TYPES["POLL_VOTE"],
451
+ payload=payload,
452
+ )
453
+ sender_ms = content.get("senderTimestampMs")
454
+ return {
455
+ "pollUpdateMessage": {
456
+ "pollCreationMessageKey": _build_message_key(
457
+ to,
458
+ bool(poll.get("fromMe", False)),
459
+ str(poll.get("id", "")),
460
+ poll.get("participant"),
461
+ ),
462
+ "vote": {
463
+ "encPayload": encrypted["encPayload"],
464
+ "encIv": encrypted["encIv"],
465
+ },
466
+ "senderTimestampMs": int(sender_ms)
467
+ if sender_ms is not None
468
+ else server_clock.now_ms(),
469
+ }
470
+ }
471
+
472
+
473
+ def _build_event_response_message(
474
+ content: MessageDict, server_clock: ServerClock, ctx: WaBuildMessageContext | None
475
+ ) -> MessageDict:
476
+ to = _require_ctx_field(ctx, "to", "event-response")
477
+ _require_ctx_field(ctx, "outgoing_stanza_id", "event-response")
478
+ me_jid = _require_ctx_field(ctx, "me_jid", "event-response")
479
+ event = content.get("event", {})
480
+ response = content.get("response")
481
+ if response not in _EVENT_RESPONSE_ENUM:
482
+ raise ValueError(f"unknown event response: {response!r}")
483
+ response_proto = WAProto_pb2.Message.EventResponseMessage()
484
+ response_proto.response = _EVENT_RESPONSE_ENUM[response]
485
+ timestamp_ms = content.get("timestampMs")
486
+ response_proto.timestampMs = (
487
+ int(timestamp_ms) if timestamp_ms is not None else server_clock.now_ms()
488
+ )
489
+ if content.get("extraGuestCount") is not None:
490
+ response_proto.extraGuestCount = int(content["extraGuestCount"])
491
+ payload = response_proto.SerializeToString()
492
+ encrypted = _encrypt_addon_for_outgoing(
493
+ message_secret=bytes(event.get("messageSecret", b"")),
494
+ parent_stanza_id=str(event.get("id", "")),
495
+ parent_msg_original_sender=to_user_jid(str(event.get("authorJid", ""))),
496
+ modification_sender=to_user_jid(me_jid),
497
+ modification_type=WA_USE_CASE_SECRET_MODIFICATION_TYPES["EVENT_RESPONSE"],
498
+ payload=payload,
499
+ )
500
+ return {
501
+ "encEventResponseMessage": {
502
+ "eventCreationMessageKey": _build_message_key(
503
+ to,
504
+ bool(event.get("fromMe", False)),
505
+ str(event.get("id", "")),
506
+ event.get("participant"),
507
+ ),
508
+ "encPayload": encrypted["encPayload"],
509
+ "encIv": encrypted["encIv"],
510
+ }
511
+ }
512
+
513
+
514
+ def _with_message_context_info(
515
+ built: WaMessageBuildResult,
516
+ message_context_info: Mapping[str, Any] | None,
517
+ ) -> WaMessageBuildResult:
518
+ if not message_context_info:
519
+ return built
520
+ merged: dict[str, Any] = {
521
+ **dict(message_context_info),
522
+ **built.message.get("messageContextInfo", {}),
523
+ }
524
+ return WaMessageBuildResult(
525
+ message={**built.message, "messageContextInfo": merged},
526
+ upload=built.upload,
527
+ )
528
+
529
+
530
+ async def _build_text_message_content(
531
+ options: WaMediaMessageOptions, content: MessageDict
532
+ ) -> MessageDict:
533
+ resolver = options.link_preview_resolver
534
+ if resolver is not None:
535
+ try:
536
+ preview = await resolver(content)
537
+ if preview is not None:
538
+ resolved = preview.resolved
539
+ return build_extended_text_with_preview(
540
+ str(content.get("text", "")),
541
+ {
542
+ "matchedText": resolved.matched_text,
543
+ "title": resolved.title,
544
+ "description": resolved.description,
545
+ "previewType": resolved.preview_type,
546
+ },
547
+ preview.thumbnail_fields,
548
+ )
549
+ except Exception as error: # noqa: BLE001 - preview failure sends plain text
550
+ converted = to_error(error)
551
+ options.logger.warn(
552
+ "link preview resolver failed, sending plain text",
553
+ {"message": converted.args[0] if converted.args else str(converted)},
554
+ )
555
+ return {"extendedTextMessage": {"text": content.get("text")}}
556
+
557
+
558
+ async def build_media_message_content(
559
+ options: WaMediaMessageOptions,
560
+ content: str | MessageDict,
561
+ ctx: WaBuildMessageContext | None = None,
562
+ ) -> WaMessageBuildResult:
563
+ """Build the proto message for one outgoing send (media raises ``NI``)."""
564
+ if isinstance(content, str):
565
+ return WaMessageBuildResult(message={"conversation": content})
566
+ if is_send_typed_message(content):
567
+ if options.server_clock is None:
568
+ raise ValueError("message build requires a server clock")
569
+ server_clock = options.server_clock
570
+ if is_send_text_message(content):
571
+ built_text = await _build_text_message_content(options, content)
572
+ return _with_message_context_info(
573
+ WaMessageBuildResult(message=built_text),
574
+ content.get("messageContextInfo"),
575
+ )
576
+ if is_send_reaction_message(content):
577
+ built = _build_reaction_message(content, server_clock, ctx)
578
+ elif is_send_revoke_message(content):
579
+ built = _build_revoke_message(content, ctx)
580
+ elif is_send_pin_message(content):
581
+ built = _build_pin_message(content, server_clock, ctx)
582
+ elif is_send_keep_message(content):
583
+ built = _build_keep_message(content, server_clock, ctx)
584
+ elif is_send_poll_message(content):
585
+ built = _build_poll_creation_message(content)
586
+ elif is_send_event_message(content):
587
+ built = _build_event_message(content)
588
+ elif is_send_poll_vote_message(content):
589
+ built = _build_poll_vote_message(content, server_clock, ctx)
590
+ elif is_send_event_response_message(content):
591
+ built = _build_event_response_message(content, server_clock, ctx)
592
+ elif is_send_media_message(content):
593
+ built_media = await _build_media_message(options, content, ctx)
594
+ return _with_message_context_info(
595
+ built_media,
596
+ content.get("messageContextInfo", content.get("message_context_info")),
597
+ )
598
+ else: # pragma: no cover - `is_send_typed_message` covers every kind
599
+ raise ValueError("invalid message content")
600
+ return _with_message_context_info(
601
+ WaMessageBuildResult(message=built), content.get("messageContextInfo")
602
+ )
603
+ if not isinstance(content, dict):
604
+ raise ValueError("invalid message content")
605
+ return WaMessageBuildResult(message=content)
606
+
607
+
608
+ _VOICE_NOTE_MIMETYPE: str = "audio/ogg; codecs=opus"
609
+
610
+ # Upload types that carry a streaming sidecar (mirrors ``needsSidecar``).
611
+ _SIDECAR_UPLOAD_TYPES: frozenset[str] = frozenset({"video", "ptv", "audio"})
612
+
613
+
614
+ @dataclass(frozen=True, slots=True)
615
+ class UploadResult:
616
+ """CDN location, media key, hashes, and optional sidecars (mirrors TS)."""
617
+
618
+ url: str = ""
619
+ direct_path: str = ""
620
+ media_key: bytes = b""
621
+ file_sha256: bytes = b""
622
+ file_enc_sha256: bytes = b""
623
+ file_length: int = 0
624
+ metadata_url: str | None = None
625
+ streaming_sidecar: bytes | None = None
626
+ first_frame_sidecar: bytes | None = None
627
+ first_frame_length: int | None = None
628
+
629
+
630
+ def _media_field(content: MessageDict, camel: str, snake: str) -> Any:
631
+ """Read a send-content field in either the wire (camelCase) or typed shape."""
632
+ value = content.get(camel)
633
+ if value is not None:
634
+ return value
635
+ return content.get(snake)
636
+
637
+
638
+ def _read_input(media_input: Any, name: str, default: Any = None) -> Any:
639
+ if isinstance(media_input, Mapping):
640
+ return media_input.get(name, default)
641
+ return getattr(media_input, name, default)
642
+
643
+
644
+ def _now_ms(options: WaMediaMessageOptions) -> int:
645
+ clock = options.server_clock
646
+ if clock is not None:
647
+ now = clock.now_ms()
648
+ if isinstance(now, (int, float)):
649
+ return int(now)
650
+ return int(time.time() * 1_000)
651
+
652
+
653
+ def _now_seconds(options: WaMediaMessageOptions) -> int:
654
+ clock = options.server_clock
655
+ if clock is not None:
656
+ now = clock.now_seconds()
657
+ if isinstance(now, (int, float)):
658
+ return int(now)
659
+ return int(time.time())
660
+
661
+
662
+ def _conn_expiry(media_conn: Any) -> int | None:
663
+ if isinstance(media_conn, Mapping):
664
+ expiry = media_conn.get("expiresAtMs", media_conn.get("expires_at_ms"))
665
+ else:
666
+ expiry = getattr(media_conn, "expires_at_ms", None)
667
+ if expiry is None:
668
+ expiry = getattr(media_conn, "expiresAtMs", None)
669
+ return int(expiry) if isinstance(expiry, (int, float)) else None
670
+
671
+
672
+ def _conn_auth(media_conn: Any) -> str:
673
+ if isinstance(media_conn, Mapping):
674
+ auth = media_conn.get("auth", "")
675
+ else:
676
+ auth = getattr(media_conn, "auth", "")
677
+ return str(auth) if isinstance(auth, str) else ""
678
+
679
+
680
+ async def get_media_conn(
681
+ options: WaMediaMessageOptions, force_refresh: bool = False
682
+ ) -> Any:
683
+ """Fetch (and cache) the media connection (mirrors ``getMediaConn``)."""
684
+ getter = options.get_media_conn_cache
685
+ cached = getter() if getter is not None else None
686
+ if not force_refresh and cached is not None:
687
+ expiry = _conn_expiry(cached)
688
+ if expiry is not None and _now_ms(options) + MEDIA_CONN_CACHE_GRACE_MS < expiry:
689
+ return cached
690
+
691
+ query = options.query_with_context
692
+ if query is None:
693
+ raise ValueError("media conn fetch requires a query context")
694
+ timeout = options.iq_timeout_ms
695
+ response = await query(
696
+ "media_conn.fetch",
697
+ build_media_conn_iq(),
698
+ timeout if timeout is not None else IQ_TIMEOUT_MS,
699
+ )
700
+ media_conn = parse_media_conn_response(response, _now_ms(options))
701
+ setter = options.set_media_conn_cache
702
+ if setter is not None:
703
+ setter(media_conn)
704
+ return media_conn
705
+
706
+
707
+ def _resolve_upload_path(upload_type: str) -> str:
708
+ upload_path = MEDIA_UPLOAD_PATHS.get(upload_type)
709
+ if not upload_path:
710
+ raise ValueError(f"unknown media upload type: {upload_type}")
711
+ return upload_path
712
+
713
+
714
+ def _parse_upload_response(body: bytes, status: int) -> dict[str, Any]:
715
+ client_media = _client_media()
716
+ client_media.assert_media_upload_status(status, "media upload")
717
+ parsed = client_media.parse_media_upload_json_body(body, "media upload")
718
+ if (
719
+ not isinstance(parsed, Mapping)
720
+ or not parsed.get("url")
721
+ or not parsed.get("direct_path")
722
+ ):
723
+ raise ValueError("media upload response missing url/direct_path")
724
+ result: dict[str, Any] = {
725
+ "url": parsed["url"],
726
+ "directPath": parsed["direct_path"],
727
+ }
728
+ if parsed.get("metadata_url"):
729
+ result["metadataUrl"] = parsed["metadata_url"]
730
+ return result
731
+
732
+
733
+ async def _upload_media_bytes(
734
+ options: WaMediaMessageOptions,
735
+ media_key: bytes,
736
+ media_bytes: bytes,
737
+ crypto_type: str,
738
+ upload_path: str,
739
+ content_type: str | None,
740
+ sidecar: bool,
741
+ first_frame_length: int | None,
742
+ timeout_ms: float | None,
743
+ signal: Any,
744
+ log_label: str | None,
745
+ ) -> UploadResult:
746
+ encrypted, media_conn = await asyncio.gather(
747
+ asyncio.to_thread(
748
+ WaMediaCrypto.encrypt_bytes,
749
+ crypto_type,
750
+ media_key,
751
+ media_bytes,
752
+ sidecar,
753
+ first_frame_length,
754
+ ),
755
+ get_media_conn(options),
756
+ )
757
+ client_media = _client_media()
758
+ host = client_media.select_media_upload_host(media_conn)
759
+ upload_url = client_media.build_media_upload_url(
760
+ host, upload_path, _conn_auth(media_conn), encrypted.file_enc_sha256
761
+ )
762
+ options.logger.debug(
763
+ log_label or "sending media upload request",
764
+ {"cryptoType": crypto_type, "host": host, "size": len(media_bytes)},
765
+ )
766
+ transfer = options.media_transfer
767
+ if transfer is None:
768
+ raise ValueError("media upload requires media_transfer")
769
+ upload_response = await transfer.upload_stream(
770
+ url=upload_url,
771
+ method="POST",
772
+ body=encrypted.ciphertext_hmac,
773
+ content_length=len(encrypted.ciphertext_hmac),
774
+ content_type=content_type,
775
+ timeout_ms=timeout_ms,
776
+ signal=signal,
777
+ )
778
+ response_body = await transfer.read_response_bytes(upload_response)
779
+ parsed = _parse_upload_response(bytes(response_body), int(upload_response.status))
780
+ return UploadResult(
781
+ url=str(parsed["url"]),
782
+ direct_path=str(parsed["directPath"]),
783
+ media_key=media_key,
784
+ file_sha256=bytes(encrypted.file_sha256),
785
+ file_enc_sha256=bytes(encrypted.file_enc_sha256),
786
+ file_length=len(media_bytes),
787
+ metadata_url=parsed.get("metadataUrl"),
788
+ streaming_sidecar=encrypted.streaming_sidecar,
789
+ first_frame_sidecar=encrypted.first_frame_sidecar,
790
+ first_frame_length=first_frame_length,
791
+ )
792
+
793
+
794
+ async def _upload_media_stream(
795
+ options: WaMediaMessageOptions,
796
+ media_key: bytes,
797
+ plaintext: BinaryIO,
798
+ crypto_type: str,
799
+ upload_path: str,
800
+ content_type: str | None,
801
+ sidecar: bool,
802
+ first_frame_length: int | None,
803
+ timeout_ms: float | None,
804
+ signal: Any,
805
+ log_label: str | None,
806
+ ) -> UploadResult:
807
+ encrypted = await WaMediaCrypto.encrypt_to_file(
808
+ crypto_type,
809
+ media_key,
810
+ plaintext,
811
+ sidecar=sidecar,
812
+ first_frame_length=first_frame_length,
813
+ )
814
+ read_handle: BinaryIO | None = None
815
+ try:
816
+ media_conn = await get_media_conn(options)
817
+ client_media = _client_media()
818
+ host = client_media.select_media_upload_host(media_conn)
819
+ upload_url = client_media.build_media_upload_url(
820
+ host, upload_path, _conn_auth(media_conn), encrypted.file_enc_sha256
821
+ )
822
+ options.logger.debug(
823
+ log_label or "sending media stream upload request",
824
+ {
825
+ "cryptoType": crypto_type,
826
+ "host": host,
827
+ "plaintextLength": encrypted.plaintext_length,
828
+ "encryptedSize": encrypted.file_size,
829
+ },
830
+ )
831
+ transfer = options.media_transfer
832
+ if transfer is None:
833
+ raise ValueError("media upload requires media_transfer")
834
+
835
+ def _open() -> BinaryIO:
836
+ return open(encrypted.file_path, "rb")
837
+
838
+ read_handle = await asyncio.to_thread(_open)
839
+ upload_response = await transfer.upload_stream(
840
+ url=upload_url,
841
+ method="POST",
842
+ body=read_handle,
843
+ content_length=encrypted.file_size,
844
+ content_type=content_type,
845
+ timeout_ms=timeout_ms,
846
+ signal=signal,
847
+ )
848
+ response_body = await transfer.read_response_bytes(upload_response)
849
+ parsed = _parse_upload_response(
850
+ bytes(response_body), int(upload_response.status)
851
+ )
852
+ return UploadResult(
853
+ url=str(parsed["url"]),
854
+ direct_path=str(parsed["directPath"]),
855
+ media_key=media_key,
856
+ file_sha256=bytes(encrypted.file_sha256),
857
+ file_enc_sha256=bytes(encrypted.file_enc_sha256),
858
+ file_length=encrypted.plaintext_length,
859
+ metadata_url=parsed.get("metadataUrl"),
860
+ streaming_sidecar=encrypted.streaming_sidecar,
861
+ first_frame_sidecar=encrypted.first_frame_sidecar,
862
+ first_frame_length=first_frame_length,
863
+ )
864
+ finally:
865
+ if read_handle is not None:
866
+ await asyncio.to_thread(read_handle.close)
867
+ await WaMediaCrypto.cleanup_encrypted_file(encrypted.file_path)
868
+
869
+
870
+ async def upload_media(
871
+ options: WaMediaMessageOptions, media_input: Any
872
+ ) -> UploadResult:
873
+ """Encrypt and upload a media payload (mirrors ``uploadMedia``).
874
+
875
+ ``media_input`` is the coordinator ``WaMediaUploadInput`` (or its dict
876
+ shape): ``source`` bytes/stream, resolved ``crypto_type``/``upload_path``,
877
+ and the sidecar/first-frame decisions already made.
878
+ """
879
+ source = _read_input(media_input, "source")
880
+ crypto_type = str(_read_input(media_input, "crypto_type", "") or "")
881
+ upload_path = str(_read_input(media_input, "upload_path", "") or "")
882
+ content_type = _read_input(media_input, "content_type")
883
+ media_key = _read_input(media_input, "media_key")
884
+ key = (
885
+ bytes(media_key)
886
+ if media_key is not None
887
+ else WaMediaCrypto.generate_media_key()
888
+ )
889
+ sidecar = _read_input(media_input, "sidecar")
890
+ if sidecar is None:
891
+ sidecar = crypto_type in _SIDECAR_UPLOAD_TYPES
892
+ first_frame_length = _read_input(media_input, "first_frame_length")
893
+ timeout_ms = _read_input(media_input, "timeout_ms")
894
+ signal = _read_input(media_input, "signal")
895
+ log_label = _read_input(media_input, "log_label")
896
+ if not upload_path:
897
+ raise ValueError(f"unknown media upload type: {crypto_type}")
898
+
899
+ if isinstance(source, (bytes, bytearray)):
900
+ return await _upload_media_bytes(
901
+ options,
902
+ key,
903
+ bytes(source),
904
+ crypto_type,
905
+ upload_path,
906
+ content_type,
907
+ bool(sidecar),
908
+ first_frame_length,
909
+ timeout_ms,
910
+ signal,
911
+ log_label,
912
+ )
913
+ if isinstance(source, str):
914
+ client_media = _client_media()
915
+ await client_media.assert_readable_file(source)
916
+ handle = open(source, "rb")
917
+ try:
918
+ return await _upload_media_stream(
919
+ options,
920
+ key,
921
+ handle,
922
+ crypto_type,
923
+ upload_path,
924
+ content_type,
925
+ bool(sidecar),
926
+ first_frame_length,
927
+ timeout_ms,
928
+ signal,
929
+ log_label,
930
+ )
931
+ finally:
932
+ await asyncio.to_thread(handle.close)
933
+ if callable(getattr(source, "read", None)):
934
+ return await _upload_media_stream(
935
+ options,
936
+ key,
937
+ source,
938
+ crypto_type,
939
+ upload_path,
940
+ content_type,
941
+ bool(sidecar),
942
+ first_frame_length,
943
+ timeout_ms,
944
+ signal,
945
+ log_label,
946
+ )
947
+ raise ValueError("media upload received unsupported source type")
948
+
949
+
950
+ def _resolve_upload_type(content: MessageDict) -> str:
951
+ content_type = str(content.get("type", ""))
952
+ if content_type == "video" and _media_field(content, "gifPlayback", "gif_playback"):
953
+ return "gif"
954
+ if content_type == "audio" and _media_field(content, "ptt", "ptt"):
955
+ return "ptt"
956
+ return content_type
957
+
958
+
959
+ def _spread(content: MessageDict) -> dict[str, Any]:
960
+ """Copy user fields except the send-envelope keys (mirrors ``spread``)."""
961
+ excluded = {
962
+ "type",
963
+ "media",
964
+ "fileLength",
965
+ "file_length",
966
+ "mimetype",
967
+ "messageContextInfo",
968
+ "message_context_info",
969
+ }
970
+ return {key: content[key] for key in content if key not in excluded}
971
+
972
+
973
+ def _upload_summary(uploaded: UploadResult) -> WaMessageUploadInfo:
974
+ return WaMessageUploadInfo(
975
+ url=uploaded.url,
976
+ direct_path=uploaded.direct_path,
977
+ file_sha256=bytes(uploaded.file_sha256),
978
+ file_length=uploaded.file_length,
979
+ metadata_url=uploaded.metadata_url,
980
+ )
981
+
982
+
983
+ async def _build_media_message(
984
+ options: WaMediaMessageOptions, content: MessageDict, ctx: Any
985
+ ) -> WaMessageBuildResult:
986
+ """Build one media message: probe, encrypt, upload (mirrors TS)."""
987
+ if content.get("type") == "sticker-pack":
988
+ return await _build_sticker_pack_media_message(options, content)
989
+ client_media = _client_media()
990
+ work = dict(content)
991
+ processor_ctx = {"logger": client_media.get_scoped_media_logger(options.logger)}
992
+
993
+ if client_media.should_normalize_voice_note(options.media, _proc_view(work)):
994
+ normalizer = getattr(options.media.processor, "normalize_voice_note", None)
995
+ if callable(normalizer):
996
+ try:
997
+ normalized = await normalizer(work.get("media"), processor_ctx)
998
+ if normalized is not None:
999
+ work = {
1000
+ **work,
1001
+ "media": normalized,
1002
+ "mimetype": _VOICE_NOTE_MIMETYPE,
1003
+ }
1004
+ except Exception as error:
1005
+ options.logger.warn(
1006
+ "voice note normalize failed, sending original media",
1007
+ {"message": str(to_error(error))},
1008
+ )
1009
+
1010
+ media_value = work.get("media")
1011
+ needs_mimetype_detection = (
1012
+ not _media_field(work, "mimetype", "mimetype")
1013
+ and work.get("type") != "sticker"
1014
+ and getattr(getattr(options.media, "processor", None), "detect_mimetype", None)
1015
+ is not None
1016
+ and client_media.is_readable_stream(media_value)
1017
+ )
1018
+ needs_temp_file = (
1019
+ client_media.has_media_processing_tasks(options.media, _proc_view(work))
1020
+ or (
1021
+ work.get("type") == "sticker"
1022
+ and work.get("firstFrameLength") is None
1023
+ and work.get("first_frame_length") is None
1024
+ )
1025
+ or needs_mimetype_detection
1026
+ )
1027
+ if media_value is None:
1028
+ raise ValueError("media message requires media bytes, a path, or a stream")
1029
+ resolved = await client_media.resolve_media_inputs(needs_temp_file, media_value)
1030
+ mimetype = await _resolve_mimetype_with_detector(
1031
+ options, work, resolved.get("processor_input"), processor_ctx
1032
+ )
1033
+
1034
+ close_upload_handle = resolved.get("temp_file_path") is not None or isinstance(
1035
+ media_value, str
1036
+ )
1037
+ try:
1038
+ first_frame_length: int | None = None
1039
+ if work.get("type") == "sticker":
1040
+ explicit = _media_field(work, "firstFrameLength", "first_frame_length")
1041
+ detected: int | None = None
1042
+ processor_input = resolved.get("processor_input")
1043
+ if explicit is None and processor_input is not None:
1044
+ header = (
1045
+ await client_media.read_file_head(processor_input, 100)
1046
+ if isinstance(processor_input, str)
1047
+ else bytes(processor_input)[:100]
1048
+ )
1049
+ anim = client_media.parse_webp_animation(header)
1050
+ if anim is not None:
1051
+ detected = anim.first_frame_length
1052
+ first_frame_length = explicit if explicit is not None else detected
1053
+
1054
+ upload_type = _resolve_upload_type(work)
1055
+ upload_input = {
1056
+ "source": resolved["upload_media"],
1057
+ "crypto_type": upload_type,
1058
+ "upload_path": _resolve_upload_path(upload_type),
1059
+ "content_type": mimetype,
1060
+ "sidecar": work.get("type") in ("video", "ptv", "audio"),
1061
+ "first_frame_length": first_frame_length
1062
+ if work.get("type") == "sticker"
1063
+ else None,
1064
+ "log_label": None,
1065
+ "timeout_ms": None,
1066
+ "signal": None,
1067
+ "media_key": None,
1068
+ }
1069
+ upload_task: Awaitable[UploadResult] = upload_media(options, upload_input)
1070
+ process_task: Awaitable[Any] = client_media.run_media_processor(
1071
+ options.media,
1072
+ resolved.get("processor_input"),
1073
+ _proc_view(work),
1074
+ options.logger,
1075
+ )
1076
+ settled: tuple[Any, Any] = await asyncio.gather(
1077
+ upload_task, process_task, return_exceptions=True
1078
+ )
1079
+ if isinstance(settled[0], BaseException):
1080
+ raise settled[0]
1081
+ if isinstance(settled[1], BaseException):
1082
+ raise settled[1]
1083
+ uploaded: UploadResult = settled[0]
1084
+ processed: Any = settled[1]
1085
+ media_key_timestamp = _now_seconds(options)
1086
+ common: dict[str, Any] = {
1087
+ "url": uploaded.url,
1088
+ "fileSha256": bytes(uploaded.file_sha256),
1089
+ "fileLength": uploaded.file_length,
1090
+ "mediaKey": bytes(uploaded.media_key),
1091
+ "fileEncSha256": bytes(uploaded.file_enc_sha256),
1092
+ "directPath": uploaded.direct_path,
1093
+ "mediaKeyTimestamp": media_key_timestamp,
1094
+ "mimetype": mimetype,
1095
+ }
1096
+ content_type = str(work.get("type", ""))
1097
+ if content_type == "image":
1098
+ inner = {
1099
+ **_spread(work),
1100
+ **common,
1101
+ "width": _media_field(work, "width", "width")
1102
+ if _media_field(work, "width", "width") is not None
1103
+ else processed.jpeg_thumbnail and processed.width,
1104
+ "height": _media_field(work, "height", "height")
1105
+ if _media_field(work, "height", "height") is not None
1106
+ else processed.jpeg_thumbnail and processed.height,
1107
+ "jpegThumbnail": _media_field(work, "jpegThumbnail", "jpeg_thumbnail")
1108
+ if _media_field(work, "jpegThumbnail", "jpeg_thumbnail") is not None
1109
+ else processed.jpeg_thumbnail,
1110
+ }
1111
+ return WaMessageBuildResult(
1112
+ message={"imageMessage": inner}, upload=_upload_summary(uploaded)
1113
+ )
1114
+ if content_type in ("video", "ptv"):
1115
+ key = "videoMessage" if content_type == "video" else "ptvMessage"
1116
+ inner = {
1117
+ **_spread(work),
1118
+ **common,
1119
+ "seconds": _media_field(work, "seconds", "seconds")
1120
+ if _media_field(work, "seconds", "seconds") is not None
1121
+ else processed.seconds,
1122
+ "width": _media_field(work, "width", "width")
1123
+ if _media_field(work, "width", "width") is not None
1124
+ else processed.width,
1125
+ "height": _media_field(work, "height", "height")
1126
+ if _media_field(work, "height", "height") is not None
1127
+ else processed.height,
1128
+ "jpegThumbnail": _media_field(work, "jpegThumbnail", "jpeg_thumbnail")
1129
+ if _media_field(work, "jpegThumbnail", "jpeg_thumbnail") is not None
1130
+ else processed.jpeg_thumbnail,
1131
+ "streamingSidecar": uploaded.streaming_sidecar,
1132
+ }
1133
+ if content_type == "video":
1134
+ inner["metadataUrl"] = uploaded.metadata_url
1135
+ return WaMessageBuildResult(
1136
+ message={key: inner}, upload=_upload_summary(uploaded)
1137
+ )
1138
+ if content_type == "audio":
1139
+ inner = {
1140
+ **_spread(work),
1141
+ **common,
1142
+ "seconds": _media_field(work, "seconds", "seconds")
1143
+ if _media_field(work, "seconds", "seconds") is not None
1144
+ else processed.seconds,
1145
+ "streamingSidecar": uploaded.streaming_sidecar,
1146
+ "waveform": _media_field(work, "waveform", "waveform")
1147
+ if _media_field(work, "waveform", "waveform") is not None
1148
+ else processed.waveform,
1149
+ }
1150
+ return WaMessageBuildResult(
1151
+ message={"audioMessage": inner}, upload=_upload_summary(uploaded)
1152
+ )
1153
+ if content_type == "document":
1154
+ file_name = _media_field(work, "fileName", "file_name")
1155
+ inner = {
1156
+ **_spread(work),
1157
+ **common,
1158
+ "fileName": file_name if file_name is not None else "file",
1159
+ "title": _media_field(work, "title", "title")
1160
+ if _media_field(work, "title", "title") is not None
1161
+ else file_name,
1162
+ "jpegThumbnail": _media_field(work, "jpegThumbnail", "jpeg_thumbnail")
1163
+ if _media_field(work, "jpegThumbnail", "jpeg_thumbnail") is not None
1164
+ else processed.jpeg_thumbnail,
1165
+ }
1166
+ return WaMessageBuildResult(
1167
+ message={"documentMessage": inner}, upload=_upload_summary(uploaded)
1168
+ )
1169
+ if content_type == "sticker":
1170
+ explicit_length = _media_field(
1171
+ work, "firstFrameLength", "first_frame_length"
1172
+ )
1173
+ inner = {
1174
+ **_spread(work),
1175
+ **common,
1176
+ "width": _media_field(work, "width", "width")
1177
+ if _media_field(work, "width", "width") is not None
1178
+ else processed.width,
1179
+ "height": _media_field(work, "height", "height")
1180
+ if _media_field(work, "height", "height") is not None
1181
+ else processed.height,
1182
+ "pngThumbnail": _media_field(work, "pngThumbnail", "png_thumbnail")
1183
+ if _media_field(work, "pngThumbnail", "png_thumbnail") is not None
1184
+ else processed.png_thumbnail,
1185
+ "isAnimated": _media_field(work, "isAnimated", "is_animated")
1186
+ if _media_field(work, "isAnimated", "is_animated") is not None
1187
+ else (
1188
+ processed.is_animated
1189
+ if processed.is_animated is not None
1190
+ else first_frame_length is not None
1191
+ ),
1192
+ "firstFrameLength": explicit_length
1193
+ if explicit_length is not None
1194
+ else uploaded.first_frame_length,
1195
+ "firstFrameSidecar": _media_field(
1196
+ work, "firstFrameSidecar", "first_frame_sidecar"
1197
+ )
1198
+ if _media_field(work, "firstFrameSidecar", "first_frame_sidecar")
1199
+ is not None
1200
+ else uploaded.first_frame_sidecar,
1201
+ "stickerSentTs": _media_field(work, "stickerSentTs", "sticker_sent_ts")
1202
+ if _media_field(work, "stickerSentTs", "sticker_sent_ts") is not None
1203
+ else _now_ms(options),
1204
+ }
1205
+ return WaMessageBuildResult(
1206
+ message={"stickerMessage": inner}, upload=_upload_summary(uploaded)
1207
+ )
1208
+ raise ValueError(f"unsupported media message type: {content_type}")
1209
+ finally:
1210
+ if close_upload_handle:
1211
+ handle = resolved.get("upload_media")
1212
+ if callable(getattr(handle, "close", None)):
1213
+ await asyncio.to_thread(handle.close)
1214
+ if resolved.get("temp_file_path"):
1215
+ await client_media.cleanup_temp_file(resolved["temp_file_path"])
1216
+
1217
+
1218
+ def _proc_view(content: MessageDict) -> dict[str, Any]:
1219
+ """Both-case view of send content for the snake_case processor helpers."""
1220
+ pairs = (
1221
+ ("jpegThumbnail", "jpeg_thumbnail"),
1222
+ ("pngThumbnail", "png_thumbnail"),
1223
+ ("isAnimated", "is_animated"),
1224
+ ("firstFrameLength", "first_frame_length"),
1225
+ ("firstFrameSidecar", "first_frame_sidecar"),
1226
+ ("messageContextInfo", "message_context_info"),
1227
+ ("fileLength", "file_length"),
1228
+ ("gifPlayback", "gif_playback"),
1229
+ ("stickerSentTs", "sticker_sent_ts"),
1230
+ )
1231
+ view = dict(content)
1232
+ for camel, snake in pairs:
1233
+ if view.get(camel) is not None and view.get(snake) is None:
1234
+ view[snake] = view[camel]
1235
+ elif view.get(snake) is not None and view.get(camel) is None:
1236
+ view[camel] = view[snake]
1237
+ return view
1238
+
1239
+
1240
+ async def _resolve_mimetype_with_detector(
1241
+ options: WaMediaMessageOptions,
1242
+ content: MessageDict,
1243
+ processor_input: bytes | str | None,
1244
+ processor_ctx: Any,
1245
+ ) -> str:
1246
+ mimetype = _media_field(content, "mimetype", "mimetype")
1247
+ if mimetype:
1248
+ return str(mimetype)
1249
+ if content.get("type") == "sticker":
1250
+ return "image/webp"
1251
+ detector = getattr(
1252
+ getattr(options.media, "processor", None), "detect_mimetype", None
1253
+ )
1254
+ if callable(detector) and processor_input is not None:
1255
+ detected = await detector(processor_input, processor_ctx)
1256
+ if detected:
1257
+ return str(detected)
1258
+ raise ValueError(
1259
+ f"mimetype is required for {content.get('type')} messages "
1260
+ "(or configure a WaMediaProcessor with detectMimetype)"
1261
+ )
1262
+
1263
+
1264
+ def _sticker_pack_origin() -> int:
1265
+ """Proto enum value for a user-created sticker pack (keeps lines short)."""
1266
+ return int(
1267
+ WAProto_pb2.Message.StickerPackMessage.StickerPackOrigin.Value("USER_CREATED")
1268
+ )
1269
+
1270
+
1271
+ def _coerce_sticker_pack(content: MessageDict) -> WaSendStickerPackMessage:
1272
+ """Build the typed sticker-pack input from a send-content dict."""
1273
+ if isinstance(content, WaSendStickerPackMessage):
1274
+ return content
1275
+ stickers: list[WaSendStickerPackStickerInput] = []
1276
+ for sticker in content.get("stickers", []) or []:
1277
+ if isinstance(sticker, Mapping):
1278
+ stickers.append(
1279
+ WaSendStickerPackStickerInput(
1280
+ media=sticker.get("media", b""),
1281
+ file_name=str(
1282
+ sticker.get("fileName", sticker.get("file_name", ""))
1283
+ ),
1284
+ emojis=tuple(sticker.get("emojis", ())),
1285
+ is_animated=sticker.get("isAnimated", sticker.get("is_animated")),
1286
+ is_lottie=sticker.get("isLottie", sticker.get("is_lottie")),
1287
+ mimetype=sticker.get("mimetype"),
1288
+ )
1289
+ )
1290
+ tray = content.get("trayIcon", content.get("tray_icon"))
1291
+ tray_icon: WaSendStickerPackTrayIcon | None = None
1292
+ if isinstance(tray, Mapping):
1293
+ tray_icon = WaSendStickerPackTrayIcon(
1294
+ media=tray.get("media", b""),
1295
+ file_name=str(tray.get("fileName", tray.get("file_name", ""))),
1296
+ )
1297
+ return WaSendStickerPackMessage(
1298
+ sticker_pack_id=str(
1299
+ content.get("stickerPackId", content.get("sticker_pack_id", ""))
1300
+ ),
1301
+ name=str(content.get("name", "")),
1302
+ publisher=str(content.get("publisher", "")),
1303
+ stickers=tuple(stickers),
1304
+ tray_icon=tray_icon,
1305
+ cover_thumbnail=content.get("coverThumbnail", content.get("cover_thumbnail")),
1306
+ message_context_info=content.get(
1307
+ "messageContextInfo", content.get("message_context_info")
1308
+ ),
1309
+ )
1310
+
1311
+
1312
+ async def _build_sticker_pack_media_message(
1313
+ options: WaMediaMessageOptions, content: MessageDict
1314
+ ) -> WaMessageBuildResult:
1315
+ """Encrypt and upload a sticker pack plus its cover (mirrors TS)."""
1316
+ typed = _coerce_sticker_pack(content)
1317
+ validate_sticker_pack_input(typed)
1318
+ cover_thumbnail = typed.cover_thumbnail
1319
+ if cover_thumbnail is None:
1320
+ raise ValueError(
1321
+ "sticker pack send requires coverThumbnail for non-newsletter recipients"
1322
+ )
1323
+
1324
+ media_key = WaMediaCrypto.generate_media_key()
1325
+ zip_entries = [
1326
+ MediaStickerPackZipEntry(file_name=entry.file_name, source=entry.source)
1327
+ for entry in to_sticker_pack_zip_entries(typed)
1328
+ ]
1329
+ zip_stream = create_sticker_pack_zip_stream(zip_entries)
1330
+ zip_bytes = b"".join(zip_stream)
1331
+
1332
+ cover_source = cover_thumbnail
1333
+ if isinstance(cover_source, str):
1334
+ client_media = _client_media()
1335
+ await client_media.assert_readable_file(cover_source)
1336
+
1337
+ bundle, cover = await asyncio.gather(
1338
+ upload_media(
1339
+ options,
1340
+ {
1341
+ "source": zip_bytes,
1342
+ "crypto_type": "sticker-pack",
1343
+ "upload_path": MEDIA_UPLOAD_PATHS["sticker-pack"],
1344
+ "content_type": "application/zip",
1345
+ "media_key": media_key,
1346
+ "sidecar": False,
1347
+ "log_label": "sending sticker pack bundle upload",
1348
+ },
1349
+ ),
1350
+ upload_media(
1351
+ options,
1352
+ {
1353
+ "source": cover_source,
1354
+ "crypto_type": "thumbnail-sticker-pack",
1355
+ "upload_path": MEDIA_UPLOAD_PATHS["thumbnail-sticker-pack"],
1356
+ "content_type": "image/jpeg",
1357
+ "media_key": media_key,
1358
+ "sidecar": False,
1359
+ "log_label": "sending sticker pack thumbnail upload",
1360
+ },
1361
+ ),
1362
+ )
1363
+ assert isinstance(bundle, UploadResult) and isinstance(cover, UploadResult)
1364
+ if cover.file_length == 0:
1365
+ raise ValueError("sticker pack coverThumbnail is empty")
1366
+
1367
+ tray = typed.tray_icon
1368
+ tray_file_name = tray.file_name if tray is not None else ""
1369
+ message: MessageDict = {
1370
+ "stickerPackMessage": {
1371
+ "stickerPackId": typed.sticker_pack_id,
1372
+ "name": typed.name,
1373
+ "publisher": typed.publisher,
1374
+ "stickers": to_sticker_pack_proto_stickers(typed),
1375
+ "fileLength": bundle.file_length,
1376
+ "fileSha256": bytes(bundle.file_sha256),
1377
+ "fileEncSha256": bytes(bundle.file_enc_sha256),
1378
+ "mediaKey": bytes(media_key),
1379
+ "mediaKeyTimestamp": _now_seconds(options),
1380
+ "directPath": bundle.direct_path,
1381
+ "thumbnailDirectPath": cover.direct_path,
1382
+ "thumbnailSha256": bytes(cover.file_sha256),
1383
+ "thumbnailEncSha256": bytes(cover.file_enc_sha256),
1384
+ "thumbnailWidth": _media_field(content, "thumbnailWidth", "thumbnail_width")
1385
+ if _media_field(content, "thumbnailWidth", "thumbnail_width") is not None
1386
+ else 252,
1387
+ "thumbnailHeight": _media_field(
1388
+ content, "thumbnailHeight", "thumbnail_height"
1389
+ )
1390
+ if _media_field(content, "thumbnailHeight", "thumbnail_height") is not None
1391
+ else 252,
1392
+ "trayIconFileName": tray_file_name,
1393
+ "stickerPackSize": bundle.file_length,
1394
+ "stickerPackOrigin": _sticker_pack_origin(),
1395
+ "imageDataHash": bytes_to_base64(bytes(cover.file_sha256)),
1396
+ "caption": content.get("caption"),
1397
+ "packDescription": _media_field(
1398
+ content, "packDescription", "pack_description"
1399
+ ),
1400
+ }
1401
+ }
1402
+ return WaMessageBuildResult(
1403
+ message=message,
1404
+ upload=WaMessageUploadInfo(
1405
+ url=bundle.url,
1406
+ direct_path=bundle.direct_path,
1407
+ file_sha256=bytes(bundle.file_sha256),
1408
+ file_length=bundle.file_length,
1409
+ ),
1410
+ )
1411
+
1412
+
1413
+ __all__ = [
1414
+ "WA_MESSAGE_SECRET_BYTES",
1415
+ "WA_PIN_DEFAULT_DURATION_SECS",
1416
+ "WA_USE_CASE_SECRET_MODIFICATION_TYPES",
1417
+ "UploadResult",
1418
+ "WaBuildMessageContext",
1419
+ "WaMediaMessageOptions",
1420
+ "WaMessageBuildResult",
1421
+ "assert_message_secret",
1422
+ "build_addon_additional_data",
1423
+ "build_extended_text_with_preview",
1424
+ "build_media_message_content",
1425
+ "create_use_case_secret",
1426
+ "get_media_conn",
1427
+ "should_use_addon_additional_data",
1428
+ "upload_media",
1429
+ ]