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
zapy/errors.py ADDED
@@ -0,0 +1,148 @@
1
+ """Public error hierarchy for ``zapy``.
2
+
3
+ Every error carries a stable :attr:`code` so AI-agent flows can branch on
4
+ failure kinds without parsing message text.
5
+
6
+ Example:
7
+ ```python
8
+ from zapy import errors
9
+
10
+ try:
11
+ await client.send_text("2348012345678", "hello")
12
+ except errors.SendError as exc:
13
+ print(exc.code) # "send_error"
14
+ ```
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ __all__ = [
20
+ "ZapyError",
21
+ "ConnectionError",
22
+ "AuthError",
23
+ "SendError",
24
+ "TimeoutError",
25
+ "NotLoggedIn",
26
+ ]
27
+
28
+
29
+ class ZapyError(Exception):
30
+ """Base class for every error raised by the ``zapy`` public API.
31
+
32
+ Example:
33
+ ```python
34
+ from zapy import errors
35
+
36
+ try:
37
+ await client.start()
38
+ except errors.ZapyError as exc:
39
+ print(exc.code)
40
+ ```
41
+ """
42
+
43
+ code: str = "zapy_error"
44
+
45
+ def __init__(self, message: str, *, code: str | None = None) -> None:
46
+ """Store ``message`` and an optional per-instance ``code`` override."""
47
+ super().__init__(message)
48
+ if code is not None:
49
+ self.code = code
50
+
51
+
52
+ class ConnectionError(ZapyError): # noqa: F811 - intentional public name
53
+ """The client is not connected, or the connection dropped.
54
+
55
+ Check the network, then call ``await client.start()`` (or use
56
+ ``client.run()`` so reconnects happen automatically).
57
+
58
+ Example:
59
+ ```python
60
+ from zapy import errors
61
+
62
+ try:
63
+ await client.send_text("2348012345678", "hi")
64
+ except errors.ConnectionError:
65
+ await client.start()
66
+ ```
67
+ """
68
+
69
+ code: str = "connection_error"
70
+
71
+
72
+ class AuthError(ZapyError):
73
+ """Pairing or login failed (bad QR scan, expired code, rejected device).
74
+
75
+ Delete the session store (``./.zapy/<session>.sqlite`` by default) and
76
+ pair again to recover.
77
+
78
+ Example:
79
+ ```python
80
+ from zapy import errors
81
+
82
+ try:
83
+ await client.start()
84
+ except errors.AuthError:
85
+ print("scan the QR code again")
86
+ ```
87
+ """
88
+
89
+ code: str = "auth_error"
90
+
91
+
92
+ class SendError(ZapyError):
93
+ """A message could not be delivered (server NACK, timeout, bad target).
94
+
95
+ Verify the recipient JID/phone number and retry; the original error is
96
+ available as ``__cause__``.
97
+
98
+ Example:
99
+ ```python
100
+ from zapy import errors
101
+
102
+ try:
103
+ await client.send_text(chat, "hi")
104
+ except errors.SendError as exc:
105
+ print("send failed:", exc)
106
+ ```
107
+ """
108
+
109
+ code: str = "send_error"
110
+
111
+
112
+ class TimeoutError(ZapyError): # noqa: F811 - intentional public name
113
+ """An operation (often :meth:`Client.wait_for`) timed out.
114
+
115
+ Retry the wait, possibly with a longer ``timeout``.
116
+
117
+ Example:
118
+ ```python
119
+ from zapy import errors
120
+
121
+ try:
122
+ await client.wait_for("message", timeout=30.0)
123
+ except errors.TimeoutError:
124
+ print("nobody replied in time")
125
+ ```
126
+ """
127
+
128
+ code: str = "timeout"
129
+
130
+
131
+ class NotLoggedIn(ZapyError):
132
+ """The client has no paired session (never paired, or logged out).
133
+
134
+ Pair first: ``await client.start()`` prints a QR code on a fresh
135
+ session; scan it with the phone to log in.
136
+
137
+ Example:
138
+ ```python
139
+ from zapy import errors
140
+
141
+ try:
142
+ await client.send_text(chat, "hi")
143
+ except errors.NotLoggedIn:
144
+ print("pair the device first")
145
+ ```
146
+ """
147
+
148
+ code: str = "not_logged_in"
zapy/events.py ADDED
@@ -0,0 +1,564 @@
1
+ """Public event dataclasses for ``zapy``.
2
+
3
+ Thin friendly wrappers mapped from the low-level coordinator payloads in
4
+ :mod:`zapy._client.types` (``WaIncomingMessageEvent``,
5
+ ``WaIncomingReceiptEvent``, connection dicts, ``auth_qr`` dicts, ...).
6
+ Protocol behavior is never reimplemented here, only reshaped.
7
+
8
+ Example:
9
+ ```python
10
+ from zapy import Client
11
+
12
+ client = Client()
13
+
14
+ @client.on("message")
15
+ async def on_message(msg):
16
+ print(msg.text, msg.sender, msg.chat)
17
+ ```
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ from collections.abc import Mapping
23
+ from dataclasses import dataclass, field
24
+ from typing import Any
25
+
26
+ from zapy._protocol import jid as _jid
27
+
28
+ __all__ = [
29
+ "Message",
30
+ "Receipt",
31
+ "ConnectionUpdate",
32
+ "QrUpdate",
33
+ "PairingCode",
34
+ "Paired",
35
+ "Disconnected",
36
+ "GroupUpdate",
37
+ "PresenceUpdate",
38
+ "ChatStateUpdate",
39
+ "CallUpdate",
40
+ "message_from_incoming",
41
+ "receipt_from_incoming",
42
+ "connection_from_payload",
43
+ "disconnected_from_payload",
44
+ "qr_from_payload",
45
+ "pairing_code_from_payload",
46
+ "paired_from_payload",
47
+ "extract_text",
48
+ "extract_media",
49
+ ]
50
+
51
+
52
+ def _field(obj: Any, name: str, default: Any = None) -> Any:
53
+ """Read ``name`` from an attribute object or a mapping."""
54
+ if isinstance(obj, Mapping):
55
+ return obj.get(name, default)
56
+ return getattr(obj, name, default)
57
+
58
+
59
+ def _text_of_mapping(raw: Mapping[str, Any]) -> str | None:
60
+ """Find displayable text inside a proto-like message mapping."""
61
+ conversation = raw.get("conversation")
62
+ if isinstance(conversation, str):
63
+ return conversation
64
+ extended = raw.get("extendedTextMessage")
65
+ if isinstance(extended, Mapping):
66
+ text = extended.get("text")
67
+ if isinstance(text, str):
68
+ return text
69
+ for key in ("imageMessage", "videoMessage", "documentMessage", "audioMessage"):
70
+ sub = raw.get(key)
71
+ if isinstance(sub, Mapping):
72
+ caption = sub.get("caption")
73
+ if isinstance(caption, str):
74
+ return caption
75
+ for key in ("ephemeralMessage", "viewOnceMessage", "viewOnceMessageV2"):
76
+ sub = raw.get(key)
77
+ if isinstance(sub, Mapping):
78
+ inner = sub.get("message")
79
+ if isinstance(inner, Mapping):
80
+ text = _text_of_mapping(inner)
81
+ if text is not None:
82
+ return text
83
+ return None
84
+
85
+
86
+ def extract_text(raw: Any) -> str | None:
87
+ """Best-effort display text for a message payload, or ``None``.
88
+
89
+ Accepts message mappings (``MessageDict``) and protobuf ``Message``
90
+ objects; anything else yields ``None``.
91
+
92
+ Example:
93
+ ```python
94
+ from zapy import events
95
+
96
+ events.extract_text({"conversation": "ping"}) # "ping"
97
+ ```
98
+ """
99
+ if raw is None:
100
+ return None
101
+ if isinstance(raw, Mapping):
102
+ return _text_of_mapping(raw)
103
+ get_text = getattr(raw, "conversation", None)
104
+ if isinstance(get_text, str) and get_text:
105
+ return get_text
106
+ has_field = getattr(raw, "HasField", None)
107
+ if callable(has_field):
108
+ for wrapper in ("ephemeralMessage", "viewOnceMessage", "viewOnceMessageV2"):
109
+ try:
110
+ if raw.HasField(wrapper):
111
+ return extract_text(getattr(raw, wrapper).message)
112
+ except Exception:
113
+ continue
114
+ for name in ("extendedTextMessage",):
115
+ try:
116
+ if raw.HasField(name):
117
+ text = getattr(getattr(raw, name), "text", None)
118
+ return text if isinstance(text, str) else None
119
+ except Exception:
120
+ continue
121
+ return None
122
+
123
+
124
+ _MEDIA_MESSAGE_KEYS = (
125
+ "imageMessage",
126
+ "videoMessage",
127
+ "audioMessage",
128
+ "documentMessage",
129
+ "stickerMessage",
130
+ "ptvMessage",
131
+ )
132
+
133
+
134
+ def extract_media(raw: Any) -> Any | None:
135
+ """Return the media sub-message inside ``raw``, or ``None``.
136
+
137
+ Accepts message mappings and protobuf ``Message`` objects.
138
+
139
+ Example:
140
+ ```python
141
+ from zapy import events
142
+
143
+ events.extract_media({"imageMessage": {"caption": "hi"}})
144
+ # {"caption": "hi"}
145
+ ```
146
+ """
147
+ if raw is None:
148
+ return None
149
+ if isinstance(raw, Mapping):
150
+ for key in _MEDIA_MESSAGE_KEYS:
151
+ sub = raw.get(key)
152
+ if sub is not None:
153
+ return sub
154
+ return None
155
+ has_field = getattr(raw, "HasField", None)
156
+ if callable(has_field):
157
+ for key in _MEDIA_MESSAGE_KEYS:
158
+ try:
159
+ if raw.HasField(key):
160
+ return getattr(raw, key)
161
+ except Exception:
162
+ continue
163
+ return None
164
+
165
+
166
+ @dataclass(frozen=True, slots=True)
167
+ class Message:
168
+ """An inbound chat message with reply/react/download conveniences.
169
+
170
+ ``raw`` is the full message payload (mapping or protobuf); ``media``
171
+ is the media sub-message or ``None``. The async helpers need the
172
+ message attached to a :class:`zapy.client.Client` (automatic for
173
+ handler payloads); otherwise they raise :class:`zapy.errors.ZapyError`.
174
+
175
+ Example:
176
+ ```python
177
+ @client.on("message")
178
+ async def on_message(msg):
179
+ if msg.text == "ping":
180
+ await msg.reply("pong")
181
+ ```
182
+ """
183
+
184
+ text: str | None = None
185
+ sender: str = ""
186
+ chat: str = ""
187
+ is_group: bool = False
188
+ from_me: bool = False
189
+ id: str = ""
190
+ timestamp: int | None = None
191
+ raw: Any = None
192
+ media: Any | None = None
193
+ push_name: str | None = None
194
+ _client: Any = field(default=None, repr=False, compare=False)
195
+ _incoming: Any = field(default=None, repr=False, compare=False)
196
+
197
+ async def reply(self, text: str) -> str:
198
+ """Reply to this message (quotes it); resolves with the new id.
199
+
200
+ Example:
201
+ ```python
202
+ await msg.reply("pong")
203
+ ```
204
+ """
205
+ client = self._require_client("reply")
206
+ result: str = await client.send_text(self.chat, text, quote=self._incoming)
207
+ return result
208
+
209
+ async def react(self, emoji: str) -> str:
210
+ """React to this message (``""`` removes); resolves with the new id.
211
+
212
+ Example:
213
+ ```python
214
+ await msg.react("👍")
215
+ ```
216
+ """
217
+ client = self._require_client("react")
218
+ result: str = await client.send_reaction(self.chat, emoji, self.id)
219
+ return result
220
+
221
+ async def download(self) -> bytes:
222
+ """Download and decrypt this message's media.
223
+
224
+ Example:
225
+ ```python
226
+ data = await msg.download()
227
+ ```
228
+ """
229
+ client = self._require_client("download")
230
+ data: bytes = await client.download_media(self)
231
+ return data
232
+
233
+ def _require_client(self, action: str) -> Any:
234
+ """Return the bound client or raise a helpful error."""
235
+ if self._client is None:
236
+ from zapy.errors import ZapyError
237
+
238
+ raise ZapyError(
239
+ f"cannot {action}: this Message is not attached to a Client "
240
+ "(messages received through Client handlers are attached)"
241
+ )
242
+ return self._client
243
+
244
+
245
+ def message_from_incoming(event: Any, client: Any = None) -> Message:
246
+ """Map a ``WaIncomingMessageEvent`` (or mapping) to a :class:`Message`.
247
+
248
+ Example:
249
+ ```python
250
+ from zapy import events
251
+
252
+ msg = events.message_from_incoming(incoming)
253
+ ```
254
+ """
255
+ key = _field(event, "key")
256
+ remote_jid = str(_field(key, "remote_jid", "") or "")
257
+ participant = _field(key, "participant")
258
+ sender = str(participant or remote_jid)
259
+ is_group = bool(_field(key, "is_group", False) or _jid.is_group_jid(remote_jid))
260
+ raw = _field(event, "message")
261
+ message_id = _field(key, "id") or _field(event, "stanza_id") or ""
262
+ return Message(
263
+ text=extract_text(raw),
264
+ sender=sender,
265
+ chat=remote_jid,
266
+ is_group=is_group,
267
+ from_me=bool(_field(key, "from_me", False)),
268
+ id=str(message_id),
269
+ timestamp=_field(event, "timestamp_seconds"),
270
+ raw=raw,
271
+ media=extract_media(raw),
272
+ push_name=_field(event, "push_name"),
273
+ _client=client,
274
+ _incoming=event,
275
+ )
276
+
277
+
278
+ @dataclass(frozen=True, slots=True)
279
+ class Receipt:
280
+ """Delivery/read/played receipts for outbound messages.
281
+
282
+ Example:
283
+ ```python
284
+ @client.on("receipt")
285
+ async def on_receipt(receipt):
286
+ print(receipt.ids, receipt.status)
287
+ ```
288
+ """
289
+
290
+ ids: tuple[str, ...] = ()
291
+ chat: str = ""
292
+ sender: str | None = None
293
+ status: str = "delivered"
294
+ timestamp: int | None = None
295
+ raw: Any = None
296
+
297
+
298
+ def receipt_from_incoming(event: Any) -> Receipt:
299
+ """Map a ``WaIncomingReceiptEvent`` (or mapping) to a :class:`Receipt`.
300
+
301
+ Example:
302
+ ```python
303
+ from zapy import events
304
+
305
+ receipt = events.receipt_from_incoming(incoming)
306
+ ```
307
+ """
308
+ ids = _field(event, "message_ids", ()) or ()
309
+ chat = str(_field(event, "chat_jid", "") or "")
310
+ sender = _field(event, "participant_jid")
311
+ return Receipt(
312
+ ids=tuple(str(item) for item in ids),
313
+ chat=chat,
314
+ sender=str(sender) if sender is not None else None,
315
+ status=str(_field(event, "status", "delivered")),
316
+ timestamp=_field(event, "timestamp_seconds"),
317
+ raw=event,
318
+ )
319
+
320
+
321
+ @dataclass(frozen=True, slots=True)
322
+ class ConnectionUpdate:
323
+ """Connection lifecycle update (open / close / connecting).
324
+
325
+ Example:
326
+ ```python
327
+ @client.on("connection")
328
+ async def on_connection(update):
329
+ print(update.status, update.reason)
330
+ ```
331
+ """
332
+
333
+ status: str = ""
334
+ reason: str | None = None
335
+ code: int | None = None
336
+ is_logged_out: bool = False
337
+ is_new_login: bool = False
338
+ raw: Any = None
339
+
340
+
341
+ def connection_from_payload(payload: Any) -> ConnectionUpdate:
342
+ """Map a ``connection`` event payload to a :class:`ConnectionUpdate`.
343
+
344
+ Example:
345
+ ```python
346
+ from zapy import events
347
+
348
+ update = events.connection_from_payload({"status": "open"})
349
+ ```
350
+ """
351
+ code = _field(payload, "code")
352
+ return ConnectionUpdate(
353
+ status=str(_field(payload, "status", "") or ""),
354
+ reason=_field(payload, "reason"),
355
+ code=int(code) if isinstance(code, (int, float)) else None,
356
+ is_logged_out=bool(_field(payload, "is_logout", False)),
357
+ is_new_login=bool(_field(payload, "is_new_login", False)),
358
+ raw=payload,
359
+ )
360
+
361
+
362
+ @dataclass(frozen=True, slots=True)
363
+ class Disconnected:
364
+ """The transport closed; ``reason`` says why (see ``ConnectionUpdate``).
365
+
366
+ Example:
367
+ ```python
368
+ @client.on("disconnected")
369
+ async def on_disconnected(event):
370
+ print("closed:", event.reason)
371
+ ```
372
+ """
373
+
374
+ reason: str | None = None
375
+ code: int | None = None
376
+ is_logged_out: bool = False
377
+ raw: Any = None
378
+
379
+
380
+ def disconnected_from_payload(payload: Any) -> Disconnected:
381
+ """Map a closing ``connection`` payload to a :class:`Disconnected`.
382
+
383
+ Example:
384
+ ```python
385
+ from zapy import events
386
+
387
+ event = events.disconnected_from_payload({"reason": "closed"})
388
+ ```
389
+ """
390
+ code = _field(payload, "code")
391
+ return Disconnected(
392
+ reason=_field(payload, "reason"),
393
+ code=int(code) if isinstance(code, (int, float)) else None,
394
+ is_logged_out=bool(_field(payload, "is_logout", False)),
395
+ raw=payload,
396
+ )
397
+
398
+
399
+ @dataclass(frozen=True, slots=True)
400
+ class QrUpdate:
401
+ """A fresh QR payload to scan with the phone (``auth_qr``).
402
+
403
+ Example:
404
+ ```python
405
+ @client.on("qr")
406
+ async def on_qr(update):
407
+ print(update.qr)
408
+ ```
409
+ """
410
+
411
+ qr: str = ""
412
+ ttl_ms: float | None = None
413
+ raw: Any = None
414
+
415
+
416
+ def qr_from_payload(payload: Any) -> QrUpdate:
417
+ """Map an ``auth_qr`` payload (or bare string) to a :class:`QrUpdate`.
418
+
419
+ Example:
420
+ ```python
421
+ from zapy import events
422
+
423
+ update = events.qr_from_payload({"qr": "2,..."})
424
+ ```
425
+ """
426
+ if isinstance(payload, str):
427
+ return QrUpdate(qr=payload, raw=payload)
428
+ ttl = _field(payload, "ttl_ms")
429
+ return QrUpdate(
430
+ qr=str(_field(payload, "qr", "") or ""),
431
+ ttl_ms=float(ttl) if isinstance(ttl, (int, float)) else None,
432
+ raw=payload,
433
+ )
434
+
435
+
436
+ @dataclass(frozen=True, slots=True)
437
+ class PairingCode:
438
+ """A numeric pairing code for linking without a QR scan.
439
+
440
+ Example:
441
+ ```python
442
+ @client.on("pairing_code")
443
+ async def on_pairing(code):
444
+ print(code.code)
445
+ ```
446
+ """
447
+
448
+ code: str = ""
449
+ raw: Any = None
450
+
451
+
452
+ def pairing_code_from_payload(payload: Any) -> PairingCode:
453
+ """Map an ``auth_pairing_code`` payload to a :class:`PairingCode`.
454
+
455
+ Example:
456
+ ```python
457
+ from zapy import events
458
+
459
+ code = events.pairing_code_from_payload({"code": "123-456"})
460
+ ```
461
+ """
462
+ if isinstance(payload, str):
463
+ return PairingCode(code=payload, raw=payload)
464
+ return PairingCode(code=str(_field(payload, "code", "") or ""), raw=payload)
465
+
466
+
467
+ @dataclass(frozen=True, slots=True)
468
+ class Paired:
469
+ """Pairing completed; credentials are persisted in the session store.
470
+
471
+ Example:
472
+ ```python
473
+ @client.on("paired")
474
+ async def on_paired(event):
475
+ print("paired!")
476
+ ```
477
+ """
478
+
479
+ credentials: Any = None
480
+ raw: Any = None
481
+
482
+
483
+ def paired_from_payload(payload: Any) -> Paired:
484
+ """Map an ``auth_paired`` payload to a :class:`Paired`.
485
+
486
+ Example:
487
+ ```python
488
+ from zapy import events
489
+
490
+ event = events.paired_from_payload({"credentials": {}})
491
+ ```
492
+ """
493
+ if isinstance(payload, Mapping):
494
+ return Paired(credentials=payload.get("credentials"), raw=payload)
495
+ return Paired(credentials=getattr(payload, "credentials", None), raw=payload)
496
+
497
+
498
+ @dataclass(frozen=True, slots=True)
499
+ class GroupUpdate:
500
+ """A group lifecycle notification; details live in ``raw``.
501
+
502
+ Example:
503
+ ```python
504
+ @client.on("group")
505
+ async def on_group(update):
506
+ print(update.action, update.group_jid)
507
+ ```
508
+ """
509
+
510
+ action: str = ""
511
+ group_jid: str | None = None
512
+ author_jid: str | None = None
513
+ timestamp: int | None = None
514
+ raw: Any = None
515
+
516
+
517
+ @dataclass(frozen=True, slots=True)
518
+ class PresenceUpdate:
519
+ """A peer presence change (available/unavailable/typing state).
520
+
521
+ Example:
522
+ ```python
523
+ @client.on("presence")
524
+ async def on_presence(update):
525
+ print(update.chat, update.state)
526
+ ```
527
+ """
528
+
529
+ chat: str | None = None
530
+ state: str = ""
531
+ raw: Any = None
532
+
533
+
534
+ @dataclass(frozen=True, slots=True)
535
+ class ChatStateUpdate:
536
+ """A peer chatstate (composing/paused/recording).
537
+
538
+ Example:
539
+ ```python
540
+ @client.on("chatstate")
541
+ async def on_chatstate(update):
542
+ print(update.chat, update.state)
543
+ ```
544
+ """
545
+
546
+ chat: str | None = None
547
+ state: str = ""
548
+ raw: Any = None
549
+
550
+
551
+ @dataclass(frozen=True, slots=True)
552
+ class CallUpdate:
553
+ """An incoming call signal; details live in ``raw``.
554
+
555
+ Example:
556
+ ```python
557
+ @client.on("call")
558
+ async def on_call(update):
559
+ print(update.call_id)
560
+ ```
561
+ """
562
+
563
+ call_id: str | None = None
564
+ raw: Any = None