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,1637 @@
1
+ """Outbound message dispatch
2
+ (mirrors ``src/client/coordinators/WaMessageDispatchCoordinator.ts``).
3
+
4
+ Ported: the group-history audience/fanout plumbing
5
+ (:class:`WaGroupHistoryAudience`, :func:`restrict_group_history_targets`,
6
+ :func:`resolve_outbound_stanza_shape`), the addressing-mode/sender helpers,
7
+ outgoing message-id generation, per-user ICDC resolution, app-state sync-key
8
+ wiring, the thin forwards (``sync_signal_session``, ``send_receipt``), and
9
+ the 1:1 signal-encrypting send pipeline (``send_message`` for direct chats,
10
+ ``publish_message_node``, ``publish_encrypted_message``,
11
+ ``publish_signal_message``, ``publish_protocol_message_to_device``).
12
+
13
+ Not yet ported: group sends (sender-key distribution), status and
14
+ broadcast-list publishes, the ``encrypt_*`` group-distribution helpers and
15
+ ``build_bot_sidecar_participant``; those methods raise
16
+ :class:`NotImplementedError` until the sender-key manager flow lands.
17
+
18
+ JID helpers come from :mod:`zapy._protocol.jid` (:func:`normalize_device_jid`
19
+ and :func:`to_user_jid` keep their :mod:`zapy._message.messaging` import
20
+ path for now; the logic is identical).
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import asyncio
26
+ import base64
27
+ import inspect
28
+ import struct
29
+ import time
30
+ from collections.abc import Awaitable, Callable, Mapping, Sequence
31
+ from dataclasses import asdict, dataclass, is_dataclass
32
+ from typing import Any, Literal, Protocol, TYPE_CHECKING
33
+
34
+ if TYPE_CHECKING:
35
+ from zapy._client.coordinators.message import WaSyncSignalSessionOptions
36
+
37
+ from google.protobuf.json_format import ParseDict
38
+
39
+ from zapy._auth.types import WaAuthCredentials
40
+ from zapy._client.types import WaSendMessageOptions
41
+ from zapy._crypto.core.primitives import md5_bytes, sha256
42
+ from zapy._crypto.core.random import random_bytes
43
+ from zapy._infra.log import Logger
44
+ from zapy._message.context_info import (
45
+ WaSendContextInfo,
46
+ WaSendContextResolveInput,
47
+ apply_context_info,
48
+ resolve_send_context_info,
49
+ )
50
+ from zapy._message.crypto import ensure_message_secret
51
+ from zapy._message.crypto.icdc import (
52
+ IcdcMeta,
53
+ LocalIdentity,
54
+ inject_device_list_metadata,
55
+ resolve_icdc_meta,
56
+ )
57
+ from zapy._message.crypto.reporting_token import build_reporting_token_artifacts
58
+ from zapy._message.encode.content import (
59
+ MessageDict,
60
+ WaOutboundMessageAttrs,
61
+ is_send_addon_crypto_message,
62
+ needs_secret_persistence,
63
+ resolve_outbound_message_attrs,
64
+ unwrap_message,
65
+ wrap_as_view_once,
66
+ )
67
+ from zapy._message.encode.device_sent import wrap_device_sent_message
68
+ from zapy._message.encode.padding import unpad_pkcs7, write_random_pad_max16
69
+ from zapy._message.messaging import (
70
+ PromiseDedup,
71
+ ServerClock,
72
+ is_group_jid,
73
+ normalize_device_jid,
74
+ to_user_jid,
75
+ )
76
+ from zapy._message.messaging.messages import (
77
+ WaBuildMessageContext,
78
+ assert_message_secret,
79
+ )
80
+ from zapy._signal.session import parse_signal_address_from_jid
81
+ from zapy._message.messaging.group_metadata import GroupMetadataCache
82
+ from zapy._message.messaging.key_protocol import AppStateSyncKeyProtocol
83
+ from zapy._message.types import (
84
+ WaEncryptedMessageInput,
85
+ WaMessagePublishOptions,
86
+ WaMessagePublishResult,
87
+ WaSendMessageContent,
88
+ WaSendReceiptInput,
89
+ )
90
+ from zapy._proto import WAProto_pb2
91
+ from zapy._protocol import defaults as _defaults
92
+ from zapy._protocol.jid import (
93
+ is_bot_jid,
94
+ is_lid_jid,
95
+ is_newsletter_jid,
96
+ is_user_jid,
97
+ normalize_recipient_jid,
98
+ )
99
+ from zapy._protocol.message import normalize_ephemeral_setting_seconds
100
+ from zapy._retry import (
101
+ WaRetryEncryptedReplayPayload,
102
+ WaRetryOpaqueNodeReplayPayload,
103
+ WaRetryPlaintextReplayPayload,
104
+ )
105
+ from zapy._retry.tracker import OutboundRetryTrackHint
106
+ from zapy._signal.session.protocol import EncryptRequest, PrefetchedSession
107
+ from zapy._store.contracts.chat_metadata import WaChatMetadataSnapshot
108
+ from zapy._store.contracts.message_secret import WaMessageSecretEntry
109
+ from zapy._transport.binary.encoder import encode_binary_node
110
+ from zapy._transport.node.builders.message import (
111
+ DirectMessageFanoutInput,
112
+ EncryptedParticipant,
113
+ build_button_addon_node,
114
+ build_direct_message_fanout_node,
115
+ build_meta_node,
116
+ )
117
+ from zapy._store.contracts.chat_metadata import WaChatMetadataStore
118
+ from zapy._store.contracts.device_list import WaDeviceListStore
119
+ from zapy._store.contracts.identity import WaIdentityStore
120
+ from zapy._store.contracts.message_secret import WaMessageSecretStore
121
+ from zapy._store.contracts.session import WaSessionStore
122
+ from zapy._store.contracts.signal import WaSignalStore
123
+ from zapy._store.contracts.thread import WaThreadStore
124
+ from zapy._transport.types import BinaryNode
125
+ from zapy._util.bytes import bytes_to_hex
126
+ from zapy._util.primitives import to_error
127
+
128
+ # Verbatim ``src/protocol/message.ts`` (stale-addressing nack code).
129
+ _STALE_GROUP_ADDRESSING_MODE = 466
130
+
131
+ _INITIATOR_CHANGED_IN_CHAT = WAProto_pb2.DisappearingMode.Initiator.Value(
132
+ "CHANGED_IN_CHAT"
133
+ )
134
+ _TRIGGER_CHAT_SETTING = WAProto_pb2.DisappearingMode.Trigger.Value("CHAT_SETTING")
135
+ _EDIT_MESSAGE_TYPE = WAProto_pb2.Message.ProtocolMessage.Type.Value("MESSAGE_EDIT")
136
+
137
+ #: ``WaSendMessageOptions`` (snake_case) to normalized send dict (camelCase).
138
+ _SEND_OPTION_ATTRS: tuple[tuple[str, str], ...] = (
139
+ ("id", "id"),
140
+ ("expected_identity", "expectedIdentity"),
141
+ ("context_info", "contextInfo"),
142
+ ("quote", "quote"),
143
+ ("forward", "forward"),
144
+ ("mentions", "mentions"),
145
+ ("expiration_seconds", "expirationSeconds"),
146
+ ("ephemeral_setting_timestamp", "ephemeralSettingTimestamp"),
147
+ ("disappearing_mode_trigger", "disappearingModeTrigger"),
148
+ ("disable_group_ephemeral_auto_inject", "disableGroupEphemeralAutoInject"),
149
+ ("disable_direct_ephemeral_auto_inject", "disableDirectEphemeralAutoInject"),
150
+ ("custom_nodes", "customNodes"),
151
+ ("view_once", "viewOnce"),
152
+ ("edit_key", "editKey"),
153
+ ("message_secret", "messageSecret"),
154
+ ("additional_attributes", "additionalAttributes"),
155
+ )
156
+
157
+ _CONTEXT_INFO_OPTION_ATTRS: tuple[str, ...] = (
158
+ "quoted_message_id",
159
+ "quoted_participant",
160
+ "quoted_remote_jid",
161
+ "quoted_message",
162
+ "is_forwarded",
163
+ "forwarding_score",
164
+ "mentioned_jids",
165
+ "is_spoiler",
166
+ "expiration_seconds",
167
+ "ephemeral_setting_timestamp",
168
+ "disappearing_mode_initiator",
169
+ "disappearing_mode_trigger",
170
+ "group_subject",
171
+ "parent_group_jid",
172
+ "raw",
173
+ )
174
+
175
+
176
+ async def _maybe_await_result(value: Any) -> Any:
177
+ """Await ``value`` when it is awaitable, else return it unchanged."""
178
+ if inspect.isawaitable(value):
179
+ return await value
180
+ return value
181
+
182
+
183
+ def _normalize_send_options_dict(
184
+ options: dict[str, Any] | WaSendMessageOptions | None,
185
+ ) -> dict[str, Any]:
186
+ """Normalize send options to a camelCase dict (mirrors the TS shape)."""
187
+ if options is None:
188
+ return {}
189
+ if isinstance(options, dict):
190
+ return dict(options)
191
+ normalized: dict[str, Any] = {}
192
+ for snake, camel in _SEND_OPTION_ATTRS:
193
+ value = getattr(options, snake, None)
194
+ if value is not None:
195
+ normalized[camel] = value
196
+ return normalized
197
+
198
+
199
+ def _normalize_publish_options(
200
+ options: WaMessagePublishOptions | Mapping[str, Any] | None,
201
+ ) -> WaMessagePublishOptions | None:
202
+ """Coerce publish options (None, dataclass, or snake/camel dict)."""
203
+ if options is None or isinstance(options, WaMessagePublishOptions):
204
+ return options
205
+ if not isinstance(options, Mapping):
206
+ raise ValueError(
207
+ "invalid message publish options: "
208
+ f"{type(options).__name__} (expected mapping)"
209
+ )
210
+ known: dict[str, Any] = {}
211
+ for snake, camel in (
212
+ ("ack_timeout_ms", "ackTimeoutMs"),
213
+ ("max_attempts", "maxAttempts"),
214
+ ("retry_delay_ms", "retryDelayMs"),
215
+ ):
216
+ raw = options.get(snake, options.get(camel))
217
+ if raw is not None:
218
+ known[snake] = raw
219
+ unknown = [
220
+ key
221
+ for key in options
222
+ if key
223
+ not in (
224
+ "ack_timeout_ms",
225
+ "ackTimeoutMs",
226
+ "max_attempts",
227
+ "maxAttempts",
228
+ "retry_delay_ms",
229
+ "retryDelayMs",
230
+ )
231
+ ]
232
+ if unknown:
233
+ raise ValueError(
234
+ "invalid message publish options: "
235
+ f"unknown fields {', '.join(sorted(str(key) for key in unknown))}"
236
+ )
237
+ return WaMessagePublishOptions(**known)
238
+
239
+
240
+ def _normalize_send_content(
241
+ content: WaSendMessageContent,
242
+ ) -> tuple[str | MessageDict, Any | None]:
243
+ """Split send content into builder input plus content-level context info."""
244
+ if isinstance(content, str):
245
+ return content, None
246
+ if isinstance(content, dict):
247
+ return content, content.get("contextInfo")
248
+ if is_dataclass(content) and not isinstance(content, type):
249
+ # DEVIATION: the TS input is a plain object; the facade passes
250
+ # dataclasses (``WaSendTextMessage``, ...). ``asdict`` yields the
251
+ # dict shape the builder guards match (``type``/``text``/...).
252
+ builder_input: MessageDict = asdict(content)
253
+ return builder_input, getattr(content, "context_info", None)
254
+ raise ValueError(f"invalid message content: {type(content).__name__}")
255
+
256
+
257
+ def _coerce_context_info(value: Any) -> WaSendContextInfo | None:
258
+ """Coerce an options-level context to :class:`WaSendContextInfo`."""
259
+ if value is None or isinstance(value, WaSendContextInfo):
260
+ return value
261
+ if isinstance(value, Mapping):
262
+ known = {key: value[key] for key in _CONTEXT_INFO_OPTION_ATTRS if key in value}
263
+ return WaSendContextInfo(**known)
264
+ raise ValueError(
265
+ "invalid send contextInfo: "
266
+ f"{type(value).__name__} (expected WaSendContextInfo or mapping)"
267
+ )
268
+
269
+
270
+ def _json_safe_message(value: Any) -> Any:
271
+ """Convert bytes to base64 strings so a dict survives ``ParseDict``."""
272
+ if isinstance(value, dict):
273
+ return {key: _json_safe_message(item) for key, item in value.items()}
274
+ if isinstance(value, (bytes, bytearray)):
275
+ return base64.b64encode(bytes(value)).decode("ascii")
276
+ if isinstance(value, (list, tuple)):
277
+ return [_json_safe_message(item) for item in value]
278
+ return value
279
+
280
+
281
+ def _message_dict_to_proto(message: MessageDict) -> WAProto_pb2.Message:
282
+ """Encode a message dict to a proto (bytes fields ride base64)."""
283
+ proto_message = ParseDict(_json_safe_message(message), WAProto_pb2.Message())
284
+ if not isinstance(proto_message, WAProto_pb2.Message):
285
+ raise ValueError("message proto encode produced no message")
286
+ return proto_message
287
+
288
+
289
+ def _resolve_edit_target(edit_key: Any) -> tuple[str | None, str | None, int | None]:
290
+ """Split an edit key into ``(id, participant, timestamp_ms)``."""
291
+ if edit_key is None:
292
+ return None, None, None
293
+ if isinstance(edit_key, Mapping):
294
+ raw_node = edit_key.get("rawNode")
295
+ if isinstance(raw_node, Mapping):
296
+ key = raw_node.get("key")
297
+ nested: Any = key if isinstance(key, Mapping) else edit_key
298
+ else:
299
+ key = edit_key.get("key")
300
+ nested = key if isinstance(key, Mapping) else edit_key
301
+ edit_id = nested.get("id")
302
+ participant = nested.get("participant")
303
+ timestamp = nested.get("timestampMs", nested.get("timestamp_ms"))
304
+ timestamp_ms = (
305
+ int(timestamp)
306
+ if isinstance(timestamp, (int, float)) and timestamp >= 0
307
+ else None
308
+ )
309
+ return (
310
+ str(edit_id) if edit_id is not None else None,
311
+ str(participant) if participant is not None else None,
312
+ timestamp_ms,
313
+ )
314
+ edit_id = getattr(edit_key, "id", None)
315
+ participant = getattr(edit_key, "participant", None)
316
+ timestamp = getattr(
317
+ edit_key, "timestamp_ms", getattr(edit_key, "timestampMs", None)
318
+ )
319
+ timestamp_ms = (
320
+ int(timestamp)
321
+ if isinstance(timestamp, (int, float)) and timestamp >= 0
322
+ else None
323
+ )
324
+ return (
325
+ str(edit_id) if edit_id is not None else None,
326
+ str(participant) if participant is not None else None,
327
+ timestamp_ms,
328
+ )
329
+
330
+
331
+ @dataclass(frozen=True, slots=True)
332
+ class WaGroupHistoryAudience:
333
+ """Membership split behind a group-history share, in the group's addressing mode."""
334
+
335
+ history_receivers: tuple[str, ...] = ()
336
+ non_history_receivers: tuple[str, ...] = ()
337
+ unknown_jids: tuple[str, ...] = ()
338
+ requested_self: bool = False
339
+ addressing_mode: Literal["pn", "lid"] = "pn"
340
+
341
+
342
+ @dataclass(frozen=True, slots=True)
343
+ class WaOutgoingMessageEvent:
344
+ """Outbound decrypted message event (``message_send`` emission)."""
345
+
346
+ to: str
347
+ id: str | None = None
348
+ message: MessageDict | None = None
349
+
350
+
351
+ class OutboundRetryTracker(Protocol):
352
+ """Tracks publishes for later retry-replay (mirrors ``OutboundRetryTracker``)."""
353
+
354
+ async def track(
355
+ self,
356
+ hint: OutboundRetryTrackHint,
357
+ publish: Callable[[], Awaitable[WaMessagePublishResult]],
358
+ ) -> WaMessagePublishResult: ...
359
+
360
+
361
+ class WaMessageDispatchCoordinator:
362
+ """Encrypts and publishes outbound messages (1:1 fanout and group sender key)."""
363
+
364
+ def __init__(self, options: WaMessageDispatchOptions) -> None:
365
+ self._deps = options
366
+ self._icdc_dedup = PromiseDedup()
367
+ self._privacy_token_dedup = PromiseDedup()
368
+ self._distribution_dedup = PromiseDedup()
369
+ self._server_clock = options.server_clock
370
+ self._mobile_message_id_format = options.mobile_message_id_format or (
371
+ lambda: False
372
+ )
373
+
374
+ async def resolve_group_history_audience(
375
+ self, group_jid: str, requested_jids: list[str]
376
+ ) -> WaGroupHistoryAudience:
377
+ """Split group members into history receivers and the rest."""
378
+ participants = await self._deps.group_metadata_cache.resolve_participant_users(
379
+ group_jid
380
+ )
381
+ me_jid = self._require_current_me_jid("shareGroupHistory")
382
+ addressing_mode = self.resolve_group_addressing_mode(
383
+ list(participants), group_jid
384
+ )
385
+ me_user_jid = to_user_jid(
386
+ self.resolve_sender_for_addressing_mode(addressing_mode, me_jid)
387
+ )
388
+ pending: set[str] = set()
389
+ for requested in requested_jids:
390
+ pending.add(to_user_jid(normalize_recipient_jid(requested)))
391
+ history_receivers: list[str] = []
392
+ non_history_receivers: list[str] = []
393
+ for participant in participants:
394
+ participant_user_jid = to_user_jid(participant)
395
+ if participant_user_jid == me_user_jid:
396
+ continue
397
+ if participant_user_jid in pending:
398
+ pending.discard(participant_user_jid)
399
+ history_receivers.append(participant_user_jid)
400
+ else:
401
+ non_history_receivers.append(participant_user_jid)
402
+ requested_self = me_user_jid in pending
403
+ pending.discard(me_user_jid)
404
+ return WaGroupHistoryAudience(
405
+ history_receivers=tuple(history_receivers),
406
+ non_history_receivers=tuple(non_history_receivers),
407
+ unknown_jids=tuple(pending),
408
+ requested_self=requested_self,
409
+ addressing_mode=addressing_mode,
410
+ )
411
+
412
+ def resolve_group_addressing_mode(
413
+ self, participant_user_jids: list[str], group_jid: str
414
+ ) -> Literal["pn", "lid"]:
415
+ """Return ``lid`` when any member is LID-addressed, else ``pn``."""
416
+ for participant in participant_user_jids:
417
+ if is_lid_jid(participant):
418
+ return "lid"
419
+ self._deps.logger.trace(
420
+ "group addressing mode resolved to pn (default)",
421
+ {"groupJid": group_jid, "participants": len(participant_user_jids)},
422
+ )
423
+ return "pn"
424
+
425
+ def resolve_outgoing_secret_sender_jid(self) -> str:
426
+ """Parent-author JID stored with an outgoing message secret."""
427
+ credentials = self._deps.get_current_credentials()
428
+ me_lid = credentials.me_lid if credentials else None
429
+ if me_lid and "@" in me_lid:
430
+ try:
431
+ return to_user_jid(me_lid)
432
+ except ValueError as error:
433
+ self._deps.logger.trace(
434
+ "ignoring malformed me lid jid",
435
+ {"meLid": me_lid, "message": str(to_error(error))},
436
+ )
437
+ me_jid = credentials.me_jid if credentials else None
438
+ if me_jid and "@" in me_jid:
439
+ try:
440
+ return to_user_jid(me_jid)
441
+ except ValueError as error:
442
+ self._deps.logger.trace(
443
+ "ignoring malformed me jid",
444
+ {"meJid": me_jid, "message": str(to_error(error))},
445
+ )
446
+ return ""
447
+
448
+ def resolve_sender_for_addressing_mode(
449
+ self, addressing_mode: Literal["pn", "lid"], me_jid: str
450
+ ) -> str:
451
+ """Sender JID matching the group's addressing mode."""
452
+ if addressing_mode == "lid":
453
+ credentials = self._deps.get_current_credentials()
454
+ me_lid = credentials.me_lid if credentials else None
455
+ if me_lid and "@" in me_lid:
456
+ try:
457
+ return normalize_device_jid(me_lid)
458
+ except ValueError as error:
459
+ self._deps.logger.trace(
460
+ "ignoring malformed me lid jid",
461
+ {"meLid": me_lid, "message": str(to_error(error))},
462
+ )
463
+ return normalize_device_jid(me_jid)
464
+
465
+ async def with_resolved_message_id(self, options: dict[str, Any]) -> dict[str, Any]:
466
+ """Return ``options`` with a generated ``id`` when it lacks a blank-free one."""
467
+ normalized_id = options.get("id")
468
+ if isinstance(normalized_id, str) and normalized_id.strip():
469
+ if normalized_id == normalized_id.strip():
470
+ return options
471
+ return {**options, "id": normalized_id.strip()}
472
+ return {**options, "id": await self.generate_outgoing_message_id()}
473
+
474
+ async def generate_outgoing_message_id(self) -> str:
475
+ """Generate an outgoing stanza id (mobile hex or ``3EB0``-prefixed hash)."""
476
+ try:
477
+ me_user_jid = to_user_jid(self._require_current_me_jid("sendMessage"))
478
+ if self._mobile_message_id_format():
479
+ timestamp_bytes = struct.pack(">Q", int(time.time() * 1000))
480
+ digest = md5_bytes(
481
+ timestamp_bytes + me_user_jid.encode("utf-8") + random_bytes(16)
482
+ )
483
+ mutable = bytearray(digest)
484
+ mutable[0] = 0xAC
485
+ return bytes_to_hex(mutable).upper()
486
+ timestamp_bytes = struct.pack(">Q", int(time.time()))
487
+ digest = sha256(
488
+ timestamp_bytes + me_user_jid.encode("utf-8") + random_bytes(8)
489
+ )
490
+ return f"3EB0{bytes_to_hex(digest[:9]).upper()}"
491
+ except Exception as error:
492
+ self._deps.logger.warn(
493
+ "failed to generate message id, falling back to random",
494
+ {"message": str(to_error(error))},
495
+ )
496
+ if self._mobile_message_id_format():
497
+ fallback = bytearray(random_bytes(16))
498
+ fallback[0] = 0xAC
499
+ return bytes_to_hex(fallback).upper()
500
+ return f"3EB0{bytes_to_hex(random_bytes(8)).upper()}"
501
+
502
+ async def resolve_user_icdc(
503
+ self,
504
+ user_jid: str,
505
+ local_identity: LocalIdentity | None = None,
506
+ ) -> IcdcMeta | None:
507
+ """Resolve the ICDC metadata for one side of a device fanout."""
508
+ suffix = "1" if local_identity is not None else "0"
509
+ return await self._icdc_dedup.run(
510
+ f"icdc:{user_jid}:{suffix}",
511
+ lambda: self._resolve_user_icdc_inner(user_jid, local_identity),
512
+ )
513
+
514
+ async def _resolve_user_icdc_inner(
515
+ self,
516
+ user_jid: str,
517
+ local_identity: LocalIdentity | None,
518
+ ) -> IcdcMeta | None:
519
+ try:
520
+ snapshots = await self._deps.device_list_store.get_user_devices_batch(
521
+ [user_jid]
522
+ )
523
+ snapshot = snapshots[0] if snapshots else None
524
+ if snapshot is None or len(snapshot.device_jids) == 0:
525
+ return None
526
+ return await resolve_icdc_meta(
527
+ snapshot.device_jids,
528
+ self._deps.identity_store,
529
+ snapshot.updated_at_ms,
530
+ local_identity,
531
+ self._deps.get_icdc_hash_length()
532
+ if self._deps.get_icdc_hash_length is not None
533
+ else None,
534
+ )
535
+ except Exception as error:
536
+ self._deps.logger.trace(
537
+ "icdc resolution failed",
538
+ {"userJid": user_jid, "message": str(to_error(error))},
539
+ )
540
+ return None
541
+
542
+ async def request_app_state_sync_keys(self, key_ids: list[bytes]) -> Sequence[str]:
543
+ """Request app-state sync keys by id."""
544
+ return await self._deps.app_state_sync_key_protocol.request_keys(key_ids)
545
+
546
+ async def send_app_state_sync_key_share(
547
+ self,
548
+ to_device_jid: str,
549
+ keys: list[Any],
550
+ missing_key_ids: list[bytes] | None = None,
551
+ ) -> None:
552
+ """Share app-state sync keys with one device."""
553
+ await self._deps.app_state_sync_key_protocol.send_key_share(
554
+ to_device_jid, keys, missing_key_ids or []
555
+ )
556
+
557
+ async def mutate_group_metadata_cache_from_group_event(self, event: Any) -> None:
558
+ """Apply a group event to the cached group metadata."""
559
+ task = self._deps.group_metadata_cache.mutate_from_group_event(event)
560
+ await task
561
+
562
+ async def sync_signal_session(
563
+ self,
564
+ jid: str,
565
+ options: WaSyncSignalSessionOptions | None = None,
566
+ ) -> None:
567
+ """Ensure a Signal session for a 1:1 JID, optionally dropping the old one."""
568
+ force = options.force if options is not None else False
569
+ reason_identity = options.reason_identity if options is not None else False
570
+ address = parse_signal_address_from_jid(jid)
571
+ if address.server == _defaults.GROUP_SERVER:
572
+ raise ValueError("syncSignalSession supports only direct chats")
573
+ if force or reason_identity:
574
+ await self._deps.session_store.delete_session(address)
575
+ await self._deps.session_resolver.ensure_session(
576
+ address, jid, None, reason_identity
577
+ )
578
+
579
+ async def send_receipt(self, receipt: WaSendReceiptInput) -> None:
580
+ """Send a message receipt via the message client."""
581
+ await self._deps.message_client.send_receipt(receipt)
582
+
583
+ def try_build_reporting_token_artifacts(
584
+ self,
585
+ message: MessageDict,
586
+ stanza_id: str | None,
587
+ sender_user_jid: str,
588
+ remote_jid: str,
589
+ context: str,
590
+ message_bytes: bytes | bytearray | None = None,
591
+ ) -> Any | None:
592
+ """Build reporting-token artifacts, or ``None`` on any failure."""
593
+ if not stanza_id:
594
+ return None
595
+ try:
596
+ # DEVIATION: synchronous; the TS version awaits only because its
597
+ # hkdf/hmac helpers are async. The dict message is converted to
598
+ # proto via the standard JSON mapping (camelCase names match).
599
+ from google.protobuf.json_format import ParseDict
600
+
601
+ from zapy._proto import WAProto_pb2
602
+
603
+ proto_message = ParseDict(message, WAProto_pb2.Message())
604
+ return build_reporting_token_artifacts(
605
+ message=proto_message,
606
+ stanza_id=stanza_id,
607
+ sender_user_jid=sender_user_jid,
608
+ remote_jid=remote_jid,
609
+ message_bytes=message_bytes,
610
+ )
611
+ except Exception as error:
612
+ self._deps.logger.warn(
613
+ "failed to generate reporting token",
614
+ {
615
+ "context": context,
616
+ "id": stanza_id,
617
+ "remoteJid": remote_jid,
618
+ "message": str(to_error(error)),
619
+ },
620
+ )
621
+ return None
622
+
623
+ def get_encoded_signed_device_identity(self) -> bytes | None:
624
+ """Encoded signed device identity, or ``None`` when not registered."""
625
+ credentials = self._deps.get_current_credentials()
626
+ signed_identity = credentials.signed_pre_identity if credentials else None
627
+ if signed_identity is None:
628
+ return None
629
+ if isinstance(signed_identity, (bytes, bytearray)):
630
+ return bytes(signed_identity)
631
+ serialize = getattr(signed_identity, "SerializeToString", None)
632
+ if callable(serialize):
633
+ return bytes(serialize())
634
+ return None
635
+
636
+ def _require_current_me_jid(self, context: str) -> str:
637
+ credentials = self._deps.get_current_credentials()
638
+ me_jid = credentials.me_jid if credentials else None
639
+ if me_jid:
640
+ return me_jid
641
+ raise ValueError(f"{context} requires registered meJid")
642
+
643
+ def _current_me_lid(self) -> str | None:
644
+ """This account's LID, or ``None`` when not a string."""
645
+ credentials = self._deps.get_current_credentials()
646
+ me_lid = credentials.me_lid if credentials else None
647
+ return me_lid if isinstance(me_lid, str) else None
648
+
649
+ def _require_dep(self, name: str) -> Any:
650
+ """Return an optional ``Any`` dependency, raising when missing."""
651
+ value: Any = getattr(self._deps, name)
652
+ if value is None:
653
+ raise ValueError(f"sendMessage requires the {name} dependency")
654
+ return value
655
+
656
+ async def _send_newsletter_message(
657
+ self,
658
+ recipient_jid: str,
659
+ content: WaSendMessageContent,
660
+ opts: dict[str, Any],
661
+ ) -> WaMessagePublishResult:
662
+ """Delegate a newsletter send with quote/compat-checked context."""
663
+ sender = self._deps.send_newsletter_message
664
+ if sender is None:
665
+ raise ValueError(
666
+ "newsletter sendMessage requires sendNewsletterMessage dependency"
667
+ )
668
+ _, content_level = _normalize_send_content(content)
669
+ newsletter_ctx = resolve_send_context_info(
670
+ WaSendContextResolveInput(
671
+ content_level=content_level
672
+ if isinstance(content_level, WaSendContextInfo)
673
+ else _coerce_context_info(content_level),
674
+ options_level=_coerce_context_info(opts.get("contextInfo")),
675
+ quote=opts.get("quote"),
676
+ forward=opts.get("forward"),
677
+ mentions=opts.get("mentions"),
678
+ )
679
+ )
680
+ unsupported: list[str] = []
681
+ if newsletter_ctx is not None:
682
+ if newsletter_ctx.quoted_message_id is not None:
683
+ unsupported.append("quote")
684
+ if newsletter_ctx.mentioned_jids:
685
+ unsupported.append("mentions")
686
+ if newsletter_ctx.is_spoiler is True:
687
+ unsupported.append("isSpoiler")
688
+ if (
689
+ newsletter_ctx.group_subject is not None
690
+ or newsletter_ctx.parent_group_jid is not None
691
+ ):
692
+ unsupported.append("group invite reply (groupSubject/parentGroupJid)")
693
+ if unsupported:
694
+ raise ValueError(
695
+ "newsletter sends do not support: " + ", ".join(unsupported)
696
+ )
697
+ send_options = await self.with_resolved_message_id(opts)
698
+ outcome = await _maybe_await_result(
699
+ sender(recipient_jid, content, send_options, newsletter_ctx)
700
+ )
701
+ if isinstance(outcome, WaMessagePublishResult):
702
+ return outcome
703
+ raise ValueError("newsletter send did not return a publish result")
704
+
705
+ async def _build_and_resolve_id(
706
+ self,
707
+ content_input: str | MessageDict,
708
+ recipient_jid: str,
709
+ opts: dict[str, Any],
710
+ ) -> tuple[Any, dict[str, Any]]:
711
+ """Build the message while resolving the outgoing stanza id."""
712
+ build_task = self._require_dep("build_message_content")(
713
+ content_input, WaBuildMessageContext(to=recipient_jid)
714
+ )
715
+ id_task = self.with_resolved_message_id(opts)
716
+ built, send_options = await asyncio.gather(build_task, id_task)
717
+ return built, send_options
718
+
719
+ async def _resolve_direct_recipient_lid(self, user_jid: str) -> str:
720
+ """LID-addressed recipient for a 1:1 send (PN passthrough when unknown)."""
721
+ if is_lid_jid(user_jid):
722
+ return user_jid
723
+ pair = await self._require_dep("signal_device_sync").resolve_user_jid_pair(
724
+ user_jid
725
+ )
726
+ lid_jid = getattr(pair, "lid_jid", None)
727
+ if isinstance(lid_jid, str) and lid_jid:
728
+ return lid_jid
729
+ return user_jid
730
+
731
+ async def _resolve_peer_recipient_pn(
732
+ self, recipient_user_jid: str, direct_recipient_jid: str
733
+ ) -> str | None:
734
+ """Cross-reference PN for a LID-addressed 1:1 send, else ``None``."""
735
+ if not is_lid_jid(direct_recipient_jid):
736
+ return None
737
+ if is_user_jid(recipient_user_jid):
738
+ return recipient_user_jid
739
+ pair = await self._require_dep("signal_device_sync").resolve_user_jid_pair(
740
+ direct_recipient_jid
741
+ )
742
+ pn_jid = getattr(pair, "pn_jid", None)
743
+ return pn_jid if isinstance(pn_jid, str) and pn_jid else None
744
+
745
+ async def _merge_ephemeral_context(
746
+ self,
747
+ recipient_jid: str,
748
+ direct_recipient_jid: str,
749
+ opts: dict[str, Any],
750
+ ) -> WaSendContextInfo | None:
751
+ """Merge chat disappearing settings under explicit send options."""
752
+ explicit = _coerce_context_info(opts.get("contextInfo"))
753
+ explicit_fields = (
754
+ {
755
+ name: getattr(explicit, name)
756
+ for name in _CONTEXT_INFO_OPTION_ATTRS
757
+ if getattr(explicit, name) is not None
758
+ }
759
+ if explicit is not None
760
+ else {}
761
+ )
762
+ # Groups raise NotImplementedError before this runs; the group flag is
763
+ # kept for the day the sender-key flow lands.
764
+ disabled = (
765
+ opts.get("disableDirectEphemeralAutoInject")
766
+ if not is_group_jid(recipient_jid)
767
+ else opts.get("disableGroupEphemeralAutoInject")
768
+ )
769
+ auto_fields: dict[str, Any] = {}
770
+ if not disabled:
771
+ auto_fields = await self._resolve_chat_ephemeral(direct_recipient_jid)
772
+ merged = {**auto_fields, **explicit_fields}
773
+ if not merged:
774
+ return None
775
+ return WaSendContextInfo(**merged)
776
+
777
+ async def _resolve_chat_ephemeral(self, recipient_jid: str) -> dict[str, Any]:
778
+ """Disappearing-message fields for one recipient, or ``{}`` when unset.
779
+
780
+ Group expirations come from the group metadata cache; 1:1 chats fall
781
+ back to the durable thread record on a cold metadata miss. A failing
782
+ store degrades the send to no ephemeral fields instead of rejecting
783
+ it (the store is opt-in persistence, not a send dependency).
784
+ """
785
+ if is_group_jid(recipient_jid):
786
+ try:
787
+ settings = (
788
+ await self._deps.group_metadata_cache.resolve_ephemeral_settings(
789
+ recipient_jid
790
+ )
791
+ )
792
+ except Exception as error:
793
+ self._deps.logger.debug(
794
+ "chat metadata lookup failed, sending without ephemeral fields",
795
+ {"jid": recipient_jid, "message": str(to_error(error))},
796
+ )
797
+ return {}
798
+ if settings is None or settings.expiration_seconds <= 0:
799
+ return {}
800
+ fields: dict[str, Any] = {
801
+ "expiration_seconds": settings.expiration_seconds,
802
+ "disappearing_mode_initiator": _INITIATOR_CHANGED_IN_CHAT,
803
+ }
804
+ if settings.trigger is not None:
805
+ fields["disappearing_mode_trigger"] = settings.trigger
806
+ return fields
807
+ try:
808
+ chat = await self._deps.chat_metadata_store.get_chat_metadata(recipient_jid)
809
+ if chat is None:
810
+ thread = await self._deps.thread_store.get_by_jid(recipient_jid)
811
+ expiration = thread.ephemeral_expiration if thread is not None else None
812
+ expiration_value = expiration if expiration is not None else 0
813
+ setting_timestamp = (
814
+ thread.ephemeral_setting_timestamp if thread is not None else None
815
+ )
816
+ snapshot = WaChatMetadataSnapshot(
817
+ chat_jid=recipient_jid,
818
+ ephemeral_expiration=expiration_value,
819
+ ephemeral_setting_timestamp=setting_timestamp
820
+ if expiration_value > 0
821
+ else None,
822
+ updated_at_ms=int(time.time() * 1000),
823
+ )
824
+ await self._deps.chat_metadata_store.upsert_chat_metadata(snapshot)
825
+ chat = snapshot
826
+ except Exception as error:
827
+ self._deps.logger.debug(
828
+ "chat metadata lookup failed, sending without ephemeral fields",
829
+ {"jid": recipient_jid, "message": str(to_error(error))},
830
+ )
831
+ return {}
832
+ expiration = chat.ephemeral_expiration
833
+ if expiration is None or expiration <= 0:
834
+ return {}
835
+ stored = chat.ephemeral_setting_timestamp
836
+ direct_fields: dict[str, Any] = {
837
+ "expiration_seconds": expiration,
838
+ "disappearing_mode_initiator": _INITIATOR_CHANGED_IN_CHAT,
839
+ "disappearing_mode_trigger": _TRIGGER_CHAT_SETTING,
840
+ }
841
+ if stored is not None:
842
+ direct_fields["ephemeral_setting_timestamp"] = (
843
+ normalize_ephemeral_setting_seconds(stored)
844
+ )
845
+ return direct_fields
846
+
847
+ def _apply_edit_wrapper(
848
+ self, message: MessageDict, recipient_jid: str, opts: dict[str, Any]
849
+ ) -> MessageDict:
850
+ """Wrap ``message`` in a ``MESSAGE_EDIT`` protocol message when asked."""
851
+ edit_id, edit_participant, edit_timestamp = _resolve_edit_target(
852
+ opts.get("editKey")
853
+ )
854
+ if edit_id is None:
855
+ return message
856
+ key: MessageDict = {
857
+ "remoteJid": recipient_jid,
858
+ "fromMe": True,
859
+ "id": edit_id,
860
+ }
861
+ if edit_participant is not None:
862
+ key["participant"] = edit_participant
863
+ return {
864
+ "protocolMessage": {
865
+ "type": _EDIT_MESSAGE_TYPE,
866
+ "key": key,
867
+ "editedMessage": message,
868
+ "timestampMs": edit_timestamp
869
+ if edit_timestamp is not None
870
+ else self._server_clock_now_ms(),
871
+ }
872
+ }
873
+
874
+ def _server_clock_now_ms(self) -> int:
875
+ """Current time in ms from the server clock."""
876
+ return self._server_clock.now_ms()
877
+
878
+ def _apply_message_secret_override(
879
+ self, message: MessageDict, opts: dict[str, Any]
880
+ ) -> MessageDict:
881
+ """Attach an explicit ``options.messageSecret`` to the message."""
882
+ secret = opts.get("messageSecret")
883
+ if secret is None:
884
+ return message
885
+ context = dict(message.get("messageContextInfo") or {})
886
+ context["messageSecret"] = assert_message_secret(
887
+ secret, "options.messageSecret"
888
+ )
889
+ return {**message, "messageContextInfo": context}
890
+
891
+ async def _persist_outgoing_secret(
892
+ self,
893
+ proto_message: WAProto_pb2.Message,
894
+ message: MessageDict,
895
+ stanza_id: Any | None,
896
+ recipient_jid: str,
897
+ ) -> None:
898
+ """Persist the outgoing message secret for polls/events/bots (or all)."""
899
+ raw_secret = bytes(proto_message.messageContextInfo.messageSecret)
900
+ if (
901
+ not raw_secret
902
+ or not isinstance(stanza_id, str)
903
+ or not stanza_id
904
+ or (
905
+ not self._deps.persist_all_message_secrets
906
+ and not needs_secret_persistence(message)
907
+ )
908
+ ):
909
+ return
910
+ try:
911
+ await self._deps.message_secret_store.set(
912
+ stanza_id,
913
+ WaMessageSecretEntry(
914
+ secret=raw_secret,
915
+ sender_jid=self.resolve_outgoing_secret_sender_jid(),
916
+ ),
917
+ )
918
+ except Exception as error:
919
+ self._deps.logger.warn(
920
+ "failed to persist outgoing message secret",
921
+ {
922
+ "id": stanza_id,
923
+ "to": recipient_jid,
924
+ "message": str(to_error(error)),
925
+ },
926
+ )
927
+
928
+ async def _resolve_sender_icdc_for_publish(
929
+ self, me_jid: str, me_user_jid: str
930
+ ) -> IcdcMeta | None:
931
+ """Sender ICDC metadata for a protocol-message publish."""
932
+ try:
933
+ reg_info = await self._deps.signal_store.get_registration_info()
934
+ except Exception as error:
935
+ self._deps.logger.trace(
936
+ "icdc registration lookup failed",
937
+ {"message": str(to_error(error))},
938
+ )
939
+ return None
940
+ local_pub_key = (
941
+ reg_info.identity_key_pair.pub_key if reg_info is not None else None
942
+ )
943
+ local_identity = (
944
+ LocalIdentity(
945
+ address=parse_signal_address_from_jid(me_jid),
946
+ pub_key=bytes(local_pub_key),
947
+ )
948
+ if local_pub_key is not None
949
+ else None
950
+ )
951
+ return await self.resolve_user_icdc(me_user_jid, local_identity)
952
+
953
+ def _assemble_custom_nodes(
954
+ self, attrs: WaOutboundMessageAttrs, opts: dict[str, Any]
955
+ ) -> list[BinaryNode]:
956
+ """Meta/biz companions plus caller custom nodes for one send."""
957
+ custom_nodes: list[BinaryNode] = []
958
+ meta_attrs = attrs.get("metaAttrs")
959
+ if meta_attrs:
960
+ custom_nodes.append(
961
+ build_meta_node({key: str(value) for key, value in meta_attrs.items()})
962
+ )
963
+ button_addon_kind = attrs.get("buttonAddonKind")
964
+ if button_addon_kind is not None:
965
+ custom_nodes.append(build_button_addon_node(button_addon_kind))
966
+ extra = opts.get("customNodes")
967
+ if extra is not None:
968
+ nodes = list(extra) if isinstance(extra, (list, tuple)) else [extra]
969
+ for node in nodes:
970
+ if not isinstance(node, BinaryNode):
971
+ raise ValueError(
972
+ "send customNodes must be BinaryNode entries, got "
973
+ f"{type(node).__name__}"
974
+ )
975
+ custom_nodes.append(node)
976
+ return custom_nodes
977
+
978
+ async def _publish_direct_fanout(
979
+ self,
980
+ *,
981
+ recipient_jid: str,
982
+ message: MessageDict,
983
+ plaintext: bytes,
984
+ stanza_type: str,
985
+ mediatype: str | None,
986
+ edit: str | None,
987
+ decrypt_fail: str | None,
988
+ custom_nodes: list[BinaryNode],
989
+ send_options: dict[str, Any],
990
+ peer_recipient_pn: str | None,
991
+ ) -> WaMessagePublishResult:
992
+ """Encrypt for every fanout device and publish the 1:1 ``<message>``."""
993
+ me_jid = self._require_current_me_jid("sendMessage")
994
+ me_lid = self._current_me_lid()
995
+ fanout_resolver = self._require_dep("fanout_resolver")
996
+ self_device_jid = fanout_resolver.resolve_self_device_jid_for_recipient(
997
+ recipient_jid, me_jid, me_lid
998
+ )
999
+ device_jids = list(
1000
+ await fanout_resolver.resolve_direct_fanout_device_jids(
1001
+ recipient_jid, self_device_jid
1002
+ )
1003
+ )
1004
+ targets: list[tuple[str, str, str]] = []
1005
+ for device_jid in device_jids:
1006
+ targets.append(
1007
+ (
1008
+ device_jid,
1009
+ to_user_jid(device_jid),
1010
+ normalize_device_jid(device_jid),
1011
+ )
1012
+ )
1013
+ recipient_user_jid = to_user_jid(recipient_jid)
1014
+ me_user_jid = to_user_jid(self_device_jid)
1015
+ self._deps.logger.trace(
1016
+ "wa client publish signal fanout",
1017
+ {"to": recipient_jid, "devices": len(device_jids), "type": stanza_type},
1018
+ )
1019
+ expected_identity_raw = send_options.get("expectedIdentity")
1020
+ expected_identity: bytes | None = (
1021
+ bytes(expected_identity_raw)
1022
+ if isinstance(expected_identity_raw, (bytes, bytearray))
1023
+ else None
1024
+ )
1025
+ expected_by_jid: dict[str, bytes] = {}
1026
+ if expected_identity is not None:
1027
+ for _, user_jid, normalized in targets:
1028
+ if user_jid == recipient_user_jid:
1029
+ expected_by_jid[normalized] = expected_identity
1030
+ resolved = await self._deps.session_resolver.ensure_sessions_batch(
1031
+ device_jids, expected_by_jid or None
1032
+ )
1033
+ resolved_by_jid = {
1034
+ normalize_device_jid(target.jid): target for target in resolved
1035
+ }
1036
+ live: list[tuple[str, str, str]] = []
1037
+ dropped_secondary: list[str] = []
1038
+ for jid, user_jid, normalized in targets:
1039
+ if normalized in resolved_by_jid:
1040
+ live.append((jid, user_jid, normalized))
1041
+ continue
1042
+ if user_jid == recipient_user_jid and normalized == user_jid:
1043
+ self._deps.logger.error(
1044
+ "direct fanout dropping primary recipient device "
1045
+ "without signal session",
1046
+ {"to": recipient_jid, "device": jid},
1047
+ )
1048
+ else:
1049
+ dropped_secondary.append(jid)
1050
+ if dropped_secondary:
1051
+ self._deps.logger.warn(
1052
+ "direct fanout dropping secondary devices without signal session",
1053
+ {
1054
+ "to": recipient_jid,
1055
+ "droppedCount": len(dropped_secondary),
1056
+ "totalExpected": len(targets),
1057
+ "sample": dropped_secondary[:3],
1058
+ },
1059
+ )
1060
+ if not live:
1061
+ raise ValueError("direct fanout missing signal sessions for all targets")
1062
+ has_self_device = any(user_jid == me_user_jid for _, user_jid, _ in live)
1063
+ self_plaintext: bytes | None = None
1064
+ if has_self_device:
1065
+ self_plaintext = write_random_pad_max16(
1066
+ _message_dict_to_proto(
1067
+ wrap_device_sent_message(message, recipient_user_jid)
1068
+ ).SerializeToString()
1069
+ )
1070
+ encrypt_requests: list[EncryptRequest] = []
1071
+ prefetched: list[PrefetchedSession] = []
1072
+ for jid, user_jid, normalized in live:
1073
+ resolved_target = resolved_by_jid[normalized]
1074
+ body = (
1075
+ self_plaintext
1076
+ if self_plaintext is not None and user_jid == me_user_jid
1077
+ else plaintext
1078
+ )
1079
+ encrypt_requests.append(
1080
+ EncryptRequest(
1081
+ address=resolved_target.address,
1082
+ plaintext=body,
1083
+ expected_identity=expected_identity
1084
+ if user_jid == recipient_user_jid
1085
+ else None,
1086
+ )
1087
+ )
1088
+ prefetched.append(
1089
+ PrefetchedSession(
1090
+ address=resolved_target.address,
1091
+ session=resolved_target.session,
1092
+ )
1093
+ )
1094
+ encrypted = await self._deps.signal_protocol.encrypt_messages_batch(
1095
+ encrypt_requests, prefetched
1096
+ )
1097
+ participants = [
1098
+ EncryptedParticipant(
1099
+ jid=live[index][0],
1100
+ enc_type=entry.type,
1101
+ ciphertext=bytes(entry.ciphertext),
1102
+ )
1103
+ for index, entry in enumerate(encrypted)
1104
+ ]
1105
+ device_identity = (
1106
+ self.get_encoded_signed_device_identity()
1107
+ if any(participant.enc_type == "pkmsg" for participant in participants)
1108
+ else None
1109
+ )
1110
+ reporting = self.try_build_reporting_token_artifacts(
1111
+ message,
1112
+ send_options.get("id") if isinstance(send_options.get("id"), str) else None,
1113
+ me_user_jid,
1114
+ recipient_user_jid,
1115
+ "direct_fanout",
1116
+ unpad_pkcs7(plaintext),
1117
+ )
1118
+ privacy_token_node: BinaryNode | None = None
1119
+ if not is_bot_jid(recipient_jid):
1120
+ try:
1121
+ resolved_token = await _maybe_await_result(
1122
+ self._deps.resolve_privacy_token_node(recipient_user_jid)
1123
+ )
1124
+ privacy_token_node = (
1125
+ resolved_token if isinstance(resolved_token, BinaryNode) else None
1126
+ )
1127
+ except Exception as error:
1128
+ self._deps.logger.warn(
1129
+ "privacy token resolution failed",
1130
+ {"to": recipient_user_jid, "message": str(to_error(error))},
1131
+ )
1132
+ fanout_custom_nodes = list(custom_nodes)
1133
+ reporting_node = (
1134
+ reporting.node if reporting is not None and reporting.node else None
1135
+ )
1136
+ if reporting_node is not None:
1137
+ fanout_custom_nodes.append(reporting_node)
1138
+ if privacy_token_node is not None:
1139
+ fanout_custom_nodes.append(privacy_token_node)
1140
+ message_node = build_direct_message_fanout_node(
1141
+ DirectMessageFanoutInput(
1142
+ to=recipient_jid,
1143
+ type=stanza_type,
1144
+ participants=participants,
1145
+ id=send_options.get("id")
1146
+ if isinstance(send_options.get("id"), str)
1147
+ else None,
1148
+ edit=edit,
1149
+ device_identity=device_identity,
1150
+ custom_nodes=fanout_custom_nodes,
1151
+ mediatype=mediatype,
1152
+ decrypt_fail=decrypt_fail,
1153
+ peer_recipient_pn=peer_recipient_pn,
1154
+ additional_attributes=send_options.get("additionalAttributes")
1155
+ if isinstance(send_options.get("additionalAttributes"), dict)
1156
+ else None,
1157
+ )
1158
+ )
1159
+ replay_payload = WaRetryPlaintextReplayPayload(
1160
+ mode="plaintext",
1161
+ to=recipient_jid,
1162
+ type=stanza_type,
1163
+ plaintext=plaintext,
1164
+ )
1165
+
1166
+ async def _publish() -> WaMessagePublishResult:
1167
+ outcome = await _maybe_await_result(
1168
+ self._deps.message_client.publish_node(message_node, None)
1169
+ )
1170
+ if isinstance(outcome, WaMessagePublishResult):
1171
+ return outcome
1172
+ raise ValueError("message publish did not return a publish result")
1173
+
1174
+ stanza_id = send_options.get("id")
1175
+ stanza_id_hint = stanza_id if isinstance(stanza_id, str) else None
1176
+ result = await self._deps.retry_tracker.track(
1177
+ OutboundRetryTrackHint(
1178
+ message_id_hint=message_node.attrs.get("id") or stanza_id_hint,
1179
+ to_jid=recipient_jid,
1180
+ replay_payload=replay_payload,
1181
+ eligible_requester_device_jids=tuple(device_jids),
1182
+ ),
1183
+ _publish,
1184
+ )
1185
+ if not isinstance(result, WaMessagePublishResult):
1186
+ raise ValueError("message publish did not return a publish result")
1187
+ self._deps.on_direct_message_sent(recipient_user_jid)
1188
+ return result
1189
+
1190
+ async def send_message(
1191
+ self,
1192
+ to: str,
1193
+ content: WaSendMessageContent,
1194
+ options: dict[str, Any] | WaSendMessageOptions | None = None,
1195
+ ) -> WaMessagePublishResult:
1196
+ """Build, encrypt and publish one message (direct chats only for now).
1197
+
1198
+ Newsletter recipients delegate to ``send_newsletter_message``; group
1199
+ recipients need the sender-key flow and raise :class:`NotImplementedError`.
1200
+ """
1201
+ opts = _normalize_send_options_dict(options)
1202
+ recipient_jid = normalize_recipient_jid(to)
1203
+ if is_newsletter_jid(recipient_jid):
1204
+ return await self._send_newsletter_message(recipient_jid, content, opts)
1205
+ content_input, content_level = _normalize_send_content(content)
1206
+ is_addon_crypto = is_send_addon_crypto_message(content_input)
1207
+ if is_addon_crypto:
1208
+ send_options = await self.with_resolved_message_id(opts)
1209
+ me_jid_for_addon = self._require_current_me_jid("sendMessage")
1210
+ built = await self._require_dep("build_message_content")(
1211
+ content_input,
1212
+ WaBuildMessageContext(
1213
+ to=recipient_jid,
1214
+ outgoing_stanza_id=send_options.get("id"),
1215
+ me_jid=to_user_jid(me_jid_for_addon),
1216
+ ),
1217
+ )
1218
+ else:
1219
+ built, send_options = await self._build_and_resolve_id(
1220
+ content_input, recipient_jid, opts
1221
+ )
1222
+ built_message = built.message
1223
+ if not isinstance(built_message, dict):
1224
+ raise ValueError("message build produced no message")
1225
+ is_group = is_group_jid(recipient_jid)
1226
+ if is_group:
1227
+ raise NotImplementedError(
1228
+ "zapy._client.coordinators.message_dispatch.send_message: "
1229
+ "group sends need the sender-key flow, which is not supported yet"
1230
+ )
1231
+ direct_recipient_jid = await self._resolve_direct_recipient_lid(
1232
+ to_user_jid(recipient_jid)
1233
+ )
1234
+ options_ctx = await self._merge_ephemeral_context(
1235
+ recipient_jid, direct_recipient_jid, opts
1236
+ )
1237
+ ctx = resolve_send_context_info(
1238
+ WaSendContextResolveInput(
1239
+ content_level=content_level
1240
+ if isinstance(content_level, WaSendContextInfo)
1241
+ else _coerce_context_info(content_level),
1242
+ options_level=options_ctx,
1243
+ quote=opts.get("quote"),
1244
+ forward=opts.get("forward"),
1245
+ mentions=opts.get("mentions"),
1246
+ target_jid=recipient_jid,
1247
+ me_lid=self._current_me_lid(),
1248
+ )
1249
+ )
1250
+ message = apply_context_info(built_message, ctx) if ctx else built_message
1251
+ if opts.get("viewOnce"):
1252
+ message = wrap_as_view_once(message)
1253
+ message = self._apply_edit_wrapper(message, recipient_jid, opts)
1254
+ message = self._apply_message_secret_override(message, opts)
1255
+ if self._deps.emit_message_send is not None:
1256
+ try:
1257
+ self._deps.emit_message_send(
1258
+ WaOutgoingMessageEvent(
1259
+ to=recipient_jid, id=send_options.get("id"), message=message
1260
+ )
1261
+ )
1262
+ except Exception as error:
1263
+ self._deps.logger.debug(
1264
+ "message_send emit failed", {"message": str(to_error(error))}
1265
+ )
1266
+ proto_message = ensure_message_secret(_message_dict_to_proto(message))
1267
+ await self._persist_outgoing_secret(
1268
+ proto_message, message, send_options.get("id"), recipient_jid
1269
+ )
1270
+ me_jid_for_icdc = self._require_current_me_jid("sendMessage")
1271
+ sender_icdc, recipient_icdc = await asyncio.gather(
1272
+ self._resolve_sender_icdc_for_publish(
1273
+ me_jid_for_icdc, to_user_jid(me_jid_for_icdc)
1274
+ ),
1275
+ self.resolve_user_icdc(to_user_jid(recipient_jid)),
1276
+ )
1277
+ proto_with_icdc = inject_device_list_metadata(
1278
+ proto_message, sender_icdc, recipient_icdc
1279
+ )
1280
+ plaintext = write_random_pad_max16(proto_with_icdc.SerializeToString())
1281
+ outbound_attrs = resolve_outbound_message_attrs(message)
1282
+ shape = resolve_outbound_stanza_shape(outbound_attrs, is_group)
1283
+ custom_nodes = self._assemble_custom_nodes(outbound_attrs, opts)
1284
+ peer_recipient_pn = await self._resolve_peer_recipient_pn(
1285
+ to_user_jid(recipient_jid), direct_recipient_jid
1286
+ )
1287
+ result = await self._publish_direct_fanout(
1288
+ recipient_jid=direct_recipient_jid,
1289
+ message=message,
1290
+ plaintext=plaintext,
1291
+ stanza_type=str(shape["type"]),
1292
+ mediatype=shape["mediatype"],
1293
+ edit=outbound_attrs.get("edit"),
1294
+ decrypt_fail=outbound_attrs.get("decryptFail"),
1295
+ custom_nodes=custom_nodes,
1296
+ send_options=send_options,
1297
+ peer_recipient_pn=peer_recipient_pn,
1298
+ )
1299
+ upload = built.upload
1300
+ if upload is not None:
1301
+ return WaMessagePublishResult(
1302
+ id=result.id,
1303
+ attempts=result.attempts,
1304
+ ack_node=result.ack_node,
1305
+ ack=result.ack,
1306
+ upload=upload,
1307
+ )
1308
+ return result
1309
+
1310
+ async def publish_message_node(
1311
+ self,
1312
+ node: BinaryNode,
1313
+ options: WaMessagePublishOptions | Mapping[str, Any] | None = None,
1314
+ ) -> WaMessagePublishResult:
1315
+ """Publish a raw ``<message>`` node through the retry tracker."""
1316
+ publish_options = _normalize_publish_options(options)
1317
+ self._deps.logger.trace(
1318
+ "wa client publish message node",
1319
+ {
1320
+ "tag": node.tag,
1321
+ "type": node.attrs.get("type"),
1322
+ "to": node.attrs.get("to"),
1323
+ },
1324
+ )
1325
+ replay_payload = WaRetryOpaqueNodeReplayPayload(
1326
+ mode="opaque_node", node=encode_binary_node(node)
1327
+ )
1328
+
1329
+ async def _publish() -> WaMessagePublishResult:
1330
+ outcome = await _maybe_await_result(
1331
+ self._deps.message_client.publish_node(node, publish_options)
1332
+ )
1333
+ if isinstance(outcome, WaMessagePublishResult):
1334
+ return outcome
1335
+ raise ValueError("message publish did not return a publish result")
1336
+
1337
+ return await self._deps.retry_tracker.track(
1338
+ OutboundRetryTrackHint(
1339
+ message_id_hint=node.attrs.get("id"),
1340
+ to_jid=node.attrs.get("to"),
1341
+ replay_payload=replay_payload,
1342
+ ),
1343
+ _publish,
1344
+ )
1345
+
1346
+ async def publish_encrypted_message(
1347
+ self,
1348
+ message: WaEncryptedMessageInput,
1349
+ options: WaMessagePublishOptions | Mapping[str, Any] | None = None,
1350
+ ) -> WaMessagePublishResult:
1351
+ """Publish a pre-encrypted message through the retry tracker."""
1352
+ publish_options = _normalize_publish_options(options)
1353
+ self._deps.logger.trace(
1354
+ "wa client publish encrypted message",
1355
+ {"to": message.to, "type": message.type, "encType": message.enc_type},
1356
+ )
1357
+ replay_payload = WaRetryEncryptedReplayPayload(
1358
+ mode="encrypted",
1359
+ to=message.to,
1360
+ type=message.type if message.type is not None else "text",
1361
+ enc_type=message.enc_type,
1362
+ ciphertext=bytes(message.ciphertext),
1363
+ participant=message.participant,
1364
+ )
1365
+
1366
+ async def _publish() -> WaMessagePublishResult:
1367
+ outcome = await _maybe_await_result(
1368
+ self._deps.message_client.publish_encrypted(message, publish_options)
1369
+ )
1370
+ if isinstance(outcome, WaMessagePublishResult):
1371
+ return outcome
1372
+ raise ValueError("message publish did not return a publish result")
1373
+
1374
+ return await self._deps.retry_tracker.track(
1375
+ OutboundRetryTrackHint(
1376
+ message_id_hint=message.id,
1377
+ to_jid=message.to,
1378
+ replay_payload=replay_payload,
1379
+ eligible_requester_device_jids=(message.to,),
1380
+ ),
1381
+ _publish,
1382
+ )
1383
+
1384
+ async def publish_signal_message(
1385
+ self, message: dict[str, Any], options: dict[str, Any] | None = None
1386
+ ) -> WaMessagePublishResult:
1387
+ """Encrypt one plaintext for a 1:1 chat and publish it.
1388
+
1389
+ ``message`` carries ``plaintext`` (bytes, required) plus the TS
1390
+ ``WaSignalMessagePublishInput`` fields (``id``, ``type``,
1391
+ ``category``, ``pushPriority``, ``participant``, ``deviceFanout``,
1392
+ ``expectedIdentity``, ``metaNode``). Group JIDs raise
1393
+ :class:`ValueError` (use the sender-key flow instead).
1394
+ """
1395
+ # DEVIATION: the TS resolves the session JID through
1396
+ # ``canonicalizeOwnAccountJid`` for hosted accounts; nothing in
1397
+ # ``zapy`` provides that yet, so the session is ensured for ``to``.
1398
+ self._require_current_me_jid("publishSignalMessage")
1399
+ recipient = message.get("to")
1400
+ if not isinstance(recipient, str) or not recipient:
1401
+ raise ValueError("publishSignalMessage requires a recipient jid")
1402
+ session_jid = recipient
1403
+ address = parse_signal_address_from_jid(session_jid)
1404
+ if address.server == _defaults.GROUP_SERVER:
1405
+ raise ValueError(
1406
+ "publishSignalMessage currently supports only direct chats; "
1407
+ "use the sender-key flow for groups"
1408
+ )
1409
+ plaintext_raw = message.get("plaintext")
1410
+ if not isinstance(plaintext_raw, (bytes, bytearray)):
1411
+ raise ValueError("publishSignalMessage requires bytes plaintext")
1412
+ expected_identity = message.get("expectedIdentity")
1413
+ if expected_identity is not None and not isinstance(
1414
+ expected_identity, (bytes, bytearray)
1415
+ ):
1416
+ raise ValueError("publishSignalMessage expectedIdentity must be bytes")
1417
+ self._deps.logger.trace(
1418
+ "wa client publish signal message",
1419
+ {"to": recipient, "sessionJid": session_jid, "type": message.get("type")},
1420
+ )
1421
+ padded = write_random_pad_max16(bytes(plaintext_raw))
1422
+ await self._deps.session_resolver.ensure_session(
1423
+ address,
1424
+ session_jid,
1425
+ bytes(expected_identity) if expected_identity is not None else None,
1426
+ )
1427
+ encrypted = await self._deps.signal_protocol.encrypt_message(
1428
+ address,
1429
+ padded,
1430
+ bytes(expected_identity) if expected_identity is not None else None,
1431
+ )
1432
+ message_type = message.get("type")
1433
+ device_identity = (
1434
+ self.get_encoded_signed_device_identity()
1435
+ if encrypted.type == "pkmsg"
1436
+ else None
1437
+ )
1438
+ meta_node = message.get("metaNode")
1439
+ publish_input = WaEncryptedMessageInput(
1440
+ to=recipient,
1441
+ enc_type=encrypted.type,
1442
+ ciphertext=bytes(encrypted.ciphertext),
1443
+ id=message.get("id") if isinstance(message.get("id"), str) else None,
1444
+ type=message_type if isinstance(message_type, str) else None,
1445
+ category=message.get("category")
1446
+ if isinstance(message.get("category"), str)
1447
+ else None,
1448
+ push_priority=message.get("pushPriority")
1449
+ if isinstance(message.get("pushPriority"), str)
1450
+ else None,
1451
+ participant=message.get("participant")
1452
+ if isinstance(message.get("participant"), str)
1453
+ else None,
1454
+ device_fanout=message.get("deviceFanout")
1455
+ if isinstance(message.get("deviceFanout"), str)
1456
+ else None,
1457
+ device_identity=device_identity,
1458
+ meta_node=meta_node if isinstance(meta_node, BinaryNode) else None,
1459
+ )
1460
+ replay_payload = WaRetryPlaintextReplayPayload(
1461
+ mode="plaintext",
1462
+ to=recipient,
1463
+ type=message_type if isinstance(message_type, str) else "text",
1464
+ plaintext=padded,
1465
+ )
1466
+ publish_options = _normalize_publish_options(
1467
+ options if isinstance(options, Mapping) else None
1468
+ )
1469
+
1470
+ async def _publish() -> WaMessagePublishResult:
1471
+ outcome = await _maybe_await_result(
1472
+ self._deps.message_client.publish_encrypted(
1473
+ publish_input, publish_options
1474
+ )
1475
+ )
1476
+ if isinstance(outcome, WaMessagePublishResult):
1477
+ return outcome
1478
+ raise ValueError("message publish did not return a publish result")
1479
+
1480
+ return await self._deps.retry_tracker.track(
1481
+ OutboundRetryTrackHint(
1482
+ message_id_hint=publish_input.id,
1483
+ to_jid=recipient,
1484
+ replay_payload=replay_payload,
1485
+ eligible_requester_device_jids=(recipient,),
1486
+ ),
1487
+ _publish,
1488
+ )
1489
+
1490
+ async def publish_protocol_message_to_device(
1491
+ self,
1492
+ device_jid: str,
1493
+ protocol_message: MessageDict,
1494
+ message_id: str | None = None,
1495
+ push_priority: str | None = None,
1496
+ ) -> WaMessagePublishResult:
1497
+ """Publish a protocol message to one device (app-state key shares)."""
1498
+ me_jid = self._require_current_me_jid("sendMessage")
1499
+ me_user_jid = to_user_jid(me_jid)
1500
+ sender_icdc = await self._resolve_sender_icdc_for_publish(me_jid, me_user_jid)
1501
+ wrapped = {"protocolMessage": protocol_message}
1502
+ proto_message = _message_dict_to_proto(wrapped)
1503
+ if sender_icdc is not None:
1504
+ proto_message = inject_device_list_metadata(
1505
+ proto_message, sender_icdc, None
1506
+ )
1507
+ return await self.publish_signal_message(
1508
+ {
1509
+ "to": device_jid,
1510
+ "plaintext": bytes(proto_message.SerializeToString()),
1511
+ "id": message_id,
1512
+ "type": "text",
1513
+ "category": "peer",
1514
+ "pushPriority": push_priority if push_priority is not None else "high",
1515
+ "metaNode": build_meta_node({"appdata": "default"}),
1516
+ }
1517
+ )
1518
+
1519
+ async def publish_status_message(
1520
+ self,
1521
+ message: MessageDict,
1522
+ recipients: list[str],
1523
+ status_setting: str | None = None,
1524
+ options: dict[str, Any] | None = None,
1525
+ ) -> WaMessagePublishResult:
1526
+ """Publish a status message (not supported yet)."""
1527
+ raise NotImplementedError(
1528
+ "zapy._client.coordinators.message_dispatch.publish_status_message: "
1529
+ "status messages are not supported yet"
1530
+ )
1531
+
1532
+ async def publish_broadcast_list_message(
1533
+ self, list_jid: str, message: MessageDict, recipients: list[str]
1534
+ ) -> WaMessagePublishResult:
1535
+ """Publish a broadcast-list message (not supported yet)."""
1536
+ raise NotImplementedError(
1537
+ "zapy._client.coordinators.message_dispatch."
1538
+ "broadcast-list messages are not supported yet"
1539
+ )
1540
+
1541
+
1542
+ @dataclass(frozen=True, slots=True)
1543
+ class WaMessageDispatchOptions:
1544
+ """Injected dependencies of :class:`WaMessageDispatchCoordinator`."""
1545
+
1546
+ logger: Logger
1547
+ group_metadata_cache: GroupMetadataCache
1548
+ app_state_sync_key_protocol: AppStateSyncKeyProtocol
1549
+ session_resolver: Any
1550
+ message_client: Any
1551
+ retry_tracker: OutboundRetryTracker
1552
+ signal_protocol: Any
1553
+ signal_store: WaSignalStore
1554
+ session_store: WaSessionStore
1555
+ identity_store: WaIdentityStore
1556
+ device_list_store: WaDeviceListStore
1557
+ thread_store: WaThreadStore
1558
+ chat_metadata_store: WaChatMetadataStore
1559
+ message_secret_store: WaMessageSecretStore
1560
+ get_current_credentials: Callable[[], WaAuthCredentials | None]
1561
+ resolve_privacy_token_node: Callable[[str], Awaitable[BinaryNode | None]]
1562
+ on_direct_message_sent: Callable[[str], None]
1563
+ server_clock: ServerClock
1564
+ emit_message_send: Callable[[WaOutgoingMessageEvent], None] | None = None
1565
+ persist_all_message_secrets: bool = False
1566
+ mobile_message_id_format: Callable[[], bool] | None = None
1567
+ get_icdc_hash_length: Callable[[], int | None] | None = None
1568
+ fanout_resolver: Any | None = None
1569
+ build_message_content: Any | None = None
1570
+ sender_key_manager: Any | None = None
1571
+ signal_device_sync: Any | None = None
1572
+ send_newsletter_message: Any | None = None
1573
+
1574
+
1575
+ def resolve_outbound_stanza_shape(
1576
+ attrs: WaOutboundMessageAttrs, is_group: bool
1577
+ ) -> dict[str, str | None]:
1578
+ """Resolve the stanza ``type`` and ``enc.mediatype`` of an outbound message.
1579
+
1580
+ A ``<biz>`` companion rides a type=text stanza with no mediatype, except on
1581
+ a group list: there the server nacks with 479 (SMAX_INVALID) unless
1582
+ type=media, mediatype=list and ``<biz><list>`` travel together.
1583
+ """
1584
+ button_addon_kind = attrs.get("buttonAddonKind")
1585
+ flattens_for_addon = button_addon_kind is not None and not (
1586
+ is_group and button_addon_kind == "list"
1587
+ )
1588
+ if flattens_for_addon:
1589
+ return {"type": "text", "mediatype": None}
1590
+ mediatype = attrs.get("mediatype")
1591
+ return {"type": attrs["typeAttr"], "mediatype": mediatype}
1592
+
1593
+
1594
+ def restrict_group_history_targets(
1595
+ message: MessageDict,
1596
+ participant_user_jids: list[str],
1597
+ sender_jid: str,
1598
+ on_dropped: Callable[[list[str], int], None] | None = None,
1599
+ ) -> list[str]:
1600
+ """Narrow a group's participant list to a history bundle's receivers.
1601
+
1602
+ Returns the full list for every other message. Receivers must be written
1603
+ in the group's addressing mode; raises when no receiver matches a current
1604
+ member (sending to the sender's own devices alone counts as no match).
1605
+ """
1606
+ history_bundle = unwrap_message(message).get("messageHistoryBundle")
1607
+ receivers: list[str] = []
1608
+ if isinstance(history_bundle, dict):
1609
+ metadata = history_bundle.get("messageHistoryMetadata")
1610
+ if isinstance(metadata, dict):
1611
+ raw_receivers = metadata.get("historyReceivers")
1612
+ if isinstance(raw_receivers, list):
1613
+ receivers = [r for r in raw_receivers if isinstance(r, str)]
1614
+ if not receivers:
1615
+ return participant_user_jids
1616
+ pending: set[str] = set()
1617
+ for receiver in receivers:
1618
+ try:
1619
+ pending.add(to_user_jid(receiver))
1620
+ except ValueError:
1621
+ pending.add(receiver)
1622
+ sender_user_jid = to_user_jid(sender_jid)
1623
+ targets: list[str] = []
1624
+ matched_receivers = 0
1625
+ for participant in participant_user_jids:
1626
+ participant_user_jid = to_user_jid(participant)
1627
+ if participant_user_jid in pending:
1628
+ pending.discard(participant_user_jid)
1629
+ matched_receivers += 1
1630
+ targets.append(participant)
1631
+ elif participant_user_jid == sender_user_jid:
1632
+ targets.append(participant)
1633
+ if pending and on_dropped is not None:
1634
+ on_dropped(sorted(pending), len(receivers))
1635
+ if matched_receivers == 0:
1636
+ raise ValueError("group history bundle resolved no receivers in the group")
1637
+ return targets