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,1153 @@
1
+ """Outbound message coordinator (mirrors ``WaMessageCoordinator``).
2
+
3
+ Coordinates outbound message sending, receipts, addon decryption, media
4
+ upload/download, and the related MEX account queries.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import asyncio
10
+ import base64
11
+ import json
12
+ import math
13
+ import os
14
+ import time
15
+ from collections.abc import Callable, Sequence
16
+ from dataclasses import dataclass, replace
17
+ from typing import Any, BinaryIO, Protocol, cast
18
+
19
+ # NOTE: ``zapy._client.types`` stays the first ``zapy`` import: importing it
20
+ # completes the ``zapy._auth.types`` import cycle before the stanza-event
21
+ # modules below execute (mirrors the import order in ``zapy._client.types``).
22
+ from zapy._client import types as _client_types
23
+ from zapy._client.coordinators.message_dispatch import WaGroupHistoryAudience
24
+ from zapy._client.media import (
25
+ WaDownloadMediaOptions as _MediaDownloadOptions,
26
+ download_media_message as _download_media_message,
27
+ )
28
+ from zapy._media.transfer.client import WaMediaTransferClient
29
+ from zapy._client.events.receipt import ReceiptTarget, aggregate_receipt_targets
30
+ from zapy._infra.log import Logger
31
+ from zapy._message.crypto.addon_crypto import (
32
+ build_addon_sender_pairs,
33
+ collect_unique_user_jids,
34
+ decode_addon_plaintext,
35
+ decrypt_addon_payload_with_sender_fallback,
36
+ identify_encrypted_addon,
37
+ resolve_addon_parent_sender_from_key,
38
+ resolve_parent_message_secret,
39
+ resolve_poll_option_names,
40
+ )
41
+ from zapy._message.context_info import proto_message_to_dict
42
+ from zapy._message.encode.content import MessageDict, unwrap_message
43
+ from zapy._message.encode.media_payload import resolve_media_payload
44
+ from zapy._message.kinds.group_history import encode_group_history_bundle
45
+ from zapy._message.messaging import is_group_jid
46
+ from zapy._message.messaging.messages import WaMediaMessageOptions, upload_media
47
+ from zapy._message.primitives.media_retry import WaMediaRetryRequest, WaMediaRetryResult
48
+ from zapy._message.primitives.peer_data_operation import PeerDataOperationSendResult
49
+ from zapy._message.types import (
50
+ WaMessagePublishResult,
51
+ WaSendMessageContent,
52
+ WaSendReceiptEventOptions,
53
+ WaSendReceiptInput,
54
+ WaSendReceiptOptions,
55
+ )
56
+ from zapy._proto import WAProto_pb2
57
+ from zapy._protocol import defaults as _defaults
58
+ from zapy._store.contracts.message import WaMessageStore
59
+ from zapy._store.contracts.message_secret import WaMessageSecretStore
60
+ from zapy._transport.types import BinaryNode
61
+ from zapy._util.coercion import resolve_optional_positive, resolve_positive
62
+ from zapy._util.primitives import to_error
63
+
64
+ # Local copies of the used parts of the JID helpers. They move to
65
+ # ``zapy._protocol.jid`` once that layer lands; the call sites already
66
+ # match the canonical shapes.
67
+ _MAX_SAFE_INTEGER = 2**53 - 1
68
+
69
+
70
+ def _normalize_recipient_jid(to: str) -> str:
71
+ """Normalize a user-supplied recipient into a canonical JID."""
72
+ text = to.strip()
73
+ if len(text) == 0:
74
+ raise ValueError("recipient cannot be empty")
75
+ has_dash = False
76
+ for char in text:
77
+ if char == "@":
78
+ return text
79
+ if char == "-":
80
+ has_dash = True
81
+ digits = "".join(char for char in text if "0" <= char <= "9")
82
+ if has_dash:
83
+ return f"{text}@{_defaults.GROUP_SERVER}"
84
+ if len(digits) == 0:
85
+ raise ValueError(f"invalid recipient: {to}")
86
+ return f"{digits}@{_defaults.HOST_DOMAIN}"
87
+
88
+
89
+ def _parse_signal_address_parts(jid: str) -> tuple[str, str, int]:
90
+ """Split a JID into ``(user, server, device)``."""
91
+ at_index = jid.find("@")
92
+ if at_index < 1 or at_index >= len(jid) - 1:
93
+ raise ValueError(f"invalid jid: {jid}")
94
+ server = jid[at_index + 1 :]
95
+ colon_index = jid.find(":")
96
+ if colon_index == -1 or colon_index > at_index:
97
+ return jid[:at_index], server, 0
98
+ if colon_index >= at_index - 1:
99
+ raise ValueError(f"invalid jid device: {jid}")
100
+ device = 0
101
+ for pos in range(colon_index + 1, at_index):
102
+ digit = ord(jid[pos]) - 48
103
+ if digit < 0 or digit > 9:
104
+ raise ValueError(f"invalid jid device: {jid}")
105
+ device = device * 10 + digit
106
+ if device > _MAX_SAFE_INTEGER:
107
+ raise ValueError(f"invalid jid device: {jid}")
108
+ return jid[:colon_index], server, device
109
+
110
+
111
+ def _apply_device_to_jid(user_jid: str, device: int | None) -> str:
112
+ """Append ``:device`` to a bare user JID; falsy devices are a no-op."""
113
+ if not device:
114
+ return user_jid
115
+ user, server, _ = _parse_signal_address_parts(user_jid)
116
+ return f"{user}:{device}@{server or _defaults.HOST_DOMAIN}"
117
+
118
+
119
+ # Local copy of the ``MEDIA_UPLOAD_PATHS`` rows this coordinator addresses.
120
+ # The canonical table lives in the media layer.
121
+ MEDIA_UPLOAD_PATHS: dict[str, str] = {
122
+ "image": "/mms/image",
123
+ "video": "/mms/video",
124
+ "audio": "/mms/audio",
125
+ "document": "/mms/document",
126
+ "sticker": "/mms/sticker",
127
+ "gif": "/mms/gif",
128
+ "ptt": "/mms/ptt",
129
+ "ptv": "/mms/video",
130
+ "ads-image": "/mms/ads-image",
131
+ "ads-video": "/mms/ads-video",
132
+ "group-history": "/mms/group-history",
133
+ "md-app-state": "/mms/md-app-state",
134
+ "md-msg-hist": "/mms/md-msg-hist",
135
+ "music-artwork": "/mms/music-artwork",
136
+ "newsletter-music-artwork": "/mms/newsletter-music-artwork",
137
+ "sticker-pack": "/mms/sticker-pack",
138
+ "thumbnail-document": "/mms/thumbnail-document",
139
+ "thumbnail-image": "/mms/thumbnail-image",
140
+ "thumbnail-link": "/mms/thumbnail-link",
141
+ "thumbnail-sticker-pack": "/mms/thumbnail-sticker-pack",
142
+ "thumbnail-video": "/mms/thumbnail-video",
143
+ "waffle-image": "/mms/waffle-image",
144
+ "waffle-video": "/mms/waffle-video",
145
+ }
146
+
147
+ # Local ``dispatchMexQuery``/``runMexQuery`` covering the JSON response path
148
+ # every message operation uses. The argo binary path belongs to the mex worker.
149
+ _MEX_DEFAULT_TIMEOUT_MS = 32_000
150
+
151
+
152
+ class WaMexQuerySocket(Protocol):
153
+ """Structural mex socket (mirrors ``WaMexQuerySocket``)."""
154
+
155
+ async def query(self, node: BinaryNode, timeout_ms: int) -> BinaryNode: ...
156
+
157
+
158
+ async def _run_mex_query(
159
+ socket: WaMexQuerySocket,
160
+ op_name: str,
161
+ doc_id: str,
162
+ variables: dict[str, Any],
163
+ ) -> Any | None:
164
+ """Run one mex operation and return its ``data`` payload (or ``None``)."""
165
+ from zapy._protocol.nodes import WA_IQ_TYPES, WA_NODE_TAGS, WA_XMLNS
166
+ from zapy._transport.node.helpers import find_node_child
167
+ from zapy._transport.node.query import assert_iq_result
168
+
169
+ body = json.dumps(
170
+ {"queryId": doc_id, "variables": variables}, separators=(",", ":")
171
+ )
172
+ node = BinaryNode(
173
+ tag=WA_NODE_TAGS["IQ"],
174
+ attrs={
175
+ "to": _defaults.HOST_DOMAIN,
176
+ "type": WA_IQ_TYPES["GET"],
177
+ "xmlns": WA_XMLNS["MEX"],
178
+ },
179
+ content=[BinaryNode(tag="query", attrs={"query_id": doc_id}, content=body)],
180
+ )
181
+ response = await socket.query(node, _MEX_DEFAULT_TIMEOUT_MS)
182
+ assert_iq_result(response, f"mex/{op_name}")
183
+ result = find_node_child(response, "result")
184
+ if result is None:
185
+ raise ValueError(f"mex/{op_name} response missing <result>")
186
+ if result.attrs.get("format", "json") != "json":
187
+ raise NotImplementedError(
188
+ "zapy._client.coordinators.message: mex argo payloads are not supported yet"
189
+ )
190
+ raw = result.content
191
+ if isinstance(raw, list) or raw is None:
192
+ raise ValueError(f"mex/{op_name} response missing <result>")
193
+ payload: Any = json.loads(
194
+ raw.decode("utf-8") if isinstance(raw, (bytes, bytearray)) else raw
195
+ )
196
+ if not isinstance(payload, dict):
197
+ return None
198
+ errors = payload.get("errors")
199
+ if isinstance(errors, list) and len(errors) > 0:
200
+ parts: list[str] = []
201
+ for entry in errors:
202
+ if not isinstance(entry, dict):
203
+ parts.append("?: ? @")
204
+ continue
205
+ extensions = entry.get("extensions")
206
+ code = (
207
+ extensions.get("error_code") if isinstance(extensions, dict) else None
208
+ )
209
+ path = entry.get("path")
210
+ path_text = (
211
+ ".".join(str(part) for part in path) if isinstance(path, list) else ""
212
+ )
213
+ parts.append(
214
+ f"{code if code is not None else '?'}: "
215
+ f"{entry.get('message') or '?'} @{path_text}"
216
+ )
217
+ raise ValueError(f"mex/{op_name} errors: {'; '.join(parts)}")
218
+ return payload.get("data")
219
+
220
+
221
+ def _try_as_string(value: Any) -> str | None:
222
+ """Lenient string coercion for external JSON payloads; else ``None``."""
223
+ return value if isinstance(value, str) and len(value) > 0 else None
224
+
225
+
226
+ def _try_as_number(value: Any) -> float | None:
227
+ """Lenient number coercion for external JSON payloads; else ``None``."""
228
+ if isinstance(value, bool):
229
+ return None
230
+ if isinstance(value, (int, float)):
231
+ return value if math.isfinite(value) else None
232
+ if isinstance(value, str):
233
+ normalized = value.strip()
234
+ if not normalized:
235
+ return None
236
+ try:
237
+ return int(normalized)
238
+ except ValueError:
239
+ pass
240
+ try:
241
+ parsed = float(normalized)
242
+ except ValueError:
243
+ return None
244
+ return parsed if math.isfinite(parsed) else None
245
+ return None
246
+
247
+
248
+ def _error_message(error: object) -> str:
249
+ """Readable message for a caught error (mirrors ``toError().message``)."""
250
+ return str(to_error(error))
251
+
252
+
253
+ def _long_to_number(value: Any) -> int:
254
+ """Coerce a protobuf timestamp to int; missing/non-numeric is ``0``."""
255
+ if value is None:
256
+ return 0
257
+ if isinstance(value, bool):
258
+ return 0
259
+ if isinstance(value, (int, float)):
260
+ if not math.isfinite(value) or abs(value) > _MAX_SAFE_INTEGER:
261
+ return 0
262
+ return int(value)
263
+ to_number = getattr(value, "toNumber", None)
264
+ if callable(to_number):
265
+ try:
266
+ return _long_to_number(to_number())
267
+ except Exception:
268
+ return 0
269
+ return 0
270
+
271
+
272
+ def _json_safe(value: Any) -> Any:
273
+ """Convert bytes to base64 strings so a message dict survives ``ParseDict``."""
274
+ if isinstance(value, dict):
275
+ return {key: _json_safe(item) for key, item in value.items()}
276
+ if isinstance(value, (bytes, bytearray)):
277
+ return base64.b64encode(bytes(value)).decode("ascii")
278
+ if isinstance(value, (list, tuple)):
279
+ return [_json_safe(item) for item in value]
280
+ return value
281
+
282
+
283
+ def _message_to_proto(data: MessageDict) -> WAProto_pb2.Message:
284
+ """Rebuild a protobuf message from a message dict (inverse of decode)."""
285
+ from google.protobuf import json_format
286
+
287
+ return json_format.ParseDict(_json_safe(data), WAProto_pb2.Message())
288
+
289
+
290
+ # Persist IDs vendored from ``spec/mex`` (``WA_MEX_PERSIST_IDS``).
291
+ _MEX_PERSIST_IDS: dict[str, str] = {
292
+ "FetchReachoutTimelock": "2398367752030964",
293
+ "FetchNewChatMessageCappingInfo": "27910975521856601",
294
+ }
295
+
296
+ # Request type vendored from ``WAProto`` (``PeerDataOperationRequestType``).
297
+ _HISTORY_SYNC_ON_DEMAND = int(
298
+ WAProto_pb2.Message.PeerDataOperationRequestType.Value("HISTORY_SYNC_ON_DEMAND")
299
+ )
300
+
301
+ # MIME type the group-history bundle is uploaded and advertised under.
302
+ _GROUP_HISTORY_BUNDLE_MIMETYPE = "application/protobuf"
303
+
304
+ _SIDECAR_UPLOAD_TYPES = frozenset({"video", "ptv", "audio", "gif", "ptt"})
305
+
306
+ WaUploadMediaSource = bytes | bytearray | str | BinaryIO
307
+
308
+ WaUploadMediaType = str
309
+
310
+
311
+ @dataclass(frozen=True, slots=True)
312
+ class WaUploadMediaOptions:
313
+ """Media upload options (mirrors ``WaUploadMediaOptions``)."""
314
+
315
+ type: str = "image"
316
+ mimetype: str | None = None
317
+ media_key: bytes | None = None
318
+ sidecar: bool | None = None
319
+ first_frame_length: int | None = None
320
+ timeout_ms: float | None = None
321
+ signal: Any | None = None
322
+
323
+
324
+ @dataclass(frozen=True, slots=True)
325
+ class WaMediaUploadResult:
326
+ """Reusable upload descriptor plus the media-key timestamp and mimetype."""
327
+
328
+ url: str = ""
329
+ direct_path: str = ""
330
+ media_key: bytes = b""
331
+ file_sha256: bytes = b""
332
+ file_enc_sha256: bytes = b""
333
+ file_length: int = 0
334
+ media_key_timestamp: int = 0
335
+ mimetype: str | None = None
336
+ streaming_sidecar: bytes | None = None
337
+ first_frame_sidecar: bytes | None = None
338
+ first_frame_length: int | None = None
339
+ metadata_url: str | None = None
340
+
341
+
342
+ @dataclass(frozen=True, slots=True)
343
+ class WaMediaUploadInput:
344
+ """Input for the media ``upload_media`` seam (mirrors ``WaMediaUploadInput``)."""
345
+
346
+ source: Any = None
347
+ crypto_type: str = ""
348
+ upload_path: str = ""
349
+ content_type: str | None = None
350
+ media_key: bytes | None = None
351
+ sidecar: bool = False
352
+ first_frame_length: int | None = None
353
+ timeout_ms: float | None = None
354
+ signal: Any | None = None
355
+ log_label: str | None = None
356
+
357
+
358
+ @dataclass(frozen=True, slots=True)
359
+ class WaRequestHistorySyncInput:
360
+ """Backfill request for older messages of one chat."""
361
+
362
+ chat_jid: str = ""
363
+ oldest_msg_id: str | None = None
364
+ oldest_msg_from_me: bool | None = None
365
+ oldest_msg_timestamp_ms: int | None = None
366
+ count: int | None = None
367
+
368
+
369
+ @dataclass(frozen=True, slots=True)
370
+ class WaRequestHistorySyncResult:
371
+ """Protocol message id of a dispatched history-sync request."""
372
+
373
+ message_id: str = ""
374
+
375
+
376
+ @dataclass(frozen=True, slots=True)
377
+ class WaShareGroupHistoryInput:
378
+ """Members, windowing, or explicit messages for a group-history share."""
379
+
380
+ to_jids: tuple[str, ...] = ()
381
+ count: int | None = None
382
+ since_ms: int | None = None
383
+ messages: tuple[MessageDict, ...] | None = None
384
+ out_of_window_pinned_messages: tuple[MessageDict, ...] | None = None
385
+
386
+
387
+ @dataclass(frozen=True, slots=True)
388
+ class WaShareGroupHistoryResult:
389
+ """Bundle/notice stanza ids plus the audience split of a history share."""
390
+
391
+ bundle_message_id: str = ""
392
+ notice_message_id: str | None = None
393
+ messages_count: int = 0
394
+ history_receivers: tuple[str, ...] = ()
395
+ non_history_receivers: tuple[str, ...] = ()
396
+
397
+
398
+ @dataclass(frozen=True, slots=True)
399
+ class WaSyncSignalSessionOptions:
400
+ """Session resync mode: ensure-only, force rebuild, or identity change."""
401
+
402
+ force: bool = False
403
+ reason_identity: bool = False
404
+
405
+
406
+ @dataclass(frozen=True, slots=True)
407
+ class WaRequestMediaReuploadOptions:
408
+ """Timeout override for an explicit media-reupload request."""
409
+
410
+ timeout_ms: int | None = None
411
+
412
+
413
+ @dataclass(frozen=True, slots=True)
414
+ class WaReachoutTimelock:
415
+ """Server-side reachout throttle for cold outreach to non-contacts."""
416
+
417
+ is_active: bool = False
418
+ enforcement_type: str | None = None
419
+ enforcement_ends_at: float | None = None
420
+
421
+
422
+ WaMessageCappingType = str
423
+
424
+
425
+ @dataclass(frozen=True, slots=True)
426
+ class WaMessageCappingInfo:
427
+ """Per-cycle new-chat message-capping quota, usage, and status flags."""
428
+
429
+ total_quota: float | None = None
430
+ used_quota: float | None = None
431
+ cycle_start_at: float | None = None
432
+ cycle_end_at: float | None = None
433
+ server_sent_at: float | None = None
434
+ ote_status: str | None = None
435
+ mv_status: str | None = None
436
+ capping_status: str | None = None
437
+
438
+
439
+ class WaMessageDispatchProtocol(Protocol):
440
+ """Structural message-dispatch surface (mirrors the dispatch coordinator)."""
441
+
442
+ async def send_message(
443
+ self,
444
+ to: str,
445
+ content: WaSendMessageContent,
446
+ options: _client_types.WaSendMessageOptions | None = None,
447
+ ) -> WaMessagePublishResult: ...
448
+ async def send_receipt(self, input: WaSendReceiptInput) -> None: ...
449
+ async def sync_signal_session(
450
+ self, jid: str, options: WaSyncSignalSessionOptions
451
+ ) -> None: ...
452
+ async def resolve_group_history_audience(
453
+ self, group_jid: str, to_jids: Sequence[str]
454
+ ) -> WaGroupHistoryAudience: ...
455
+
456
+
457
+ class WaMediaRetryProtocol(Protocol):
458
+ """Structural media-retry surface (mirrors ``MediaRetryRequester``)."""
459
+
460
+ def request(
461
+ self, input: WaMediaRetryRequest
462
+ ) -> asyncio.Future[WaMediaRetryResult]: ...
463
+
464
+
465
+ class WaPeerDataOperationProtocol(Protocol):
466
+ """Structural PDO surface (mirrors ``PeerDataOperationRequester``)."""
467
+
468
+ async def send(
469
+ self, request_type: int, body: dict[str, Any]
470
+ ) -> PeerDataOperationSendResult: ...
471
+
472
+
473
+ class WaTrustedContactTokenProtocol(Protocol):
474
+ """Structural trusted-contact-token surface used on identity change."""
475
+
476
+ async def reissue_on_identity_change(self, jid: str) -> None: ...
477
+
478
+
479
+ @dataclass(frozen=True, slots=True)
480
+ class WaMessageCoordinatorDeps:
481
+ """Dependencies for :class:`WaMessageCoordinator`."""
482
+
483
+ message_dispatch: WaMessageDispatchProtocol
484
+ media_transfer: Any
485
+ media_retry: WaMediaRetryProtocol
486
+ media_upload_options: WaMediaMessageOptions
487
+ logger: Logger
488
+ message_store: WaMessageStore
489
+ message_secret_store: WaMessageSecretStore
490
+ trusted_contact_token: WaTrustedContactTokenProtocol
491
+ emit_addon: Callable[[_client_types.WaIncomingAddonEvent], None]
492
+ mex_socket: WaMexQuerySocket
493
+ peer_data_operation: WaPeerDataOperationProtocol
494
+ is_group_history_send_enabled: Callable[[], bool]
495
+ get_ab_prop_number: Callable[[str], int]
496
+
497
+
498
+ def _oldest_timestamp_seconds(messages: Sequence[MessageDict]) -> int | None:
499
+ """Oldest ``messageTimestamp`` across ``messages`` (seconds)."""
500
+ oldest: int | None = None
501
+ for item in messages:
502
+ timestamp = _long_to_number(item.get("messageTimestamp"))
503
+ if timestamp > 0 and (oldest is None or timestamp < oldest):
504
+ oldest = timestamp
505
+ return oldest
506
+
507
+
508
+ def _parse_reachout_timelock_mex_response(data: Any) -> WaReachoutTimelock:
509
+ record = data if isinstance(data, dict) else {}
510
+ root = record.get("xwa2_fetch_account_reachout_timelock")
511
+ root_record = root if isinstance(root, dict) else {}
512
+ return WaReachoutTimelock(
513
+ is_active=root_record.get("is_active") is True,
514
+ enforcement_type=_try_as_string(root_record.get("enforcement_type")),
515
+ enforcement_ends_at=_try_as_number(root_record.get("time_enforcement_ends")),
516
+ )
517
+
518
+
519
+ def _parse_message_capping_mex_response(data: Any) -> WaMessageCappingInfo:
520
+ record = data if isinstance(data, dict) else {}
521
+ root = record.get("xwa2_message_capping_info")
522
+ root_record = root if isinstance(root, dict) else {}
523
+ return WaMessageCappingInfo(
524
+ total_quota=_try_as_number(root_record.get("total_quota")),
525
+ used_quota=_try_as_number(root_record.get("used_quota")),
526
+ cycle_start_at=_try_as_number(root_record.get("cycle_start_timestamp")),
527
+ cycle_end_at=_try_as_number(root_record.get("cycle_end_timestamp")),
528
+ server_sent_at=_try_as_number(root_record.get("server_sent_timestamp")),
529
+ ote_status=_try_as_string(root_record.get("ote_status")),
530
+ mv_status=_try_as_string(root_record.get("mv_status")),
531
+ capping_status=_try_as_string(root_record.get("capping_status")),
532
+ )
533
+
534
+
535
+ async def _normalize_upload_source(source: WaUploadMediaSource) -> bytes | BinaryIO:
536
+ """Normalize an upload source to bytes or a binary stream."""
537
+ if isinstance(source, (bytes, bytearray)):
538
+ return bytes(source)
539
+ if isinstance(source, str):
540
+ if not os.path.isfile(source):
541
+ raise ValueError(f"media upload received unreadable file: {source}")
542
+ return open(source, "rb")
543
+ if hasattr(source, "read"):
544
+ return source
545
+ raise ValueError("media upload received unsupported source type")
546
+
547
+
548
+ class WaMessageCoordinator:
549
+ """Outbound messaging: sends, receipts, addons, media, MEX queries."""
550
+
551
+ def __init__(self, deps: WaMessageCoordinatorDeps) -> None:
552
+ self._message_dispatch = deps.message_dispatch
553
+ self._media_transfer = deps.media_transfer
554
+ self._media_retry = deps.media_retry
555
+ self._media_upload_options = deps.media_upload_options
556
+ self._logger = deps.logger
557
+ self._message_store = deps.message_store
558
+ self._message_secret_store = deps.message_secret_store
559
+ self._trusted_contact_token = deps.trusted_contact_token
560
+ self._emit_addon = deps.emit_addon
561
+ self._mex_socket = deps.mex_socket
562
+ self._peer_data_operation = deps.peer_data_operation
563
+ self._is_group_history_send_enabled = deps.is_group_history_send_enabled
564
+ self._get_ab_prop_number = deps.get_ab_prop_number
565
+
566
+ async def request_history_sync(
567
+ self, input: WaRequestHistorySyncInput
568
+ ) -> WaRequestHistorySyncResult:
569
+ """Ask the server to backfill older messages; resolves on dispatch."""
570
+ chat_jid = _normalize_recipient_jid(input.chat_jid)
571
+ on_demand_count = resolve_optional_positive(input.count, "count")
572
+ timestamp_ms = input.oldest_msg_timestamp_ms
573
+ if timestamp_ms is not None:
574
+ if (
575
+ isinstance(timestamp_ms, bool)
576
+ or not isinstance(timestamp_ms, (int, float))
577
+ or not math.isfinite(timestamp_ms)
578
+ or int(timestamp_ms) != timestamp_ms
579
+ or abs(timestamp_ms) > _MAX_SAFE_INTEGER
580
+ or timestamp_ms < 0
581
+ ):
582
+ raise ValueError(
583
+ f"invalid oldestMsgTimestampMs: {input.oldest_msg_timestamp_ms}"
584
+ )
585
+ request: dict[str, Any] = {
586
+ "chatJid": chat_jid,
587
+ "supportInlineResponse": True,
588
+ }
589
+ if input.oldest_msg_id is not None:
590
+ request["oldestMsgId"] = input.oldest_msg_id
591
+ if input.oldest_msg_from_me is not None:
592
+ request["oldestMsgFromMe"] = input.oldest_msg_from_me
593
+ if timestamp_ms is not None:
594
+ request["oldestMsgTimestampMs"] = timestamp_ms
595
+ if on_demand_count is not None:
596
+ request["onDemandMsgCount"] = on_demand_count
597
+ result = await self._peer_data_operation.send(
598
+ _HISTORY_SYNC_ON_DEMAND, {"historySyncOnDemandRequest": request}
599
+ )
600
+ return WaRequestHistorySyncResult(message_id=result.message_id)
601
+
602
+ async def share_group_history(
603
+ self, group_jid: str, input: WaShareGroupHistoryInput
604
+ ) -> WaShareGroupHistoryResult:
605
+ """Share recent group history with newly joined members."""
606
+ normalized_group_jid = _normalize_recipient_jid(group_jid)
607
+ if not is_group_jid(normalized_group_jid):
608
+ raise ValueError(
609
+ f"shareGroupHistory requires a group jid: {normalized_group_jid}"
610
+ )
611
+ if len(input.to_jids) == 0:
612
+ raise ValueError("shareGroupHistory requires at least one recipient")
613
+ message_limit = resolve_positive(
614
+ input.count,
615
+ self._get_ab_prop_number("group_history_message_count_limit"),
616
+ "count",
617
+ )
618
+ if not self._is_group_history_send_enabled():
619
+ raise ValueError(
620
+ "shareGroupHistory is disabled for this account "
621
+ "(group_history_send is off)"
622
+ )
623
+ audience = await self._message_dispatch.resolve_group_history_audience(
624
+ normalized_group_jid, input.to_jids
625
+ )
626
+ if audience.requested_self:
627
+ raise ValueError(
628
+ "shareGroupHistory cannot share history with this account itself"
629
+ )
630
+ if len(audience.unknown_jids) > 0:
631
+ raise ValueError(
632
+ "shareGroupHistory recipients are not members of the group "
633
+ f"(addressing mode: {audience.addressing_mode}): "
634
+ f"{', '.join(audience.unknown_jids)}"
635
+ )
636
+ if len(audience.history_receivers) == 0:
637
+ raise ValueError("shareGroupHistory resolved no recipients")
638
+ messages: Sequence[MessageDict]
639
+ if input.messages is not None:
640
+ messages = input.messages
641
+ else:
642
+ messages = await self._load_group_history_messages(
643
+ normalized_group_jid, message_limit, input.since_ms
644
+ )
645
+ if len(messages) == 0:
646
+ raise ValueError("shareGroupHistory found no messages to share")
647
+ bundle = encode_group_history_bundle(
648
+ messages, input.out_of_window_pinned_messages
649
+ )
650
+ upload = await upload_media(
651
+ self._media_upload_options,
652
+ WaMediaUploadInput(
653
+ source=bundle.compressed,
654
+ crypto_type="group-history",
655
+ upload_path=MEDIA_UPLOAD_PATHS["group-history"],
656
+ content_type=_GROUP_HISTORY_BUNDLE_MIMETYPE,
657
+ sidecar=False,
658
+ log_label="group history bundle upload",
659
+ ),
660
+ )
661
+ oldest_in_window = _oldest_timestamp_seconds(messages)
662
+ out_of_window = list(input.out_of_window_pinned_messages or [])
663
+ oldest_pin = _oldest_timestamp_seconds(out_of_window)
664
+ if oldest_pin is None:
665
+ oldest_in_bundle = oldest_in_window
666
+ elif oldest_in_window is None:
667
+ oldest_in_bundle = oldest_pin
668
+ else:
669
+ oldest_in_bundle = min(oldest_in_window, oldest_pin)
670
+ metadata: dict[str, Any] = {
671
+ "historyReceivers": list(audience.history_receivers),
672
+ "nonHistoryReceivers": list(audience.non_history_receivers),
673
+ "messageCount": len(messages),
674
+ "oldestMessageTimestampInWindow": oldest_in_window,
675
+ "oldestMessageTimestampInBundle": oldest_in_bundle,
676
+ }
677
+ clock = self._media_upload_options.server_clock
678
+ media_key_timestamp = (
679
+ clock.now_seconds() if clock is not None else int(time.time())
680
+ )
681
+ bundle_result = await self.send(
682
+ normalized_group_jid,
683
+ {
684
+ "messageHistoryBundle": {
685
+ "mimetype": _GROUP_HISTORY_BUNDLE_MIMETYPE,
686
+ "fileSha256": upload.file_sha256,
687
+ "fileEncSha256": upload.file_enc_sha256,
688
+ "mediaKey": upload.media_key,
689
+ "directPath": upload.direct_path,
690
+ "mediaKeyTimestamp": media_key_timestamp,
691
+ "messageHistoryMetadata": metadata,
692
+ }
693
+ },
694
+ )
695
+ notice_message_id: str | None = None
696
+ try:
697
+ notice_message_id = (
698
+ await self.send(
699
+ normalized_group_jid,
700
+ {"messageHistoryNotice": {"messageHistoryMetadata": metadata}},
701
+ )
702
+ ).id
703
+ except Exception as error:
704
+ self._logger.warn(
705
+ "group history notice failed after the bundle was delivered",
706
+ {
707
+ "groupJid": normalized_group_jid,
708
+ "id": bundle_result.id,
709
+ "receiverCount": len(audience.history_receivers),
710
+ "message": _error_message(error),
711
+ },
712
+ )
713
+ self._logger.debug(
714
+ "shared group history",
715
+ {
716
+ "groupJid": normalized_group_jid,
717
+ "id": bundle_result.id,
718
+ "messagesCount": len(messages),
719
+ "receiverCount": len(audience.history_receivers),
720
+ },
721
+ )
722
+ return WaShareGroupHistoryResult(
723
+ bundle_message_id=bundle_result.id,
724
+ notice_message_id=notice_message_id,
725
+ messages_count=len(messages),
726
+ history_receivers=tuple(audience.history_receivers),
727
+ non_history_receivers=tuple(audience.non_history_receivers),
728
+ )
729
+
730
+ async def _load_group_history_messages(
731
+ self, group_jid: str, limit: int, since_ms: int | None
732
+ ) -> list[MessageDict]:
733
+ """Read the most recent group messages back out of the mailbox store."""
734
+ records = await self._message_store.list_by_thread(group_jid, limit)
735
+ messages: list[MessageDict] = []
736
+ for record in records:
737
+ if not record.message_bytes:
738
+ continue
739
+ if since_ms is not None and (record.timestamp_ms or 0) < since_ms:
740
+ continue
741
+ decoded = WAProto_pb2.Message()
742
+ decoded.ParseFromString(bytes(record.message_bytes))
743
+ key: dict[str, Any] = {
744
+ "id": record.id,
745
+ "remoteJid": group_jid,
746
+ "fromMe": record.from_me,
747
+ "participant": record.participant_jid or record.sender_jid,
748
+ }
749
+ messages.append(
750
+ {
751
+ "key": key,
752
+ "message": proto_message_to_dict(decoded),
753
+ "messageTimestamp": int((record.timestamp_ms or 0) // 1_000),
754
+ }
755
+ )
756
+ return messages
757
+
758
+ async def get_reachout_timelock(self) -> WaReachoutTimelock:
759
+ """Fetch the server-side reachout timelock for cold outreach."""
760
+ data = await _run_mex_query(
761
+ self._mex_socket,
762
+ "FetchReachoutTimelock",
763
+ _MEX_PERSIST_IDS["FetchReachoutTimelock"],
764
+ {},
765
+ )
766
+ return _parse_reachout_timelock_mex_response(data)
767
+
768
+ async def get_new_chat_message_capping(
769
+ self, type: WaMessageCappingType = "INDIVIDUAL_NEW_CHAT_THREAD"
770
+ ) -> WaMessageCappingInfo:
771
+ """Fetch the per-cycle new-chat message-capping info."""
772
+ data = await _run_mex_query(
773
+ self._mex_socket,
774
+ "FetchNewChatMessageCappingInfo",
775
+ _MEX_PERSIST_IDS["FetchNewChatMessageCappingInfo"],
776
+ {"input": {"type": type}},
777
+ )
778
+ return _parse_message_capping_mex_response(data)
779
+
780
+ async def sync_signal_session(
781
+ self,
782
+ jid: str,
783
+ options: bool | WaSyncSignalSessionOptions | None = None,
784
+ ) -> None:
785
+ """Ensure, rebuild, or identity-reset the Signal session for ``jid``."""
786
+ if isinstance(options, bool):
787
+ normalized = WaSyncSignalSessionOptions(reason_identity=options)
788
+ elif options is None:
789
+ normalized = WaSyncSignalSessionOptions()
790
+ else:
791
+ normalized = options
792
+ await self._message_dispatch.sync_signal_session(jid, normalized)
793
+ if normalized.reason_identity:
794
+ task = asyncio.ensure_future(
795
+ self._trusted_contact_token.reissue_on_identity_change(jid)
796
+ )
797
+
798
+ def _done(finished: asyncio.Task[None]) -> None:
799
+ try:
800
+ finished.result()
801
+ except Exception as error:
802
+ self._logger.warn(
803
+ "tc token reissue on identity change failed",
804
+ {"jid": jid, "message": _error_message(error)},
805
+ )
806
+
807
+ task.add_done_callback(_done)
808
+
809
+ async def send(
810
+ self,
811
+ to: str,
812
+ content: WaSendMessageContent,
813
+ options: _client_types.WaSendMessageOptions | None = None,
814
+ ) -> WaMessagePublishResult:
815
+ """Send a message of any kind to ``to``; resolves with the publish result."""
816
+ return await self._message_dispatch.send_message(
817
+ to,
818
+ content,
819
+ options if options is not None else _client_types.WaSendMessageOptions(),
820
+ )
821
+
822
+ async def send_receipt(
823
+ self,
824
+ first: str
825
+ | _client_types.WaIncomingMessageEvent
826
+ | Sequence[_client_types.WaIncomingMessageEvent],
827
+ second: str | Sequence[str] | WaSendReceiptEventOptions | None = None,
828
+ third: WaSendReceiptOptions | None = None,
829
+ ) -> None:
830
+ """Send delivery/read/played/inactive receipts for message ids."""
831
+ if isinstance(first, str):
832
+ ids = cast(str | Sequence[str], second)
833
+ await self._dispatch_receipt(
834
+ first, ids, third if third is not None else WaSendReceiptOptions()
835
+ )
836
+ return
837
+ events = (
838
+ [first]
839
+ if isinstance(first, _client_types.WaIncomingMessageEvent)
840
+ else list(first)
841
+ )
842
+ options = (
843
+ second
844
+ if isinstance(second, WaSendReceiptEventOptions)
845
+ else WaSendReceiptEventOptions()
846
+ )
847
+ targets: list[ReceiptTarget] = []
848
+ for event in events:
849
+ key = event.key
850
+ if key is None or not key.remote_jid or not key.id:
851
+ raise ValueError("sendReceipt event is missing key.remoteJid or key.id")
852
+ sender_jid = key.participant or key.remote_jid
853
+ targets.append(
854
+ ReceiptTarget(
855
+ chat_jid=key.remote_jid,
856
+ id=key.id,
857
+ sender_jid=_apply_device_to_jid(sender_jid, key.sender_device)
858
+ if sender_jid
859
+ else None,
860
+ is_group_chat=key.is_group,
861
+ is_broadcast_chat=key.is_broadcast,
862
+ )
863
+ )
864
+ for group in aggregate_receipt_targets(targets):
865
+ await self._dispatch_receipt(
866
+ group.jid,
867
+ group.ids,
868
+ WaSendReceiptOptions(
869
+ type=options.type,
870
+ recipient=options.recipient,
871
+ category=options.category,
872
+ from_=options.from_,
873
+ t=options.t,
874
+ peer_participant_pn=options.peer_participant_pn,
875
+ content=options.content,
876
+ participant=group.participant,
877
+ ),
878
+ )
879
+
880
+ async def upload(
881
+ self, source: WaUploadMediaSource, options: WaUploadMediaOptions
882
+ ) -> WaMediaUploadResult:
883
+ """Encrypt and upload standalone media; returns the reusable descriptor."""
884
+ upload_path = MEDIA_UPLOAD_PATHS.get(options.type)
885
+ if upload_path is None:
886
+ raise ValueError(f"unknown media upload type: {options.type}")
887
+ result = await upload_media(
888
+ self._media_upload_options,
889
+ WaMediaUploadInput(
890
+ source=await _normalize_upload_source(source),
891
+ crypto_type=options.type,
892
+ upload_path=upload_path,
893
+ content_type=options.mimetype,
894
+ media_key=options.media_key,
895
+ sidecar=options.sidecar
896
+ if options.sidecar is not None
897
+ else options.type in _SIDECAR_UPLOAD_TYPES,
898
+ first_frame_length=options.first_frame_length,
899
+ timeout_ms=options.timeout_ms,
900
+ signal=options.signal,
901
+ log_label="user media upload",
902
+ ),
903
+ )
904
+ clock = self._media_upload_options.server_clock
905
+ return WaMediaUploadResult(
906
+ url=result.url,
907
+ direct_path=result.direct_path,
908
+ media_key=result.media_key,
909
+ file_sha256=result.file_sha256,
910
+ file_enc_sha256=result.file_enc_sha256,
911
+ file_length=result.file_length,
912
+ media_key_timestamp=clock.now_seconds()
913
+ if clock is not None
914
+ else int(time.time()),
915
+ mimetype=options.mimetype,
916
+ streaming_sidecar=getattr(result, "streaming_sidecar", None),
917
+ first_frame_sidecar=getattr(result, "first_frame_sidecar", None),
918
+ first_frame_length=getattr(result, "first_frame_length", None),
919
+ metadata_url=getattr(result, "metadata_url", None),
920
+ )
921
+
922
+ async def download(
923
+ self,
924
+ source: _client_types.WaIncomingMessageEvent | MessageDict,
925
+ options: _client_types.WaDownloadMediaOptions | None = None,
926
+ ) -> Any:
927
+ """Download and decrypt media (bytes; the oracle returns a stream).
928
+
929
+ The port buffers through :func:`download_media_message`, so the
930
+ stream-vs-bytes gap documented there applies here too.
931
+ """
932
+ opts = options or _client_types.WaDownloadMediaOptions()
933
+ transfer = self._media_transfer or WaMediaTransferClient()
934
+ message = (
935
+ source.message
936
+ if isinstance(source, _client_types.WaIncomingMessageEvent)
937
+ else source
938
+ )
939
+ if not isinstance(message, dict):
940
+ raise ValueError("message has no downloadable media")
941
+ return await _download_media_message(
942
+ message,
943
+ _MediaDownloadOptions(
944
+ max_bytes=opts.max_bytes,
945
+ timeout_ms=None if opts.timeout_ms is None else int(opts.timeout_ms),
946
+ ),
947
+ transfer,
948
+ )
949
+
950
+ async def download_to_file(
951
+ self,
952
+ source: _client_types.WaIncomingMessageEvent | MessageDict,
953
+ file_path: str,
954
+ options: _client_types.WaDownloadMediaOptions | None = None,
955
+ ) -> None:
956
+ """Write decrypted media to ``file_path`` (no partial file is left).
957
+
958
+ The oracle pipes the live stream, so a failure there can leave a
959
+ partial file; the port downloads first and writes once, so a
960
+ failure leaves nothing behind.
961
+ """
962
+ data = await self.download(source, options)
963
+ with open(file_path, "wb") as handle:
964
+ handle.write(bytes(data))
965
+
966
+ async def download_bytes(
967
+ self,
968
+ source: _client_types.WaIncomingMessageEvent | MessageDict,
969
+ options: _client_types.WaDownloadMediaOptions | None = None,
970
+ ) -> bytes:
971
+ """Buffer decrypted media into bytes (use only for small media)."""
972
+ return bytes(await self.download(source, options))
973
+
974
+ def request_media_reupload(
975
+ self,
976
+ source: _client_types.WaIncomingMessageEvent | WaMediaRetryRequest,
977
+ options: WaRequestMediaReuploadOptions | None = None,
978
+ ) -> asyncio.Future[WaMediaRetryResult]:
979
+ """Ask the sender to re-upload expired media (joins in-flight requests)."""
980
+ if not isinstance(source, _client_types.WaIncomingMessageEvent):
981
+ return self._media_retry.request(source)
982
+ key = source.key
983
+ if key is None or not key.id or not key.remote_jid:
984
+ raise ValueError(
985
+ "requestMediaReupload event is missing key.remoteJid or key.id"
986
+ )
987
+ if key.is_newsletter:
988
+ raise ValueError(
989
+ "requestMediaReupload is not supported on newsletter messages"
990
+ )
991
+ message = source.message if isinstance(source.message, dict) else None
992
+ payload = resolve_media_payload(message)
993
+ if payload is None:
994
+ raise ValueError("message has no downloadable media")
995
+ return self._media_retry.request(
996
+ WaMediaRetryRequest(
997
+ message_id=key.id,
998
+ chat_jid=key.remote_jid,
999
+ media_key=bytes(payload.media_key),
1000
+ from_me=bool(key.from_me),
1001
+ participant=key.participant,
1002
+ timeout_ms=options.timeout_ms if options is not None else None,
1003
+ )
1004
+ )
1005
+
1006
+ async def try_decrypt_addon(
1007
+ self, event: _client_types.WaIncomingMessageEvent
1008
+ ) -> None:
1009
+ """Decrypt an addon payload on ``event`` and emit the typed addon event."""
1010
+ message = event.message
1011
+ if not isinstance(message, dict):
1012
+ return
1013
+ try:
1014
+ proto_message = _message_to_proto(message)
1015
+ except Exception:
1016
+ return
1017
+ addon = identify_encrypted_addon(proto_message)
1018
+ if addon is None:
1019
+ return
1020
+ target_message_id = addon.target_message_key.id
1021
+ if not target_message_id:
1022
+ return
1023
+ parent = await resolve_parent_message_secret(
1024
+ target_message_id, self._message_secret_store, self._message_store
1025
+ )
1026
+ if parent is None:
1027
+ key = event.key
1028
+ context = {
1029
+ "id": key.id if key is not None else None,
1030
+ "targetId": target_message_id,
1031
+ "kind": addon.kind,
1032
+ }
1033
+ if unwrap_message(message).get("secretEncryptedMessage") is not None:
1034
+ self._logger.warn(
1035
+ "addon parent message secret not found - enable the `messages` "
1036
+ "mailbox to support decryption of secretEncryptedMessage "
1037
+ "addons on arbitrary parents",
1038
+ context,
1039
+ )
1040
+ else:
1041
+ self._logger.debug("addon parent message secret not found", context)
1042
+ return
1043
+ key = event.key
1044
+ if key is None:
1045
+ return
1046
+ raw_node = event.raw_node
1047
+ raw_attrs = raw_node.attrs if raw_node is not None else {}
1048
+ modification_sender_raw = key.participant or key.remote_jid
1049
+ if not modification_sender_raw:
1050
+ return
1051
+ modification_candidates = collect_unique_user_jids(
1052
+ raw_attrs.get("from") if key.from_me else None,
1053
+ modification_sender_raw,
1054
+ key.participant_alt,
1055
+ key.remote_jid_alt,
1056
+ raw_attrs.get("participant_pn"),
1057
+ raw_attrs.get("sender_pn"),
1058
+ raw_attrs.get("participant"),
1059
+ None if key.is_group else raw_attrs.get("from"),
1060
+ )
1061
+ key_parent_sender = resolve_addon_parent_sender_from_key(
1062
+ addon.target_message_key, bool(key.is_group)
1063
+ )
1064
+ parent_candidates = collect_unique_user_jids(
1065
+ key_parent_sender, parent.sender_jid
1066
+ )
1067
+ sender_pairs = build_addon_sender_pairs(
1068
+ parent_candidates=parent_candidates,
1069
+ modification_candidates=modification_candidates,
1070
+ )
1071
+ plaintext = decrypt_addon_payload_with_sender_fallback(
1072
+ message_secret=parent.secret,
1073
+ stanza_id=target_message_id,
1074
+ sender_pairs=sender_pairs,
1075
+ modification_type=addon.modification_type,
1076
+ ciphertext=addon.enc_payload,
1077
+ iv=addon.enc_iv,
1078
+ )
1079
+ decrypted = decode_addon_plaintext(addon.kind, plaintext)
1080
+ if decrypted.kind == "poll_vote" and isinstance(
1081
+ decrypted.payload, WAProto_pb2.Message.PollVoteMessage
1082
+ ):
1083
+ selected = list(decrypted.payload.selectedOptions)
1084
+ if len(selected) > 0:
1085
+ names = await resolve_poll_option_names(
1086
+ [bytes(option) for option in selected],
1087
+ target_message_id,
1088
+ self._message_store,
1089
+ )
1090
+ if names is not None:
1091
+ decrypted = replace(decrypted, selected_option_names=names)
1092
+ self._emit_addon(
1093
+ _client_types.WaIncomingAddonEvent(
1094
+ key=key,
1095
+ raw_node=raw_node,
1096
+ kind=cast(_client_types.WaAddonKind, addon.kind),
1097
+ target_message_id=target_message_id,
1098
+ decrypted=decrypted,
1099
+ raw=proto_message,
1100
+ offline=bool(event.offline),
1101
+ )
1102
+ )
1103
+
1104
+ async def _dispatch_receipt(
1105
+ self,
1106
+ jid: str,
1107
+ ids: str | Sequence[str],
1108
+ options: WaSendReceiptOptions,
1109
+ ) -> None:
1110
+ id_list = [ids] if isinstance(ids, str) else list(ids)
1111
+ if len(id_list) == 0:
1112
+ raise ValueError("sendReceipt requires at least one message id")
1113
+ await self._message_dispatch.send_receipt(
1114
+ WaSendReceiptInput(
1115
+ to=jid,
1116
+ id=id_list[0],
1117
+ type=options.type,
1118
+ participant=options.participant,
1119
+ recipient=options.recipient,
1120
+ category=options.category,
1121
+ from_=options.from_,
1122
+ t=options.t,
1123
+ peer_participant_pn=options.peer_participant_pn,
1124
+ list_ids=tuple(id_list[1:]) if len(id_list) > 1 else None,
1125
+ content=options.content,
1126
+ )
1127
+ )
1128
+
1129
+
1130
+ __all__ = [
1131
+ "MEDIA_UPLOAD_PATHS",
1132
+ "WaMediaRetryProtocol",
1133
+ "WaMediaUploadInput",
1134
+ "WaMediaUploadResult",
1135
+ "WaMessageCappingInfo",
1136
+ "WaMessageCappingType",
1137
+ "WaMessageCoordinator",
1138
+ "WaMessageCoordinatorDeps",
1139
+ "WaMessageDispatchProtocol",
1140
+ "WaMexQuerySocket",
1141
+ "WaPeerDataOperationProtocol",
1142
+ "WaReachoutTimelock",
1143
+ "WaRequestHistorySyncInput",
1144
+ "WaRequestHistorySyncResult",
1145
+ "WaRequestMediaReuploadOptions",
1146
+ "WaShareGroupHistoryInput",
1147
+ "WaShareGroupHistoryResult",
1148
+ "WaSyncSignalSessionOptions",
1149
+ "WaTrustedContactTokenProtocol",
1150
+ "WaUploadMediaOptions",
1151
+ "WaUploadMediaSource",
1152
+ "WaUploadMediaType",
1153
+ ]