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,2538 @@
1
+ """App-state mutation coordinator (mirrors ``WaAppStateMutationCoordinator``).
2
+
3
+ TEMPORARY (sibling layers not yet ported): the ``WA_APPSTATE_*`` schema
4
+ table, the legacy index-arg map, the collection states, the enum helpers and
5
+ the mutation-event parser below are verbatim ports of ``src/appstate-spec.ts``
6
+ (generated from ``spec/appstate``), ``src/protocol/appstate.ts`` and
7
+ ``src/client/events/appstate-mutation.ts``, plus the used parts of
8
+ ``src/protocol/jid.ts``. They move to ``zapy._appstate`` / ``zapy._protocol``
9
+ once those land; the call sites already match the canonical shapes.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import asyncio
15
+ import json
16
+ import math
17
+ import time
18
+ from collections.abc import Awaitable, Callable, Mapping, Sequence
19
+ from dataclasses import dataclass
20
+ from typing import Any, Protocol
21
+
22
+ from zapy._infra.log import Logger
23
+ from zapy._message.messaging import ServerClock
24
+ from zapy._proto import WAProto_pb2
25
+ from zapy._store.contracts.contact import WaStoredContactRecord
26
+ from zapy._store.contracts.message import WaMessageStore
27
+ from zapy._util.coercion import resolve_positive
28
+ from zapy._util.primitives import to_error
29
+
30
+ # Verbatim ``src/protocol/appstate.ts``.
31
+ _WA_APP_STATE_COLLECTION_STATES: dict[str, str] = {
32
+ "SUCCESS": "success",
33
+ "SUCCESS_HAS_MORE": "success_has_more",
34
+ "CONFLICT": "conflict",
35
+ "CONFLICT_HAS_MORE": "conflict_has_more",
36
+ "ERROR_RETRY": "error_retry",
37
+ "ERROR_FATAL": "error_fatal",
38
+ "BLOCKED": "blocked",
39
+ }
40
+
41
+ _WA_APP_STATE_ARCHIVE_RANGE_DEFAULT_LIMIT: int = 256
42
+
43
+ _WA_EMPTY_MUTATION_MAC: bytes = b""
44
+
45
+ # Verbatim ``src/appstate-spec.ts``.
46
+ _WA_APPSTATE_LEGACY_INDEX_ARGS: dict[str, dict[str, str]] = {
47
+ "LabelEdit": {"id": "labelId"},
48
+ "BusinessBroadcastCampaign": {"campaign": "campaignId"},
49
+ }
50
+
51
+
52
+ def _is_jid_type(jid: str, server: str) -> bool:
53
+ at_index = len(jid) - len(server) - 1
54
+ if at_index < 1 or jid[at_index] != "@" or not jid.endswith(server):
55
+ return False
56
+ return "@" not in jid[:at_index]
57
+
58
+
59
+ def _is_lid_jid(jid: str) -> bool:
60
+ """Whether the JID lives on the `@lid` server."""
61
+ return _is_jid_type(jid, "lid")
62
+
63
+
64
+ def _is_user_jid(jid: str) -> bool:
65
+ """Whether the JID lives on the `@s.whatsapp.net` server."""
66
+ return _is_jid_type(jid, "s.whatsapp.net")
67
+
68
+
69
+ def _is_group_jid(jid: str) -> bool:
70
+ """Whether the JID lives on the `@g.us` server."""
71
+ return _is_jid_type(jid, "g.us")
72
+
73
+
74
+ def _is_broadcast_jid(jid: str) -> bool:
75
+ """Whether the JID lives on the `@broadcast` server."""
76
+ return _is_jid_type(jid, "broadcast")
77
+
78
+
79
+ def _is_group_or_broadcast_jid(jid: str) -> bool:
80
+ """Whether the JID is a group or broadcast JID."""
81
+ return _is_group_jid(jid) or _is_broadcast_jid(jid)
82
+
83
+
84
+ def _normalize_recipient_jid(to: str) -> str:
85
+ """Normalize a user-supplied recipient into a canonical JID."""
86
+ text = to.strip()
87
+ if not text:
88
+ raise ValueError("recipient cannot be empty")
89
+ has_dash = False
90
+ for char in text:
91
+ if char == "@":
92
+ return text
93
+ if char == "-":
94
+ has_dash = True
95
+ digits = "".join(char for char in text if char.isdigit())
96
+ if has_dash:
97
+ return f"{text}@g.us"
98
+ if not digits:
99
+ raise ValueError(f"invalid recipient: {to}")
100
+ return f"{digits}@s.whatsapp.net"
101
+
102
+
103
+ def _to_user_jid(jid: str) -> str:
104
+ """Strip the ``:device`` segment, returning the bare ``user@server`` form."""
105
+ at_index = jid.find("@")
106
+ if at_index < 1 or at_index >= len(jid) - 1:
107
+ raise ValueError(f"invalid jid: {jid}")
108
+ colon_index = jid.find(":")
109
+ if colon_index == -1 or colon_index > at_index:
110
+ return jid
111
+ user = jid[:colon_index]
112
+ server = jid[at_index + 1 :]
113
+ device = jid[colon_index + 1 : at_index]
114
+ if not device or not device.isdigit():
115
+ raise ValueError(f"invalid jid device: {jid}")
116
+ return f"{user}@{server}"
117
+
118
+
119
+ def _normalize_device_jid(jid: str) -> str:
120
+ """Return the JID in its full device form (`user@server` when device is 0)."""
121
+ at_index = jid.find("@")
122
+ if at_index < 1:
123
+ raise ValueError(f"invalid jid: {jid}")
124
+ user_part = jid[:at_index]
125
+ server = jid[at_index + 1 :]
126
+ if ":" in user_part:
127
+ user, device_text = user_part.split(":", 1)
128
+ device = int(device_text) if device_text.isdigit() else 0
129
+ else:
130
+ user, device = user_part, 0
131
+ if device == 0:
132
+ return f"{user}@{server}"
133
+ return f"{user}:{device}@{server}"
134
+
135
+
136
+ # Index parts are 4-tuples: (kind, literal_value, name, proto_enum).
137
+ _IndexPart = tuple[str, str | None, str | None, str | None]
138
+
139
+
140
+ @dataclass(frozen=True, slots=True)
141
+ class _WaAppstateSchema:
142
+ """One app-state schema row (verbatim ``spec/appstate`` shape)."""
143
+
144
+ name: str
145
+ collection: str
146
+ version: int
147
+ scope: str
148
+ value_field: str | None
149
+ value_proto_type: str | None
150
+ value_enum_fields: dict[str, str] | None
151
+ index_parts: tuple[_IndexPart, ...]
152
+
153
+
154
+ def _schema(
155
+ name: str,
156
+ collection: str,
157
+ version: int,
158
+ scope: str,
159
+ value_field: str | None,
160
+ value_proto_type: str | None,
161
+ value_enum_fields: dict[str, str] | None,
162
+ index_parts: tuple[_IndexPart, ...],
163
+ ) -> _WaAppstateSchema:
164
+ """Build one schema row (keeps the generated table below compact)."""
165
+ return _WaAppstateSchema(
166
+ name=name,
167
+ collection=collection,
168
+ version=version,
169
+ scope=scope,
170
+ value_field=value_field,
171
+ value_proto_type=value_proto_type,
172
+ value_enum_fields=value_enum_fields,
173
+ index_parts=index_parts,
174
+ )
175
+
176
+
177
+ _WA_APPSTATE_SCHEMAS: dict[str, _WaAppstateSchema] = {
178
+ "AdsCtwaPerCustomerDataSharing": _schema(
179
+ "ctwaPerCustomerDataSharing",
180
+ "regular_high",
181
+ 1,
182
+ "account",
183
+ "ctwaPerCustomerDataSharingAction",
184
+ "SyncActionValue.CtwaPerCustomerDataSharingAction",
185
+ None,
186
+ (
187
+ ("literal", "ctwaPerCustomerDataSharing", None, None),
188
+ ("string", None, "accountLid", None),
189
+ ),
190
+ ),
191
+ "Agent": _schema(
192
+ "deviceAgent",
193
+ "regular",
194
+ 7,
195
+ "account",
196
+ "agentAction",
197
+ "SyncActionValue.AgentAction",
198
+ None,
199
+ (
200
+ ("literal", "deviceAgent", None, None),
201
+ ("string", None, "agentId", None),
202
+ ),
203
+ ),
204
+ "AiThreadDelete": _schema(
205
+ "ai_thread_delete",
206
+ "regular_high",
207
+ 7,
208
+ "chat",
209
+ None,
210
+ None,
211
+ None,
212
+ (
213
+ ("literal", "ai_thread_delete", None, None),
214
+ ("jid", None, "chatJid", None),
215
+ ("string", None, "id", None),
216
+ ),
217
+ ),
218
+ "AiThreadPin": _schema(
219
+ "thread_pin",
220
+ "regular_low",
221
+ 7,
222
+ "chat",
223
+ "threadPinAction",
224
+ "SyncActionValue.ThreadPinAction",
225
+ None,
226
+ (
227
+ ("literal", "thread_pin", None, None),
228
+ ("jid", None, "chatJid", None),
229
+ ("string", None, "id", None),
230
+ ),
231
+ ),
232
+ "AiThreadRename": _schema(
233
+ "ai_thread_rename",
234
+ "regular_low",
235
+ 7,
236
+ "chat",
237
+ "aiThreadRenameAction",
238
+ "SyncActionValue.AiThreadRenameAction",
239
+ None,
240
+ (
241
+ ("literal", "ai_thread_rename", None, None),
242
+ ("jid", None, "chatJid", None),
243
+ ("string", None, "id", None),
244
+ ),
245
+ ),
246
+ "AndroidUnsupportedActions": _schema(
247
+ "android_unsupported_actions",
248
+ "regular_low",
249
+ 4,
250
+ "account",
251
+ "androidUnsupportedActions",
252
+ "SyncActionValue.AndroidUnsupportedActions",
253
+ None,
254
+ (("literal", "android_unsupported_actions", None, None),),
255
+ ),
256
+ "Archive": _schema(
257
+ "archive",
258
+ "regular_low",
259
+ 3,
260
+ "chatMessageRange",
261
+ "archiveChatAction",
262
+ "SyncActionValue.ArchiveChatAction",
263
+ None,
264
+ (
265
+ ("literal", "archive", None, None),
266
+ ("jid", None, "chatJid", None),
267
+ ),
268
+ ),
269
+ "AvatarUpdated": _schema(
270
+ "avatar_updated_action",
271
+ "regular",
272
+ 7,
273
+ "account",
274
+ None,
275
+ None,
276
+ None,
277
+ (("literal", "avatar_updated_action", None, None),),
278
+ ),
279
+ "BBProPendingCustomerBaseAction": _schema(
280
+ "bb_pro_pending_customer_base_action",
281
+ "regular_low",
282
+ 7,
283
+ "account",
284
+ "bbProPendingCustomerBaseAction",
285
+ "SyncActionValue.BBProPendingCustomerBaseAction",
286
+ None,
287
+ (
288
+ ("literal", "bb_pro_pending_customer_base_action", None, None),
289
+ ("string", None, "action", None),
290
+ ),
291
+ ),
292
+ "BizAiSettingsNudge": _schema(
293
+ "biz_ai_settings_nudge",
294
+ "regular_high",
295
+ 1,
296
+ "account",
297
+ "bizAiSettingsNudgeAction",
298
+ "SyncActionValue.BizAISettingsNudgeAction",
299
+ {"category": "BizAISettingsNudgeAction.BizAISettingsCategory"},
300
+ (("literal", "biz_ai_settings_nudge", None, None),),
301
+ ),
302
+ "BotWelcomeRequest": _schema(
303
+ "bot_welcome_request",
304
+ "regular_low",
305
+ 2,
306
+ "chat",
307
+ "botWelcomeRequestAction",
308
+ "SyncActionValue.BotWelcomeRequestAction",
309
+ None,
310
+ (
311
+ ("literal", "bot_welcome_request", None, None),
312
+ ("jid", None, "chatJid", None),
313
+ ),
314
+ ),
315
+ "BusinessBroadcastCampaign": _schema(
316
+ "business_broadcast_campaign",
317
+ "regular",
318
+ 1,
319
+ "account",
320
+ "businessBroadcastCampaignAction",
321
+ "SyncActionValue.BusinessBroadcastCampaignAction",
322
+ {
323
+ "bbProStatus": "BusinessBroadcastCampaignBBProStatus",
324
+ "status": "BusinessBroadcastCampaignStatus",
325
+ },
326
+ (
327
+ ("literal", "business_broadcast_campaign", None, None),
328
+ ("string", None, "campaignId", None),
329
+ ),
330
+ ),
331
+ "BusinessBroadcastInsights": _schema(
332
+ "business_broadcast_insights_sync",
333
+ "regular",
334
+ 1,
335
+ "account",
336
+ "businessBroadcastInsightsAction",
337
+ "SyncActionValue.BusinessBroadcastInsightsAction",
338
+ None,
339
+ (
340
+ ("literal", "business_broadcast_insights_sync", None, None),
341
+ ("string", None, "campaignId", None),
342
+ ),
343
+ ),
344
+ "BusinessBroadcastList": _schema(
345
+ "business_broadcast_list",
346
+ "regular",
347
+ 1,
348
+ "account",
349
+ "businessBroadcastListAction",
350
+ "SyncActionValue.BusinessBroadcastListAction",
351
+ None,
352
+ (
353
+ ("literal", "business_broadcast_list", None, None),
354
+ ("string", None, "id", None),
355
+ ),
356
+ ),
357
+ "CallLog": _schema(
358
+ "call_log",
359
+ "regular",
360
+ 1,
361
+ "account",
362
+ "callLogAction",
363
+ "SyncActionValue.CallLogAction",
364
+ {
365
+ "callLogRecord.callResult": "CallLogRecord.CallResult",
366
+ "callLogRecord.callType": "CallLogRecord.CallType",
367
+ "callLogRecord.participants.callResult": "CallLogRecord.CallResult",
368
+ "callLogRecord.silenceReason": "CallLogRecord.SilenceReason",
369
+ },
370
+ (
371
+ ("literal", "call_log", None, None),
372
+ ("string", None, "key1", None),
373
+ ("string", None, "callId", None),
374
+ ("string", None, "fromMe", None),
375
+ ),
376
+ ),
377
+ "ChatAssignment": _schema(
378
+ "agentChatAssignment",
379
+ "regular",
380
+ 7,
381
+ "chat",
382
+ "chatAssignment",
383
+ "SyncActionValue.ChatAssignmentAction",
384
+ None,
385
+ (
386
+ ("literal", "agentChatAssignment", None, None),
387
+ ("jid", None, "chatJid", None),
388
+ ),
389
+ ),
390
+ "ChatAssignmentOpenedStatus": _schema(
391
+ "agentChatAssignmentOpenedStatus",
392
+ "regular",
393
+ 7,
394
+ "chat",
395
+ "chatAssignmentOpenedStatus",
396
+ "SyncActionValue.ChatAssignmentOpenedStatusAction",
397
+ None,
398
+ (
399
+ ("literal", "agentChatAssignmentOpenedStatus", None, None),
400
+ ("jid", None, "chatJid", None),
401
+ ("string", None, "agentId", None),
402
+ ),
403
+ ),
404
+ "ChatLockSettings": _schema(
405
+ "setting_chatLock",
406
+ "regular_low",
407
+ 7,
408
+ "account",
409
+ "chatLockSettings",
410
+ "ChatLockSettings",
411
+ None,
412
+ (("literal", "setting_chatLock", None, None),),
413
+ ),
414
+ "ClearChat": _schema(
415
+ "clearChat",
416
+ "regular_high",
417
+ 6,
418
+ "chatMessageRange",
419
+ "clearChatAction",
420
+ "SyncActionValue.ClearChatAction",
421
+ None,
422
+ (
423
+ ("literal", "clearChat", None, None),
424
+ ("jid", None, "chatJid", None),
425
+ ("string", None, "deleteStarred", None),
426
+ ("string", None, "deleteMedia", None),
427
+ ),
428
+ ),
429
+ "Contact": _schema(
430
+ "contact",
431
+ "critical_unblock_low",
432
+ 2,
433
+ "account",
434
+ "contactAction",
435
+ "SyncActionValue.ContactAction",
436
+ None,
437
+ (
438
+ ("literal", "contact", None, None),
439
+ ("string", None, "id", None),
440
+ ),
441
+ ),
442
+ "ContactManagerMetadata": _schema(
443
+ "contact_manager_metadata",
444
+ "regular_low",
445
+ 1,
446
+ "account",
447
+ "contactManagerMetadataAction",
448
+ "SyncActionValue.ContactManagerMetadataAction",
449
+ None,
450
+ (
451
+ ("literal", "contact_manager_metadata", None, None),
452
+ ("string", None, "key1", None),
453
+ ),
454
+ ),
455
+ "CustomPaymentMethods": _schema(
456
+ "custom_payment_methods",
457
+ "regular_low",
458
+ 7,
459
+ "account",
460
+ "customPaymentMethodsAction",
461
+ "SyncActionValue.CustomPaymentMethodsAction",
462
+ None,
463
+ (("literal", "custom_payment_methods", None, None),),
464
+ ),
465
+ "CustomerData": _schema(
466
+ "customer_data",
467
+ "regular_low",
468
+ 1,
469
+ "account",
470
+ "customerDataAction",
471
+ "SyncActionValue.CustomerDataAction",
472
+ None,
473
+ (
474
+ ("literal", "customer_data", None, None),
475
+ ("string", None, "chatJid", None),
476
+ ),
477
+ ),
478
+ "DeleteChat": _schema(
479
+ "deleteChat",
480
+ "regular_high",
481
+ 6,
482
+ "chatMessageRange",
483
+ "deleteChatAction",
484
+ "SyncActionValue.DeleteChatAction",
485
+ None,
486
+ (
487
+ ("literal", "deleteChat", None, None),
488
+ ("jid", None, "chatJid", None),
489
+ ("string", None, "deleteMedia", None),
490
+ ),
491
+ ),
492
+ "DeleteMessageForMe": _schema(
493
+ "deleteMessageForMe",
494
+ "regular_high",
495
+ 3,
496
+ "message",
497
+ "deleteMessageForMeAction",
498
+ "SyncActionValue.DeleteMessageForMeAction",
499
+ None,
500
+ (
501
+ ("literal", "deleteMessageForMe", None, None),
502
+ ("jid", None, "remote", None),
503
+ ("string", None, "id", None),
504
+ ("boolString", None, "fromMe", None),
505
+ ("jidOrZero", None, "participant", None),
506
+ ),
507
+ ),
508
+ "DetectedOutcomeStatus": _schema(
509
+ "detected_outcomes_status_action",
510
+ "regular",
511
+ 1,
512
+ "account",
513
+ "detectedOutcomesStatusAction",
514
+ "SyncActionValue.DetectedOutcomesStatusAction",
515
+ None,
516
+ (("literal", "detected_outcomes_status_action", None, None),),
517
+ ),
518
+ "DeviceCapabilities": _schema(
519
+ "device_capabilities",
520
+ "regular_low",
521
+ 7,
522
+ "account",
523
+ "deviceCapabilities",
524
+ "DeviceCapabilities",
525
+ None,
526
+ (
527
+ ("literal", "device_capabilities", None, None),
528
+ ("string", None, "jid", None),
529
+ ),
530
+ ),
531
+ "DeviceCapabilitiesV2": _schema(
532
+ "device_capabilities_v2",
533
+ "regular_low",
534
+ 7,
535
+ "account",
536
+ "deviceCapabilitiesV2",
537
+ "DeviceCapabilities",
538
+ None,
539
+ (
540
+ ("literal", "device_capabilities_v2", None, None),
541
+ ("string", None, "jid", None),
542
+ ),
543
+ ),
544
+ "DisableLinkPreviews": _schema(
545
+ "setting_disableLinkPreviews",
546
+ "regular",
547
+ 8,
548
+ "account",
549
+ "privacySettingDisableLinkPreviewsAction",
550
+ "SyncActionValue.PrivacySettingDisableLinkPreviewsAction",
551
+ None,
552
+ (("literal", "setting_disableLinkPreviews", None, None),),
553
+ ),
554
+ "ExternalWebBeta": _schema(
555
+ "external_web_beta",
556
+ "regular",
557
+ 3,
558
+ "account",
559
+ "externalWebBetaAction",
560
+ "SyncActionValue.ExternalWebBetaAction",
561
+ None,
562
+ (("literal", "external_web_beta", None, None),),
563
+ ),
564
+ "FavoriteSticker": _schema(
565
+ "favoriteSticker",
566
+ "regular_low",
567
+ 7,
568
+ "account",
569
+ "stickerAction",
570
+ "SyncActionValue.StickerAction",
571
+ None,
572
+ (
573
+ ("literal", "favoriteSticker", None, None),
574
+ ("string", None, "filehash", None),
575
+ ),
576
+ ),
577
+ "Favorites": _schema(
578
+ "favorites",
579
+ "regular_high",
580
+ 1,
581
+ "account",
582
+ "favoritesAction",
583
+ "SyncActionValue.FavoritesAction",
584
+ None,
585
+ (("literal", "favorites", None, None),),
586
+ ),
587
+ "GroupHistoryToggle": _schema(
588
+ "group_history_toggle",
589
+ "regular_low",
590
+ 1,
591
+ "chat",
592
+ "groupHistoryToggleAction",
593
+ "SyncActionValue.GroupHistoryToggleAction",
594
+ {"groupHistoryToggleMode": "GroupHistoryToggleAction.GroupHistoryToggleMode"},
595
+ (
596
+ ("literal", "group_history_toggle", None, None),
597
+ ("jid", None, "chatJid", None),
598
+ ),
599
+ ),
600
+ "InteractiveMessageAction": _schema(
601
+ "interactive_message_action",
602
+ "regular_low",
603
+ 1,
604
+ "message",
605
+ "interactiveMessageAction",
606
+ "SyncActionValue.InteractiveMessageAction",
607
+ {"type": "InteractiveMessageAction.InteractiveMessageActionMode"},
608
+ (
609
+ ("literal", "interactive_message_action", None, None),
610
+ ("jid", None, "remote", None),
611
+ ("string", None, "id", None),
612
+ ("boolString", None, "fromMe", None),
613
+ ("jidOrZero", None, "participant", None),
614
+ ("string", None, "arg5", None),
615
+ ),
616
+ ),
617
+ "LabelEdit": _schema(
618
+ "label_edit",
619
+ "regular",
620
+ 3,
621
+ "account",
622
+ "labelEditAction",
623
+ "SyncActionValue.LabelEditAction",
624
+ {"type": "LabelEditAction.ListType"},
625
+ (
626
+ ("literal", "label_edit", None, None),
627
+ ("string", None, "labelId", None),
628
+ ),
629
+ ),
630
+ "LabelJid": _schema(
631
+ "label_jid",
632
+ "regular",
633
+ 3,
634
+ "chatOrContact",
635
+ "labelAssociationAction",
636
+ "SyncActionValue.LabelAssociationAction",
637
+ None,
638
+ (
639
+ ("literal", "label_jid", None, None),
640
+ ("string", None, "labelId", None),
641
+ ("jid", None, "chatJid", None),
642
+ ),
643
+ ),
644
+ "LabelReordering": _schema(
645
+ "label_reordering",
646
+ "regular",
647
+ 3,
648
+ "account",
649
+ "labelReorderingAction",
650
+ "SyncActionValue.LabelReorderingAction",
651
+ None,
652
+ (("literal", "label_reordering", None, None),),
653
+ ),
654
+ "LabelSublist": _schema(
655
+ "label_sublist",
656
+ "regular",
657
+ 1,
658
+ "chatOrContact",
659
+ "labelSublistAction",
660
+ "SyncActionValue.LabelSublistAction",
661
+ None,
662
+ (
663
+ ("literal", "label_sublist", None, None),
664
+ ("string", None, "predefinedId", None),
665
+ ("jid", None, "chatJid", None),
666
+ ),
667
+ ),
668
+ "LidContact": _schema(
669
+ "lid_contact",
670
+ "critical_unblock_low",
671
+ 1,
672
+ "account",
673
+ "lidContactAction",
674
+ "SyncActionValue.LidContactAction",
675
+ None,
676
+ (
677
+ ("literal", "lid_contact", None, None),
678
+ ("string", None, "id", None),
679
+ ),
680
+ ),
681
+ "LocaleSetting": _schema(
682
+ "setting_locale",
683
+ "critical_block",
684
+ 3,
685
+ "account",
686
+ "localeSetting",
687
+ "SyncActionValue.LocaleSetting",
688
+ None,
689
+ (("literal", "setting_locale", None, None),),
690
+ ),
691
+ "LockChat": _schema(
692
+ "lock",
693
+ "regular_low",
694
+ 7,
695
+ "chat",
696
+ "lockChatAction",
697
+ "SyncActionValue.LockChatAction",
698
+ None,
699
+ (
700
+ ("literal", "lock", None, None),
701
+ ("jid", None, "chatJid", None),
702
+ ),
703
+ ),
704
+ "MarkChatAsRead": _schema(
705
+ "markChatAsRead",
706
+ "regular_low",
707
+ 3,
708
+ "chatMessageRange",
709
+ "markChatAsReadAction",
710
+ "SyncActionValue.MarkChatAsReadAction",
711
+ None,
712
+ (
713
+ ("literal", "markChatAsRead", None, None),
714
+ ("jid", None, "chatJid", None),
715
+ ),
716
+ ),
717
+ "MarketingMessage": _schema(
718
+ "marketingMessage",
719
+ "regular",
720
+ 7,
721
+ "account",
722
+ "marketingMessageAction",
723
+ "SyncActionValue.MarketingMessageAction",
724
+ {"type": "MarketingMessageAction.MarketingMessagePrototypeType"},
725
+ (
726
+ ("literal", "marketingMessage", None, None),
727
+ ("string", None, "id", None),
728
+ ),
729
+ ),
730
+ "MarketingMessageBroadcast": _schema(
731
+ "marketingMessageBroadcast",
732
+ "regular",
733
+ 7,
734
+ "account",
735
+ None,
736
+ None,
737
+ None,
738
+ (
739
+ ("literal", "marketingMessageBroadcast", None, None),
740
+ ("string", None, "premiumMessageId", None),
741
+ ("string", None, "messageId", None),
742
+ ),
743
+ ),
744
+ "MerchantPaymentPartner": _schema(
745
+ "merchant_payment_partner",
746
+ "regular_low",
747
+ 7,
748
+ "account",
749
+ None,
750
+ None,
751
+ None,
752
+ (("literal", "merchant_payment_partner", None, None),),
753
+ ),
754
+ "Mute": _schema(
755
+ "mute",
756
+ "regular_high",
757
+ 2,
758
+ "chat",
759
+ "muteAction",
760
+ "SyncActionValue.MuteAction",
761
+ None,
762
+ (
763
+ ("literal", "mute", None, None),
764
+ ("jid", None, "chatJid", None),
765
+ ),
766
+ ),
767
+ "NctSaltSync": _schema(
768
+ "nct_salt_sync",
769
+ "regular_high",
770
+ 1,
771
+ "account",
772
+ "nctSaltSyncAction",
773
+ "SyncActionValue.NctSaltSyncAction",
774
+ None,
775
+ (("literal", "nct_salt_sync", None, None),),
776
+ ),
777
+ "NoteEdit": _schema(
778
+ "note_edit",
779
+ "regular_low",
780
+ 7,
781
+ "account",
782
+ "noteEditAction",
783
+ "SyncActionValue.NoteEditAction",
784
+ {"type": "NoteEditAction.NoteType"},
785
+ (
786
+ ("literal", "note_edit", None, None),
787
+ ("string", None, "id", None),
788
+ ),
789
+ ),
790
+ "Nux": _schema(
791
+ "nux",
792
+ "regular_low",
793
+ 7,
794
+ "account",
795
+ "nuxAction",
796
+ "SyncActionValue.NuxAction",
797
+ None,
798
+ (
799
+ ("literal", "nux", None, None),
800
+ ("string", None, "nuxKey", None),
801
+ ),
802
+ ),
803
+ "OutContact": _schema(
804
+ "out_contact",
805
+ "regular_low",
806
+ 1,
807
+ "account",
808
+ "outContactAction",
809
+ "SyncActionValue.OutContactAction",
810
+ None,
811
+ (
812
+ ("literal", "out_contact", None, None),
813
+ ("string", None, "id", None),
814
+ ),
815
+ ),
816
+ "PaymentInfo": _schema(
817
+ "payment_info",
818
+ "regular_low",
819
+ 7,
820
+ "account",
821
+ "paymentInfoAction",
822
+ "SyncActionValue.PaymentInfoAction",
823
+ None,
824
+ (("literal", "payment_info", None, None),),
825
+ ),
826
+ "PaymentTos": _schema(
827
+ "payment_tos",
828
+ "regular_low",
829
+ 7,
830
+ "account",
831
+ "paymentTosAction",
832
+ "SyncActionValue.PaymentTosAction",
833
+ {"paymentNotice": "PaymentTosAction.PaymentNotice"},
834
+ (("literal", "payment_tos", None, None),),
835
+ ),
836
+ "Pin": _schema(
837
+ "pin_v1",
838
+ "regular_low",
839
+ 5,
840
+ "chat",
841
+ "pinAction",
842
+ "SyncActionValue.PinAction",
843
+ None,
844
+ (
845
+ ("literal", "pin_v1", None, None),
846
+ ("jid", None, "chatJid", None),
847
+ ),
848
+ ),
849
+ "PnForLidChat": _schema(
850
+ "pnForLidChat",
851
+ "regular",
852
+ 8,
853
+ "account",
854
+ "pnForLidChatAction",
855
+ "SyncActionValue.PnForLidChatAction",
856
+ None,
857
+ (
858
+ ("literal", "pnForLidChat", None, None),
859
+ ("string", None, "lid", None),
860
+ ),
861
+ ),
862
+ "PrimaryFeature": _schema(
863
+ "primary_feature",
864
+ "regular",
865
+ 7,
866
+ "account",
867
+ "primaryFeature",
868
+ "SyncActionValue.PrimaryFeature",
869
+ None,
870
+ (("literal", "primary_feature", None, None),),
871
+ ),
872
+ "PrimaryVersion": _schema(
873
+ "primary_version",
874
+ "regular_low",
875
+ 7,
876
+ "account",
877
+ "primaryVersionAction",
878
+ "SyncActionValue.PrimaryVersionAction",
879
+ None,
880
+ (
881
+ ("literal", "primary_version", None, None),
882
+ ("string", None, "key1", None),
883
+ ),
884
+ ),
885
+ "QuickReply": _schema(
886
+ "quick_reply",
887
+ "regular",
888
+ 2,
889
+ "account",
890
+ "quickReplyAction",
891
+ "SyncActionValue.QuickReplyAction",
892
+ None,
893
+ (
894
+ ("literal", "quick_reply", None, None),
895
+ ("string", None, "id", None),
896
+ ),
897
+ ),
898
+ "RemoveRecentSticker": _schema(
899
+ "removeRecentSticker",
900
+ "regular_low",
901
+ 7,
902
+ "account",
903
+ "removeRecentStickerAction",
904
+ "SyncActionValue.RemoveRecentStickerAction",
905
+ None,
906
+ (
907
+ ("literal", "removeRecentSticker", None, None),
908
+ ("string", None, "filehash", None),
909
+ ),
910
+ ),
911
+ "Sentinel": _schema(
912
+ "sentinel",
913
+ "regular_low",
914
+ 3,
915
+ "account",
916
+ "keyExpiration",
917
+ "SyncActionValue.KeyExpiration",
918
+ None,
919
+ (
920
+ ("literal", "sentinel", None, None),
921
+ ("string", None, "collection", None),
922
+ ),
923
+ ),
924
+ "SettingPushName": _schema(
925
+ "setting_pushName",
926
+ "critical_block",
927
+ 1,
928
+ "account",
929
+ "pushNameSetting",
930
+ "SyncActionValue.PushNameSetting",
931
+ None,
932
+ (("literal", "setting_pushName", None, None),),
933
+ ),
934
+ "SettingsSync": _schema(
935
+ "settings_sync",
936
+ "regular_low",
937
+ 1,
938
+ "account",
939
+ "settingsSyncAction",
940
+ "SyncActionValue.SettingsSyncAction",
941
+ {
942
+ "bannerNotificationDisplayMode": "SettingsSyncAction.DisplayMode",
943
+ "mediaAutoDownloadQuality": (
944
+ "SettingsSyncAction.MediaAutoDownloadQualitySetting"
945
+ ),
946
+ "mediaUploadQuality": "SettingsSyncAction.MediaQualitySetting",
947
+ "unreadCounterBadgeDisplayMode": "SettingsSyncAction.DisplayMode",
948
+ },
949
+ (
950
+ ("literal", "settings_sync", None, None),
951
+ ("enum", None, "settingPlatform", "SettingsSyncAction.SettingPlatform"),
952
+ ("enum", None, "settingKey", "SettingsSyncAction.SettingKey"),
953
+ ("jid", None, "chatJid", None),
954
+ ),
955
+ ),
956
+ "ShareOwnPn": _schema(
957
+ "shareOwnPn",
958
+ "regular",
959
+ 8,
960
+ "account",
961
+ None,
962
+ None,
963
+ None,
964
+ (
965
+ ("literal", "shareOwnPn", None, None),
966
+ ("string", None, "lid", None),
967
+ ),
968
+ ),
969
+ "Star": _schema(
970
+ "star",
971
+ "regular_high",
972
+ 2,
973
+ "message",
974
+ "starAction",
975
+ "SyncActionValue.StarAction",
976
+ None,
977
+ (
978
+ ("literal", "star", None, None),
979
+ ("jid", None, "remote", None),
980
+ ("string", None, "id", None),
981
+ ("boolString", None, "fromMe", None),
982
+ ("jidOrZero", None, "participant", None),
983
+ ),
984
+ ),
985
+ "StatusPrivacy": _schema(
986
+ "status_privacy",
987
+ "regular_high",
988
+ 7,
989
+ "account",
990
+ "statusPrivacy",
991
+ "SyncActionValue.StatusPrivacyAction",
992
+ {
993
+ "mode": "StatusPrivacyAction.StatusDistributionMode",
994
+ "modes": "StatusPrivacyAction.StatusDistributionMode",
995
+ },
996
+ (("literal", "status_privacy", None, None),),
997
+ ),
998
+ "SubscriptionsSyncV2": _schema(
999
+ "subscriptions_sync_v2",
1000
+ "regular",
1001
+ 1,
1002
+ "account",
1003
+ "subscriptionsSyncV2Action",
1004
+ "SyncActionValue.SubscriptionsSyncV2Action",
1005
+ None,
1006
+ (("literal", "subscriptions_sync_v2", None, None),),
1007
+ ),
1008
+ "TimeFormat": _schema(
1009
+ "time_format",
1010
+ "regular_low",
1011
+ 7,
1012
+ "account",
1013
+ "timeFormatAction",
1014
+ "SyncActionValue.TimeFormatAction",
1015
+ None,
1016
+ (("literal", "time_format", None, None),),
1017
+ ),
1018
+ "UnarchiveChatsSetting": _schema(
1019
+ "setting_unarchiveChats",
1020
+ "regular_low",
1021
+ 4,
1022
+ "account",
1023
+ "unarchiveChatsSetting",
1024
+ "SyncActionValue.UnarchiveChatsSetting",
1025
+ None,
1026
+ (("literal", "setting_unarchiveChats", None, None),),
1027
+ ),
1028
+ "UserStatusMute": _schema(
1029
+ "userStatusMute",
1030
+ "regular_high",
1031
+ 7,
1032
+ "account",
1033
+ "userStatusMuteAction",
1034
+ "SyncActionValue.UserStatusMuteAction",
1035
+ None,
1036
+ (
1037
+ ("literal", "userStatusMute", None, None),
1038
+ ("string", None, "id", None),
1039
+ ),
1040
+ ),
1041
+ "VoipRelayAllCalls": _schema(
1042
+ "setting_relayAllCalls",
1043
+ "regular",
1044
+ 1,
1045
+ "account",
1046
+ "privacySettingRelayAllCalls",
1047
+ "SyncActionValue.PrivacySettingRelayAllCalls",
1048
+ None,
1049
+ (("literal", "setting_relayAllCalls", None, None),),
1050
+ ),
1051
+ "WaffleAccountLinkState": _schema(
1052
+ "waffle_account_link_state",
1053
+ "regular_high",
1054
+ 1,
1055
+ "account",
1056
+ "waffleAccountLinkStateAction",
1057
+ "SyncActionValue.WaffleAccountLinkStateAction",
1058
+ {"linkState": "WaffleAccountLinkStateAction.AccountLinkState"},
1059
+ (("literal", "waffle_account_link_state", None, None),),
1060
+ ),
1061
+ "WasaRootSecret": _schema(
1062
+ "wasa_root_secret",
1063
+ "regular_high",
1064
+ 1,
1065
+ "chat",
1066
+ "wasaRootSecretAction",
1067
+ "SyncActionValue.WASARootSecretAction",
1068
+ {"secrets.status": "WASARootSecretAction.RootSecretEntry.Status"},
1069
+ (
1070
+ ("literal", "wasa_root_secret", None, None),
1071
+ ("jid", None, "chatJid", None),
1072
+ ),
1073
+ ),
1074
+ }
1075
+
1076
+ _WA_APPSTATE_SCHEMA_BY_ACTION_NAME: dict[str, str] = {
1077
+ schema.name: key for key, schema in _WA_APPSTATE_SCHEMAS.items()
1078
+ }
1079
+
1080
+
1081
+ def get_appstate_schema_by_action_name(
1082
+ action_name: str,
1083
+ ) -> tuple[str, _WaAppstateSchema] | None:
1084
+ """Resolve an action wire name to its schema key and schema."""
1085
+ key = _WA_APPSTATE_SCHEMA_BY_ACTION_NAME.get(action_name)
1086
+ if key is None:
1087
+ return None
1088
+ return key, _WA_APPSTATE_SCHEMAS[key]
1089
+
1090
+
1091
+ def _resolve_enum_object(proto_enum_path: str) -> Any | None:
1092
+ """Resolve a dotted enum path below ``SyncActionValue`` (or top level)."""
1093
+ cursor: Any = WAProto_pb2.SyncActionValue
1094
+ for segment in proto_enum_path.split("."):
1095
+ cursor = getattr(cursor, segment, None)
1096
+ if cursor is None:
1097
+ break
1098
+ if cursor is not None:
1099
+ return cursor
1100
+ return getattr(WAProto_pb2, proto_enum_path, None)
1101
+
1102
+
1103
+ def encode_enum_value(proto_enum_path: str, name: str) -> int | None:
1104
+ """Encode an enum name to its number, or ``None`` when unresolvable."""
1105
+ enum_obj = _resolve_enum_object(proto_enum_path)
1106
+ if enum_obj is None:
1107
+ return None
1108
+ try:
1109
+ return int(enum_obj.Value(name))
1110
+ except Exception:
1111
+ return None
1112
+
1113
+
1114
+ def decode_enum_value(proto_enum_path: str, value: int) -> str | None:
1115
+ """Decode an enum number to its name, or ``None`` when unresolvable."""
1116
+ enum_obj = _resolve_enum_object(proto_enum_path)
1117
+ if enum_obj is None:
1118
+ return None
1119
+ try:
1120
+ return str(enum_obj.Name(value))
1121
+ except Exception:
1122
+ return None
1123
+
1124
+
1125
+ def decode_index_args_from_schema(
1126
+ schema: _WaAppstateSchema, parts: Sequence[str]
1127
+ ) -> dict[str, Any] | None:
1128
+ """Decode index parts into a fresh args dict, or ``None`` on mismatch."""
1129
+ if len(parts) != len(schema.index_parts):
1130
+ return None
1131
+ args: dict[str, Any] = {}
1132
+ for part, raw in zip(schema.index_parts, parts):
1133
+ kind, _literal, name, proto_enum = part
1134
+ if kind == "literal":
1135
+ continue
1136
+ if name is None:
1137
+ return None
1138
+ if kind == "boolString":
1139
+ if raw != "0" and raw != "1":
1140
+ return None
1141
+ args[name] = raw == "1"
1142
+ continue
1143
+ if kind == "jidOrZero":
1144
+ args[name] = None if raw == "0" else raw
1145
+ continue
1146
+ if kind == "enum":
1147
+ if proto_enum is None:
1148
+ return None
1149
+ numeric = int(raw) if raw.lstrip("-").isdigit() else None
1150
+ decoded = (
1151
+ decode_enum_value(proto_enum, numeric) if numeric is not None else None
1152
+ )
1153
+ args[name] = decoded if decoded is not None else raw
1154
+ continue
1155
+ args[name] = raw
1156
+ return args
1157
+
1158
+
1159
+ def build_mutation_index_from_schema(
1160
+ schema: _WaAppstateSchema, index_args: Mapping[str, Any]
1161
+ ) -> str:
1162
+ """Build the wire-level JSON index string for ``schema``."""
1163
+ parts: list[str] = []
1164
+ for part in schema.index_parts:
1165
+ kind, literal, name, proto_enum = part
1166
+ if kind == "literal":
1167
+ parts.append(literal or "")
1168
+ continue
1169
+ if name is None:
1170
+ raise ValueError(
1171
+ f'app-state index part for schema "{schema.name}" is missing a name'
1172
+ )
1173
+ arg = index_args.get(name)
1174
+ if kind == "boolString":
1175
+ parts.append("1" if arg else "0")
1176
+ continue
1177
+ if kind == "jidOrZero":
1178
+ if arg is None:
1179
+ from_me_slot = next(
1180
+ (
1181
+ item
1182
+ for item in schema.index_parts
1183
+ if item[0] == "boolString" and item[2] == "fromMe"
1184
+ ),
1185
+ None,
1186
+ )
1187
+ if from_me_slot is not None and index_args.get("fromMe") is not True:
1188
+ raise ValueError(
1189
+ f'app-state index arg "{name}" for schema "{schema.name}"'
1190
+ " requires a JID when fromMe is not true"
1191
+ )
1192
+ parts.append("0")
1193
+ continue
1194
+ parts.append(str(arg))
1195
+ continue
1196
+ if kind == "enum":
1197
+ if isinstance(arg, bool):
1198
+ raise ValueError(
1199
+ f'app-state enum index arg "{name}" for schema "{schema.name}"'
1200
+ " must be a string"
1201
+ )
1202
+ if isinstance(arg, int):
1203
+ parts.append(str(arg))
1204
+ continue
1205
+ if not isinstance(arg, str):
1206
+ raise ValueError(
1207
+ f'app-state enum index arg "{name}" for schema "{schema.name}"'
1208
+ " must be a string"
1209
+ )
1210
+ numeric = encode_enum_value(proto_enum or "", arg)
1211
+ if numeric is None:
1212
+ raise ValueError(
1213
+ f'app-state enum index arg "{name}"="{arg}" is not in enum'
1214
+ f" {proto_enum}"
1215
+ )
1216
+ parts.append(str(numeric))
1217
+ continue
1218
+ if not isinstance(arg, str):
1219
+ raise ValueError(
1220
+ f'app-state index arg "{name}" for schema "{schema.name}"'
1221
+ " must be a string"
1222
+ )
1223
+ parts.append(arg)
1224
+ return json.dumps(parts)
1225
+
1226
+
1227
+ @dataclass(frozen=True, slots=True)
1228
+ class WaAppStateMutationInput:
1229
+ """One pending app-state mutation (verbatim ``WaAppStateMutationInput``)."""
1230
+
1231
+ collection: str
1232
+ operation: str
1233
+ index: str
1234
+ value: dict[str, Any] | None = None
1235
+ version: int = 0
1236
+ timestamp: int = 0
1237
+
1238
+
1239
+ def build_set_mutation_from_schema(
1240
+ *,
1241
+ schema: _WaAppstateSchema,
1242
+ index_args: Mapping[str, Any],
1243
+ value: Mapping[str, Any],
1244
+ timestamp: int,
1245
+ ) -> WaAppStateMutationInput:
1246
+ """Build a `set` mutation input against ``schema``."""
1247
+ return WaAppStateMutationInput(
1248
+ collection=schema.collection,
1249
+ operation="set",
1250
+ index=build_mutation_index_from_schema(schema, index_args),
1251
+ value={**dict(value), "timestamp": timestamp},
1252
+ version=schema.version,
1253
+ timestamp=timestamp,
1254
+ )
1255
+
1256
+
1257
+ def build_remove_mutation_from_schema(
1258
+ *,
1259
+ schema: _WaAppstateSchema,
1260
+ index_args: Mapping[str, Any],
1261
+ timestamp: int,
1262
+ ) -> WaAppStateMutationInput:
1263
+ """Build a `remove` mutation input against ``schema``."""
1264
+ return WaAppStateMutationInput(
1265
+ collection=schema.collection,
1266
+ operation="remove",
1267
+ index=build_mutation_index_from_schema(schema, index_args),
1268
+ version=schema.version,
1269
+ timestamp=timestamp,
1270
+ )
1271
+
1272
+
1273
+ @dataclass(frozen=True, slots=True)
1274
+ class WaAppStateMutation:
1275
+ """One applied app-state mutation (verbatim ``WaAppStateMutation``)."""
1276
+
1277
+ collection: str
1278
+ operation: str
1279
+ source: str
1280
+ index: str
1281
+ value: dict[str, Any] | None
1282
+ version: int
1283
+ index_mac: bytes
1284
+ value_mac: bytes
1285
+ key_id: bytes
1286
+ timestamp: int
1287
+
1288
+
1289
+ @dataclass(frozen=True, slots=True)
1290
+ class WaAppStateCollectionSyncResult:
1291
+ """Sync outcome of one collection, with its mutations when present."""
1292
+
1293
+ collection: str
1294
+ state: str
1295
+ version: int | None = None
1296
+ mutations: Sequence[WaAppStateMutation] | None = None
1297
+
1298
+
1299
+ @dataclass(frozen=True, slots=True)
1300
+ class WaAppStateSyncResult:
1301
+ """Per-collection result of an app-state sync round."""
1302
+
1303
+ collections: Sequence[WaAppStateCollectionSyncResult] = ()
1304
+
1305
+
1306
+ @dataclass(frozen=True, slots=True)
1307
+ class WaAppStateSyncOptions:
1308
+ """Sync-round options: scope, pending mutations, blob downloads."""
1309
+
1310
+ collections: Sequence[str] | None = None
1311
+ pending_mutations: Sequence[WaAppStateMutationInput] | None = None
1312
+ download_external_blob: (
1313
+ Callable[[str, str, Mapping[str, Any]], Awaitable[bytes]] | None
1314
+ ) = None
1315
+ timeout_ms: float | None = None
1316
+
1317
+
1318
+ @dataclass(frozen=True, slots=True)
1319
+ class WaAppStateMessageKey:
1320
+ """Message key subset used in app-state mutation calls."""
1321
+
1322
+ chat_jid: str
1323
+ id: str
1324
+ from_me: bool
1325
+ participant_jid: str | None = None
1326
+
1327
+
1328
+ @dataclass(frozen=True, slots=True)
1329
+ class WaClearChatOptions:
1330
+ """Clear-chat flags (starred messages / media preserved by default)."""
1331
+
1332
+ delete_starred: bool = False
1333
+ delete_media: bool = False
1334
+
1335
+
1336
+ @dataclass(frozen=True, slots=True)
1337
+ class WaDeleteChatOptions:
1338
+ """Delete-chat flags (media preserved by default)."""
1339
+
1340
+ delete_media: bool = False
1341
+
1342
+
1343
+ @dataclass(frozen=True, slots=True)
1344
+ class WaDeleteMessageForMeOptions:
1345
+ """Delete-for-me flags plus the optional message timestamp."""
1346
+
1347
+ delete_media: bool = False
1348
+ message_timestamp_ms: int | None = None
1349
+
1350
+
1351
+ @dataclass(frozen=True, slots=True)
1352
+ class WaSetStatusPrivacyInput:
1353
+ """Status-broadcast distribution policy plus allow/deny lists."""
1354
+
1355
+ mode: int | str
1356
+ user_jids: Sequence[str] | None = None
1357
+ share_to_fb: bool | None = None
1358
+ share_to_ig: bool | None = None
1359
+
1360
+
1361
+ @dataclass(frozen=True, slots=True)
1362
+ class WaBroadcastListParticipant:
1363
+ """One broadcast-list member in both addressing forms."""
1364
+
1365
+ lid_jid: str
1366
+ pn_jid: str | None = None
1367
+
1368
+
1369
+ @dataclass(frozen=True, slots=True)
1370
+ class WaSetBroadcastListInput:
1371
+ """Create-or-update payload for the broadcast list ``id``."""
1372
+
1373
+ id: str
1374
+ list_name: str
1375
+ participants: Sequence[WaBroadcastListParticipant] = ()
1376
+ label_ids: Sequence[str] | None = None
1377
+
1378
+
1379
+ class WaAppStateSyncClient(Protocol):
1380
+ """Sync-round surface ``WaAppStateMutationCoordinator`` consumes."""
1381
+
1382
+ async def sync(
1383
+ self, options: WaAppStateSyncOptions | None = None
1384
+ ) -> WaAppStateSyncResult: ...
1385
+
1386
+
1387
+ class WaMediaTransferClient(Protocol):
1388
+ """Blob download surface ``WaAppStateMutationCoordinator`` consumes."""
1389
+
1390
+ async def download_and_decrypt(self, options: Mapping[str, Any]) -> bytes: ...
1391
+
1392
+
1393
+ async def download_external_blob_reference(
1394
+ media_transfer: WaMediaTransferClient,
1395
+ reference: Mapping[str, Any],
1396
+ ) -> bytes:
1397
+ """Download and decrypt an external app-state blob via the media client."""
1398
+ direct_path = reference.get("directPath")
1399
+ if not direct_path:
1400
+ raise ValueError("external blob reference is missing directPath")
1401
+ return await media_transfer.download_and_decrypt(
1402
+ {
1403
+ "directPath": direct_path,
1404
+ "mediaType": "md-app-state",
1405
+ "mediaKey": reference.get("mediaKey"),
1406
+ "fileSha256": reference.get("fileSha256"),
1407
+ "fileEncSha256": reference.get("fileEncSha256"),
1408
+ }
1409
+ )
1410
+
1411
+
1412
+ def _decode_value_at_path(value: Any, segments: Sequence[str], enum_path: str) -> Any:
1413
+ if isinstance(value, list):
1414
+ return [_decode_value_at_path(item, segments, enum_path) for item in value]
1415
+ if isinstance(value, dict) and segments:
1416
+ head, rest = segments[0], segments[1:]
1417
+ if head not in value:
1418
+ return value
1419
+ out = dict(value)
1420
+ if not rest:
1421
+ current = out[head]
1422
+ if isinstance(current, list):
1423
+ out[head] = [
1424
+ decoded
1425
+ if isinstance(item, int)
1426
+ and not isinstance(item, bool)
1427
+ and (decoded := decode_enum_value(enum_path, item)) is not None
1428
+ else item
1429
+ for item in current
1430
+ ]
1431
+ elif (
1432
+ isinstance(current, int)
1433
+ and not isinstance(current, bool)
1434
+ and decode_enum_value(enum_path, current) is not None
1435
+ ):
1436
+ out[head] = decode_enum_value(enum_path, current)
1437
+ else:
1438
+ out[head] = _decode_value_at_path(out[head], rest, enum_path)
1439
+ return out
1440
+ return value
1441
+
1442
+
1443
+ def _apply_enum_decode_to_data(
1444
+ enum_fields: dict[str, str] | None, data: dict[str, Any]
1445
+ ) -> dict[str, Any]:
1446
+ if not enum_fields:
1447
+ return data
1448
+ out = data
1449
+ for field_path, enum_path in enum_fields.items():
1450
+ if _resolve_enum_object(enum_path) is None:
1451
+ continue
1452
+ decoded = _decode_value_at_path(out, field_path.split("."), enum_path)
1453
+ out = decoded if isinstance(decoded, dict) else out
1454
+ return out
1455
+
1456
+
1457
+ def _unwrap_data(
1458
+ schema: _WaAppstateSchema, value: dict[str, Any] | None
1459
+ ) -> dict[str, Any] | None:
1460
+ if not value:
1461
+ return None
1462
+ if schema.value_field is None:
1463
+ return {key: item for key, item in value.items() if key != "timestamp"}
1464
+ sub = value.get(schema.value_field)
1465
+ if not isinstance(sub, dict):
1466
+ return None
1467
+ return _apply_enum_decode_to_data(schema.value_enum_fields, dict(sub))
1468
+
1469
+
1470
+ def _parse_index_parts(index: str) -> list[str] | None:
1471
+ try:
1472
+ parsed = json.loads(index)
1473
+ except ValueError:
1474
+ return None
1475
+ if not isinstance(parsed, list):
1476
+ return None
1477
+ parts: list[str] = []
1478
+ for item in parsed:
1479
+ if isinstance(item, str):
1480
+ parts.append(item)
1481
+ elif isinstance(item, bool):
1482
+ parts.append("true" if item else "false")
1483
+ elif isinstance(item, (int, float)):
1484
+ parts.append(str(int(item)) if float(item).is_integer() else str(item))
1485
+ else:
1486
+ return None
1487
+ return parts
1488
+
1489
+
1490
+ def parse_app_state_mutation_event(
1491
+ mutation: WaAppStateMutation,
1492
+ ) -> dict[str, Any] | None:
1493
+ """Parse one applied mutation into its ``app_state_mutation`` event dict."""
1494
+ parts = _parse_index_parts(mutation.index)
1495
+ if not parts:
1496
+ return None
1497
+ resolved = get_appstate_schema_by_action_name(parts[0])
1498
+ if resolved is None:
1499
+ return None
1500
+ key, schema = resolved
1501
+ index_args = decode_index_args_from_schema(schema, parts)
1502
+ if index_args is None:
1503
+ return None
1504
+ legacy = _WA_APPSTATE_LEGACY_INDEX_ARGS.get(key)
1505
+ if legacy:
1506
+ for legacy_name, current_name in legacy.items():
1507
+ index_args[legacy_name] = index_args.get(current_name)
1508
+ base: dict[str, Any] = {
1509
+ "source": mutation.source,
1510
+ "collection": mutation.collection,
1511
+ "version": mutation.version,
1512
+ "timestamp": mutation.timestamp,
1513
+ "_raw": {
1514
+ "index": mutation.index,
1515
+ "indexParts": parts,
1516
+ "value": mutation.value,
1517
+ },
1518
+ }
1519
+ if mutation.operation == "remove":
1520
+ return {"schema": key, "operation": "remove", **index_args, **base}
1521
+ data = _unwrap_data(schema, mutation.value)
1522
+ return {"schema": key, "operation": "set", **index_args, **(data or {}), **base}
1523
+
1524
+
1525
+ def _split_flat_input(
1526
+ schema: _WaAppstateSchema, flat_input: Mapping[str, Any]
1527
+ ) -> tuple[dict[str, Any], dict[str, Any]]:
1528
+ index_names = {
1529
+ part[2] for part in schema.index_parts if part[0] != "literal" and part[2]
1530
+ }
1531
+ legacy: dict[str, str] | None = None
1532
+ for legacy_key, mapping in _WA_APPSTATE_LEGACY_INDEX_ARGS.items():
1533
+ if _WA_APPSTATE_SCHEMAS.get(legacy_key) is schema:
1534
+ legacy = mapping
1535
+ break
1536
+ index_args: dict[str, Any] = {}
1537
+ data: dict[str, Any] = {}
1538
+ for key, item in flat_input.items():
1539
+ if key == "schema":
1540
+ continue
1541
+ if key in index_names:
1542
+ index_args[key] = item
1543
+ continue
1544
+ if legacy is not None and key in legacy:
1545
+ continue
1546
+ data[key] = item
1547
+ if legacy:
1548
+ for legacy_name, current_name in legacy.items():
1549
+ if index_args.get(current_name) is None and legacy_name in flat_input:
1550
+ index_args[current_name] = flat_input[legacy_name]
1551
+ return index_args, data
1552
+
1553
+
1554
+ def _encode_enum_leaf(value: Any, enum_path: str) -> Any:
1555
+ if isinstance(value, bool):
1556
+ return value
1557
+ if isinstance(value, int):
1558
+ return value
1559
+ if not isinstance(value, str):
1560
+ return value
1561
+ numeric = encode_enum_value(enum_path, value)
1562
+ if numeric is None:
1563
+ raise ValueError(f'enum value "{value}" not in {enum_path}')
1564
+ return numeric
1565
+
1566
+
1567
+ def _encode_at_path(
1568
+ obj: dict[str, Any], segments: Sequence[str], enum_path: str
1569
+ ) -> None:
1570
+ if not segments:
1571
+ return
1572
+ head, rest = segments[0], segments[1:]
1573
+ if head not in obj:
1574
+ return
1575
+ value = obj[head]
1576
+ if not rest:
1577
+ if isinstance(value, list):
1578
+ obj[head] = [_encode_enum_leaf(item, enum_path) for item in value]
1579
+ elif value is not None:
1580
+ obj[head] = _encode_enum_leaf(value, enum_path)
1581
+ return
1582
+ if isinstance(value, list):
1583
+ for item in value:
1584
+ if isinstance(item, dict):
1585
+ _encode_at_path(item, rest, enum_path)
1586
+ elif isinstance(value, dict):
1587
+ _encode_at_path(value, rest, enum_path)
1588
+
1589
+
1590
+ def _apply_enum_encode_to_data(
1591
+ enum_fields: dict[str, str] | None, data: Mapping[str, Any]
1592
+ ) -> dict[str, Any]:
1593
+ if not enum_fields:
1594
+ return dict(data)
1595
+ out: dict[str, Any] = dict(data)
1596
+ for field_path, enum_path in enum_fields.items():
1597
+ _encode_at_path(out, field_path.split("."), enum_path)
1598
+ return out
1599
+
1600
+
1601
+ def _wrap_data(schema: _WaAppstateSchema, data: Mapping[str, Any]) -> dict[str, Any]:
1602
+ encoded = _apply_enum_encode_to_data(schema.value_enum_fields, data)
1603
+ if schema.value_field is None:
1604
+ return dict(encoded)
1605
+ return {schema.value_field: encoded}
1606
+
1607
+
1608
+ def _is_valid_epoch_ms(value: Any) -> bool:
1609
+ return (
1610
+ isinstance(value, int)
1611
+ and not isinstance(value, bool)
1612
+ and math.isfinite(float(value))
1613
+ and -(2**53) < value < 2**53
1614
+ and value >= 0
1615
+ )
1616
+
1617
+
1618
+ class WaAppStateMutationCoordinator:
1619
+ """Coordinates app-state mutations and emits parsed mutation events."""
1620
+
1621
+ def __init__(
1622
+ self,
1623
+ *,
1624
+ logger: Logger,
1625
+ message_store: WaMessageStore,
1626
+ app_state_sync: WaAppStateSyncClient,
1627
+ media_transfer: WaMediaTransferClient,
1628
+ is_connected: Callable[[], bool],
1629
+ server_clock: ServerClock,
1630
+ archive_range_limit: int | None = None,
1631
+ emit_mutation: Callable[[dict[str, Any]], None] | None = None,
1632
+ emit_mutation_send: Callable[[dict[str, Any]], None] | None = None,
1633
+ emit_snapshot_mutations: bool = False,
1634
+ nct_salt_sink: Callable[[bytes | None], Awaitable[None]] | None = None,
1635
+ contact_sink: Callable[[WaStoredContactRecord], None] | None = None,
1636
+ push_name_sink: Callable[[str], None] | None = None,
1637
+ ) -> None:
1638
+ self._logger = logger
1639
+ self._message_store = message_store
1640
+ self._app_state_sync = app_state_sync
1641
+ self._media_transfer = media_transfer
1642
+ self._is_connected = is_connected
1643
+ self._server_clock = server_clock
1644
+ self._archive_range_limit = resolve_positive(
1645
+ archive_range_limit,
1646
+ _WA_APP_STATE_ARCHIVE_RANGE_DEFAULT_LIMIT,
1647
+ "WaAppStateMutationCoordinatorOptions.archiveRangeLimit",
1648
+ )
1649
+ self._emit_mutation = emit_mutation
1650
+ self._emit_mutation_send = emit_mutation_send
1651
+ self._emit_snapshot_mutations = emit_snapshot_mutations is True
1652
+ self._nct_salt_sink = nct_salt_sink
1653
+ self._contact_sink = contact_sink
1654
+ self._push_name_sink = push_name_sink
1655
+ self._pending_mutations: dict[str, WaAppStateMutationInput] = {}
1656
+ self._flush_future: asyncio.Task[None] | None = None
1657
+
1658
+ async def sync(
1659
+ self, options: WaAppStateSyncOptions | None = None
1660
+ ) -> WaAppStateSyncResult:
1661
+ """Run an app-state sync round, optionally applying pending mutations."""
1662
+ if not self._is_connected():
1663
+ raise ValueError("client is not connected")
1664
+ opts = options if options is not None else WaAppStateSyncOptions()
1665
+
1666
+ async def _download(
1667
+ collection: str, kind: str, reference: Mapping[str, Any]
1668
+ ) -> bytes:
1669
+ return await download_external_blob_reference(
1670
+ self._media_transfer, reference
1671
+ )
1672
+
1673
+ sync_options = WaAppStateSyncOptions(
1674
+ collections=opts.collections,
1675
+ pending_mutations=opts.pending_mutations,
1676
+ download_external_blob=opts.download_external_blob or _download,
1677
+ timeout_ms=opts.timeout_ms,
1678
+ )
1679
+ sync_result = await self._app_state_sync.sync(sync_options)
1680
+ blocked = self.get_blocked_collections(sync_result)
1681
+ if blocked:
1682
+ self._logger.warn(
1683
+ "app-state sync has blocked collections",
1684
+ {"blockedCollections": ",".join(blocked)},
1685
+ )
1686
+ self.emit_events_from_sync_result(sync_result)
1687
+ return sync_result
1688
+
1689
+ def get_blocked_collections(self, sync_result: WaAppStateSyncResult) -> list[str]:
1690
+ """Return the names of collections reported as `BLOCKED`."""
1691
+ return [
1692
+ entry.collection
1693
+ for entry in sync_result.collections
1694
+ if entry.state == _WA_APP_STATE_COLLECTION_STATES["BLOCKED"]
1695
+ ]
1696
+
1697
+ def emit_events_from_sync_result(self, sync_result: WaAppStateSyncResult) -> None:
1698
+ """Emit one event per winning (collection, index) mutation."""
1699
+ for collection_result in sync_result.collections:
1700
+ mutations = list(collection_result.mutations or [])
1701
+ if self._contact_sink is not None or self._push_name_sink is not None:
1702
+ sink_last_index: dict[str, int] = {}
1703
+ for i, mutation in enumerate(mutations):
1704
+ sink_last_index[f"{mutation.collection}\x01{mutation.index}"] = i
1705
+ for i, mutation in enumerate(mutations):
1706
+ if (
1707
+ sink_last_index[f"{mutation.collection}\x01{mutation.index}"]
1708
+ != i
1709
+ ):
1710
+ continue
1711
+ try:
1712
+ self._handle_contact_mutation(mutation)
1713
+ except Exception as error:
1714
+ normalized = to_error(error)
1715
+ message = str(normalized.args[0]) if normalized.args else ""
1716
+ self._logger.debug(
1717
+ "contact sink failed",
1718
+ {
1719
+ "collection": mutation.collection,
1720
+ "index": mutation.index,
1721
+ "message": message,
1722
+ },
1723
+ )
1724
+ try:
1725
+ self._handle_push_name_mutation(mutation)
1726
+ except Exception as error:
1727
+ normalized = to_error(error)
1728
+ message = str(normalized.args[0]) if normalized.args else ""
1729
+ self._logger.debug(
1730
+ "pushName sink failed",
1731
+ {
1732
+ "collection": mutation.collection,
1733
+ "index": mutation.index,
1734
+ "message": message,
1735
+ },
1736
+ )
1737
+ last_index_by_key: dict[str, int] = {}
1738
+ for i, mutation in enumerate(mutations):
1739
+ if not self._emit_snapshot_mutations and mutation.source == "snapshot":
1740
+ continue
1741
+ last_index_by_key[f"{mutation.collection}\x01{mutation.index}"] = i
1742
+ for i, mutation in enumerate(mutations):
1743
+ if not self._emit_snapshot_mutations and mutation.source == "snapshot":
1744
+ continue
1745
+ coalesce_key = f"{mutation.collection}\x01{mutation.index}"
1746
+ if last_index_by_key.get(coalesce_key) != i:
1747
+ continue
1748
+ try:
1749
+ self._handle_nct_salt_mutation(mutation)
1750
+ event = parse_app_state_mutation_event(mutation)
1751
+ if event is None:
1752
+ continue
1753
+ if self._emit_mutation is not None:
1754
+ self._emit_mutation(event)
1755
+ except Exception as error:
1756
+ normalized = to_error(error)
1757
+ message = str(normalized.args[0]) if normalized.args else ""
1758
+ self._logger.debug(
1759
+ "failed to parse app-state mutation event",
1760
+ {
1761
+ "collection": mutation.collection,
1762
+ "source": mutation.source,
1763
+ "index": mutation.index,
1764
+ "message": message,
1765
+ },
1766
+ )
1767
+
1768
+ def _handle_nct_salt_mutation(self, mutation: WaAppStateMutation) -> None:
1769
+ if self._nct_salt_sink is None:
1770
+ return
1771
+ value = mutation.value or {}
1772
+ nct_action = value.get("nctSaltSyncAction")
1773
+ if not isinstance(nct_action, dict):
1774
+ return
1775
+ sink = self._nct_salt_sink
1776
+ if mutation.operation == "set" and nct_action.get("salt"):
1777
+ salt = bytes(nct_action["salt"])
1778
+
1779
+ async def _set() -> None:
1780
+ try:
1781
+ await sink(salt)
1782
+ except Exception as error:
1783
+ normalized = to_error(error)
1784
+ message = str(normalized.args[0]) if normalized.args else ""
1785
+ self._logger.warn("nct salt sync set failed", {"message": message})
1786
+
1787
+ asyncio.get_running_loop().create_task(_set())
1788
+ elif mutation.operation == "remove":
1789
+
1790
+ async def _remove() -> None:
1791
+ try:
1792
+ await sink(None)
1793
+ except Exception as error:
1794
+ normalized = to_error(error)
1795
+ message = str(normalized.args[0]) if normalized.args else ""
1796
+ self._logger.warn(
1797
+ "nct salt sync remove failed", {"message": message}
1798
+ )
1799
+
1800
+ asyncio.get_running_loop().create_task(_remove())
1801
+
1802
+ def _handle_contact_mutation(self, mutation: WaAppStateMutation) -> None:
1803
+ if self._contact_sink is None:
1804
+ return
1805
+ if '"contact"' not in mutation.index:
1806
+ return
1807
+ try:
1808
+ parts = json.loads(mutation.index)
1809
+ except ValueError:
1810
+ return
1811
+ if (
1812
+ not isinstance(parts, list)
1813
+ or len(parts) < 2
1814
+ or parts[0] != "contact"
1815
+ or not isinstance(parts[1], str)
1816
+ ):
1817
+ return
1818
+ index_jid = parts[1]
1819
+ last_updated_ms = (
1820
+ mutation.timestamp if mutation.timestamp > 0 else int(time.time() * 1000)
1821
+ )
1822
+ if mutation.operation == "remove":
1823
+ return
1824
+ action = (mutation.value or {}).get("contactAction")
1825
+ if not isinstance(action, dict):
1826
+ return
1827
+ lid_jid = action.get("lidJid")
1828
+ lid = lid_jid if isinstance(lid_jid, str) and _is_lid_jid(lid_jid) else None
1829
+ jid = lid or index_jid
1830
+ full_name = action.get("fullName")
1831
+ first_name = action.get("firstName")
1832
+ display_name: str | None = None
1833
+ if isinstance(full_name, str) and full_name:
1834
+ display_name = full_name
1835
+ elif isinstance(first_name, str) and first_name:
1836
+ display_name = first_name
1837
+ self._contact_sink(
1838
+ WaStoredContactRecord(
1839
+ jid=jid,
1840
+ last_updated_ms=last_updated_ms,
1841
+ display_name=display_name,
1842
+ lid=lid or (index_jid if _is_lid_jid(index_jid) else None),
1843
+ phone_number=index_jid if _is_user_jid(index_jid) else None,
1844
+ )
1845
+ )
1846
+
1847
+ def _handle_push_name_mutation(self, mutation: WaAppStateMutation) -> None:
1848
+ if self._push_name_sink is None:
1849
+ return
1850
+ if mutation.operation != "set":
1851
+ return
1852
+ if "setting_pushName" not in mutation.index:
1853
+ return
1854
+ name = (mutation.value or {}).get("pushNameSetting")
1855
+ if not isinstance(name, dict):
1856
+ return
1857
+ push_name = name.get("name")
1858
+ if not isinstance(push_name, str):
1859
+ return
1860
+ self._push_name_sink(push_name)
1861
+
1862
+ async def set_chat_mute(
1863
+ self,
1864
+ chat_jid: str,
1865
+ muted: bool,
1866
+ mute_end_timestamp_ms: int | None = None,
1867
+ ) -> None:
1868
+ """Mute or unmute a chat (``mute_end_timestamp_ms`` required to mute)."""
1869
+ chat_index_jid = self._normalize_chat_mutation_jid(chat_jid)
1870
+ timestamp = self._server_clock.now_ms()
1871
+ if mute_end_timestamp_ms is not None and not _is_valid_epoch_ms(
1872
+ mute_end_timestamp_ms
1873
+ ):
1874
+ raise ValueError(f"invalid muteEndTimestampMs: {mute_end_timestamp_ms}")
1875
+ if muted and mute_end_timestamp_ms is None:
1876
+ raise ValueError(
1877
+ "setChatMute requires muteEndTimestampMs when muted is true"
1878
+ )
1879
+ value: dict[str, Any] = {
1880
+ "muteAction": {
1881
+ "muted": muted,
1882
+ **(
1883
+ {}
1884
+ if mute_end_timestamp_ms is None
1885
+ else {"muteEndTimestamp": mute_end_timestamp_ms}
1886
+ ),
1887
+ }
1888
+ }
1889
+ await self._enqueue_and_flush(
1890
+ [
1891
+ build_set_mutation_from_schema(
1892
+ schema=_WA_APPSTATE_SCHEMAS["Mute"],
1893
+ index_args={"chatJid": chat_index_jid},
1894
+ value=value,
1895
+ timestamp=timestamp,
1896
+ )
1897
+ ]
1898
+ )
1899
+
1900
+ async def set_message_star(
1901
+ self, message: WaAppStateMessageKey, starred: bool
1902
+ ) -> None:
1903
+ """Star or un-star a specific message."""
1904
+ message_index = self._build_message_mutation_index(message)
1905
+ timestamp = self._server_clock.now_ms()
1906
+ await self._enqueue_and_flush(
1907
+ [
1908
+ build_set_mutation_from_schema(
1909
+ schema=_WA_APPSTATE_SCHEMAS["Star"],
1910
+ index_args=message_index,
1911
+ value={"starAction": {"starred": starred}},
1912
+ timestamp=timestamp,
1913
+ )
1914
+ ]
1915
+ )
1916
+
1917
+ async def set_chat_read(self, chat_jid: str, read: bool) -> None:
1918
+ """Mark the chat as read or unread."""
1919
+ chat_index_jid = self._normalize_chat_mutation_jid(chat_jid)
1920
+ timestamp = self._server_clock.now_ms()
1921
+ message_range = await self._build_chat_message_range(chat_index_jid)
1922
+ await self._enqueue_and_flush(
1923
+ [
1924
+ build_set_mutation_from_schema(
1925
+ schema=_WA_APPSTATE_SCHEMAS["MarkChatAsRead"],
1926
+ index_args={"chatJid": chat_index_jid},
1927
+ value={
1928
+ "markChatAsReadAction": {
1929
+ "read": read,
1930
+ "messageRange": message_range,
1931
+ }
1932
+ },
1933
+ timestamp=timestamp,
1934
+ )
1935
+ ]
1936
+ )
1937
+
1938
+ async def set_chat_pin(self, chat_jid: str, pinned: bool) -> None:
1939
+ """Pin or unpin the chat (pinning clears any active archive flag)."""
1940
+ chat_index_jid = self._normalize_chat_mutation_jid(chat_jid)
1941
+ timestamp = self._server_clock.now_ms()
1942
+ pending = [
1943
+ build_set_mutation_from_schema(
1944
+ schema=_WA_APPSTATE_SCHEMAS["Pin"],
1945
+ index_args={"chatJid": chat_index_jid},
1946
+ value={"pinAction": {"pinned": pinned}},
1947
+ timestamp=timestamp,
1948
+ )
1949
+ ]
1950
+ if pinned:
1951
+ pending.append(
1952
+ await self._create_archive_mutation(chat_index_jid, False, timestamp)
1953
+ )
1954
+ await self._enqueue_and_flush(pending)
1955
+
1956
+ async def set_chat_archive(self, chat_jid: str, archived: bool) -> None:
1957
+ """Archive or unarchive the chat (archiving clears any pin)."""
1958
+ chat_index_jid = self._normalize_chat_mutation_jid(chat_jid)
1959
+ timestamp = self._server_clock.now_ms()
1960
+ pending = [
1961
+ await self._create_archive_mutation(chat_index_jid, archived, timestamp)
1962
+ ]
1963
+ if archived:
1964
+ pending.append(
1965
+ build_set_mutation_from_schema(
1966
+ schema=_WA_APPSTATE_SCHEMAS["Pin"],
1967
+ index_args={"chatJid": chat_index_jid},
1968
+ value={"pinAction": {"pinned": False}},
1969
+ timestamp=timestamp,
1970
+ )
1971
+ )
1972
+ await self._enqueue_and_flush(pending)
1973
+
1974
+ async def clear_chat(
1975
+ self, chat_jid: str, options: WaClearChatOptions | None = None
1976
+ ) -> None:
1977
+ """Clear the chat history (preserving starred messages/media by default)."""
1978
+ opts = options if options is not None else WaClearChatOptions()
1979
+ chat_index_jid = self._normalize_chat_mutation_jid(chat_jid)
1980
+ timestamp = self._server_clock.now_ms()
1981
+ message_range = await self._build_chat_message_range(chat_index_jid)
1982
+ await self._enqueue_and_flush(
1983
+ [
1984
+ build_set_mutation_from_schema(
1985
+ schema=_WA_APPSTATE_SCHEMAS["ClearChat"],
1986
+ index_args={
1987
+ "chatJid": chat_index_jid,
1988
+ "deleteStarred": "1" if opts.delete_starred else "0",
1989
+ "deleteMedia": "1" if opts.delete_media else "0",
1990
+ },
1991
+ value={"clearChatAction": {"messageRange": message_range}},
1992
+ timestamp=timestamp,
1993
+ )
1994
+ ]
1995
+ )
1996
+
1997
+ async def delete_chat(
1998
+ self, chat_jid: str, options: WaDeleteChatOptions | None = None
1999
+ ) -> None:
2000
+ """Delete the chat entirely (local-only)."""
2001
+ opts = options if options is not None else WaDeleteChatOptions()
2002
+ chat_index_jid = self._normalize_chat_mutation_jid(chat_jid)
2003
+ timestamp = self._server_clock.now_ms()
2004
+ message_range = await self._build_chat_message_range(chat_index_jid)
2005
+ await self._enqueue_and_flush(
2006
+ [
2007
+ build_set_mutation_from_schema(
2008
+ schema=_WA_APPSTATE_SCHEMAS["DeleteChat"],
2009
+ index_args={
2010
+ "chatJid": chat_index_jid,
2011
+ "deleteMedia": "1" if opts.delete_media else "0",
2012
+ },
2013
+ value={"deleteChatAction": {"messageRange": message_range}},
2014
+ timestamp=timestamp,
2015
+ )
2016
+ ]
2017
+ )
2018
+
2019
+ async def delete_message_for_me(
2020
+ self,
2021
+ message: WaAppStateMessageKey,
2022
+ options: WaDeleteMessageForMeOptions | None = None,
2023
+ ) -> None:
2024
+ """Delete a single message locally (recipient copies are untouched)."""
2025
+ opts = options if options is not None else WaDeleteMessageForMeOptions()
2026
+ message_index = self._build_message_mutation_index(message)
2027
+ timestamp = self._server_clock.now_ms()
2028
+ message_timestamp_ms = opts.message_timestamp_ms
2029
+ message_timestamp: int | None = None
2030
+ if message_timestamp_ms is not None:
2031
+ if not _is_valid_epoch_ms(message_timestamp_ms):
2032
+ raise ValueError(f"invalid messageTimestampMs: {message_timestamp_ms}")
2033
+ message_timestamp = math.floor(message_timestamp_ms / 1_000)
2034
+ await self._enqueue_and_flush(
2035
+ [
2036
+ build_set_mutation_from_schema(
2037
+ schema=_WA_APPSTATE_SCHEMAS["DeleteMessageForMe"],
2038
+ index_args=message_index,
2039
+ value={
2040
+ "deleteMessageForMeAction": {
2041
+ "deleteMedia": opts.delete_media,
2042
+ **(
2043
+ {}
2044
+ if message_timestamp is None
2045
+ else {"messageTimestamp": message_timestamp}
2046
+ ),
2047
+ }
2048
+ },
2049
+ timestamp=timestamp,
2050
+ )
2051
+ ]
2052
+ )
2053
+
2054
+ async def set_chat_lock(self, chat_jid: str, locked: bool) -> None:
2055
+ """Lock or unlock the chat (locking clears archive and pin)."""
2056
+ chat_index_jid = self._normalize_chat_mutation_jid(chat_jid)
2057
+ timestamp = self._server_clock.now_ms()
2058
+ pending: list[WaAppStateMutationInput] = []
2059
+ if locked:
2060
+ pending.append(
2061
+ await self._create_archive_mutation(chat_index_jid, False, timestamp)
2062
+ )
2063
+ pending.append(
2064
+ build_set_mutation_from_schema(
2065
+ schema=_WA_APPSTATE_SCHEMAS["Pin"],
2066
+ index_args={"chatJid": chat_index_jid},
2067
+ value={"pinAction": {"pinned": False}},
2068
+ timestamp=timestamp,
2069
+ )
2070
+ )
2071
+ pending.append(
2072
+ build_set_mutation_from_schema(
2073
+ schema=_WA_APPSTATE_SCHEMAS["LockChat"],
2074
+ index_args={"chatJid": chat_index_jid},
2075
+ value={"lockChatAction": {"locked": locked}},
2076
+ timestamp=timestamp,
2077
+ )
2078
+ )
2079
+ await self._enqueue_and_flush(pending)
2080
+
2081
+ async def flush_mutations(self) -> None:
2082
+ """Drain queued mutations through a sync round (shared in-flight flush)."""
2083
+ if self._flush_future is not None:
2084
+ await self._flush_future
2085
+ return
2086
+ task = asyncio.get_running_loop().create_task(
2087
+ self._flush_pending_mutations_loop()
2088
+ )
2089
+ self._flush_future = task
2090
+ try:
2091
+ await task
2092
+ finally:
2093
+ if self._flush_future is task:
2094
+ self._flush_future = None
2095
+
2096
+ async def _enqueue_and_flush(
2097
+ self, mutations: Sequence[WaAppStateMutationInput]
2098
+ ) -> None:
2099
+ for mutation in mutations:
2100
+ self._enqueue_mutation(mutation)
2101
+ self._emit_local_mutation(mutation)
2102
+ await self.flush_mutations()
2103
+
2104
+ def _emit_local_mutation(self, mutation_input: WaAppStateMutationInput) -> None:
2105
+ if self._emit_mutation_send is None:
2106
+ return
2107
+ value = mutation_input.value if mutation_input.operation == "set" else None
2108
+ try:
2109
+ event = parse_app_state_mutation_event(
2110
+ WaAppStateMutation(
2111
+ collection=mutation_input.collection,
2112
+ operation=mutation_input.operation,
2113
+ source="local",
2114
+ index=mutation_input.index,
2115
+ value=value,
2116
+ version=mutation_input.version,
2117
+ index_mac=_WA_EMPTY_MUTATION_MAC,
2118
+ value_mac=_WA_EMPTY_MUTATION_MAC,
2119
+ key_id=_WA_EMPTY_MUTATION_MAC,
2120
+ timestamp=mutation_input.timestamp,
2121
+ )
2122
+ )
2123
+ if event is not None:
2124
+ self._emit_mutation_send(event)
2125
+ except Exception as error:
2126
+ normalized = to_error(error)
2127
+ message = str(normalized.args[0]) if normalized.args else ""
2128
+ self._logger.debug(
2129
+ "failed to emit local app-state mutation event",
2130
+ {
2131
+ "collection": mutation_input.collection,
2132
+ "index": mutation_input.index,
2133
+ "message": message,
2134
+ },
2135
+ )
2136
+
2137
+ def _enqueue_mutation(self, mutation: WaAppStateMutationInput) -> None:
2138
+ key = f"{mutation.collection}\x01{mutation.index}"
2139
+ if key in self._pending_mutations:
2140
+ del self._pending_mutations[key]
2141
+ self._pending_mutations[key] = mutation
2142
+
2143
+ def _take_pending_mutations_batch(self) -> list[WaAppStateMutationInput]:
2144
+ if not self._pending_mutations:
2145
+ return []
2146
+ batch = list(self._pending_mutations.values())
2147
+ self._pending_mutations.clear()
2148
+ return batch
2149
+
2150
+ async def _flush_pending_mutations_loop(self) -> None:
2151
+ while True:
2152
+ batch = self._take_pending_mutations_batch()
2153
+ if not batch:
2154
+ return
2155
+ self._logger.debug(
2156
+ "app-state mutation flush start",
2157
+ {
2158
+ "pending": len(batch),
2159
+ "actions": self._describe_mutation_actions(batch),
2160
+ },
2161
+ )
2162
+ collections: list[str] = []
2163
+ seen: set[str] = set()
2164
+ for mutation in batch:
2165
+ if mutation.collection not in seen:
2166
+ seen.add(mutation.collection)
2167
+ collections.append(mutation.collection)
2168
+ try:
2169
+ sync_result = await self.sync(
2170
+ WaAppStateSyncOptions(
2171
+ collections=collections, pending_mutations=batch
2172
+ )
2173
+ )
2174
+ except Exception as error:
2175
+ self._requeue_mutations(batch)
2176
+ normalized = to_error(error)
2177
+ message = str(normalized.args[0]) if normalized.args else ""
2178
+ self._logger.warn(
2179
+ "app-state mutation flush failed",
2180
+ {
2181
+ "pending": len(batch),
2182
+ "actions": self._describe_mutation_actions(batch),
2183
+ "message": message,
2184
+ },
2185
+ )
2186
+ raise
2187
+ state_by_collection = {
2188
+ entry.collection: entry.state for entry in sync_result.collections
2189
+ }
2190
+ success_states = {
2191
+ _WA_APP_STATE_COLLECTION_STATES["SUCCESS"],
2192
+ _WA_APP_STATE_COLLECTION_STATES["SUCCESS_HAS_MORE"],
2193
+ }
2194
+ failed = [
2195
+ collection
2196
+ for collection in collections
2197
+ if state_by_collection.get(collection) not in success_states
2198
+ ]
2199
+ if not failed:
2200
+ self._logger.debug(
2201
+ "app-state mutation flush completed", {"pending": len(batch)}
2202
+ )
2203
+ continue
2204
+ self._requeue_mutations(
2205
+ [mutation for mutation in batch if mutation.collection in failed]
2206
+ )
2207
+ flush_error = ValueError(
2208
+ f"app-state mutation flush incomplete ({','.join(failed)})"
2209
+ )
2210
+ self._logger.warn(
2211
+ "app-state mutation flush incomplete",
2212
+ {
2213
+ "pending": len(batch),
2214
+ "actions": self._describe_mutation_actions(batch),
2215
+ "failedCollections": ",".join(failed),
2216
+ "message": str(flush_error.args[0]),
2217
+ },
2218
+ )
2219
+ raise flush_error
2220
+
2221
+ def _requeue_mutations(self, mutations: Sequence[WaAppStateMutationInput]) -> None:
2222
+ if not mutations:
2223
+ return
2224
+ existing = list(self._pending_mutations.values())
2225
+ self._pending_mutations.clear()
2226
+ for mutation in mutations:
2227
+ self._enqueue_mutation(mutation)
2228
+ for mutation in existing:
2229
+ self._enqueue_mutation(mutation)
2230
+
2231
+ async def set_status_privacy(self, status_input: WaSetStatusPrivacyInput) -> None:
2232
+ """Set the account-wide status-broadcast distribution policy."""
2233
+ if isinstance(status_input.mode, bool):
2234
+ raise ValueError(f"setStatusPrivacy: invalid mode {status_input.mode!r}")
2235
+ if isinstance(status_input.mode, int):
2236
+ mode_value: int | None = status_input.mode
2237
+ else:
2238
+ mode_value = encode_enum_value(
2239
+ "StatusPrivacyAction.StatusDistributionMode", status_input.mode
2240
+ )
2241
+ if (
2242
+ mode_value is None
2243
+ or isinstance(mode_value, bool)
2244
+ or not float(mode_value).is_integer()
2245
+ ):
2246
+ raise ValueError(f"setStatusPrivacy: invalid mode {status_input.mode!r}")
2247
+ value: dict[str, Any] = {
2248
+ "statusPrivacy": {
2249
+ "mode": mode_value,
2250
+ "userJid": list(status_input.user_jids or []),
2251
+ **(
2252
+ {}
2253
+ if status_input.share_to_fb is None
2254
+ else {"shareToFb": status_input.share_to_fb}
2255
+ ),
2256
+ **(
2257
+ {}
2258
+ if status_input.share_to_ig is None
2259
+ else {"shareToIg": status_input.share_to_ig}
2260
+ ),
2261
+ }
2262
+ }
2263
+ timestamp = self._server_clock.now_ms()
2264
+ await self._enqueue_and_flush(
2265
+ [
2266
+ build_set_mutation_from_schema(
2267
+ schema=_WA_APPSTATE_SCHEMAS["StatusPrivacy"],
2268
+ index_args={},
2269
+ value=value,
2270
+ timestamp=timestamp,
2271
+ )
2272
+ ]
2273
+ )
2274
+
2275
+ async def set_user_status_mute(self, jid: str, muted: bool) -> None:
2276
+ """Mute/unmute a single user's status broadcasts."""
2277
+ index_jid = self._normalize_chat_mutation_jid(jid)
2278
+ if _is_group_or_broadcast_jid(index_jid):
2279
+ raise ValueError(f"setUserStatusMute requires a user jid, got {jid}")
2280
+ timestamp = self._server_clock.now_ms()
2281
+ await self._enqueue_and_flush(
2282
+ [
2283
+ build_set_mutation_from_schema(
2284
+ schema=_WA_APPSTATE_SCHEMAS["UserStatusMute"],
2285
+ index_args={"id": index_jid},
2286
+ value={"userStatusMuteAction": {"muted": muted}},
2287
+ timestamp=timestamp,
2288
+ )
2289
+ ]
2290
+ )
2291
+
2292
+ async def set_broadcast_list(self, list_input: WaSetBroadcastListInput) -> None:
2293
+ """Create or update the broadcast list identified by ``list_input.id``."""
2294
+ participants = [
2295
+ {
2296
+ "lidJid": entry.lid_jid,
2297
+ **({} if entry.pn_jid is None else {"pnJid": entry.pn_jid}),
2298
+ }
2299
+ for entry in list_input.participants
2300
+ ]
2301
+ timestamp = self._server_clock.now_ms()
2302
+ await self._enqueue_and_flush(
2303
+ [
2304
+ build_set_mutation_from_schema(
2305
+ schema=_WA_APPSTATE_SCHEMAS["BusinessBroadcastList"],
2306
+ index_args={"id": list_input.id},
2307
+ value={
2308
+ "businessBroadcastListAction": {
2309
+ "participants": participants,
2310
+ "listName": list_input.list_name,
2311
+ "labelIds": list(list_input.label_ids or []),
2312
+ }
2313
+ },
2314
+ timestamp=timestamp,
2315
+ )
2316
+ ]
2317
+ )
2318
+
2319
+ async def remove_broadcast_list(self, list_id: str) -> None:
2320
+ """Delete the broadcast list identified by ``list_id``."""
2321
+ timestamp = self._server_clock.now_ms()
2322
+ await self._enqueue_and_flush(
2323
+ [
2324
+ build_remove_mutation_from_schema(
2325
+ schema=_WA_APPSTATE_SCHEMAS["BusinessBroadcastList"],
2326
+ index_args={"id": list_id},
2327
+ timestamp=timestamp,
2328
+ )
2329
+ ]
2330
+ )
2331
+
2332
+ async def set(self, flat_input: Mapping[str, Any]) -> None:
2333
+ """Apply a `set` mutation against any registered app-state schema."""
2334
+ schema_name = flat_input.get("schema")
2335
+ if not isinstance(schema_name, str):
2336
+ raise ValueError("set requires a schema name")
2337
+ schema = _WA_APPSTATE_SCHEMAS.get(schema_name)
2338
+ if schema is None:
2339
+ raise ValueError(f"unknown app-state schema: {schema_name}")
2340
+ index_args, data = _split_flat_input(schema, flat_input)
2341
+ value = _wrap_data(schema, data)
2342
+ timestamp = self._server_clock.now_ms()
2343
+ mutation = build_set_mutation_from_schema(
2344
+ schema=schema,
2345
+ index_args=index_args,
2346
+ value=value,
2347
+ timestamp=timestamp,
2348
+ )
2349
+ await self._enqueue_and_flush([mutation])
2350
+
2351
+ async def remove(self, flat_input: Mapping[str, Any]) -> None:
2352
+ """Apply a `remove` mutation against any registered app-state schema."""
2353
+ schema_name = flat_input.get("schema")
2354
+ if not isinstance(schema_name, str):
2355
+ raise ValueError("remove requires a schema name")
2356
+ schema = _WA_APPSTATE_SCHEMAS.get(schema_name)
2357
+ if schema is None:
2358
+ raise ValueError(f"unknown app-state schema: {schema_name}")
2359
+ index_args, _data = _split_flat_input(schema, flat_input)
2360
+ timestamp = self._server_clock.now_ms()
2361
+ mutation = build_remove_mutation_from_schema(
2362
+ schema=schema, index_args=index_args, timestamp=timestamp
2363
+ )
2364
+ await self._enqueue_and_flush([mutation])
2365
+
2366
+ async def _create_archive_mutation(
2367
+ self, chat_index_jid: str, archived: bool, timestamp: int
2368
+ ) -> WaAppStateMutationInput:
2369
+ message_range = await self._build_chat_message_range(chat_index_jid)
2370
+ return build_set_mutation_from_schema(
2371
+ schema=_WA_APPSTATE_SCHEMAS["Archive"],
2372
+ index_args={"chatJid": chat_index_jid},
2373
+ value={
2374
+ "archiveChatAction": {
2375
+ "archived": archived,
2376
+ "messageRange": message_range,
2377
+ }
2378
+ },
2379
+ timestamp=timestamp,
2380
+ )
2381
+
2382
+ async def _build_chat_message_range(self, chat_index_jid: str) -> dict[str, Any]:
2383
+ records = await self._message_store.list_by_thread(
2384
+ chat_index_jid, self._archive_range_limit
2385
+ )
2386
+ messages: list[dict[str, Any]] = []
2387
+ last_message_timestamp: int | None = None
2388
+ skipped_missing_group_participant = 0
2389
+ for record in records:
2390
+ timestamp_seconds = self._to_optional_timestamp_seconds(record.timestamp_ms)
2391
+ message = self._to_chat_message_range_message(
2392
+ record, chat_index_jid, timestamp_seconds
2393
+ )
2394
+ if message is None:
2395
+ skipped_missing_group_participant += 1
2396
+ continue
2397
+ if timestamp_seconds is not None and (
2398
+ last_message_timestamp is None
2399
+ or timestamp_seconds > last_message_timestamp
2400
+ ):
2401
+ last_message_timestamp = timestamp_seconds
2402
+ messages.append(message)
2403
+ if skipped_missing_group_participant > 0:
2404
+ self._logger.debug(
2405
+ "app-state message range skipped invalid group messages",
2406
+ {
2407
+ "chatJid": chat_index_jid,
2408
+ "skippedMissingGroupParticipant": skipped_missing_group_participant,
2409
+ },
2410
+ )
2411
+ range_result: dict[str, Any] = {"messages": messages}
2412
+ if last_message_timestamp is not None:
2413
+ range_result["lastMessageTimestamp"] = last_message_timestamp
2414
+ return range_result
2415
+
2416
+ def _to_chat_message_range_message(
2417
+ self,
2418
+ record: Any,
2419
+ chat_index_jid: str,
2420
+ timestamp_seconds: int | None,
2421
+ ) -> dict[str, Any] | None:
2422
+ key: dict[str, Any] = {
2423
+ "remoteJid": chat_index_jid,
2424
+ "fromMe": record.from_me,
2425
+ "id": record.id,
2426
+ }
2427
+ if _is_group_jid(chat_index_jid) and not record.from_me:
2428
+ participant = record.participant_jid or record.sender_jid
2429
+ if not participant:
2430
+ return None
2431
+ key["participant"] = self._normalize_message_range_participant(participant)
2432
+ message: dict[str, Any] = {"key": key}
2433
+ if timestamp_seconds is not None:
2434
+ message["timestamp"] = timestamp_seconds
2435
+ return message
2436
+
2437
+ def _normalize_message_range_participant(self, participant_jid: str) -> str:
2438
+ normalized = _normalize_recipient_jid(participant_jid)
2439
+ if _is_group_or_broadcast_jid(normalized):
2440
+ raise ValueError(
2441
+ "invalid group/broadcast participant in message range:"
2442
+ f" {participant_jid}"
2443
+ )
2444
+ return _normalize_device_jid(normalized)
2445
+
2446
+ def _to_optional_timestamp_seconds(self, timestamp_ms: int | None) -> int | None:
2447
+ if timestamp_ms is None:
2448
+ return None
2449
+ if not _is_valid_epoch_ms(timestamp_ms):
2450
+ return None
2451
+ return math.floor(timestamp_ms / 1_000)
2452
+
2453
+ def _normalize_chat_mutation_jid(self, chat_jid: str) -> str:
2454
+ normalized = _normalize_recipient_jid(chat_jid)
2455
+ if _is_group_or_broadcast_jid(normalized):
2456
+ return normalized
2457
+ return _to_user_jid(normalized)
2458
+
2459
+ def _build_message_mutation_index(
2460
+ self, message: WaAppStateMessageKey
2461
+ ) -> dict[str, Any]:
2462
+ chat_index_jid = self._normalize_chat_mutation_jid(message.chat_jid)
2463
+ message_id = message.id.strip()
2464
+ if not message_id:
2465
+ raise ValueError("message id cannot be empty")
2466
+ from_me = message.from_me is True
2467
+ participant = self._resolve_message_mutation_participant(
2468
+ chat_index_jid, from_me, message.participant_jid
2469
+ )
2470
+ return {
2471
+ "remote": chat_index_jid,
2472
+ "id": message_id,
2473
+ "fromMe": from_me,
2474
+ "participant": participant,
2475
+ }
2476
+
2477
+ def _resolve_message_mutation_participant(
2478
+ self,
2479
+ chat_index_jid: str,
2480
+ from_me: bool,
2481
+ participant_jid: str | None,
2482
+ ) -> str:
2483
+ if from_me or not _is_group_or_broadcast_jid(chat_index_jid):
2484
+ return "0"
2485
+ if not participant_jid:
2486
+ raise ValueError(
2487
+ "participantJid is required for incoming message mutations"
2488
+ " in group/broadcast chats"
2489
+ )
2490
+ normalized = _normalize_recipient_jid(participant_jid)
2491
+ if _is_group_or_broadcast_jid(normalized):
2492
+ raise ValueError(
2493
+ f"invalid participantJid for message mutation: {participant_jid}"
2494
+ )
2495
+ return _normalize_device_jid(normalized)
2496
+
2497
+ def _describe_mutation_actions(
2498
+ self, mutations: Sequence[WaAppStateMutationInput]
2499
+ ) -> str:
2500
+ described: list[str] = []
2501
+ for mutation in mutations:
2502
+ try:
2503
+ parsed = json.loads(mutation.index)
2504
+ if isinstance(parsed, list) and parsed and isinstance(parsed[0], str):
2505
+ described.append(f"{mutation.collection}:{parsed[0]}")
2506
+ continue
2507
+ except ValueError:
2508
+ pass
2509
+ described.append(f"{mutation.collection}:unknown")
2510
+ return ",".join(described)
2511
+
2512
+
2513
+ __all__ = [
2514
+ "WaAppStateCollectionSyncResult",
2515
+ "WaAppStateMessageKey",
2516
+ "WaAppStateMutation",
2517
+ "WaAppStateMutationCoordinator",
2518
+ "WaAppStateMutationInput",
2519
+ "WaAppStateSyncClient",
2520
+ "WaAppStateSyncOptions",
2521
+ "WaAppStateSyncResult",
2522
+ "WaBroadcastListParticipant",
2523
+ "WaClearChatOptions",
2524
+ "WaDeleteChatOptions",
2525
+ "WaDeleteMessageForMeOptions",
2526
+ "WaMediaTransferClient",
2527
+ "WaSetBroadcastListInput",
2528
+ "WaSetStatusPrivacyInput",
2529
+ "build_mutation_index_from_schema",
2530
+ "build_remove_mutation_from_schema",
2531
+ "build_set_mutation_from_schema",
2532
+ "decode_enum_value",
2533
+ "decode_index_args_from_schema",
2534
+ "download_external_blob_reference",
2535
+ "encode_enum_value",
2536
+ "get_appstate_schema_by_action_name",
2537
+ "parse_app_state_mutation_event",
2538
+ ]