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,2020 @@
1
+ """Client wiring (mirrors ``src/client/WaClientFactory.ts``).
2
+
3
+
4
+ :func:`resolve_wa_client_base` is fully implemented.
5
+ :func:`build_wa_client_dependencies` mirrors the oracle's coordinator graph
6
+ one-to-one, but the coordinator,
7
+ connection, app-state, media-transfer, message-dispatch and plugin modules
8
+ it wires are owned by sibling workers and do not exist yet. To keep this
9
+ module importable (and the gates green) until they land, those pieces are
10
+ loaded with :mod:`importlib` inside the function body instead of static
11
+ imports; every reference carries the oracle path it will resolve to.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import dataclasses
17
+ import importlib
18
+ import inspect
19
+ from collections.abc import Awaitable, Callable
20
+ from types import SimpleNamespace
21
+ from dataclasses import dataclass, field
22
+ from typing import Any
23
+
24
+ from zapy._auth.types import WaAuthClientOptions, WaSuccessPersistAttributes
25
+ from zapy._infra.log import Logger
26
+ from zapy._protocol import defaults as _defaults
27
+ from zapy._protocol.device_identity import (
28
+ WaDeviceIdentityOptions,
29
+ resolve_wa_device_identity,
30
+ )
31
+ from zapy._store.create_store import WaStoreSession
32
+ from zapy._transport.comms import WaComms
33
+ from zapy._transport.proxy import is_proxy_agent, is_proxy_dispatcher
34
+ from zapy._transport.types import BinaryNode
35
+
36
+ from zapy._client.types import WaClientOptions, WaIncomingNodeHandlerRegistration
37
+
38
+ __all__ = [
39
+ "WaClientBase",
40
+ "WaClientBuildRuntime",
41
+ "WaClientDependencies",
42
+ "resolve_wa_client_base",
43
+ "build_wa_client_dependencies",
44
+ ]
45
+
46
+
47
+ def _missing_default(name: str, oracle_value: int) -> int:
48
+ """Read a timeout from ``zapy._protocol.defaults`` (oracle ``WA_DEFAULTS``).
49
+
50
+ The full defaults table belongs to the protocol worker; until it lands,
51
+ fall back to the value copied verbatim from
52
+ ``src/protocol/defaults.ts`` so resolution never invents behavior.
53
+ """
54
+ return int(getattr(_defaults, name, oracle_value))
55
+
56
+
57
+ @dataclass(frozen=True, slots=True)
58
+ class WaClientBase:
59
+ """Validated options plus the per-session store bundle."""
60
+
61
+ options: WaClientOptions
62
+ logger: Logger
63
+ session_store: WaStoreSession
64
+
65
+
66
+ @dataclass(frozen=True, slots=True)
67
+ class WaClientBuildRuntime:
68
+ """Callbacks the client hands to the dependency graph (mirrors TS)."""
69
+
70
+ send_node: Callable[[BinaryNode], Awaitable[None]]
71
+ query: Callable[[BinaryNode, float | None, Any], Awaitable[BinaryNode]]
72
+ query_with_context: Callable[..., Awaitable[BinaryNode]]
73
+ sync_app_state: Callable[[], Awaitable[None]]
74
+ sync_app_state_with_options: Callable[..., Awaitable[Any]]
75
+ emit_event: Callable[..., Any]
76
+ has_event_listener: Callable[[str], bool]
77
+ handle_incoming_message_event: Callable[[Any], Awaitable[None]]
78
+ handle_error: Callable[[Exception], None]
79
+ handle_incoming_frame: Callable[[bytes], Awaitable[None]]
80
+ clear_stored_state: Callable[[], Awaitable[None]]
81
+ resume_incoming_events: Callable[[], None]
82
+ subscribe_protocol_message: Callable[[Callable[[Any], None]], Callable[[], None]]
83
+ persist_contact: Callable[[Any], None]
84
+
85
+
86
+ @dataclass(frozen=True, slots=True)
87
+ class WaClientDependencies:
88
+ """Internal coordinator graph (mirrors ``WaClientDependencies``).
89
+
90
+ Every field is the coordinator the oracle wires under the same name;
91
+ all are :data:`Any` until the owning sibling modules land.
92
+ """
93
+
94
+ node_transport: Any = None
95
+ node_orchestrator: Any = None
96
+ keep_alive: Any = None
97
+ media_transfer: Any = None
98
+ media_message_build_options: Any = None
99
+ message_client: Any = None
100
+ sender_key_manager: Any = None
101
+ signal_protocol: Any = None
102
+ signal_digest_sync: Any = None
103
+ signal_device_sync: Any = None
104
+ signal_identity_sync: Any = None
105
+ signal_missing_pre_keys_sync: Any = None
106
+ signal_rotate_key: Any = None
107
+ signal_session_sync: Any = None
108
+ session_resolver: Any = None
109
+ auth_client: Any = None
110
+ message_dispatch: Any = None
111
+ message_coordinator: Any = None
112
+ presence_coordinator: Any = None
113
+ retry_coordinator: Any = None
114
+ app_state_sync: Any = None
115
+ chat_coordinator: Any = None
116
+ stream_control: Any = None
117
+ incoming_node: Any = None
118
+ low_level_coordinator: Any = None
119
+ passive_tasks: Any = None
120
+ group_coordinator: Any = None
121
+ status_coordinator: Any = None
122
+ broadcast_list_coordinator: Any = None
123
+ newsletter_coordinator: Any = None
124
+ privacy_coordinator: Any = None
125
+ profile_coordinator: Any = None
126
+ business_coordinator: Any = None
127
+ bot_coordinator: Any = None
128
+ email_coordinator: Any = None
129
+ receipt_queue: Any = None
130
+ connection_manager: Any = None
131
+ trusted_contact_token: Any = None
132
+ ab_props_coordinator: Any = None
133
+ peer_data_operation: Any = None
134
+ mobile_coordinator: Any = None
135
+ is_mobile_primary: Callable[[], bool] = field(default=lambda: False)
136
+
137
+
138
+ def _is_proxy_transport(value: object) -> bool:
139
+ """Mirror of TS ``isProxyTransport`` (dispatcher or agent)."""
140
+ return is_proxy_dispatcher(value) or is_proxy_agent(value)
141
+
142
+
143
+ def _assert_proxy_transport(value: Any, path: str) -> None:
144
+ if value is None:
145
+ return
146
+ if not _is_proxy_transport(value):
147
+ raise ValueError(
148
+ f"{path} must be a proxy transport instance "
149
+ "(dispatcher with dispatch(...) or agent with addRequest(...))"
150
+ )
151
+
152
+
153
+ def validate_proxy_options(options: WaClientOptions) -> None:
154
+ """Reject proxy shapes that are not dispatcher/agent transports.
155
+
156
+ Error strings are identical to the oracle's.
157
+ """
158
+ from zapy._client.types import WaClientProxyOptions
159
+
160
+ raw_proxy: Any = options.proxy
161
+ if raw_proxy is None:
162
+ return
163
+ if isinstance(raw_proxy, WaClientProxyOptions):
164
+ _assert_proxy_transport(raw_proxy.ws, "proxy.ws")
165
+ _assert_proxy_transport(raw_proxy.media_upload, "proxy.mediaUpload")
166
+ _assert_proxy_transport(raw_proxy.media_download, "proxy.mediaDownload")
167
+ return
168
+ if not isinstance(raw_proxy, dict):
169
+ raise ValueError(
170
+ "proxy must be an object with optional ws/mediaUpload/mediaDownload"
171
+ )
172
+ _assert_proxy_transport(raw_proxy.get("ws"), "proxy.ws")
173
+ _assert_proxy_transport(raw_proxy.get("mediaUpload"), "proxy.mediaUpload")
174
+ _assert_proxy_transport(raw_proxy.get("mediaDownload"), "proxy.mediaDownload")
175
+
176
+
177
+ def resolve_wa_client_base(options: WaClientOptions, logger: Logger) -> WaClientBase:
178
+ """Validate options and resolve defaults (mirrors ``resolveWaClientBase``)."""
179
+ validate_proxy_options(options)
180
+
181
+ device = resolve_wa_device_identity(
182
+ WaDeviceIdentityOptions(
183
+ device_browser=options.device_browser,
184
+ device_os_display_name=options.device_os_display_name,
185
+ device_os_version=options.device_os_version,
186
+ device_platform=options.device_platform,
187
+ )
188
+ )
189
+ session_id = options.session_id.strip()
190
+ if not session_id:
191
+ raise ValueError("sessionId must be a non-empty string")
192
+
193
+ session_store = options.store.session(session_id)
194
+ normalized = dataclasses.replace(
195
+ options,
196
+ session_id=session_id,
197
+ device_browser=device.browser,
198
+ device_os_display_name=device.os_display_name,
199
+ device_os_version=device.os_version,
200
+ device_platform=device.platform,
201
+ urls=(
202
+ options.urls
203
+ if options.urls is not None
204
+ else (
205
+ options.chat_socket_urls
206
+ if options.chat_socket_urls is not None
207
+ else list(_defaults.CHAT_SOCKET_URLS)
208
+ )
209
+ ),
210
+ iq_timeout_ms=(
211
+ options.iq_timeout_ms
212
+ if options.iq_timeout_ms is not None
213
+ else _missing_default("IQ_TIMEOUT_MS", 15_000)
214
+ ),
215
+ node_query_timeout_ms=(
216
+ options.node_query_timeout_ms
217
+ if options.node_query_timeout_ms is not None
218
+ else _missing_default("NODE_QUERY_TIMEOUT_MS", 15_000)
219
+ ),
220
+ keep_alive_interval_ms=(
221
+ options.keep_alive_interval_ms
222
+ if options.keep_alive_interval_ms is not None
223
+ else _missing_default("HEALTH_CHECK_INTERVAL_MS", 15_000)
224
+ ),
225
+ dead_socket_timeout_ms=(
226
+ options.dead_socket_timeout_ms
227
+ if options.dead_socket_timeout_ms is not None
228
+ else _missing_default("DEAD_SOCKET_TIMEOUT_MS", 20_000)
229
+ ),
230
+ media_timeout_ms=(
231
+ options.media_timeout_ms
232
+ if options.media_timeout_ms is not None
233
+ else _missing_default("MEDIA_TIMEOUT_MS", 30_000)
234
+ ),
235
+ app_state_sync_timeout_ms=(
236
+ options.app_state_sync_timeout_ms
237
+ if options.app_state_sync_timeout_ms is not None
238
+ else _missing_default("APP_STATE_SYNC_TIMEOUT_MS", 30_000)
239
+ ),
240
+ signal_fetch_key_bundles_timeout_ms=(
241
+ options.signal_fetch_key_bundles_timeout_ms
242
+ if options.signal_fetch_key_bundles_timeout_ms is not None
243
+ else _missing_default("SIGNAL_FETCH_KEY_BUNDLES_TIMEOUT_MS", 20_000)
244
+ ),
245
+ message_ack_timeout_ms=(
246
+ options.message_ack_timeout_ms
247
+ if options.message_ack_timeout_ms is not None
248
+ else _missing_default("MESSAGE_ACK_TIMEOUT_MS", 10_000)
249
+ ),
250
+ message_max_attempts=(
251
+ options.message_max_attempts
252
+ if options.message_max_attempts is not None
253
+ else _missing_default("MESSAGE_MAX_ATTEMPTS", 3)
254
+ ),
255
+ message_retry_delay_ms=(
256
+ options.message_retry_delay_ms
257
+ if options.message_retry_delay_ms is not None
258
+ else _missing_default("MESSAGE_RETRY_DELAY_MS", 750)
259
+ ),
260
+ )
261
+ return WaClientBase(options=normalized, logger=logger, session_store=session_store)
262
+
263
+
264
+ def _load(symbol_path: str) -> Any:
265
+ """Import ``module:attr`` lazily (sibling modules land separately)."""
266
+ module_name, _, attr = symbol_path.partition(":")
267
+ return getattr(importlib.import_module(module_name), attr)
268
+
269
+
270
+ class _MissingSibling:
271
+ """Placeholder for a not-yet-ported layer (L11 media, L12 app-state).
272
+
273
+ Instantiation accepts anything so client construction succeeds; any
274
+ real use raises a clear error pointing at the owning layer.
275
+ """
276
+
277
+ def __init__(self, path: str) -> None:
278
+ self._path = path
279
+
280
+ def __call__(self, *args: Any, **kwargs: Any) -> "_MissingSibling":
281
+ return self
282
+
283
+ def __getattr__(self, item: str) -> Any:
284
+ if item.startswith("__") and item.endswith("__"):
285
+ raise AttributeError(item)
286
+ raise NotImplementedError(f"{self._path} is not available in this build")
287
+
288
+
289
+ def _load_or_missing(symbol_path: str, layer: str) -> Any:
290
+ """Like :func:`_load`, but returns a clear placeholder when absent."""
291
+ try:
292
+ return _load(symbol_path)
293
+ except (ImportError, AttributeError):
294
+ return _MissingSibling(layer)
295
+
296
+
297
+ class _PendingMexSocket:
298
+ """Stand-in MEX socket: construction succeeds, use raises."""
299
+
300
+ def __init__(self, reason: str = "mex transport is not supported yet") -> None:
301
+ self._reason = reason
302
+
303
+ async def run_mex_query(self, op_key: str, variables: dict[str, Any]) -> Any:
304
+ raise NotImplementedError(self._reason)
305
+
306
+
307
+ @dataclasses.dataclass(frozen=True)
308
+ class _DirtySyncRuntime:
309
+ """Adapter mapping the factory dict onto :class:`WaDirtySyncRuntime`."""
310
+
311
+ logger: Any
312
+ query_with_context: Any
313
+ get_current_credentials: Any
314
+ sync_app_state: Any
315
+ generate_usync_sid: Any
316
+ sync_account_privacy: Any
317
+ emit_blocklist: Any
318
+ newsletter_list_subscribed: Any = None
319
+
320
+
321
+ class _PassiveTasksRuntime:
322
+ """Adapt factory pieces to the passive-tasks runtime (mirrors the TS adapter)."""
323
+
324
+ def __init__(
325
+ self,
326
+ *,
327
+ query_with_context: Any,
328
+ auth_client: Any,
329
+ node_orchestrator: Any,
330
+ receipt_queue: Any,
331
+ get_current_credentials: Any,
332
+ ab_props_coordinator: Any,
333
+ mark_online_on_connect: bool,
334
+ ) -> None:
335
+ self._query_with_context = query_with_context
336
+ self._auth_client = auth_client
337
+ self._node_orchestrator = node_orchestrator
338
+ self._receipt_queue = receipt_queue
339
+ self._get_current_credentials = get_current_credentials
340
+ self._ab_props_coordinator = ab_props_coordinator
341
+ self._mark_online_on_connect = mark_online_on_connect
342
+
343
+ async def query_with_context(
344
+ self,
345
+ context: str,
346
+ node: BinaryNode,
347
+ timeout_ms: float | None = None,
348
+ context_data: dict[str, Any] | None = None,
349
+ options: Any = None,
350
+ ) -> BinaryNode:
351
+ result = await self._query_with_context(
352
+ context, node, timeout_ms, context_data, options
353
+ )
354
+ assert isinstance(result, BinaryNode)
355
+ return result
356
+
357
+ def get_current_credentials(self) -> Any:
358
+ return self._get_current_credentials()
359
+
360
+ async def persist_server_has_pre_keys(self, value: bool) -> None:
361
+ await self._auth_client.persist_server_has_pre_keys(value)
362
+
363
+ async def send_node_direct(self, node: BinaryNode) -> None:
364
+ await self._node_orchestrator.send_node(node)
365
+
366
+ def take_dangling_receipts(self) -> list[BinaryNode]:
367
+ taken = self._receipt_queue.take()
368
+ assert isinstance(taken, list)
369
+ return taken
370
+
371
+ def requeue_dangling_receipt(self, node: BinaryNode) -> None:
372
+ self._receipt_queue.enqueue(node)
373
+
374
+ def should_queue_dangling_receipt(
375
+ self, node: BinaryNode, error: BaseException
376
+ ) -> bool:
377
+ return bool(self._receipt_queue.should_queue(node, error))
378
+
379
+ def sync_ab_props(self) -> None:
380
+ self._ab_props_coordinator.sync()
381
+
382
+ async def send_initial_presence(self) -> None:
383
+ from zapy._transport.node.builders.presence import (
384
+ BuildPresenceNodeInput,
385
+ build_presence_node,
386
+ )
387
+
388
+ credentials = self._get_current_credentials()
389
+ name = (
390
+ credentials.get("me_display_name")
391
+ if isinstance(credentials, dict)
392
+ else getattr(credentials, "me_display_name", None)
393
+ )
394
+ if self._mark_online_on_connect:
395
+ node = build_presence_node(BuildPresenceNodeInput(name=name))
396
+ else:
397
+ node = build_presence_node(
398
+ BuildPresenceNodeInput(type="unavailable", name=name)
399
+ )
400
+ await self._node_orchestrator.send_node(node)
401
+
402
+
403
+ @dataclasses.dataclass(frozen=True)
404
+ class _AuthSocketShim:
405
+ """Adapt runtime send/query callables to :class:`AuthClientSocket`."""
406
+
407
+ _send: Any
408
+ _query_fn: Any
409
+
410
+ async def send_node(self, node: BinaryNode) -> None:
411
+ result = self._send(node)
412
+ if inspect.isawaitable(result):
413
+ await result
414
+
415
+ async def query(
416
+ self, node: BinaryNode, timeout_ms: float | None = None
417
+ ) -> BinaryNode:
418
+ result = await self._query_fn(node, timeout_ms)
419
+ assert isinstance(result, BinaryNode)
420
+ return result
421
+
422
+
423
+ def build_wa_client_dependencies(
424
+ base: WaClientBase, runtime: WaClientBuildRuntime
425
+ ) -> WaClientDependencies:
426
+ """Wire the coordinator graph (mirrors ``buildWaClientDependencies``).
427
+
428
+ Every coordinator class is loaded lazily from its canonical
429
+ ``zapy`` path. Not-yet-ported layers (L11 media, L12 app-state) resolve
430
+ to placeholders that raise :class:`NotImplementedError` only when used;
431
+ mobile transport raises immediately as an explicit non-goal.
432
+ Construction arguments mirror the oracle one-to-one (snake_cased).
433
+ """
434
+ options = base.options
435
+ logger = base.logger
436
+ session_store = base.session_store
437
+
438
+ WaReceiptQueue = _load("zapy._client.connection.receipt_queue:WaReceiptQueue")
439
+ create_server_clock = _load("zapy._message.messaging:create_server_clock")
440
+ WaNodeTransport = _load("zapy._transport.node.transport:WaNodeTransport")
441
+ WaNodeOrchestrator = _load("zapy._transport.node.orchestrator:WaNodeOrchestrator")
442
+ WaKeepAlive = _load("zapy._transport.keepalive.keep_alive:WaKeepAlive")
443
+ WaKeepAliveOptions = _load(
444
+ "zapy._transport.keepalive.keep_alive:WaKeepAliveOptions"
445
+ )
446
+ WaMediaTransferClient = _load_or_missing(
447
+ "zapy._media.transfer.client:WaMediaTransferClient", "zapy._media (L11)"
448
+ )
449
+ WaMediaTransferClientOptions = _load_or_missing(
450
+ "zapy._media.types:WaMediaTransferClientOptions", "zapy._media (L11)"
451
+ )
452
+ WaMessageClient = _load("zapy._message.client:WaMessageClient")
453
+ SenderKeyManager = _load("zapy._signal.group.manager:SenderKeyManager")
454
+ SignalProtocol = _load("zapy._signal.session.protocol:SignalProtocol")
455
+ SignalProtocolStores = _load("zapy._signal.session.protocol:SignalProtocolStores")
456
+ SignalDigestSyncApi = _load("zapy._signal.api.digest_sync:SignalDigestSyncApi")
457
+ SignalDeviceSyncApi = _load("zapy._signal.api.device_sync:SignalDeviceSyncApi")
458
+ SignalIdentitySyncApi = _load(
459
+ "zapy._signal.api.identity_sync:SignalIdentitySyncApi"
460
+ )
461
+ SignalMissingPreKeysSyncApi = _load(
462
+ "zapy._signal.api.missing_pre_keys_sync:SignalMissingPreKeysSyncApi"
463
+ )
464
+ SignalRotateKeyApi = _load("zapy._signal.api.rotate_key:SignalRotateKeyApi")
465
+ SignalSessionSyncApi = _load("zapy._signal.api.session_sync:SignalSessionSyncApi")
466
+ create_signal_session_resolver = _load(
467
+ "zapy._signal.session.resolver:create_signal_session_resolver"
468
+ )
469
+ WaAuthClient = _load("zapy._auth.auth_client:WaAuthClient")
470
+ WaAuthClientCallbacks = _load("zapy._auth.auth_client:WaAuthClientCallbacks")
471
+ WaAuthClientDeps = _load("zapy._auth.auth_client:WaAuthClientDeps")
472
+ WaMessageDispatchCoordinator = _load(
473
+ "zapy._client.coordinators.message_dispatch:WaMessageDispatchCoordinator"
474
+ )
475
+ WaMessageDispatchOptions = _load(
476
+ "zapy._client.coordinators.message_dispatch:WaMessageDispatchOptions"
477
+ )
478
+ WaMessageCoordinator = _load(
479
+ "zapy._client.coordinators.message:WaMessageCoordinator"
480
+ )
481
+ WaMessageCoordinatorDeps = _load(
482
+ "zapy._client.coordinators.message:WaMessageCoordinatorDeps"
483
+ )
484
+ create_presence_coordinator = _load(
485
+ "zapy._client.coordinators.presence:create_presence_coordinator"
486
+ )
487
+ WaRetryCoordinator = _load("zapy._client.coordinators.retry:WaRetryCoordinator")
488
+ WaRetryCoordinatorOptions = _load(
489
+ "zapy._client.coordinators.retry:WaRetryCoordinatorOptions"
490
+ )
491
+ WaAppStateSyncClient = _load_or_missing(
492
+ "zapy._appstate.sync.client:WaAppStateSyncClient", "zapy._appstate (L12)"
493
+ )
494
+ WaAppStateMutationCoordinator = _load(
495
+ "zapy._client.coordinators.app_state_mutation:WaAppStateMutationCoordinator"
496
+ )
497
+ create_stream_control_handler = _load(
498
+ "zapy._client.coordinators.stream_control:create_stream_control_handler"
499
+ )
500
+ WaIncomingNodeCoordinator = _load(
501
+ "zapy._client.coordinators.incoming_node:WaIncomingNodeCoordinator"
502
+ )
503
+ create_low_level_coordinator = _load(
504
+ "zapy._client.coordinators.low_level:create_low_level_coordinator"
505
+ )
506
+ WaPassiveTasksCoordinator = _load(
507
+ "zapy._client.coordinators.passive_tasks:WaPassiveTasksCoordinator"
508
+ )
509
+ WaConnectionManager = _load("zapy._client.connection.manager:WaConnectionManager")
510
+ WaTrustedContactTokenCoordinator = _load(
511
+ "zapy._client.coordinators.trusted_contact_token:"
512
+ "WaTrustedContactTokenCoordinator"
513
+ )
514
+ WaAbPropsCoordinator = _load(
515
+ "zapy._client.coordinators.ab_props:WaAbPropsCoordinator"
516
+ )
517
+ WaOfflineResumeCoordinator = _load(
518
+ "zapy._client.coordinators.offline_resume:WaOfflineResumeCoordinator"
519
+ )
520
+ create_group_coordinator = _load(
521
+ "zapy._client.coordinators.group:create_group_coordinator"
522
+ )
523
+ create_status_coordinator = _load(
524
+ "zapy._client.coordinators.status:create_status_coordinator"
525
+ )
526
+ create_broadcast_list_coordinator = _load(
527
+ "zapy._client.coordinators.broadcast_list:create_broadcast_list_coordinator"
528
+ )
529
+ create_newsletter_coordinator_from_options = _load(
530
+ "zapy._client.coordinators.newsletter:"
531
+ "create_newsletter_coordinator_from_options"
532
+ )
533
+ WA_ABPROPS = _load("zapy._protocol.abprops_spec:WA_ABPROPS")
534
+ WA_ABPROPS_BY_CODE = _load("zapy._protocol.abprops_spec:WA_ABPROPS_BY_CODE")
535
+ PeerDataOperationRequesterOptions = _load(
536
+ "zapy._message.primitives.peer_data_operation:PeerDataOperationRequesterOptions"
537
+ )
538
+ MediaRetryRequesterOptions = _load(
539
+ "zapy._message.primitives.media_retry:WaMediaRetryRequesterOptions"
540
+ )
541
+ WaProfileCoordinatorOptions = _load(
542
+ "zapy._client.coordinators.profile:WaProfileCoordinatorOptions"
543
+ )
544
+ WaIncomingNodeCoordinatorOptions = _load(
545
+ "zapy._client.coordinators.incoming_node:WaIncomingNodeCoordinatorOptions"
546
+ )
547
+ create_privacy_coordinator = _load(
548
+ "zapy._client.coordinators.privacy:create_privacy_coordinator"
549
+ )
550
+ create_profile_coordinator = _load(
551
+ "zapy._client.coordinators.profile:create_profile_coordinator"
552
+ )
553
+ create_business_coordinator = _load(
554
+ "zapy._client.coordinators.business:create_business_coordinator"
555
+ )
556
+ create_bot_coordinator = _load(
557
+ "zapy._client.coordinators.bot:create_bot_coordinator"
558
+ )
559
+ create_email_coordinator = _load(
560
+ "zapy._client.coordinators.email:create_email_coordinator"
561
+ )
562
+ create_device_fanout_resolver = _load(
563
+ "zapy._message.messaging.fanout:create_device_fanout_resolver"
564
+ )
565
+ create_group_metadata_cache = _load(
566
+ "zapy._message.messaging.group_metadata:create_group_metadata_cache"
567
+ )
568
+ create_app_state_sync_key_protocol = _load(
569
+ "zapy._message.messaging.key_protocol:create_app_state_sync_key_protocol"
570
+ )
571
+ resolve_link_preview = _load(
572
+ "zapy._message.messaging.link_preview:resolve_link_preview"
573
+ )
574
+ build_media_message_content = _load(
575
+ "zapy._message.messaging.messages:build_media_message_content"
576
+ )
577
+ WaMediaMessageOptions = _load(
578
+ "zapy._message.messaging.messages:WaMediaMessageOptions"
579
+ )
580
+ get_client_media_conn = _load_or_missing(
581
+ "zapy._message.messaging.messages:get_media_conn",
582
+ "zapy._message.messaging.messages:get_media_conn (L11)",
583
+ )
584
+ create_default_link_preview_fetcher = _load(
585
+ "zapy._message.addons.link_preview.fetcher:create_default_link_preview_fetcher"
586
+ )
587
+ DefaultLinkPreviewFetcherOptions = _load(
588
+ "zapy._message.addons.link_preview.fetcher:DefaultLinkPreviewFetcherOptions"
589
+ )
590
+
591
+ async def _unported_link_preview_download(request: Any) -> Any:
592
+ raise NotImplementedError(
593
+ "link preview download needs the media transfer layer (L11); "
594
+ "inject link_preview.fetcher to override"
595
+ )
596
+
597
+ process_newsletter_live_updates = _load(
598
+ "zapy._message.kinds.newsletter:process_newsletter_live_updates"
599
+ )
600
+ handle_incoming_message_ack = _load(
601
+ "zapy._message.primitives.incoming:handle_incoming_message_ack"
602
+ )
603
+ WaIncomingMessageAckHandlerOptions = _load(
604
+ "zapy._message.primitives.incoming:WaIncomingMessageAckHandlerOptions"
605
+ )
606
+ create_media_retry_requester = _load(
607
+ "zapy._message.primitives.media_retry:create_media_retry_requester"
608
+ )
609
+ create_peer_data_operation_requester = _load(
610
+ "zapy._message.primitives.peer_data_operation:"
611
+ "create_peer_data_operation_requester"
612
+ )
613
+ create_outbound_retry_tracker = _load(
614
+ "zapy._retry.tracker:create_outbound_retry_tracker"
615
+ )
616
+ to_proxy_agent = _load("zapy._transport.proxy:to_proxy_agent")
617
+ build_ack_node = _load("zapy._transport.node.builders.global_:build_ack_node")
618
+ find_node_child = _load("zapy._transport.node.helpers:find_node_child")
619
+ get_first_node_child = _load("zapy._transport.node.helpers:get_first_node_child")
620
+ create_usync_sid_generator = _load(
621
+ "zapy._transport.node.usync:create_usync_sid_generator"
622
+ )
623
+ parse_device_notification = _load(
624
+ "zapy._client.events.devices:parse_device_notification"
625
+ )
626
+ handle_dirty_bits = _load("zapy._client.events.dirty:handle_dirty_bits")
627
+ parse_dirty_bits = _load("zapy._client.events.dirty:parse_dirty_bits")
628
+ parse_identity_change_notification = _load(
629
+ "zapy._client.events.identity:parse_identity_change_notification"
630
+ )
631
+ parse_privacy_token_notification = _load(
632
+ "zapy._client.events.privacy_token:parse_privacy_token_notification"
633
+ )
634
+ parse_own_username_notification = _load(
635
+ "zapy._client.events.username:parse_own_username_notification"
636
+ )
637
+
638
+ def to_error(error: Any) -> Exception:
639
+ return error if isinstance(error, Exception) else Exception(str(error))
640
+
641
+ receipt_queue = WaReceiptQueue()
642
+
643
+ connection_manager: Any = None
644
+ passive_tasks: Any = None
645
+ media_conn_cache_fallback: Any = None
646
+ ab_props_coordinator: Any = None
647
+ message_dispatch: Any = None
648
+ offline_resume: Any = None
649
+
650
+ def _await_server_restart_after_pairing() -> Any:
651
+ return None
652
+
653
+ server_clock = create_server_clock(
654
+ lambda: (
655
+ connection_manager.get_clock_skew_ms()
656
+ if connection_manager is not None
657
+ else None
658
+ )
659
+ )
660
+
661
+ node_transport = WaNodeTransport(logger)
662
+ node_orchestrator = WaNodeOrchestrator(
663
+ send_node=node_transport.send_node,
664
+ logger=logger,
665
+ default_timeout_ms=options.node_query_timeout_ms,
666
+ host_domain=_defaults.HOST_DOMAIN,
667
+ mobile_iq_id_format=lambda: is_mobile_primary(),
668
+ )
669
+ keep_alive = WaKeepAlive(
670
+ WaKeepAliveOptions(
671
+ logger=logger,
672
+ node_orchestrator=node_orchestrator,
673
+ get_comms=lambda: (
674
+ connection_manager.get_comms()
675
+ if connection_manager is not None
676
+ else None
677
+ ),
678
+ interval_ms=options.keep_alive_interval_ms,
679
+ get_interval_ms=lambda: (
680
+ ab_props_coordinator.get_config_value("heartbeat_interval_s") * 1_000
681
+ ),
682
+ timeout_ms=options.dead_socket_timeout_ms,
683
+ host_domain=_defaults.HOST_DOMAIN,
684
+ on_clock_skew_ms=lambda clock_skew_ms: (
685
+ connection_manager.set_clock_skew_ms(clock_skew_ms, "keepalive")
686
+ if connection_manager is not None
687
+ else None
688
+ ),
689
+ )
690
+ )
691
+ media_transfer = WaMediaTransferClient(
692
+ WaMediaTransferClientOptions(
693
+ logger=logger,
694
+ default_timeout_ms=options.media_timeout_ms,
695
+ default_upload_agent=to_proxy_agent(
696
+ options.proxy.get("mediaUpload")
697
+ if isinstance(options.proxy, dict)
698
+ else getattr(options.proxy, "media_upload", None)
699
+ )
700
+ if options.proxy is not None
701
+ else None,
702
+ default_download_agent=to_proxy_agent(
703
+ options.proxy.get("mediaDownload")
704
+ if isinstance(options.proxy, dict)
705
+ else getattr(options.proxy, "media_download", None)
706
+ )
707
+ if options.proxy is not None
708
+ else None,
709
+ skip_mac_verification=bool(
710
+ options.dangerous
711
+ and getattr(options.dangerous, "disable_media_mac_verification", False)
712
+ ),
713
+ )
714
+ )
715
+
716
+ link_preview_options = options.link_preview or {}
717
+ link_preview_fetcher = (
718
+ link_preview_options.get("fetcher")
719
+ if isinstance(link_preview_options, dict)
720
+ else getattr(link_preview_options, "fetcher", None)
721
+ ) or create_default_link_preview_fetcher(
722
+ DefaultLinkPreviewFetcherOptions(
723
+ download=_unported_link_preview_download,
724
+ )
725
+ )
726
+
727
+ def _link_preview_resolver(surface: Any = None) -> Any:
728
+ def resolve(content: Any) -> Any:
729
+ return resolve_link_preview(
730
+ getattr(content, "text", ""),
731
+ getattr(content, "link_preview", None),
732
+ {
733
+ "logger": logger,
734
+ "media_transfer": media_transfer,
735
+ "get_media_conn": lambda: get_client_media_conn(
736
+ media_message_build_options
737
+ ),
738
+ "fetcher": link_preview_fetcher,
739
+ "options": link_preview_options,
740
+ "server_clock": server_clock,
741
+ "surface": surface,
742
+ },
743
+ )
744
+
745
+ return resolve
746
+
747
+ media_message_build_options = WaMediaMessageOptions(
748
+ logger=logger,
749
+ media_transfer=media_transfer,
750
+ iq_timeout_ms=options.iq_timeout_ms,
751
+ query_with_context=runtime.query_with_context,
752
+ get_media_conn_cache=lambda: (
753
+ connection_manager.get_media_conn_cache()
754
+ if connection_manager is not None
755
+ else media_conn_cache_fallback
756
+ ),
757
+ set_media_conn_cache=lambda media_conn: (
758
+ connection_manager.set_media_conn_cache(media_conn)
759
+ if connection_manager is not None
760
+ else None
761
+ ),
762
+ server_clock=server_clock,
763
+ media=options.media,
764
+ link_preview_resolver=_link_preview_resolver(),
765
+ )
766
+
767
+ message_client = WaMessageClient(
768
+ logger=logger,
769
+ send_node=runtime.send_node,
770
+ query=runtime.query,
771
+ default_ack_timeout_ms=options.message_ack_timeout_ms,
772
+ default_max_attempts=options.message_max_attempts,
773
+ default_retry_delay_ms=options.message_retry_delay_ms,
774
+ )
775
+ sender_key_manager = SenderKeyManager(
776
+ session_store.sender_key,
777
+ get_future_messages_max=lambda: ab_props_coordinator.get_config_value(
778
+ "web_signal_future_messages_max"
779
+ ),
780
+ skip_signature_verification=bool(
781
+ options.dangerous
782
+ and getattr(
783
+ options.dangerous,
784
+ "disable_sender_key_signature_verification",
785
+ False,
786
+ )
787
+ ),
788
+ )
789
+ signal_protocol = SignalProtocol(
790
+ SignalProtocolStores(
791
+ signal=session_store.signal,
792
+ pre_key=session_store.pre_key,
793
+ session=session_store.session,
794
+ identity=session_store.identity,
795
+ ),
796
+ logger,
797
+ )
798
+
799
+ async def _signal_system_query(
800
+ node: BinaryNode, timeout_ms: float | None = None, _options: Any = None
801
+ ) -> BinaryNode:
802
+ return await runtime.query(node, timeout_ms, {"use_system_id": True})
803
+
804
+ signal_digest_sync = SignalDigestSyncApi(
805
+ logger=logger,
806
+ query=_signal_system_query,
807
+ signal_store=session_store.signal,
808
+ pre_key_store=session_store.pre_key,
809
+ default_timeout_ms=options.signal_fetch_key_bundles_timeout_ms,
810
+ )
811
+ generate_usync_sid = create_usync_sid_generator()
812
+ signal_device_sync = SignalDeviceSyncApi(
813
+ logger=logger,
814
+ query=runtime.query,
815
+ device_list_store=session_store.device_list,
816
+ default_timeout_ms=options.signal_fetch_key_bundles_timeout_ms,
817
+ generate_sid=generate_usync_sid,
818
+ )
819
+ signal_identity_sync = SignalIdentitySyncApi(
820
+ logger=logger,
821
+ query=_signal_system_query,
822
+ identity_store=session_store.identity,
823
+ default_timeout_ms=options.signal_fetch_key_bundles_timeout_ms,
824
+ )
825
+ signal_missing_pre_keys_sync = SignalMissingPreKeysSyncApi(
826
+ logger=logger,
827
+ query=_signal_system_query,
828
+ default_timeout_ms=options.signal_fetch_key_bundles_timeout_ms,
829
+ )
830
+ signal_rotate_key = SignalRotateKeyApi(
831
+ logger=logger,
832
+ query=_signal_system_query,
833
+ signal_store=session_store.signal,
834
+ default_timeout_ms=options.signal_fetch_key_bundles_timeout_ms,
835
+ )
836
+ signal_session_sync = SignalSessionSyncApi(
837
+ logger=logger,
838
+ query=_signal_system_query,
839
+ default_timeout_ms=options.signal_fetch_key_bundles_timeout_ms,
840
+ )
841
+
842
+ auth_client = WaAuthClient(
843
+ WaAuthClientOptions(
844
+ device_browser=options.device_browser,
845
+ device_os_display_name=options.device_os_display_name,
846
+ device_os_version=options.device_os_version,
847
+ device_platform=options.device_platform,
848
+ require_full_sync=(
849
+ options.history.require_full_sync
850
+ if options.history is not None
851
+ and options.history.require_full_sync is not None
852
+ else options.require_full_sync
853
+ ),
854
+ version=options.version,
855
+ dangerous=options.dangerous,
856
+ mobile_transport=options.mobile_transport,
857
+ ),
858
+ WaAuthClientDeps(
859
+ logger=logger,
860
+ auth_store=session_store.auth,
861
+ signal_store=session_store.signal,
862
+ pre_key_store=session_store.pre_key,
863
+ socket=_AuthSocketShim(_send=runtime.send_node, _query_fn=runtime.query),
864
+ is_connected=lambda: (
865
+ connection_manager.is_connected()
866
+ if connection_manager is not None
867
+ else False
868
+ ),
869
+ callbacks=WaAuthClientCallbacks(
870
+ on_qr=lambda qr, ttl_ms: runtime.emit_event(
871
+ "auth_qr", {"qr": qr, "ttl_ms": ttl_ms}
872
+ ),
873
+ on_pairing_code=lambda code: runtime.emit_event(
874
+ "auth_pairing_code", {"code": code}
875
+ ),
876
+ on_pairing_refresh=lambda force_manual: runtime.emit_event(
877
+ "auth_pairing_required", {"force_manual": force_manual}
878
+ ),
879
+ on_paired=lambda credentials: (
880
+ runtime.emit_event("auth_paired", {"credentials": credentials}),
881
+ _await_server_restart_after_pairing(),
882
+ ),
883
+ on_error=runtime.handle_error,
884
+ on_passkey_required=lambda has_signer: runtime.emit_event(
885
+ "auth_passkey_required", {"has_signer": has_signer}
886
+ ),
887
+ sign_passkey_assertion=options.sign_passkey_assertion,
888
+ ),
889
+ ),
890
+ )
891
+ get_current_credentials = auth_client.get_current_credentials
892
+
893
+ def is_mobile_primary() -> bool:
894
+ credentials = get_current_credentials()
895
+ return options.mobile_transport is not None or bool(
896
+ credentials and credentials.get("device_info")
897
+ if isinstance(credentials, dict)
898
+ else getattr(credentials, "device_info", None)
899
+ )
900
+
901
+ group_coordinator = create_group_coordinator(
902
+ query_with_context=runtime.query_with_context,
903
+ )
904
+ newsletter_coordinator = create_newsletter_coordinator_from_options(
905
+ {
906
+ "mex_socket": None,
907
+ "send_node": runtime.send_node,
908
+ "publish_message_node": lambda node, opts: (
909
+ message_dispatch.publish_message_node(node, opts)
910
+ ),
911
+ "query_with_context": runtime.query_with_context,
912
+ "generate_stanza_id": lambda: (
913
+ message_dispatch.generate_outgoing_message_id()
914
+ ),
915
+ "media_transfer": media_transfer,
916
+ "get_media_conn": lambda: get_client_media_conn(
917
+ media_message_build_options
918
+ ),
919
+ "link_preview_resolver": _link_preview_resolver("newsletter"),
920
+ "get_ab_prop_string": lambda name: ab_props_coordinator.get_config_value(
921
+ name
922
+ ),
923
+ "logger": logger,
924
+ }
925
+ )
926
+ privacy_coordinator = create_privacy_coordinator(
927
+ logger=logger,
928
+ contact_store=session_store.contacts,
929
+ query_with_context=runtime.query_with_context,
930
+ resolve_user_jid_pair=lambda user_jid: signal_device_sync.resolve_user_jid_pair(
931
+ user_jid
932
+ ),
933
+ get_self_lid=lambda: (
934
+ lambda creds: creds.get("me_lid") if isinstance(creds, dict) else None
935
+ )(get_current_credentials()),
936
+ emit_privacy=lambda event: runtime.emit_event("privacy", event),
937
+ is_username_privacy_list_identifier_enabled=lambda: bool(
938
+ ab_props_coordinator.get_config_value(
939
+ "username_contact_privacy_setting_allow_uncontact_set_enable"
940
+ )
941
+ ),
942
+ )
943
+
944
+ async def _unported_cover_upload(photo: bytes, context: object) -> dict[str, Any]:
945
+ raise NotImplementedError(
946
+ "business cover-photo upload needs the media transfer layer (L11)"
947
+ )
948
+
949
+ parse_business_profile_node = _load(
950
+ "zapy._client.events.business:parse_business_profile_node"
951
+ )
952
+ parse_verified_name_node = _load(
953
+ "zapy._client.events.business:parse_verified_name_node"
954
+ )
955
+
956
+ def _business_profile_to_mapping(
957
+ node: BinaryNode,
958
+ ) -> dict[str, Any] | None:
959
+ result = parse_business_profile_node(node)
960
+ return dataclasses.asdict(result) if result is not None else None
961
+
962
+ def _verified_name_to_mapping(
963
+ node: BinaryNode,
964
+ ) -> dict[str, Any] | None:
965
+ result = parse_verified_name_node(node)
966
+ return dataclasses.asdict(result) if result is not None else None
967
+
968
+ business_coordinator = create_business_coordinator(
969
+ query_with_context=runtime.query_with_context,
970
+ get_media_conn=lambda: get_client_media_conn(media_message_build_options),
971
+ logger=logger,
972
+ generate_sid=generate_usync_sid,
973
+ parse_business_profile=lambda node: _business_profile_to_mapping(
974
+ parse_business_profile_node(node)
975
+ ),
976
+ parse_verified_name_node=lambda node: _verified_name_to_mapping(
977
+ parse_verified_name_node(node)
978
+ ),
979
+ upload_cover_photo_bytes=_unported_cover_upload,
980
+ )
981
+ email_coordinator = create_email_coordinator(
982
+ **{"query_with_context": runtime.query_with_context}
983
+ )
984
+ retry_tracker = create_outbound_retry_tracker(
985
+ **{"retry_store": session_store.retry, "logger": logger}
986
+ )
987
+ session_resolver = create_signal_session_resolver(
988
+ **{
989
+ "signal_protocol": signal_protocol,
990
+ "session_store": session_store.session,
991
+ "identity_store": session_store.identity,
992
+ "signal_identity_sync": signal_identity_sync,
993
+ "signal_session_sync": signal_session_sync,
994
+ "logger": logger,
995
+ }
996
+ )
997
+ fanout_resolver = create_device_fanout_resolver(
998
+ **{
999
+ "signal_device_sync": signal_device_sync,
1000
+ "get_current_credentials": get_current_credentials,
1001
+ "logger": logger,
1002
+ }
1003
+ )
1004
+ group_metadata_cache = create_group_metadata_cache(
1005
+ **{
1006
+ "group_metadata_store": session_store.group_metadata,
1007
+ "query_group_metadata": lambda group_jid: (
1008
+ group_coordinator.query_group_metadata(group_jid)
1009
+ ),
1010
+ "logger": logger,
1011
+ }
1012
+ )
1013
+ trusted_contact_token = WaTrustedContactTokenCoordinator(
1014
+ logger=logger,
1015
+ store=session_store.privacy_token,
1016
+ runtime={
1017
+ "query_with_context": runtime.query_with_context,
1018
+ "emit_event": runtime.emit_event,
1019
+ "get_current_credentials": get_current_credentials,
1020
+ },
1021
+ server_clock=server_clock,
1022
+ duration_s=getattr(options.privacy_token, "tc_token_duration_s", None)
1023
+ if options.privacy_token is not None
1024
+ else None,
1025
+ num_buckets=getattr(options.privacy_token, "tc_token_num_buckets", None)
1026
+ if options.privacy_token is not None
1027
+ else None,
1028
+ sender_duration_s=getattr(
1029
+ options.privacy_token, "tc_token_sender_duration_s", None
1030
+ )
1031
+ if options.privacy_token is not None
1032
+ else None,
1033
+ sender_num_buckets=getattr(
1034
+ options.privacy_token, "tc_token_sender_num_buckets", None
1035
+ )
1036
+ if options.privacy_token is not None
1037
+ else None,
1038
+ max_duration_s=getattr(options.privacy_token, "tc_token_max_duration_s", None)
1039
+ if options.privacy_token is not None
1040
+ else None,
1041
+ get_config_overrides=lambda: {
1042
+ "duration_s": ab_props_coordinator.get_config_value("tctoken_duration"),
1043
+ "num_buckets": ab_props_coordinator.get_config_value("tctoken_num_buckets"),
1044
+ "sender_duration_s": ab_props_coordinator.get_config_value(
1045
+ "tctoken_duration_sender"
1046
+ ),
1047
+ "sender_num_buckets": ab_props_coordinator.get_config_value(
1048
+ "tctoken_num_buckets_sender"
1049
+ ),
1050
+ },
1051
+ )
1052
+ ab_props_coordinator = WaAbPropsCoordinator(
1053
+ logger=logger,
1054
+ query_with_context=runtime.query_with_context,
1055
+ props_table=WA_ABPROPS,
1056
+ resolve_name_by_code=lambda code: WA_ABPROPS_BY_CODE.get(code),
1057
+ )
1058
+
1059
+ def _publish_protocol_message_to_device(
1060
+ device_jid: Any, protocol_message: Any, opts: Any
1061
+ ) -> Any:
1062
+ return message_dispatch.publish_protocol_message_to_device(
1063
+ device_jid, protocol_message, opts
1064
+ )
1065
+
1066
+ def _send_newsletter_message(
1067
+ newsletter_jid: Any,
1068
+ content: Any,
1069
+ send_options: Any,
1070
+ context_info: Any,
1071
+ ) -> Any:
1072
+ return newsletter_coordinator.send(
1073
+ newsletter_jid,
1074
+ content,
1075
+ {
1076
+ "stanza_id": send_options.get("id"),
1077
+ "context_info": context_info,
1078
+ "additional_attributes": send_options.get("additional_attributes"),
1079
+ },
1080
+ )
1081
+
1082
+ app_state_sync_key_protocol = create_app_state_sync_key_protocol(
1083
+ **{
1084
+ "publish_protocol_message_to_device": (_publish_protocol_message_to_device),
1085
+ "fanout_resolver": fanout_resolver,
1086
+ "get_current_credentials": get_current_credentials,
1087
+ "logger": logger,
1088
+ }
1089
+ )
1090
+ message_dispatch = WaMessageDispatchCoordinator(
1091
+ WaMessageDispatchOptions(
1092
+ logger=logger,
1093
+ emit_message_send=lambda event: runtime.emit_event("message_send", event),
1094
+ message_client=message_client,
1095
+ retry_tracker=retry_tracker,
1096
+ session_resolver=session_resolver,
1097
+ fanout_resolver=fanout_resolver,
1098
+ group_metadata_cache=group_metadata_cache,
1099
+ app_state_sync_key_protocol=app_state_sync_key_protocol,
1100
+ build_message_content=lambda content, ctx: build_media_message_content(
1101
+ media_message_build_options, content, ctx
1102
+ ),
1103
+ sender_key_manager=sender_key_manager,
1104
+ signal_protocol=signal_protocol,
1105
+ signal_store=session_store.signal,
1106
+ session_store=session_store.session,
1107
+ identity_store=session_store.identity,
1108
+ device_list_store=session_store.device_list,
1109
+ thread_store=session_store.threads,
1110
+ chat_metadata_store=session_store.chat_metadata,
1111
+ signal_device_sync=signal_device_sync,
1112
+ message_secret_store=session_store.message_secret,
1113
+ persist_all_message_secrets=bool(
1114
+ options.addons is not None
1115
+ and options.addons.persist_all_secrets is True
1116
+ ),
1117
+ get_current_credentials=get_current_credentials,
1118
+ resolve_privacy_token_node=lambda recipient_jid: (
1119
+ trusted_contact_token.resolve_token_for_message(recipient_jid)
1120
+ ),
1121
+ on_direct_message_sent=lambda recipient_jid: (
1122
+ trusted_contact_token.maybe_issue_sender_token(recipient_jid)
1123
+ ),
1124
+ send_newsletter_message=_send_newsletter_message,
1125
+ get_icdc_hash_length=lambda: ab_props_coordinator.get_config_value(
1126
+ "md_icdc_hash_length"
1127
+ ),
1128
+ mobile_message_id_format=is_mobile_primary,
1129
+ server_clock=server_clock,
1130
+ )
1131
+ )
1132
+
1133
+ presence_coordinator = create_presence_coordinator(
1134
+ **{
1135
+ "send_node": lambda node: node_orchestrator.send_node(node, False),
1136
+ "get_current_credentials": get_current_credentials,
1137
+ "resolve_privacy_token_node": lambda jid: (
1138
+ trusted_contact_token.resolve_receiver_token_node(jid)
1139
+ ),
1140
+ }
1141
+ )
1142
+ peer_data_operation = create_peer_data_operation_requester(
1143
+ PeerDataOperationRequesterOptions(
1144
+ logger=logger,
1145
+ publish_protocol_message_to_device=(_publish_protocol_message_to_device),
1146
+ get_current_credentials=get_current_credentials,
1147
+ generate_outgoing_message_id=lambda: (
1148
+ message_dispatch.generate_outgoing_message_id()
1149
+ ),
1150
+ subscribe_to_protocol_message=runtime.subscribe_protocol_message,
1151
+ )
1152
+ )
1153
+ media_retry_requester = create_media_retry_requester(
1154
+ MediaRetryRequesterOptions(
1155
+ logger=logger,
1156
+ send_node=lambda node: node_orchestrator.send_node(node, False),
1157
+ get_current_credentials=get_current_credentials,
1158
+ )
1159
+ )
1160
+ message_coordinator = WaMessageCoordinator(
1161
+ WaMessageCoordinatorDeps(
1162
+ message_dispatch=message_dispatch,
1163
+ media_transfer=media_transfer,
1164
+ media_retry=media_retry_requester,
1165
+ media_upload_options=media_message_build_options,
1166
+ logger=logger,
1167
+ message_store=session_store.messages,
1168
+ message_secret_store=session_store.message_secret,
1169
+ trusted_contact_token=trusted_contact_token,
1170
+ emit_addon=lambda event: runtime.emit_event("message_addon", event),
1171
+ mex_socket=_PendingMexSocket(
1172
+ "message coordinator mex is not supported yet"
1173
+ ),
1174
+ peer_data_operation=peer_data_operation,
1175
+ is_group_history_send_enabled=lambda: ab_props_coordinator.get_config_value(
1176
+ "group_history_send"
1177
+ ),
1178
+ get_ab_prop_number=lambda name: ab_props_coordinator.get_config_value(name),
1179
+ )
1180
+ )
1181
+ retry_coordinator = WaRetryCoordinator(
1182
+ WaRetryCoordinatorOptions(
1183
+ logger=logger,
1184
+ retry_store=session_store.retry,
1185
+ signal_store=session_store.signal,
1186
+ pre_key_store=session_store.pre_key,
1187
+ session_store=session_store.session,
1188
+ sender_key_store=session_store.sender_key,
1189
+ signal_protocol=signal_protocol,
1190
+ session_resolver=session_resolver,
1191
+ signal_device_sync=signal_device_sync,
1192
+ signal_missing_pre_keys_sync=signal_missing_pre_keys_sync,
1193
+ message_client=message_client,
1194
+ send_node=runtime.send_node,
1195
+ get_current_credentials=get_current_credentials,
1196
+ resolve_user_icdc=lambda user_jid: message_dispatch.resolve_user_icdc(
1197
+ user_jid
1198
+ ),
1199
+ resolve_privacy_token_node=lambda recipient_jid: (
1200
+ trusted_contact_token.resolve_token_for_message(recipient_jid)
1201
+ ),
1202
+ peer_data_operation=peer_data_operation,
1203
+ emit_incoming_message=lambda event: runtime.handle_incoming_message_event(
1204
+ event
1205
+ ),
1206
+ is_mobile_primary=is_mobile_primary,
1207
+ get_ab_prop_number=lambda name: ab_props_coordinator.get_config_value(name),
1208
+ )
1209
+ )
1210
+ bot_coordinator = create_bot_coordinator(
1211
+ **{
1212
+ "logger": logger,
1213
+ "query_with_context": runtime.query_with_context,
1214
+ "build_message_content": lambda content: build_media_message_content(
1215
+ media_message_build_options, content
1216
+ ),
1217
+ "send_message": lambda to, content, send_options: (
1218
+ message_dispatch.send_message(to, content, send_options or {})
1219
+ ),
1220
+ "message_store": session_store.messages,
1221
+ "message_secret_store": session_store.message_secret,
1222
+ "get_current_credentials": get_current_credentials,
1223
+ "emit_bot_chunk": lambda event: runtime.emit_event(
1224
+ "message_bot_chunk", event
1225
+ ),
1226
+ "generate_sid": generate_usync_sid,
1227
+ }
1228
+ )
1229
+ app_state_sync = WaAppStateSyncClient(
1230
+ logger=logger,
1231
+ query=runtime.query,
1232
+ get_current_me_jid=lambda: (
1233
+ lambda creds: (
1234
+ creds.get("me_jid")
1235
+ if isinstance(creds, dict)
1236
+ else getattr(creds, "me_jid", None)
1237
+ )
1238
+ )(get_current_credentials()),
1239
+ default_timeout_ms=options.app_state_sync_timeout_ms,
1240
+ store=session_store.app_state,
1241
+ server_clock=server_clock,
1242
+ on_missing_keys=lambda key_ids: message_dispatch.request_app_state_sync_keys(
1243
+ key_ids
1244
+ ),
1245
+ skip_mac_verification=bool(
1246
+ options.dangerous
1247
+ and getattr(options.dangerous, "disable_app_state_mac_verification", False)
1248
+ ),
1249
+ mobile_primary=is_mobile_primary,
1250
+ send_key_share=lambda to_device_jid, keys, missing_key_ids: (
1251
+ message_dispatch.send_app_state_sync_key_share(
1252
+ to_device_jid, keys, missing_key_ids
1253
+ )
1254
+ ),
1255
+ trigger_sync=lambda: runtime.sync_app_state(),
1256
+ )
1257
+
1258
+ async def _apply_own_push_name(name: str) -> None:
1259
+ credentials = get_current_credentials()
1260
+ current = (
1261
+ credentials.get("me_display_name")
1262
+ if isinstance(credentials, dict)
1263
+ else getattr(credentials, "me_display_name", None)
1264
+ )
1265
+ if current == name:
1266
+ return
1267
+ await auth_client.persist_success_attributes(
1268
+ WaSuccessPersistAttributes(me_display_name=name)
1269
+ )
1270
+ if connection_manager is not None and connection_manager.is_connected():
1271
+ await presence_coordinator.send()
1272
+
1273
+ app_state_mutations = WaAppStateMutationCoordinator(
1274
+ logger=logger,
1275
+ message_store=session_store.messages,
1276
+ app_state_sync=app_state_sync,
1277
+ media_transfer=media_transfer,
1278
+ is_connected=lambda: (
1279
+ connection_manager.is_connected()
1280
+ if connection_manager is not None
1281
+ else False
1282
+ ),
1283
+ server_clock=server_clock,
1284
+ emit_snapshot_mutations=bool(
1285
+ options.chat_events is not None
1286
+ and options.chat_events.emit_snapshot_mutations is True
1287
+ ),
1288
+ emit_mutation=lambda event: runtime.emit_event("mutation", event),
1289
+ emit_mutation_send=lambda event: runtime.emit_event("mutation_send", event),
1290
+ nct_salt_sink=lambda salt: trusted_contact_token.handle_nct_salt_sync(salt),
1291
+ contact_sink=runtime.persist_contact,
1292
+ push_name_sink=lambda name: _apply_own_push_name(name),
1293
+ )
1294
+ profile_coordinator = create_profile_coordinator(
1295
+ WaProfileCoordinatorOptions(
1296
+ query_with_context=runtime.query_with_context,
1297
+ generate_sid=generate_usync_sid,
1298
+ mex_socket=_PendingMexSocket("profile mex queries are not supported yet"),
1299
+ query_lids_by_phone_jids=lambda phone_jids: (
1300
+ signal_device_sync.query_lids_by_phone_jids(phone_jids)
1301
+ ),
1302
+ mutations=app_state_mutations,
1303
+ apply_own_push_name=_apply_own_push_name,
1304
+ resolve_privacy_token_node=lambda jid: (
1305
+ trusted_contact_token.resolve_receiver_token_node(jid)
1306
+ ),
1307
+ logger=logger,
1308
+ )
1309
+ )
1310
+ status_coordinator = create_status_coordinator(
1311
+ **{
1312
+ "app_state_mutations": app_state_mutations,
1313
+ "build_message_content": lambda content: build_media_message_content(
1314
+ media_message_build_options, content
1315
+ ),
1316
+ "publish_status_message": lambda input: (
1317
+ message_dispatch.publish_status_message(input)
1318
+ ),
1319
+ }
1320
+ )
1321
+ broadcast_list_coordinator = create_broadcast_list_coordinator(
1322
+ **{
1323
+ "app_state_mutations": app_state_mutations,
1324
+ "build_message_content": lambda content: build_media_message_content(
1325
+ media_message_build_options, content
1326
+ ),
1327
+ "publish_broadcast_list_message": lambda input: (
1328
+ message_dispatch.publish_broadcast_list_message(input)
1329
+ ),
1330
+ }
1331
+ )
1332
+
1333
+ connection_manager = WaConnectionManager(
1334
+ logger=logger,
1335
+ options=options,
1336
+ create_comms=lambda comms_config, comms_logger: WaComms(
1337
+ comms_config, comms_logger
1338
+ ),
1339
+ auth_client=auth_client,
1340
+ keep_alive=keep_alive,
1341
+ node_orchestrator=node_orchestrator,
1342
+ node_transport=node_transport,
1343
+ get_passive_tasks=lambda: passive_tasks,
1344
+ clear_stored_credentials=runtime.clear_stored_state,
1345
+ on_post_pair_reconnected=lambda: runtime.emit_event(
1346
+ "connection",
1347
+ {
1348
+ "status": "open",
1349
+ "reason": "connected",
1350
+ "code": None,
1351
+ "is_logout": False,
1352
+ "is_new_login": True,
1353
+ },
1354
+ ),
1355
+ )
1356
+ if media_conn_cache_fallback is not None:
1357
+ connection_manager.set_media_conn_cache(media_conn_cache_fallback)
1358
+
1359
+ def _bind_connection_manager() -> None:
1360
+ nonlocal _await_server_restart_after_pairing
1361
+
1362
+ def _restart() -> Any:
1363
+ manager: Any = connection_manager
1364
+ return manager.await_server_restart_after_pairing()
1365
+
1366
+ _await_server_restart_after_pairing = _restart
1367
+
1368
+ _bind_connection_manager()
1369
+
1370
+ async def _disconnect_with_client_side_effects(
1371
+ reason: str, is_logout: bool, code: Any
1372
+ ) -> None:
1373
+ ab_props_coordinator.reset()
1374
+ offline_resume.reset()
1375
+ privacy_coordinator.stop_account_sync_refresh()
1376
+ if connection_manager is not None:
1377
+ await connection_manager.disconnect()
1378
+ runtime.emit_event(
1379
+ "connection",
1380
+ {
1381
+ "status": "close",
1382
+ "reason": reason,
1383
+ "code": code,
1384
+ "is_logout": is_logout,
1385
+ "is_new_login": False,
1386
+ },
1387
+ )
1388
+
1389
+ async def _connect_with_client_side_effects(reason: str) -> None:
1390
+ runtime.resume_incoming_events()
1391
+ if connection_manager is not None:
1392
+ await connection_manager.connect(runtime.handle_incoming_frame)
1393
+ credentials = get_current_credentials()
1394
+ me_jid = (
1395
+ credentials.get("me_jid")
1396
+ if isinstance(credentials, dict)
1397
+ else getattr(credentials, "me_jid", None)
1398
+ )
1399
+ if not me_jid:
1400
+ return
1401
+ runtime.emit_event(
1402
+ "connection",
1403
+ {
1404
+ "status": "open",
1405
+ "reason": reason,
1406
+ "code": None,
1407
+ "is_logout": False,
1408
+ "is_new_login": False,
1409
+ },
1410
+ )
1411
+
1412
+ async def _clear_stored_credentials_with_client_side_effects() -> None:
1413
+ if connection_manager is not None:
1414
+ await connection_manager.clear_stored_credentials()
1415
+
1416
+ stream_control = create_stream_control_handler(
1417
+ **{
1418
+ "logger": logger,
1419
+ "get_comms": lambda: (
1420
+ connection_manager.get_comms()
1421
+ if connection_manager is not None
1422
+ else None
1423
+ ),
1424
+ "clear_pending_queries": lambda error: node_orchestrator.clear_pending(
1425
+ error
1426
+ ),
1427
+ "clear_media_conn_cache": lambda: (
1428
+ connection_manager.set_media_conn_cache(None)
1429
+ if connection_manager is not None
1430
+ else None
1431
+ ),
1432
+ "disconnect": _disconnect_with_client_side_effects,
1433
+ "clear_stored_credentials": (
1434
+ _clear_stored_credentials_with_client_side_effects
1435
+ ),
1436
+ "connect": _connect_with_client_side_effects,
1437
+ "handle_pairing_restart": lambda: (
1438
+ connection_manager.handle_server_restart_request()
1439
+ if connection_manager is not None
1440
+ else False
1441
+ ),
1442
+ }
1443
+ )
1444
+
1445
+ async def _handle_client_dirty_bits(dirty_bits: Any) -> None:
1446
+ await handle_dirty_bits(
1447
+ _DirtySyncRuntime(
1448
+ logger=logger,
1449
+ query_with_context=runtime.query_with_context,
1450
+ get_current_credentials=get_current_credentials,
1451
+ sync_app_state=runtime.sync_app_state,
1452
+ generate_usync_sid=generate_usync_sid,
1453
+ sync_account_privacy=lambda: (
1454
+ privacy_coordinator.refresh_from_account_sync()
1455
+ ),
1456
+ emit_blocklist=lambda blocklist: runtime.emit_event(
1457
+ "blocklist", blocklist
1458
+ ),
1459
+ newsletter_list_subscribed=lambda: (
1460
+ newsletter_coordinator.list_subscribed()
1461
+ ),
1462
+ ),
1463
+ dirty_bits,
1464
+ )
1465
+
1466
+ incoming_message_ack_options = WaIncomingMessageAckHandlerOptions(
1467
+ **{
1468
+ "logger": logger,
1469
+ "send_node": runtime.send_node,
1470
+ "get_me_jid": lambda: (
1471
+ lambda creds: creds.get("me_jid") if isinstance(creds, dict) else None
1472
+ )(get_current_credentials()),
1473
+ "get_me_lid": lambda: (
1474
+ lambda creds: creds.get("me_lid") if isinstance(creds, dict) else None
1475
+ )(get_current_credentials()),
1476
+ "signal_protocol": signal_protocol,
1477
+ "sender_key_manager": sender_key_manager,
1478
+ "on_decrypt_failure": lambda context, error: (
1479
+ retry_coordinator.on_decrypt_failure(context, error)
1480
+ ),
1481
+ "request_placeholder_resend": lambda context: (
1482
+ retry_coordinator.on_unavailable_message(context)
1483
+ ),
1484
+ "emit_incoming_message": lambda event: (
1485
+ runtime.handle_incoming_message_event(event)
1486
+ ),
1487
+ "emit_newsletter_message_update": lambda event: runtime.emit_event(
1488
+ "newsletter_message_update", event
1489
+ ),
1490
+ "emit_unavailable_message": lambda event: runtime.emit_event(
1491
+ "message_unavailable", event
1492
+ ),
1493
+ "emit_unhandled_stanza": lambda event: runtime.emit_event(
1494
+ "debug_unhandled_stanza", event
1495
+ ),
1496
+ "emit_decrypted_payload": lambda build: (
1497
+ None
1498
+ if not runtime.has_event_listener("debug_decrypted_payload")
1499
+ else runtime.emit_event("debug_decrypted_payload", build())
1500
+ ),
1501
+ }
1502
+ )
1503
+ offline_resume = WaOfflineResumeCoordinator(
1504
+ logger=logger,
1505
+ runtime={
1506
+ "send_node": lambda node: node_orchestrator.send_node(node, False),
1507
+ "emit_offline_resume": lambda event: runtime.emit_event(
1508
+ "offline_resume", event
1509
+ ),
1510
+ },
1511
+ )
1512
+ incoming_node = WaIncomingNodeCoordinator(
1513
+ WaIncomingNodeCoordinatorOptions(
1514
+ logger=logger,
1515
+ offline_resume=offline_resume,
1516
+ runtime=SimpleNamespace(
1517
+ **{
1518
+ "handle_stream_control_result": (
1519
+ stream_control.handle_stream_control_result
1520
+ ),
1521
+ "persist_success_attributes": lambda attributes: (
1522
+ auth_client.persist_success_attributes(
1523
+ attributes, counts_as_login=True
1524
+ )
1525
+ ),
1526
+ "emit_success_node": lambda node: runtime.emit_event(
1527
+ "debug_connection_success", {"node": node}
1528
+ ),
1529
+ "update_clock_skew_from_success": lambda server_unix_seconds: (
1530
+ connection_manager.update_clock_skew_from_success(
1531
+ server_unix_seconds
1532
+ )
1533
+ ),
1534
+ "should_warmup_media_conn": lambda: bool(
1535
+ (
1536
+ lambda creds: (
1537
+ creds.get("me_jid")
1538
+ if isinstance(creds, dict)
1539
+ else getattr(creds, "me_jid", None)
1540
+ )
1541
+ )(get_current_credentials())
1542
+ and connection_manager.is_connected()
1543
+ ),
1544
+ "warmup_media_conn": lambda: get_client_media_conn(
1545
+ media_message_build_options, True
1546
+ ),
1547
+ "persist_routing_info": lambda routing_info: (
1548
+ auth_client.persist_routing_info(routing_info)
1549
+ ),
1550
+ "try_resolve_pending_node": lambda node: (
1551
+ node_orchestrator.try_resolve_pending(node)
1552
+ ),
1553
+ "handle_generic_incoming_node": lambda node: (
1554
+ node_orchestrator.handle_incoming_node(node)
1555
+ ),
1556
+ "handle_incoming_iq_set_node": lambda node: (
1557
+ auth_client.handle_incoming_iq_set(node)
1558
+ ),
1559
+ "handle_link_code_notification_node": lambda node: (
1560
+ auth_client.handle_link_code_notification(node)
1561
+ ),
1562
+ "handle_companion_reg_refresh_notification_node": lambda node: (
1563
+ auth_client.handle_companion_reg_refresh_notification(node)
1564
+ ),
1565
+ "handle_incoming_message_node": lambda node: (
1566
+ handle_incoming_message_ack(node, incoming_message_ack_options)
1567
+ ),
1568
+ "send_node": runtime.send_node,
1569
+ "handle_incoming_retry_receipt": lambda node: (
1570
+ retry_coordinator.handle_incoming_retry_receipt(node)
1571
+ ),
1572
+ "handle_media_retry_notification": lambda node: (
1573
+ media_retry_requester.handle_notification(node)
1574
+ ),
1575
+ "track_outbound_receipt": lambda node: (
1576
+ retry_coordinator.track_outbound_receipt(node)
1577
+ ),
1578
+ "emit_incoming_receipt": lambda event: runtime.emit_event(
1579
+ "receipt", event
1580
+ ),
1581
+ "emit_incoming_presence": lambda event: runtime.emit_event(
1582
+ "presence", event
1583
+ ),
1584
+ "emit_incoming_chatstate": lambda event: runtime.emit_event(
1585
+ "chatstate", event
1586
+ ),
1587
+ "emit_incoming_call": lambda event: runtime.emit_event(
1588
+ "call", event
1589
+ ),
1590
+ "get_current_credentials": get_current_credentials,
1591
+ "emit_incoming_failure": lambda event: runtime.emit_event(
1592
+ "stream_failure", event
1593
+ ),
1594
+ "emit_incoming_error_stanza": lambda event: runtime.emit_event(
1595
+ "stanza_error", event
1596
+ ),
1597
+ "emit_incoming_notification": lambda event: runtime.emit_event(
1598
+ "debug_notification", event
1599
+ ),
1600
+ "emit_offline_thread_metadata": lambda event: runtime.emit_event(
1601
+ "offline_thread_metadata", event
1602
+ ),
1603
+ "emit_mex_notification": lambda event: runtime.emit_event(
1604
+ "mex_notification", event
1605
+ ),
1606
+ "emit_registration_code": lambda event: runtime.emit_event(
1607
+ "mobile_registration_code", event
1608
+ ),
1609
+ "emit_account_takeover_notice": lambda event: runtime.emit_event(
1610
+ "mobile_account_takeover_notice", event
1611
+ ),
1612
+ "emit_group_event": lambda event: runtime.emit_event(
1613
+ "group", event
1614
+ ),
1615
+ "emit_business_event": lambda event: runtime.emit_event(
1616
+ "business", event
1617
+ ),
1618
+ "emit_picture_event": lambda event: runtime.emit_event(
1619
+ "picture", event
1620
+ ),
1621
+ "emit_unhandled_incoming_node": lambda event: runtime.emit_event(
1622
+ "debug_unhandled_stanza", event
1623
+ ),
1624
+ "sync_app_state": runtime.sync_app_state,
1625
+ "stop_comms": lambda: (
1626
+ connection_manager.get_comms().stop_comms()
1627
+ if connection_manager is not None
1628
+ else None
1629
+ ),
1630
+ "disconnect": _disconnect_with_client_side_effects,
1631
+ "clear_stored_credentials": (
1632
+ _clear_stored_credentials_with_client_side_effects
1633
+ ),
1634
+ "parse_dirty_bits": lambda nodes: parse_dirty_bits(nodes, logger),
1635
+ "handle_dirty_bits": _handle_client_dirty_bits,
1636
+ }
1637
+ ),
1638
+ )
1639
+ )
1640
+
1641
+ async def _handle_newsletter_notification(node: BinaryNode) -> bool:
1642
+ is_newsletter_jid = _load("zapy._protocol.jid:is_newsletter_jid")
1643
+
1644
+ newsletter_jid = node.attrs.get("from", "")
1645
+ if not newsletter_jid or not is_newsletter_jid(newsletter_jid):
1646
+ return False
1647
+ first_child = get_first_node_child(node)
1648
+ child_tag = first_child.tag if first_child is not None else None
1649
+ action = "live_updates" if child_tag == "live_updates" else "unknown"
1650
+ runtime.emit_event(
1651
+ "newsletter",
1652
+ {
1653
+ "raw_node": node,
1654
+ "stanza_id": node.attrs.get("id"),
1655
+ "chat_jid": newsletter_jid,
1656
+ "stanza_type": node.attrs.get("type"),
1657
+ "offline": "offline" in node.attrs,
1658
+ "newsletter_jid": newsletter_jid,
1659
+ "action": action,
1660
+ "sub_type": child_tag,
1661
+ },
1662
+ )
1663
+ if action == "live_updates":
1664
+ process_newsletter_live_updates(
1665
+ node,
1666
+ {
1667
+ "logger": logger,
1668
+ "emit_incoming_message": (
1669
+ incoming_message_ack_options.emit_incoming_message
1670
+ ),
1671
+ "emit_newsletter_message_update": (
1672
+ incoming_message_ack_options.emit_newsletter_message_update
1673
+ ),
1674
+ "emit_unhandled_stanza": (
1675
+ incoming_message_ack_options.emit_unhandled_stanza
1676
+ ),
1677
+ },
1678
+ )
1679
+ return False
1680
+
1681
+ incoming_node.register_incoming_handler(
1682
+ WaIncomingNodeHandlerRegistration(
1683
+ tag="notification",
1684
+ subtype="newsletter",
1685
+ prepend=True,
1686
+ handler=_handle_newsletter_notification,
1687
+ )
1688
+ )
1689
+
1690
+ def _attr(obj: Any, name: str, default: Any = None) -> Any:
1691
+ if isinstance(obj, dict):
1692
+ return obj.get(name, default)
1693
+ return getattr(obj, name, default)
1694
+
1695
+ async def _handle_encrypt_notification(node: BinaryNode) -> bool:
1696
+ first_child = get_first_node_child(node)
1697
+ if first_child is None:
1698
+ return False
1699
+ child_tag = first_child.tag
1700
+ if child_tag == "count":
1701
+ ack_node = build_ack_node(
1702
+ kind="notification", node=node, include_type=False
1703
+ )
1704
+ await runtime.send_node(ack_node)
1705
+ if passive_tasks is None:
1706
+ logger.warn("encrypt-count: passive tasks not available")
1707
+ return True
1708
+ try:
1709
+ await passive_tasks.handle_pre_key_low_notification()
1710
+ except Exception as error:
1711
+ logger.warn(
1712
+ "encrypt-count: prekey upload failed",
1713
+ {"message": str(to_error(error))},
1714
+ )
1715
+ return True
1716
+ if child_tag == "digest":
1717
+ ack_node = build_ack_node(
1718
+ kind="notification", node=node, include_type=False
1719
+ )
1720
+ await runtime.send_node(ack_node)
1721
+ if passive_tasks is None:
1722
+ logger.warn("encrypt-digest: passive tasks not available")
1723
+ return True
1724
+ try:
1725
+ await passive_tasks.handle_digest_notification()
1726
+ except Exception as error:
1727
+ logger.warn(
1728
+ "encrypt-digest: digest sync failed",
1729
+ {"message": str(to_error(error))},
1730
+ )
1731
+ return True
1732
+ if child_tag == "identity":
1733
+ parsed = parse_identity_change_notification(node)
1734
+ if not parsed:
1735
+ return False
1736
+ ack_node = build_ack_node(
1737
+ kind="notification", node=node, include_type=False
1738
+ )
1739
+ await runtime.send_node(ack_node)
1740
+ parse_signal_address_from_jid = _load(
1741
+ "zapy._protocol.jid:parse_signal_address_from_jid"
1742
+ )
1743
+ to_user_jid = _load("zapy._protocol.jid:to_user_jid")
1744
+ from_jid = _attr(parsed, "from_jid")
1745
+ address = parse_signal_address_from_jid(from_jid)
1746
+ if _attr(address, "device", 0) != 0:
1747
+ logger.debug(
1748
+ "identity-change: ignoring companion device", {"jid": from_jid}
1749
+ )
1750
+ return True
1751
+ credentials = get_current_credentials()
1752
+ me_jid = _attr(credentials, "me_jid")
1753
+ if me_jid and to_user_jid(me_jid) == to_user_jid(from_jid):
1754
+ logger.error("self primary identity changed, disconnecting")
1755
+ comms = (
1756
+ connection_manager.get_comms()
1757
+ if connection_manager is not None
1758
+ else None
1759
+ )
1760
+ if comms is not None:
1761
+ comms.stop_comms()
1762
+ await _disconnect_with_client_side_effects(
1763
+ "primary_identity_key_change", True, None
1764
+ )
1765
+ await _clear_stored_credentials_with_client_side_effects()
1766
+ return True
1767
+ old_identity = await session_store.identity.get_remote_identity(address)
1768
+ if old_identity:
1769
+ logger.info("identity-change: clearing session", {"jid": from_jid})
1770
+ await session_store.session.delete_session(address)
1771
+ user_jid = to_user_jid(from_jid)
1772
+ try:
1773
+ await trusted_contact_token.reissue_on_identity_change(user_jid)
1774
+ except Exception as error:
1775
+ logger.warn(
1776
+ "identity-change: reissue tc token failed",
1777
+ {"message": str(to_error(error))},
1778
+ )
1779
+ runtime.emit_event(
1780
+ "debug_notification",
1781
+ {
1782
+ "raw_node": node,
1783
+ "stanza_id": _attr(parsed, "stanza_id"),
1784
+ "chat_jid": from_jid,
1785
+ "stanza_type": "encrypt",
1786
+ "offline": "offline" in node.attrs,
1787
+ "notification_type": "encrypt",
1788
+ "classification": "core",
1789
+ "details": {
1790
+ "kind": "identity_change",
1791
+ "display_name": _attr(parsed, "display_name"),
1792
+ "lid": _attr(parsed, "lid"),
1793
+ "had_previous_identity": bool(old_identity),
1794
+ },
1795
+ },
1796
+ )
1797
+ return True
1798
+ return False
1799
+
1800
+ async def _handle_account_sync_notification(node: BinaryNode) -> bool:
1801
+ if find_node_child(node, "privacy") is not None:
1802
+ privacy_coordinator.schedule_account_sync_refresh()
1803
+ username_event = parse_own_username_notification(node)
1804
+ if username_event is not None:
1805
+ runtime.emit_event("own_username", username_event)
1806
+ return False
1807
+
1808
+ async def _handle_devices_notification(node: BinaryNode) -> bool:
1809
+ parsed = parse_device_notification(node)
1810
+ if not parsed:
1811
+ return False
1812
+ ack_node = build_ack_node(kind="notification", node=node, include_type=False)
1813
+ await runtime.send_node(ack_node)
1814
+ parse_signal_address_from_jid = _load(
1815
+ "zapy._protocol.jid:parse_signal_address_from_jid"
1816
+ )
1817
+ to_user_jid = _load("zapy._protocol.jid:to_user_jid")
1818
+ from_jid = _attr(parsed, "from_jid")
1819
+ user_jid = to_user_jid(from_jid)
1820
+ if _attr(parsed, "action") == "remove":
1821
+ base_address = parse_signal_address_from_jid(from_jid)
1822
+ for device in _attr(parsed, "devices") or ():
1823
+ address = {
1824
+ "user": _attr(base_address, "user"),
1825
+ "server": _attr(base_address, "server"),
1826
+ "device": _attr(device, "device_id"),
1827
+ }
1828
+ try:
1829
+ await session_store.session.delete_session(address)
1830
+ except Exception as error:
1831
+ logger.warn(
1832
+ "devices-notification: delete session failed",
1833
+ {"message": str(to_error(error))},
1834
+ )
1835
+ device_list_store = getattr(session_store, "device_list", None)
1836
+ if device_list_store is not None:
1837
+ try:
1838
+ await device_list_store.delete_user_devices(user_jid)
1839
+ except Exception as error:
1840
+ logger.warn(
1841
+ "devices-notification: invalidate cache failed",
1842
+ {"message": str(to_error(error))},
1843
+ )
1844
+ if _attr(parsed, "action") == "update":
1845
+ try:
1846
+ await signal_device_sync.sync_device_list([user_jid])
1847
+ except Exception as error:
1848
+ logger.warn(
1849
+ "devices-notification: sync device list failed",
1850
+ {"message": str(to_error(error))},
1851
+ )
1852
+ runtime.emit_event(
1853
+ "debug_notification",
1854
+ {
1855
+ "raw_node": node,
1856
+ "stanza_id": _attr(parsed, "stanza_id"),
1857
+ "chat_jid": from_jid,
1858
+ "stanza_type": "devices",
1859
+ "offline": "offline" in node.attrs,
1860
+ "notification_type": "devices",
1861
+ "classification": "core",
1862
+ "details": {
1863
+ "kind": "device_list_change",
1864
+ "action": _attr(parsed, "action"),
1865
+ "devices": _attr(parsed, "devices"),
1866
+ },
1867
+ },
1868
+ )
1869
+ return True
1870
+
1871
+ async def _handle_privacy_token_notification(node: BinaryNode) -> bool:
1872
+ from_jid = node.attrs.get("from") or node.attrs.get("sender_lid")
1873
+ if not from_jid:
1874
+ return False
1875
+ tokens = parse_privacy_token_notification(node)
1876
+ if not tokens:
1877
+ return False
1878
+ await trusted_contact_token.handle_incoming_token(from_jid, tokens)
1879
+ ack_node = build_ack_node(
1880
+ kind="notification", node=node, type_override="privacy_token"
1881
+ )
1882
+ await runtime.send_node(ack_node)
1883
+ return True
1884
+
1885
+ async def _handle_server_notification(node: BinaryNode) -> bool:
1886
+ first_child = get_first_node_child(node)
1887
+ if first_child is None or first_child.tag != "abprops":
1888
+ return False
1889
+ ack_node = build_ack_node(kind="notification", node=node, include_type=False)
1890
+ await runtime.send_node(ack_node)
1891
+ ab_props_coordinator.sync()
1892
+ return True
1893
+
1894
+ incoming_node.register_incoming_handler(
1895
+ WaIncomingNodeHandlerRegistration(
1896
+ tag="notification",
1897
+ subtype="encrypt",
1898
+ prepend=True,
1899
+ handler=_handle_encrypt_notification,
1900
+ )
1901
+ )
1902
+ incoming_node.register_incoming_handler(
1903
+ WaIncomingNodeHandlerRegistration(
1904
+ tag="notification",
1905
+ subtype="account_sync",
1906
+ prepend=True,
1907
+ # The stanza carries the changed category inline, but it is a
1908
+ # trigger only: the whole set is refetched instead. Observer only.
1909
+ handler=_handle_account_sync_notification,
1910
+ )
1911
+ )
1912
+ incoming_node.register_incoming_handler(
1913
+ WaIncomingNodeHandlerRegistration(
1914
+ tag="notification",
1915
+ subtype="devices",
1916
+ prepend=True,
1917
+ handler=_handle_devices_notification,
1918
+ )
1919
+ )
1920
+ incoming_node.register_incoming_handler(
1921
+ WaIncomingNodeHandlerRegistration(
1922
+ tag="notification",
1923
+ subtype="privacy_token",
1924
+ prepend=True,
1925
+ handler=_handle_privacy_token_notification,
1926
+ )
1927
+ )
1928
+ incoming_node.register_incoming_handler(
1929
+ WaIncomingNodeHandlerRegistration(
1930
+ tag="notification",
1931
+ subtype="server",
1932
+ prepend=True,
1933
+ handler=_handle_server_notification,
1934
+ )
1935
+ )
1936
+
1937
+ passive_tasks = WaPassiveTasksCoordinator(
1938
+ logger=logger,
1939
+ signal_store=session_store.signal,
1940
+ pre_key_store=session_store.pre_key,
1941
+ signal_digest_sync=signal_digest_sync,
1942
+ signal_rotate_key=signal_rotate_key,
1943
+ runtime=_PassiveTasksRuntime(
1944
+ query_with_context=runtime.query_with_context,
1945
+ auth_client=auth_client,
1946
+ node_orchestrator=node_orchestrator,
1947
+ receipt_queue=receipt_queue,
1948
+ get_current_credentials=get_current_credentials,
1949
+ ab_props_coordinator=ab_props_coordinator,
1950
+ mark_online_on_connect=bool(options.mark_online_on_connect),
1951
+ ),
1952
+ mobile_primary=is_mobile_primary,
1953
+ app_state_sync=app_state_sync,
1954
+ )
1955
+ low_level_coordinator = create_low_level_coordinator(
1956
+ **{
1957
+ "logger": logger,
1958
+ "node_orchestrator": node_orchestrator,
1959
+ "incoming_node": incoming_node,
1960
+ "receipt_queue": receipt_queue,
1961
+ "is_connected": lambda: (
1962
+ connection_manager.is_connected()
1963
+ if connection_manager is not None
1964
+ else False
1965
+ ),
1966
+ "default_iq_timeout_ms": options.iq_timeout_ms,
1967
+ }
1968
+ )
1969
+
1970
+ if is_mobile_primary():
1971
+ raise NotImplementedError(
1972
+ "mobile transport (WaMobile*) is an explicit non-goal; "
1973
+ "use the web companion path"
1974
+ )
1975
+ mobile_coordinator = None
1976
+
1977
+ return WaClientDependencies(
1978
+ node_transport=node_transport,
1979
+ node_orchestrator=node_orchestrator,
1980
+ keep_alive=keep_alive,
1981
+ media_transfer=media_transfer,
1982
+ media_message_build_options=media_message_build_options,
1983
+ message_client=message_client,
1984
+ sender_key_manager=sender_key_manager,
1985
+ signal_protocol=signal_protocol,
1986
+ signal_digest_sync=signal_digest_sync,
1987
+ signal_device_sync=signal_device_sync,
1988
+ signal_identity_sync=signal_identity_sync,
1989
+ signal_missing_pre_keys_sync=signal_missing_pre_keys_sync,
1990
+ signal_rotate_key=signal_rotate_key,
1991
+ signal_session_sync=signal_session_sync,
1992
+ session_resolver=session_resolver,
1993
+ auth_client=auth_client,
1994
+ message_dispatch=message_dispatch,
1995
+ message_coordinator=message_coordinator,
1996
+ presence_coordinator=presence_coordinator,
1997
+ retry_coordinator=retry_coordinator,
1998
+ app_state_sync=app_state_sync,
1999
+ chat_coordinator=app_state_mutations,
2000
+ stream_control=stream_control,
2001
+ incoming_node=incoming_node,
2002
+ low_level_coordinator=low_level_coordinator,
2003
+ passive_tasks=passive_tasks,
2004
+ group_coordinator=group_coordinator,
2005
+ status_coordinator=status_coordinator,
2006
+ broadcast_list_coordinator=broadcast_list_coordinator,
2007
+ newsletter_coordinator=newsletter_coordinator,
2008
+ privacy_coordinator=privacy_coordinator,
2009
+ profile_coordinator=profile_coordinator,
2010
+ business_coordinator=business_coordinator,
2011
+ bot_coordinator=bot_coordinator,
2012
+ email_coordinator=email_coordinator,
2013
+ receipt_queue=receipt_queue,
2014
+ connection_manager=connection_manager,
2015
+ trusted_contact_token=trusted_contact_token,
2016
+ ab_props_coordinator=ab_props_coordinator,
2017
+ peer_data_operation=peer_data_operation,
2018
+ mobile_coordinator=mobile_coordinator,
2019
+ is_mobile_primary=is_mobile_primary,
2020
+ )