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,1478 @@
1
+ """Group and community coordinator
2
+ (mirrors ``src/client/coordinators/WaGroupCoordinator.ts``).
3
+
4
+ TEMPORARY (sibling layers not yet ported): ``WA_GROUP_PARTICIPANT_TYPES``,
5
+ ``WA_GROUP_MEMBERSHIP_ACTION_TAGS`` and ``WA_GROUP_NOTIFICATION_TAGS`` are
6
+ verbatim copies of ``src/protocol/group.ts`` / ``src/protocol/notification.ts``.
7
+ They move to ``zapy._protocol`` once it lands; the call sites already match the
8
+ canonical shapes.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import math
14
+ import time
15
+ from collections.abc import Awaitable, Callable, Mapping
16
+ from dataclasses import dataclass, field
17
+ from typing import Any, Literal
18
+
19
+ from zapy._client.events.group import parse_participants
20
+ from zapy._message.messaging import WA_ADDRESSING_MODES, parse_jid_full
21
+ from zapy._protocol import defaults as _defaults
22
+ from zapy._protocol.nodes import WA_IQ_TYPES, WA_NODE_TAGS, WA_XMLNS
23
+ from zapy._transport.node.builders.account_sync import (
24
+ build_list_participating_groups_iq,
25
+ )
26
+ from zapy._transport.node.builders.community import (
27
+ BuildUnlinkSubGroupsIqInput,
28
+ SubGroupLink,
29
+ build_deactivate_community_iq,
30
+ build_linked_groups_participants_iq,
31
+ build_link_sub_groups_iq,
32
+ build_unlink_sub_groups_iq,
33
+ )
34
+ from zapy._transport.node.builders.group import (
35
+ BuildCreateGroupIqInput,
36
+ WaGroupMemberAddMode,
37
+ WaGroupMemberLinkMode,
38
+ WaGroupMemberShareGroupHistoryMode,
39
+ build_cancel_membership_requests_iq,
40
+ build_create_group_iq,
41
+ build_get_membership_approval_requests_iq,
42
+ build_group_participant_change_iq,
43
+ build_join_linked_group_iq,
44
+ build_leave_group_iq,
45
+ build_membership_requests_action_iq,
46
+ build_set_group_ephemeral_iq,
47
+ build_set_group_member_add_mode_iq,
48
+ build_set_group_member_link_mode_iq,
49
+ build_set_group_member_share_group_history_mode_iq,
50
+ )
51
+ from zapy._transport.node.helpers import (
52
+ find_node_child,
53
+ get_node_children_by_tag,
54
+ get_node_children_by_tag_from_children,
55
+ get_node_text_content,
56
+ has_node_child,
57
+ )
58
+ from zapy._transport.node.query import assert_iq_result, build_iq_node
59
+ from zapy._transport.types import BinaryNode
60
+
61
+ # Verbatim ``src/protocol/group.ts``.
62
+ WA_GROUP_PARTICIPANT_TYPES: dict[str, str] = {
63
+ "SUPERADMIN": "superadmin",
64
+ "ADMIN": "admin",
65
+ "REGULAR": "participant",
66
+ }
67
+
68
+ # Verbatim ``src/protocol/notification.ts`` (rows used by group settings).
69
+ WA_GROUP_NOTIFICATION_TAGS: dict[str, str] = {
70
+ "ANNOUNCEMENT": "announcement",
71
+ "NOT_ANNOUNCEMENT": "not_announcement",
72
+ "LOCKED": "locked",
73
+ "UNLOCKED": "unlocked",
74
+ "EPHEMERAL": "ephemeral",
75
+ "NOT_EPHEMERAL": "not_ephemeral",
76
+ "MEMBERSHIP_APPROVAL_MODE": "membership_approval_mode",
77
+ "ALLOW_NON_ADMIN_SUB_GROUP_CREATION": "allow_non_admin_sub_group_creation",
78
+ "NOT_ALLOW_NON_ADMIN_SUB_GROUP_CREATION": (
79
+ "not_allow_non_admin_sub_group_creation"
80
+ ),
81
+ "GROUP_HISTORY": "group_history",
82
+ "NO_GROUP_HISTORY": "no_group_history",
83
+ "ALLOW_ADMIN_REPORTS": "allow_admin_reports",
84
+ "NOT_ALLOW_ADMIN_REPORTS": "not_allow_admin_reports",
85
+ "NO_FREQUENTLY_FORWARDED": "no_frequently_forwarded",
86
+ "FREQUENTLY_FORWARDED_OK": "frequently_forwarded_ok",
87
+ }
88
+
89
+ WaGroupSetting = Literal[
90
+ "announcement",
91
+ "restrict",
92
+ "ephemeral",
93
+ "membership_approval_mode",
94
+ "allow_non_admin_sub_group_creation",
95
+ "group_history",
96
+ "allow_admin_reports",
97
+ "no_frequently_forwarded",
98
+ ]
99
+
100
+ WaParticipantActionStatus = Literal["ok", "error"]
101
+
102
+
103
+ @dataclass(frozen=True, slots=True)
104
+ class WaGroupParticipant:
105
+ """One group member with its admin flags and addressing aliases."""
106
+
107
+ jid: str
108
+ type: str
109
+ is_admin: bool
110
+ is_super_admin: bool
111
+ lid: str | None = None
112
+ phone_number: str | None = None
113
+ display_name: str | None = None
114
+ username: str | None = None
115
+ expiration_seconds: int | None = None
116
+
117
+
118
+ @dataclass(frozen=True, slots=True)
119
+ class WaGroupMetadata:
120
+ """Full metadata for a group (mirrors ``WaGroupMetadata``)."""
121
+
122
+ jid: str
123
+ subject: str
124
+ restrict: bool
125
+ announce: bool
126
+ is_parent_group: bool
127
+ is_closed_community: bool
128
+ default_subgroup: bool
129
+ general_subgroup: bool
130
+ hidden_subgroup: bool
131
+ allow_non_admin_sub_group_creation: bool
132
+ membership_approval_enabled: bool
133
+ no_frequently_forwarded: bool
134
+ support: bool
135
+ suspended: bool
136
+ incognito: bool
137
+ allow_admin_reports: bool
138
+ auto_add_disabled: bool
139
+ group_history: bool
140
+ capi: bool
141
+ group_safety_check: bool
142
+ participant_label_enabled: bool
143
+ limit_sharing_enabled: bool
144
+ participants: tuple[WaGroupParticipant, ...] = ()
145
+ subject_owner: str | None = None
146
+ subject_owner_phone_number: str | None = None
147
+ subject_owner_username: str | None = None
148
+ subject_time: int | None = None
149
+ owner: str | None = None
150
+ owner_phone_number: str | None = None
151
+ owner_username: str | None = None
152
+ owner_country_code: str | None = None
153
+ creation: int | None = None
154
+ desc: str | None = None
155
+ desc_id: str | None = None
156
+ desc_owner: str | None = None
157
+ desc_time: int | None = None
158
+ ephemeral: int | None = None
159
+ ephemeral_trigger: int | None = None
160
+ size: int | None = None
161
+ addressing_mode: Literal["lid", "pn"] | None = None
162
+ evolution_version: int | None = None
163
+ member_add_mode: str | None = None
164
+ member_link_mode: str | None = None
165
+ member_share_group_history_mode: str | None = None
166
+ growth_locked_expiration: int | None = None
167
+ appeal_status: Literal["approved", "in_review", "none", "rejected"] | None = None
168
+ appeal_update_time: int | None = None
169
+ linked_parent_jid: str | None = None
170
+
171
+
172
+ @dataclass(frozen=True, slots=True)
173
+ class WaGroupJoinViaLinkResult:
174
+ """Outcome of joining a group via invite code."""
175
+
176
+ status: Literal["joined", "pending"]
177
+ group_jid: str
178
+
179
+
180
+ @dataclass(frozen=True, slots=True)
181
+ class WaMembershipRequest:
182
+ """One pending membership-approval request."""
183
+
184
+ jid: str
185
+ request_time: int = 0
186
+ requestor: str | None = None
187
+ requestor_phone: str | None = None
188
+ requestor_username: str | None = None
189
+ parent_group_jid: str | None = None
190
+ request_method: str | None = None
191
+
192
+
193
+ @dataclass(frozen=True, slots=True)
194
+ class WaGroupCreateOptions:
195
+ """Options for :meth:`WaGroupCoordinator.create_group`."""
196
+
197
+ description: str | None = None
198
+ linked_parent_jid: str | None = None
199
+
200
+
201
+ @dataclass(frozen=True, slots=True)
202
+ class WaCommunityCreateOptions:
203
+ """Options for :meth:`WaGroupCoordinator.create_community`."""
204
+
205
+ description: str | None = None
206
+ membership_approval_mode: Literal["open", "request_required"] | None = None
207
+ allow_non_admin_sub_group_creation: bool | None = None
208
+ create_general_chat: bool | None = None
209
+
210
+
211
+ @dataclass(frozen=True, slots=True)
212
+ class WaCommunitySubGroupResult:
213
+ """Per-sub-group outcome of a link/unlink call."""
214
+
215
+ jid: str
216
+ error: int | None = None
217
+
218
+
219
+ @dataclass(frozen=True, slots=True)
220
+ class WaLinkSubGroupsResult:
221
+ """Outcome of linking sub-groups to a community."""
222
+
223
+ linked_jids: tuple[str, ...] = ()
224
+ failed: tuple[WaCommunitySubGroupResult, ...] = ()
225
+
226
+
227
+ @dataclass(frozen=True, slots=True)
228
+ class WaUnlinkSubGroupsResult:
229
+ """Outcome of unlinking sub-groups from a community."""
230
+
231
+ unlinked_jids: tuple[str, ...] = ()
232
+ failed: tuple[WaCommunitySubGroupResult, ...] = ()
233
+
234
+
235
+ @dataclass(frozen=True, slots=True)
236
+ class WaCommunitySubGroup:
237
+ """One sub-group (or announcement group) of a community."""
238
+
239
+ jid: str
240
+ default_subgroup: bool = False
241
+ subject: str | None = None
242
+ subject_time: int | None = None
243
+ general_subgroup: bool = False
244
+ hidden_subgroup: bool = False
245
+ membership_approval_enabled: bool = False
246
+ pending_membership_requests: int = 0
247
+
248
+
249
+ @dataclass(frozen=True, slots=True)
250
+ class WaCommunitySubGroupsResult:
251
+ """Sub-groups plus announcement group of a community."""
252
+
253
+ community_jid: str
254
+ announcement_group: WaCommunitySubGroup | None = None
255
+ sub_groups: tuple[WaCommunitySubGroup, ...] = ()
256
+
257
+
258
+ @dataclass(frozen=True, slots=True)
259
+ class WaCommunitySubGroupSuggestion:
260
+ """One suggested sub-group for a community."""
261
+
262
+ jid: str
263
+ subject: str | None = None
264
+ description: str | None = None
265
+ creator: str | None = None
266
+ creation_time: int | None = None
267
+ participant_count: int | None = None
268
+ is_existing_group: bool = False
269
+ hidden_group: bool = False
270
+
271
+
272
+ @dataclass(frozen=True, slots=True)
273
+ class WaGroupSuspensionAppealResult:
274
+ """Outcome of a group-suspension appeal."""
275
+
276
+ success: bool
277
+ response_code: str | None = None
278
+ error_message: str | None = None
279
+ appeal_creation_time: int | None = None
280
+
281
+
282
+ @dataclass(frozen=True, slots=True)
283
+ class WaGroupInviteParticipantSample:
284
+ """One trimmed participant entry of an invite preview."""
285
+
286
+ jid: str
287
+ phone_number: str | None = None
288
+ type: str | None = None
289
+
290
+
291
+ @dataclass(frozen=True, slots=True)
292
+ class GroupCommons:
293
+ """Fields shared by full metadata and invite previews."""
294
+
295
+ jid: str
296
+ subject: str
297
+ membership_approval_enabled: bool = False
298
+ size: int | None = None
299
+ creation: int | None = None
300
+ subject_owner: str | None = None
301
+ subject_owner_phone_number: str | None = None
302
+ subject_owner_username: str | None = None
303
+ subject_time: int | None = None
304
+ addressing_mode: Literal["lid", "pn"] | None = None
305
+ desc: str | None = None
306
+ desc_id: str | None = None
307
+ desc_owner: str | None = None
308
+ desc_time: int | None = None
309
+ ephemeral: int | None = None
310
+ ephemeral_trigger: int | None = None
311
+ linked_parent_jid: str | None = None
312
+
313
+
314
+ @dataclass(frozen=True, slots=True)
315
+ class WaGroupInviteInfo(GroupCommons):
316
+ """Preview of a group behind an invite code."""
317
+
318
+ hidden_group: bool = False
319
+ default_subgroup: bool = False
320
+ general_chat: bool = False
321
+ has_capi: bool = False
322
+ has_pending_membership_request: bool = False
323
+ participants: tuple[WaGroupInviteParticipantSample, ...] = ()
324
+
325
+
326
+ @dataclass(frozen=True, slots=True)
327
+ class WaParticipantActionResult:
328
+ """Per-JID outcome of a participant add/remove/promote/demote."""
329
+
330
+ jid: str
331
+ status: WaParticipantActionStatus
332
+ code: int
333
+ raw: BinaryNode = field(compare=False)
334
+ phone_number: str | None = None
335
+ username: str | None = None
336
+
337
+
338
+ @dataclass(frozen=True, slots=True)
339
+ class WaRevokeInviteResult:
340
+ """Fresh invite code plus participants affected by the rotation."""
341
+
342
+ code: str
343
+ affected_participants: tuple[WaParticipantActionResult, ...] = ()
344
+
345
+
346
+ WaGroupParticipantChangeAction = Literal["add", "remove", "promote", "demote"]
347
+
348
+ _MexQueryFn = Callable[[str, Mapping[str, Any]], Awaitable[Mapping[str, Any] | None]]
349
+
350
+ _APPEAL_STATUSES = frozenset({"approved", "in_review", "none", "rejected"})
351
+
352
+ _SETTING_TAGS: dict[WaGroupSetting, dict[str, str]] = {
353
+ "announcement": {
354
+ "on": WA_GROUP_NOTIFICATION_TAGS["ANNOUNCEMENT"],
355
+ "off": WA_GROUP_NOTIFICATION_TAGS["NOT_ANNOUNCEMENT"],
356
+ },
357
+ "restrict": {
358
+ "on": WA_GROUP_NOTIFICATION_TAGS["LOCKED"],
359
+ "off": WA_GROUP_NOTIFICATION_TAGS["UNLOCKED"],
360
+ },
361
+ "ephemeral": {
362
+ "on": WA_GROUP_NOTIFICATION_TAGS["EPHEMERAL"],
363
+ "off": WA_GROUP_NOTIFICATION_TAGS["NOT_EPHEMERAL"],
364
+ },
365
+ "membership_approval_mode": {
366
+ "on": WA_GROUP_NOTIFICATION_TAGS["MEMBERSHIP_APPROVAL_MODE"],
367
+ "off": WA_GROUP_NOTIFICATION_TAGS["MEMBERSHIP_APPROVAL_MODE"],
368
+ },
369
+ "allow_non_admin_sub_group_creation": {
370
+ "on": WA_GROUP_NOTIFICATION_TAGS["ALLOW_NON_ADMIN_SUB_GROUP_CREATION"],
371
+ "off": WA_GROUP_NOTIFICATION_TAGS["NOT_ALLOW_NON_ADMIN_SUB_GROUP_CREATION"],
372
+ },
373
+ "group_history": {
374
+ "on": WA_GROUP_NOTIFICATION_TAGS["GROUP_HISTORY"],
375
+ "off": WA_GROUP_NOTIFICATION_TAGS["NO_GROUP_HISTORY"],
376
+ },
377
+ "allow_admin_reports": {
378
+ "on": WA_GROUP_NOTIFICATION_TAGS["ALLOW_ADMIN_REPORTS"],
379
+ "off": WA_GROUP_NOTIFICATION_TAGS["NOT_ALLOW_ADMIN_REPORTS"],
380
+ },
381
+ "no_frequently_forwarded": {
382
+ "on": WA_GROUP_NOTIFICATION_TAGS["NO_FREQUENTLY_FORWARDED"],
383
+ "off": WA_GROUP_NOTIFICATION_TAGS["FREQUENTLY_FORWARDED_OK"],
384
+ },
385
+ }
386
+
387
+
388
+ def _try_as_number(value: Any) -> int | float | None:
389
+ """Return ``value`` as a number, else ``None`` (verbatim ``tryAsNumber``)."""
390
+ if isinstance(value, bool):
391
+ return None
392
+ if isinstance(value, (int, float)):
393
+ return value if math.isfinite(value) else None
394
+ if isinstance(value, str):
395
+ normalized = value.strip()
396
+ if not normalized:
397
+ return None
398
+ try:
399
+ parsed = float(normalized)
400
+ except ValueError:
401
+ return None
402
+ return parsed if math.isfinite(parsed) else None
403
+ return None
404
+
405
+
406
+ def _try_as_string(value: Any) -> str | None:
407
+ """Return non-empty ``value`` when it is a string, else ``None``."""
408
+ return value if isinstance(value, str) and len(value) > 0 else None
409
+
410
+
411
+ def _try_as_record(value: Any) -> dict[str, Any] | None:
412
+ """Return ``value`` when it is a mapping, else ``None``."""
413
+ return dict(value) if isinstance(value, Mapping) else None
414
+
415
+
416
+ def _format_validation_value(value: Any) -> str:
417
+ """Render a rejected numeric input like the TS template does."""
418
+ if isinstance(value, float):
419
+ if math.isnan(value):
420
+ return "NaN"
421
+ if math.isinf(value):
422
+ return "Infinity" if value > 0 else "-Infinity"
423
+ return str(value)
424
+
425
+
426
+ def parse_group_participants(node: BinaryNode) -> list[WaGroupParticipant]:
427
+ """Parse the participant list of a group/metadata container node."""
428
+ parsed = parse_participants(node)
429
+ participants: list[WaGroupParticipant] = []
430
+ for entry in parsed:
431
+ if not entry.jid:
432
+ continue
433
+ participant_type = entry.role or WA_GROUP_PARTICIPANT_TYPES["REGULAR"]
434
+ participants.append(
435
+ WaGroupParticipant(
436
+ jid=entry.jid,
437
+ type=participant_type,
438
+ is_admin=participant_type
439
+ in (
440
+ WA_GROUP_PARTICIPANT_TYPES["ADMIN"],
441
+ WA_GROUP_PARTICIPANT_TYPES["SUPERADMIN"],
442
+ ),
443
+ is_super_admin=participant_type
444
+ == WA_GROUP_PARTICIPANT_TYPES["SUPERADMIN"],
445
+ lid=entry.lid_jid,
446
+ phone_number=entry.phone_jid,
447
+ display_name=entry.display_name,
448
+ username=entry.username,
449
+ expiration_seconds=entry.expiration_seconds,
450
+ )
451
+ )
452
+ return participants
453
+
454
+
455
+ def find_group_target(node: BinaryNode) -> BinaryNode:
456
+ """Return ``node`` itself or its ``<group>`` child, else raise."""
457
+ if node.tag == WA_NODE_TAGS["GROUP"]:
458
+ return node
459
+ group_node = find_node_child(node, WA_NODE_TAGS["GROUP"])
460
+ if group_node is None:
461
+ raise ValueError(f"expected <group> node in response, got <{node.tag}>")
462
+ return group_node
463
+
464
+
465
+ def parse_group_commons(target: BinaryNode) -> GroupCommons:
466
+ """Parse the metadata fields shared by groups and invite previews."""
467
+ attrs = target.attrs
468
+ desc_node = find_node_child(target, WA_NODE_TAGS["DESCRIPTION"])
469
+ desc_body = find_node_child(desc_node, WA_NODE_TAGS["BODY"]) if desc_node else None
470
+ desc = get_node_text_content(desc_body) if desc_body is not None else None
471
+ ephemeral_node = find_node_child(target, WA_NODE_TAGS["EPHEMERAL"])
472
+ parent_node = find_node_child(target, "parent")
473
+ linked_parent_node = find_node_child(target, "linked_parent")
474
+ membership_approval_node = find_node_child(
475
+ target, WA_NODE_TAGS["MEMBERSHIP_APPROVAL_MODE"]
476
+ )
477
+ group_join_node = (
478
+ find_node_child(membership_approval_node, WA_NODE_TAGS["GROUP_JOIN"])
479
+ if membership_approval_node is not None
480
+ else None
481
+ )
482
+ addressing_mode_raw = attrs.get("addressing_mode")
483
+ addressing_mode: Literal["lid", "pn"] | None = None
484
+ if addressing_mode_raw == WA_ADDRESSING_MODES["LID"]:
485
+ addressing_mode = WA_ADDRESSING_MODES["LID"] # type: ignore[assignment]
486
+ elif addressing_mode_raw == WA_ADDRESSING_MODES["PN"]:
487
+ addressing_mode = WA_ADDRESSING_MODES["PN"] # type: ignore[assignment]
488
+ raw_jid = attrs.get("id") or attrs.get("jid") or ""
489
+ jid = (
490
+ f"{raw_jid}@{_defaults.GROUP_SERVER}"
491
+ if raw_jid and "@" not in raw_jid
492
+ else raw_jid
493
+ )
494
+ return GroupCommons(
495
+ jid=jid,
496
+ subject=attrs.get("subject", ""),
497
+ size=int(attrs["size"]) if attrs.get("size") else None,
498
+ creation=int(attrs["creation"]) if attrs.get("creation") else None,
499
+ subject_owner=attrs.get("s_o") or attrs.get("subject_owner"),
500
+ subject_owner_phone_number=attrs.get("s_o_pn"),
501
+ subject_owner_username=attrs.get("s_o_username"),
502
+ subject_time=int(attrs["s_t"]) if attrs.get("s_t") else None,
503
+ addressing_mode=addressing_mode,
504
+ desc=desc,
505
+ desc_id=desc_node.attrs.get("id") if desc_node is not None else None,
506
+ desc_owner=desc_node.attrs.get("participant")
507
+ if desc_node is not None
508
+ else None,
509
+ desc_time=(
510
+ int(desc_node.attrs["t"])
511
+ if desc_node is not None and desc_node.attrs.get("t")
512
+ else None
513
+ ),
514
+ ephemeral=(
515
+ int(ephemeral_node.attrs["expiration"])
516
+ if ephemeral_node is not None and ephemeral_node.attrs.get("expiration")
517
+ else None
518
+ ),
519
+ ephemeral_trigger=(
520
+ int(ephemeral_node.attrs["trigger"])
521
+ if ephemeral_node is not None and ephemeral_node.attrs.get("trigger")
522
+ else None
523
+ ),
524
+ linked_parent_jid=(
525
+ linked_parent_node.attrs.get("jid")
526
+ if linked_parent_node is not None
527
+ else parent_node.attrs.get("jid")
528
+ if parent_node is not None
529
+ else None
530
+ ),
531
+ membership_approval_enabled=(
532
+ group_join_node.attrs.get("state") == "on"
533
+ if group_join_node is not None
534
+ else False
535
+ ),
536
+ )
537
+
538
+
539
+ def parse_group_metadata(node: BinaryNode) -> WaGroupMetadata:
540
+ """Parse full group metadata from an IQ result (or ``<group>`` node)."""
541
+ target = find_group_target(node)
542
+ attrs = target.attrs
543
+ commons = parse_group_commons(target)
544
+ appeal_status: Literal["approved", "in_review", "none", "rejected"] | None = None
545
+ appeal_status_node = find_node_child(target, "appeal_status")
546
+ appeal_status_raw = (
547
+ appeal_status_node.attrs.get("type") if appeal_status_node is not None else None
548
+ )
549
+ if appeal_status_raw is not None and appeal_status_raw in _APPEAL_STATUSES:
550
+ appeal_status = appeal_status_raw # type: ignore[assignment]
551
+ parent_node = find_node_child(target, "parent")
552
+ growth_locked_node = find_node_child(target, "growth_locked")
553
+ appeal_update_time_node = find_node_child(target, "appeal_update_time")
554
+ evolution_version_node = find_node_child(target, "evolution_version")
555
+ member_add_mode_node = find_node_child(target, "member_add_mode")
556
+ member_link_mode_node = find_node_child(target, "member_link_mode")
557
+ member_share_node = find_node_child(target, "member_share_group_history_mode")
558
+ return WaGroupMetadata(
559
+ jid=commons.jid,
560
+ subject=commons.subject,
561
+ size=commons.size,
562
+ creation=commons.creation,
563
+ subject_owner=commons.subject_owner,
564
+ subject_owner_phone_number=commons.subject_owner_phone_number,
565
+ subject_owner_username=commons.subject_owner_username,
566
+ subject_time=commons.subject_time,
567
+ addressing_mode=commons.addressing_mode,
568
+ desc=commons.desc,
569
+ desc_id=commons.desc_id,
570
+ desc_owner=commons.desc_owner,
571
+ desc_time=commons.desc_time,
572
+ ephemeral=commons.ephemeral,
573
+ ephemeral_trigger=commons.ephemeral_trigger,
574
+ linked_parent_jid=commons.linked_parent_jid,
575
+ membership_approval_enabled=commons.membership_approval_enabled,
576
+ owner=attrs.get("creator") or attrs.get("owner"),
577
+ owner_phone_number=attrs.get("creator_pn"),
578
+ owner_username=attrs.get("creator_username"),
579
+ owner_country_code=attrs.get("creator_country_code"),
580
+ restrict=has_node_child(target, WA_NODE_TAGS["LOCKED"]),
581
+ announce=has_node_child(target, WA_NODE_TAGS["ANNOUNCEMENT"]),
582
+ is_parent_group=parent_node is not None,
583
+ is_closed_community=(
584
+ parent_node.attrs.get("default_membership_approval_mode")
585
+ == "request_required"
586
+ if parent_node is not None
587
+ else False
588
+ ),
589
+ default_subgroup=has_node_child(target, "default_sub_group"),
590
+ general_subgroup=has_node_child(target, "general_chat"),
591
+ hidden_subgroup=has_node_child(target, "hidden_group"),
592
+ allow_non_admin_sub_group_creation=has_node_child(
593
+ target, "allow_non_admin_sub_group_creation"
594
+ ),
595
+ no_frequently_forwarded=has_node_child(target, "no_frequently_forwarded"),
596
+ support=has_node_child(target, "support"),
597
+ suspended=has_node_child(target, "suspended"),
598
+ incognito=has_node_child(target, "incognito"),
599
+ allow_admin_reports=has_node_child(target, "allow_admin_reports"),
600
+ auto_add_disabled=has_node_child(target, "auto_add_disabled"),
601
+ group_history=has_node_child(target, "group_history"),
602
+ capi=has_node_child(target, "capi"),
603
+ group_safety_check=has_node_child(target, "group_safety_check"),
604
+ participant_label_enabled=has_node_child(target, "participant_label_enabled"),
605
+ limit_sharing_enabled=has_node_child(target, "limit_sharing_enabled"),
606
+ evolution_version=(
607
+ int(evolution_version_node.attrs["value"])
608
+ if evolution_version_node is not None
609
+ and evolution_version_node.attrs.get("value")
610
+ else None
611
+ ),
612
+ member_add_mode=(
613
+ get_node_text_content(member_add_mode_node)
614
+ if member_add_mode_node is not None
615
+ else None
616
+ ),
617
+ member_link_mode=(
618
+ get_node_text_content(member_link_mode_node)
619
+ if member_link_mode_node is not None
620
+ else None
621
+ ),
622
+ member_share_group_history_mode=(
623
+ get_node_text_content(member_share_node)
624
+ if member_share_node is not None
625
+ else None
626
+ ),
627
+ growth_locked_expiration=(
628
+ int(growth_locked_node.attrs["expiration"])
629
+ if growth_locked_node is not None
630
+ and growth_locked_node.attrs.get("expiration")
631
+ else None
632
+ ),
633
+ appeal_status=appeal_status,
634
+ appeal_update_time=(
635
+ int(appeal_update_time_node.attrs["value"])
636
+ if appeal_update_time_node is not None
637
+ and appeal_update_time_node.attrs.get("value")
638
+ else None
639
+ ),
640
+ participants=tuple(parse_group_participants(target)),
641
+ )
642
+
643
+
644
+ def parse_participant_action_result(
645
+ node: BinaryNode,
646
+ ) -> WaParticipantActionResult | None:
647
+ """Parse one ``<participant>`` outcome node (``None`` without a JID)."""
648
+ jid = node.attrs.get("jid")
649
+ if not jid:
650
+ return None
651
+ error_code = node.attrs.get("error")
652
+ code = int(error_code) if error_code else 200
653
+ return WaParticipantActionResult(
654
+ jid=jid,
655
+ status="ok" if 200 <= code < 300 else "error",
656
+ code=code,
657
+ phone_number=node.attrs.get("phone_number"),
658
+ username=node.attrs.get("username"),
659
+ raw=node,
660
+ )
661
+
662
+
663
+ def parse_participant_action_results(
664
+ iq_result: BinaryNode, action: WaGroupParticipantChangeAction
665
+ ) -> list[WaParticipantActionResult]:
666
+ """Parse the per-JID outcomes of a participant-change IQ result."""
667
+ wrapper = find_node_child(iq_result, action)
668
+ target = wrapper if wrapper is not None else iq_result
669
+ results: list[WaParticipantActionResult] = []
670
+ for child in get_node_children_by_tag(target, WA_NODE_TAGS["PARTICIPANT"]):
671
+ parsed = parse_participant_action_result(child)
672
+ if parsed is not None:
673
+ results.append(parsed)
674
+ return results
675
+
676
+
677
+ def parse_group_invite_info(node: BinaryNode) -> WaGroupInviteInfo:
678
+ """Parse an invite preview from an IQ result (or ``<group>`` node)."""
679
+ target = find_group_target(node)
680
+ commons = parse_group_commons(target)
681
+ participants: list[WaGroupInviteParticipantSample] = []
682
+ for child in get_node_children_by_tag(target, WA_NODE_TAGS["PARTICIPANT"]):
683
+ jid_attr = child.attrs.get("jid")
684
+ if not jid_attr:
685
+ continue
686
+ participants.append(
687
+ WaGroupInviteParticipantSample(
688
+ jid=jid_attr,
689
+ phone_number=child.attrs.get("phone_number"),
690
+ type=child.attrs.get("type"),
691
+ )
692
+ )
693
+ return WaGroupInviteInfo(
694
+ jid=commons.jid,
695
+ subject=commons.subject,
696
+ size=commons.size,
697
+ creation=commons.creation,
698
+ subject_owner=commons.subject_owner,
699
+ subject_owner_phone_number=commons.subject_owner_phone_number,
700
+ subject_owner_username=commons.subject_owner_username,
701
+ subject_time=commons.subject_time,
702
+ addressing_mode=commons.addressing_mode,
703
+ desc=commons.desc,
704
+ desc_id=commons.desc_id,
705
+ desc_owner=commons.desc_owner,
706
+ desc_time=commons.desc_time,
707
+ ephemeral=commons.ephemeral,
708
+ ephemeral_trigger=commons.ephemeral_trigger,
709
+ linked_parent_jid=commons.linked_parent_jid,
710
+ membership_approval_enabled=commons.membership_approval_enabled,
711
+ hidden_group=has_node_child(target, "hidden_group"),
712
+ default_subgroup=has_node_child(target, "default_sub_group"),
713
+ general_chat=has_node_child(target, "general_chat"),
714
+ has_capi=has_node_child(target, "capi"),
715
+ has_pending_membership_request=has_node_child(
716
+ target, "membership_approval_request"
717
+ ),
718
+ participants=tuple(participants),
719
+ )
720
+
721
+
722
+ def parse_membership_approval_requests(node: BinaryNode) -> list[WaMembershipRequest]:
723
+ """Parse pending membership-approval requests from an IQ result."""
724
+ container = find_node_child(node, "membership_approval_requests")
725
+ if container is None:
726
+ return []
727
+ requests: list[WaMembershipRequest] = []
728
+ for request_node in get_node_children_by_tag(
729
+ container, "membership_approval_request"
730
+ ):
731
+ jid = request_node.attrs.get("jid")
732
+ if not jid:
733
+ continue
734
+ request_time_raw = request_node.attrs.get("request_time")
735
+ requests.append(
736
+ WaMembershipRequest(
737
+ jid=jid,
738
+ requestor=request_node.attrs.get("requestor"),
739
+ requestor_phone=request_node.attrs.get("requestor_pn"),
740
+ requestor_username=request_node.attrs.get("requestor_username"),
741
+ parent_group_jid=request_node.attrs.get("parent_group_jid"),
742
+ request_time=int(request_time_raw) if request_time_raw else 0,
743
+ request_method=request_node.attrs.get("request_method"),
744
+ )
745
+ )
746
+ return requests
747
+
748
+
749
+ def _parse_sub_group_node(node: Any, default_subgroup: bool) -> WaCommunitySubGroup:
750
+ """Parse one MEX sub-group node."""
751
+ record = _try_as_record(node)
752
+ subject = _try_as_record(record.get("subject") if record else None)
753
+ properties = _try_as_record(record.get("properties") if record else None)
754
+ approvals = _try_as_record(
755
+ record.get("membership_approval_requests") if record else None
756
+ )
757
+ subject_time_raw = (
758
+ _try_as_number(subject.get("creation_time")) if subject is not None else None
759
+ )
760
+ approvals_total_raw = _try_as_number(
761
+ approvals.get("total_count") if approvals is not None else None
762
+ )
763
+ return WaCommunitySubGroup(
764
+ jid=_try_as_string(record.get("id") if record else None) or "",
765
+ subject=(_try_as_string(subject.get("value")) if subject is not None else None),
766
+ subject_time=int(subject_time_raw) if subject_time_raw is not None else None,
767
+ default_subgroup=default_subgroup,
768
+ general_subgroup=(
769
+ properties.get("general_chat") is True if properties else False
770
+ ),
771
+ hidden_subgroup=properties.get("hidden_group") is True if properties else False,
772
+ membership_approval_enabled=(
773
+ properties.get("membership_approval_mode_enabled") is True
774
+ if properties
775
+ else False
776
+ ),
777
+ pending_membership_requests=(
778
+ int(approvals_total_raw) if approvals_total_raw is not None else 0
779
+ ),
780
+ )
781
+
782
+
783
+ def parse_group_is_internal_mex_response(data: Mapping[str, Any] | None) -> bool:
784
+ """Whether the MEX group query flags the group as internal."""
785
+ if data is None:
786
+ return False
787
+ query = _try_as_record(data.get("xwa2_group_query_by_id"))
788
+ properties = _try_as_record(query.get("properties") if query else None)
789
+ return properties is not None and properties.get("internal") is True
790
+
791
+
792
+ def parse_group_suspension_appeal_mex_response(
793
+ data: Mapping[str, Any] | None,
794
+ ) -> WaGroupSuspensionAppealResult:
795
+ """Parse a group-suspension-appeal MEX response."""
796
+ root = _try_as_record(
797
+ data.get("wa_create_group_suspension_appeal") if data else None
798
+ )
799
+ response_code = _try_as_string(root.get("response_code")) if root else None
800
+ return WaGroupSuspensionAppealResult(
801
+ success=response_code in ("SUCCESS", "APPEAL_ALREADY_EXISTS"),
802
+ response_code=response_code,
803
+ error_message=_try_as_string(root.get("error_message")) if root else None,
804
+ appeal_creation_time=(
805
+ int(v)
806
+ if (v := _try_as_number(root.get("appeal_creation_time")) if root else None)
807
+ is not None
808
+ else None
809
+ ),
810
+ )
811
+
812
+
813
+ def parse_sub_group_suggestions_mex_response(
814
+ data: Mapping[str, Any] | None,
815
+ ) -> list[WaCommunitySubGroupSuggestion]:
816
+ """Parse sub-group suggestions from a MEX response."""
817
+ query = _try_as_record(data.get("xwa2_group_query_by_id") if data else None)
818
+ suggestions = _try_as_record(query.get("sub_group_suggestions") if query else None)
819
+ edges = suggestions.get("edges") if suggestions else None
820
+ results: list[WaCommunitySubGroupSuggestion] = []
821
+ if not isinstance(edges, list):
822
+ return results
823
+ for edge in edges:
824
+ edge_record = _try_as_record(edge)
825
+ node = _try_as_record(edge_record.get("node")) if edge_record else None
826
+ if node is None or not node.get("id"):
827
+ continue
828
+ subject = _try_as_record(node.get("subject"))
829
+ description = _try_as_record(node.get("description"))
830
+ creator = _try_as_record(node.get("creator"))
831
+ results.append(
832
+ WaCommunitySubGroupSuggestion(
833
+ jid=str(node["id"]),
834
+ subject=_try_as_string(subject.get("value")) if subject else None,
835
+ description=(
836
+ _try_as_string(description.get("value")) if description else None
837
+ ),
838
+ creator=_try_as_string(creator.get("id")) if creator else None,
839
+ creation_time=(
840
+ int(v)
841
+ if (v := _try_as_number(node.get("creation_time"))) is not None
842
+ else None
843
+ ),
844
+ participant_count=(
845
+ int(v)
846
+ if (v := _try_as_number(node.get("total_participants_count")))
847
+ is not None
848
+ else None
849
+ ),
850
+ is_existing_group=node.get("is_existing_group") is True,
851
+ hidden_group=node.get("hidden_group") is True,
852
+ )
853
+ )
854
+ return results
855
+
856
+
857
+ QueryWithContextFn = Callable[
858
+ [str, BinaryNode, float | None, Mapping[str, Any] | None],
859
+ Awaitable[BinaryNode],
860
+ ]
861
+
862
+
863
+ class WaGroupCoordinator:
864
+ """Group and community queries/mutations
865
+ (created by :func:`create_group_coordinator`).
866
+
867
+ Community sub-APIs (``fetch_sub_groups``, ``is_internal_group``,
868
+ ``transfer_community_ownership``, ``fetch_subgroup_suggestions``,
869
+ ``submit_group_suspension_appeal``) require an active MEX transport and
870
+ raise when unavailable.
871
+ """
872
+
873
+ def __init__(
874
+ self,
875
+ query_with_context: QueryWithContextFn,
876
+ mex_query: _MexQueryFn | None = None,
877
+ ) -> None:
878
+ self._query_with_context = query_with_context
879
+ self._mex_query = mex_query
880
+
881
+ def _require_mex(self, context: str) -> _MexQueryFn:
882
+ if self._mex_query is None:
883
+ raise ValueError(f"{context} requires a mex transport")
884
+ return self._mex_query
885
+
886
+ async def _change_participants(
887
+ self,
888
+ action: WaGroupParticipantChangeAction,
889
+ group_jid: str,
890
+ participants: list[str],
891
+ ) -> list[WaParticipantActionResult]:
892
+ context = f"group.{action}Participants"
893
+ node = build_group_participant_change_iq(
894
+ group_jid=group_jid, action=action, participants=participants
895
+ )
896
+ result = await self._query_with_context(context, node, None, None)
897
+ assert_iq_result(result, context)
898
+ return parse_participant_action_results(result, action)
899
+
900
+ async def _query_invite(
901
+ self, iq_type: str, group_jid: str, context: str
902
+ ) -> tuple[BinaryNode, str]:
903
+ node = build_iq_node(
904
+ iq_type,
905
+ group_jid,
906
+ WA_XMLNS["GROUPS"],
907
+ [BinaryNode(tag=WA_NODE_TAGS["INVITE"], attrs={})],
908
+ )
909
+ result = await self._query_with_context(context, node, None, None)
910
+ assert_iq_result(result, context)
911
+ invite_node = find_node_child(result, WA_NODE_TAGS["INVITE"])
912
+ code = invite_node.attrs.get("code") if invite_node is not None else None
913
+ if not code:
914
+ raise ValueError(f"{context}: missing invite code in response")
915
+ return result, code
916
+
917
+ async def query_group_metadata(self, group_jid: str) -> WaGroupMetadata:
918
+ """Fetch the full metadata for ``group_jid``."""
919
+ node = build_iq_node(
920
+ WA_IQ_TYPES["GET"],
921
+ group_jid,
922
+ WA_XMLNS["GROUPS"],
923
+ [BinaryNode(tag=WA_NODE_TAGS["QUERY"], attrs={})],
924
+ )
925
+ result = await self._query_with_context("group.metadata", node, None, None)
926
+ assert_iq_result(result, "group.metadata")
927
+ return parse_group_metadata(result)
928
+
929
+ async def query_all_groups(self) -> list[WaGroupMetadata]:
930
+ """List every group the current account participates in."""
931
+ result = await self._query_with_context(
932
+ "group.list", build_list_participating_groups_iq(), None, None
933
+ )
934
+ assert_iq_result(result, "group.list")
935
+ group_nodes = get_node_children_by_tag_from_children(
936
+ result, WA_NODE_TAGS["GROUP"]
937
+ )
938
+ return [parse_group_metadata(node) for node in group_nodes]
939
+
940
+ async def query_group_invite_info(self, code: str) -> WaGroupInviteInfo:
941
+ """Preview the group behind invite ``code``."""
942
+ node = build_iq_node(
943
+ WA_IQ_TYPES["GET"],
944
+ _defaults.GROUP_SERVER,
945
+ WA_XMLNS["GROUPS"],
946
+ [BinaryNode(tag=WA_NODE_TAGS["INVITE"], attrs={"code": code})],
947
+ )
948
+ result = await self._query_with_context("group.invite.info", node, None, None)
949
+ assert_iq_result(result, "group.invite.info")
950
+ return parse_group_invite_info(result)
951
+
952
+ async def create_group(
953
+ self,
954
+ subject: str,
955
+ participants: list[str],
956
+ options: WaGroupCreateOptions | None = None,
957
+ ) -> WaGroupMetadata:
958
+ """Create a new group with ``subject`` and the given participant JIDs."""
959
+ node = build_create_group_iq(
960
+ BuildCreateGroupIqInput(
961
+ subject=subject,
962
+ participants=list(participants),
963
+ description=options.description if options else None,
964
+ linked_parent_jid=(options.linked_parent_jid if options else None),
965
+ )
966
+ )
967
+ result = await self._query_with_context("group.create", node, None, None)
968
+ assert_iq_result(result, "group.create")
969
+ return parse_group_metadata(result)
970
+
971
+ async def set_subject(self, group_jid: str, subject: str) -> None:
972
+ """Rename the group."""
973
+ node = build_iq_node(
974
+ WA_IQ_TYPES["SET"],
975
+ group_jid,
976
+ WA_XMLNS["GROUPS"],
977
+ [BinaryNode(tag=WA_NODE_TAGS["SUBJECT"], attrs={}, content=subject)],
978
+ )
979
+ result = await self._query_with_context("group.setSubject", node, None, None)
980
+ assert_iq_result(result, "group.setSubject")
981
+
982
+ async def set_description(
983
+ self, group_jid: str, description: str | None, prev_desc_id: str | None = None
984
+ ) -> None:
985
+ """Set or clear (``None``) the group description."""
986
+ desc_id = str(int(time.time() * 1000))
987
+ attrs: dict[str, str] = {"id": desc_id}
988
+ if prev_desc_id:
989
+ attrs["prev"] = prev_desc_id
990
+ content: bytes | str | list[BinaryNode] | None
991
+ if description is None:
992
+ attrs["delete"] = "true"
993
+ content = None
994
+ else:
995
+ content = [
996
+ BinaryNode(tag=WA_NODE_TAGS["BODY"], attrs={}, content=description)
997
+ ]
998
+ node = build_iq_node(
999
+ WA_IQ_TYPES["SET"],
1000
+ group_jid,
1001
+ WA_XMLNS["GROUPS"],
1002
+ [BinaryNode(tag=WA_NODE_TAGS["DESCRIPTION"], attrs=attrs, content=content)],
1003
+ )
1004
+ result = await self._query_with_context(
1005
+ "group.setDescription", node, None, None
1006
+ )
1007
+ assert_iq_result(result, "group.setDescription")
1008
+
1009
+ async def set_member_add_mode(
1010
+ self, group_jid: str, mode: WaGroupMemberAddMode
1011
+ ) -> None:
1012
+ """Set who can add members (``admin_add`` / ``all_member_add``)."""
1013
+ node = build_set_group_member_add_mode_iq(group_jid=group_jid, mode=mode)
1014
+ result = await self._query_with_context(
1015
+ "group.setMemberAddMode", node, None, {"groupJid": group_jid, "mode": mode}
1016
+ )
1017
+ assert_iq_result(result, "group.setMemberAddMode")
1018
+
1019
+ async def set_member_link_mode(
1020
+ self, group_jid: str, mode: WaGroupMemberLinkMode
1021
+ ) -> None:
1022
+ """Set who can share the invite link (``admin_link`` / ``all_member_link``)."""
1023
+ node = build_set_group_member_link_mode_iq(group_jid=group_jid, mode=mode)
1024
+ result = await self._query_with_context(
1025
+ "group.setMemberLinkMode", node, None, {"groupJid": group_jid, "mode": mode}
1026
+ )
1027
+ assert_iq_result(result, "group.setMemberLinkMode")
1028
+
1029
+ async def set_member_share_group_history_mode(
1030
+ self, group_jid: str, mode: WaGroupMemberShareGroupHistoryMode
1031
+ ) -> None:
1032
+ """Set whether new members see prior chat history."""
1033
+ node = build_set_group_member_share_group_history_mode_iq(
1034
+ group_jid=group_jid, mode=mode
1035
+ )
1036
+ result = await self._query_with_context(
1037
+ "group.setMemberShareGroupHistoryMode",
1038
+ node,
1039
+ None,
1040
+ {"groupJid": group_jid, "mode": mode},
1041
+ )
1042
+ assert_iq_result(result, "group.setMemberShareGroupHistoryMode")
1043
+
1044
+ async def set_ephemeral_duration(
1045
+ self,
1046
+ group_jid: str,
1047
+ expiration_seconds: int | float,
1048
+ trigger: int | float | None = None,
1049
+ ) -> None:
1050
+ """Set the per-group disappearing-message lifetime in seconds."""
1051
+ if (
1052
+ not isinstance(expiration_seconds, (int, float))
1053
+ or isinstance(expiration_seconds, bool)
1054
+ or not math.isfinite(expiration_seconds)
1055
+ or int(expiration_seconds) != expiration_seconds
1056
+ or expiration_seconds < 0
1057
+ ):
1058
+ raise ValueError(
1059
+ "invalid expirationSeconds: "
1060
+ f"{_format_validation_value(expiration_seconds)}"
1061
+ )
1062
+ if trigger is not None and (
1063
+ not isinstance(trigger, (int, float))
1064
+ or isinstance(trigger, bool)
1065
+ or not math.isfinite(trigger)
1066
+ or int(trigger) != trigger
1067
+ or trigger < 0
1068
+ ):
1069
+ raise ValueError(f"invalid trigger: {_format_validation_value(trigger)}")
1070
+ node = build_set_group_ephemeral_iq(
1071
+ group_jid=group_jid,
1072
+ expiration_seconds=int(expiration_seconds),
1073
+ trigger=None if trigger is None else int(trigger),
1074
+ )
1075
+ context_data: dict[str, Any] = {
1076
+ "groupJid": group_jid,
1077
+ "expirationSeconds": expiration_seconds,
1078
+ }
1079
+ if trigger is not None:
1080
+ context_data["trigger"] = trigger
1081
+ result = await self._query_with_context(
1082
+ "group.setEphemeralDuration", node, None, context_data
1083
+ )
1084
+ assert_iq_result(result, "group.setEphemeralDuration")
1085
+
1086
+ async def set_setting(
1087
+ self, group_jid: str, setting: WaGroupSetting, enabled: bool
1088
+ ) -> None:
1089
+ """Toggle a named group setting on or off."""
1090
+ tags = _SETTING_TAGS[setting]
1091
+ tag = tags["on"] if enabled else tags["off"]
1092
+ content: list[BinaryNode] | None = None
1093
+ if setting == "membership_approval_mode":
1094
+ content = [
1095
+ BinaryNode(
1096
+ tag=WA_NODE_TAGS["GROUP_JOIN"],
1097
+ attrs={"state": "on" if enabled else "off"},
1098
+ )
1099
+ ]
1100
+ node = build_iq_node(
1101
+ WA_IQ_TYPES["SET"],
1102
+ group_jid,
1103
+ WA_XMLNS["GROUPS"],
1104
+ [BinaryNode(tag=tag, attrs={}, content=content)],
1105
+ )
1106
+ result = await self._query_with_context("group.setSetting", node, None, None)
1107
+ assert_iq_result(result, "group.setSetting")
1108
+
1109
+ async def add_participants(
1110
+ self, group_jid: str, participants: list[str]
1111
+ ) -> list[WaParticipantActionResult]:
1112
+ """Add participant JIDs; per-JID results carry the server status."""
1113
+ return await self._change_participants("add", group_jid, participants)
1114
+
1115
+ async def remove_participants(
1116
+ self, group_jid: str, participants: list[str]
1117
+ ) -> list[WaParticipantActionResult]:
1118
+ """Remove participant JIDs; same per-JID result shape as add."""
1119
+ return await self._change_participants("remove", group_jid, participants)
1120
+
1121
+ async def promote_participants(
1122
+ self, group_jid: str, participants: list[str]
1123
+ ) -> list[WaParticipantActionResult]:
1124
+ """Promote participants to admins."""
1125
+ return await self._change_participants("promote", group_jid, participants)
1126
+
1127
+ async def demote_participants(
1128
+ self, group_jid: str, participants: list[str]
1129
+ ) -> list[WaParticipantActionResult]:
1130
+ """Demote admins back to regular participants."""
1131
+ return await self._change_participants("demote", group_jid, participants)
1132
+
1133
+ async def leave_group(self, group_jids: list[str]) -> None:
1134
+ """Leave one or more groups (batched in a single IQ)."""
1135
+ node = build_leave_group_iq(list(group_jids))
1136
+ result = await self._query_with_context("group.leave", node, None, None)
1137
+ assert_iq_result(result, "group.leave")
1138
+
1139
+ async def query_invite_code(self, group_jid: str) -> str:
1140
+ """Fetch the current invite code for ``group_jid``."""
1141
+ _, code = await self._query_invite(
1142
+ WA_IQ_TYPES["GET"], group_jid, "group.queryInviteCode"
1143
+ )
1144
+ return code
1145
+
1146
+ async def revoke_invite(self, group_jid: str) -> WaRevokeInviteResult:
1147
+ """Rotate the invite link; returns the fresh code."""
1148
+ result, code = await self._query_invite(
1149
+ WA_IQ_TYPES["SET"], group_jid, "group.revokeInvite"
1150
+ )
1151
+ affected: list[WaParticipantActionResult] = []
1152
+ for child in get_node_children_by_tag(result, WA_NODE_TAGS["PARTICIPANT"]):
1153
+ parsed = parse_participant_action_result(child)
1154
+ if parsed is not None:
1155
+ affected.append(parsed)
1156
+ return WaRevokeInviteResult(code=code, affected_participants=tuple(affected))
1157
+
1158
+ async def join_group_via_link(self, code: str) -> WaGroupJoinViaLinkResult:
1159
+ """Join a group via invite ``code`` (``pending`` when approval is needed)."""
1160
+ node = build_iq_node(
1161
+ WA_IQ_TYPES["SET"],
1162
+ _defaults.GROUP_SERVER,
1163
+ WA_XMLNS["GROUPS"],
1164
+ [BinaryNode(tag=WA_NODE_TAGS["INVITE"], attrs={"code": code})],
1165
+ )
1166
+ result = await self._query_with_context("group.joinViaLink", node, None, None)
1167
+ assert_iq_result(result, "group.joinViaLink")
1168
+ approval_node = find_node_child(result, "membership_approval_request")
1169
+ status: Literal["joined", "pending"] = "pending" if approval_node else "joined"
1170
+ target = (
1171
+ approval_node
1172
+ if approval_node is not None
1173
+ else find_node_child(result, WA_NODE_TAGS["GROUP"])
1174
+ )
1175
+ if target is None:
1176
+ raise ValueError(
1177
+ "expected <group> or <membership_approval_request> in join response"
1178
+ )
1179
+ group_jid = target.attrs.get("jid")
1180
+ if not group_jid:
1181
+ raise ValueError(f"{target.tag} in join response has no jid")
1182
+ return WaGroupJoinViaLinkResult(status=status, group_jid=group_jid)
1183
+
1184
+ async def join_group_via_invite(self, code: str) -> WaGroupMetadata:
1185
+ """Join a group via invite ``code``; returns the joined metadata."""
1186
+ node = build_iq_node(
1187
+ WA_IQ_TYPES["SET"],
1188
+ _defaults.GROUP_SERVER,
1189
+ WA_XMLNS["GROUPS"],
1190
+ [BinaryNode(tag=WA_NODE_TAGS["INVITE"], attrs={"code": code})],
1191
+ )
1192
+ result = await self._query_with_context("group.joinViaInvite", node, None, None)
1193
+ assert_iq_result(result, "group.joinViaInvite")
1194
+ return parse_group_metadata(result)
1195
+
1196
+ async def create_community(
1197
+ self, subject: str, options: WaCommunityCreateOptions | None = None
1198
+ ) -> WaGroupMetadata:
1199
+ """Create a community (parent group)."""
1200
+ if options is not None and options.membership_approval_mode == "open":
1201
+ parent: bool | dict[str, str] | None = True
1202
+ else:
1203
+ parent = {"default_membership_approval_mode": "request_required"}
1204
+ node = build_create_group_iq(
1205
+ BuildCreateGroupIqInput(
1206
+ subject=subject,
1207
+ participants=[],
1208
+ description=options.description if options else None,
1209
+ parent=parent,
1210
+ allow_non_admin_sub_group_creation=(
1211
+ options.allow_non_admin_sub_group_creation if options else None
1212
+ )
1213
+ or False,
1214
+ create_general_chat=(options.create_general_chat if options else None)
1215
+ or False,
1216
+ )
1217
+ )
1218
+ result = await self._query_with_context("community.create", node, None, None)
1219
+ assert_iq_result(result, "community.create")
1220
+ return parse_group_metadata(result)
1221
+
1222
+ async def deactivate_community(self, community_jid: str) -> None:
1223
+ """Deactivate (delete) a community."""
1224
+ node = build_deactivate_community_iq(community_jid)
1225
+ result = await self._query_with_context(
1226
+ "community.deactivate", node, None, None
1227
+ )
1228
+ assert_iq_result(result, "community.deactivate")
1229
+
1230
+ async def link_sub_groups(
1231
+ self, community_jid: str, sub_group_jids: list[str]
1232
+ ) -> WaLinkSubGroupsResult:
1233
+ """Link existing groups as sub-groups of ``community_jid``."""
1234
+ node = build_link_sub_groups_iq(
1235
+ community_jid=community_jid,
1236
+ sub_groups=[SubGroupLink(jid=jid) for jid in sub_group_jids],
1237
+ )
1238
+ result = await self._query_with_context(
1239
+ "community.linkSubGroups", node, None, None
1240
+ )
1241
+ assert_iq_result(result, "community.linkSubGroups")
1242
+ links_node = find_node_child(result, "links")
1243
+ link_node = (
1244
+ find_node_child(links_node, "link") if links_node is not None else None
1245
+ )
1246
+ group_nodes = (
1247
+ get_node_children_by_tag(link_node, WA_NODE_TAGS["GROUP"])
1248
+ if link_node is not None
1249
+ else []
1250
+ )
1251
+ linked_jids: list[str] = []
1252
+ failed: list[WaCommunitySubGroupResult] = []
1253
+ for group_node in group_nodes:
1254
+ jid = group_node.attrs.get("jid")
1255
+ if not jid:
1256
+ continue
1257
+ error_node = find_node_child(group_node, WA_NODE_TAGS["ERROR"])
1258
+ error_attr = error_node.attrs.get("code") if error_node else None
1259
+ if error_attr is not None:
1260
+ failed.append(WaCommunitySubGroupResult(jid=jid, error=int(error_attr)))
1261
+ else:
1262
+ linked_jids.append(jid)
1263
+ return WaLinkSubGroupsResult(
1264
+ linked_jids=tuple(linked_jids), failed=tuple(failed)
1265
+ )
1266
+
1267
+ async def unlink_sub_groups(
1268
+ self,
1269
+ community_jid: str,
1270
+ sub_group_jids: list[str],
1271
+ remove_orphaned_members: bool = False,
1272
+ ) -> WaUnlinkSubGroupsResult:
1273
+ """Unlink sub-groups from a community."""
1274
+ node = build_unlink_sub_groups_iq(
1275
+ BuildUnlinkSubGroupsIqInput(
1276
+ community_jid=community_jid,
1277
+ sub_group_jids=list(sub_group_jids),
1278
+ remove_orphaned_members=remove_orphaned_members,
1279
+ )
1280
+ )
1281
+ result = await self._query_with_context(
1282
+ "community.unlinkSubGroups", node, None, None
1283
+ )
1284
+ assert_iq_result(result, "community.unlinkSubGroups")
1285
+ unlink_node = find_node_child(result, "unlink")
1286
+ group_nodes = (
1287
+ get_node_children_by_tag(unlink_node, WA_NODE_TAGS["GROUP"])
1288
+ if unlink_node is not None
1289
+ else []
1290
+ )
1291
+ unlinked_jids: list[str] = []
1292
+ failed: list[WaCommunitySubGroupResult] = []
1293
+ for group_node in group_nodes:
1294
+ jid = group_node.attrs.get("jid")
1295
+ if not jid:
1296
+ continue
1297
+ error_node = find_node_child(group_node, WA_NODE_TAGS["ERROR"])
1298
+ error_attr = error_node.attrs.get("code") if error_node else None
1299
+ if error_attr is not None:
1300
+ failed.append(WaCommunitySubGroupResult(jid=jid, error=int(error_attr)))
1301
+ else:
1302
+ unlinked_jids.append(jid)
1303
+ return WaUnlinkSubGroupsResult(
1304
+ unlinked_jids=tuple(unlinked_jids), failed=tuple(failed)
1305
+ )
1306
+
1307
+ async def query_linked_groups_participants(
1308
+ self, community_jid: str
1309
+ ) -> list[WaGroupParticipant]:
1310
+ """Return the merged participant list across a community's groups."""
1311
+ node = build_linked_groups_participants_iq(community_jid)
1312
+ result = await self._query_with_context(
1313
+ "community.linkedGroupsParticipants", node, None, None
1314
+ )
1315
+ assert_iq_result(result, "community.linkedGroupsParticipants")
1316
+ container = find_node_child(result, "linked_groups_participants")
1317
+ return parse_group_participants(container) if container is not None else []
1318
+
1319
+ async def fetch_sub_groups(self, community_jid: str) -> WaCommunitySubGroupsResult:
1320
+ """List sub-groups (and announcement group) of a community via MEX."""
1321
+ mex_query = self._require_mex("community.fetchSubGroups")
1322
+ data = await mex_query(
1323
+ "FetchAllSubgroups",
1324
+ {
1325
+ "group_id": community_jid,
1326
+ "query_context": "INTERACTIVE",
1327
+ "sub_group_hint_id": None,
1328
+ },
1329
+ )
1330
+ query = _try_as_record(data.get("xwa2_group_query_by_id") if data else None)
1331
+ announcement_raw = query.get("default_sub_group") if query else None
1332
+ sub_groups_raw = _try_as_record(query.get("sub_groups")) if query else None
1333
+ edges = sub_groups_raw.get("edges") if sub_groups_raw else None
1334
+ sub_groups: list[WaCommunitySubGroup] = []
1335
+ if isinstance(edges, list):
1336
+ for edge in edges:
1337
+ edge_record = _try_as_record(edge)
1338
+ edge_node = edge_record.get("node") if edge_record else None
1339
+ if edge_node is None:
1340
+ continue
1341
+ sub_groups.append(_parse_sub_group_node(edge_node, False))
1342
+ return WaCommunitySubGroupsResult(
1343
+ community_jid=community_jid,
1344
+ announcement_group=(
1345
+ _parse_sub_group_node(announcement_raw, True)
1346
+ if announcement_raw is not None
1347
+ else None
1348
+ ),
1349
+ sub_groups=tuple(sub_groups),
1350
+ )
1351
+
1352
+ async def query_membership_approval_requests(
1353
+ self, group_jid: str
1354
+ ) -> list[WaMembershipRequest]:
1355
+ """List pending membership-approval requests for the group."""
1356
+ node = build_get_membership_approval_requests_iq(group_jid)
1357
+ result = await self._query_with_context(
1358
+ "group.membershipRequests", node, None, None
1359
+ )
1360
+ assert_iq_result(result, "group.membershipRequests")
1361
+ return parse_membership_approval_requests(result)
1362
+
1363
+ async def approve_membership_requests(
1364
+ self, group_jid: str, participant_jids: list[str]
1365
+ ) -> None:
1366
+ """Approve the listed pending join requests."""
1367
+ node = build_membership_requests_action_iq(
1368
+ group_jid=group_jid, approve=list(participant_jids)
1369
+ )
1370
+ result = await self._query_with_context(
1371
+ "group.membershipRequests.approve", node, None, None
1372
+ )
1373
+ assert_iq_result(result, "group.membershipRequests.approve")
1374
+
1375
+ async def reject_membership_requests(
1376
+ self, group_jid: str, participant_jids: list[str]
1377
+ ) -> None:
1378
+ """Reject the listed pending join requests."""
1379
+ node = build_membership_requests_action_iq(
1380
+ group_jid=group_jid, reject=list(participant_jids)
1381
+ )
1382
+ result = await self._query_with_context(
1383
+ "group.membershipRequests.reject", node, None, None
1384
+ )
1385
+ assert_iq_result(result, "group.membershipRequests.reject")
1386
+
1387
+ async def cancel_membership_requests(
1388
+ self, group_jid: str, participant_jids: list[str]
1389
+ ) -> None:
1390
+ """Cancel the current account's own pending join requests."""
1391
+ node = build_cancel_membership_requests_iq(
1392
+ group_jid=group_jid, participant_jids=list(participant_jids)
1393
+ )
1394
+ result = await self._query_with_context(
1395
+ "group.membershipRequests.cancel", node, None, None
1396
+ )
1397
+ assert_iq_result(result, "group.membershipRequests.cancel")
1398
+
1399
+ async def join_linked_group(
1400
+ self, community_jid: str, sub_group_jid: str, type: str | None = None
1401
+ ) -> None:
1402
+ """Join a linked sub-group of a community the account belongs to."""
1403
+ node = build_join_linked_group_iq(
1404
+ group_jid=community_jid, sub_group_jid=sub_group_jid, type=type
1405
+ )
1406
+ result = await self._query_with_context(
1407
+ "community.joinLinkedGroup", node, None, None
1408
+ )
1409
+ assert_iq_result(result, "community.joinLinkedGroup")
1410
+
1411
+ async def is_internal_group(self, group_jid: str) -> bool:
1412
+ """Whether the group is flagged as an internal WhatsApp group."""
1413
+ mex_query = self._require_mex("group.isInternalGroup")
1414
+ data = await mex_query("FetchGroupIsInternal", {"id": group_jid})
1415
+ return parse_group_is_internal_mex_response(data)
1416
+
1417
+ async def transfer_community_ownership(
1418
+ self, community_jid: str, new_owner_jid: str
1419
+ ) -> None:
1420
+ """Transfer community ownership (superadmin handoff)."""
1421
+ mex_query = self._require_mex("community.transferOwnership")
1422
+ await mex_query(
1423
+ "TransferCommunityOwnership",
1424
+ {
1425
+ "input": {
1426
+ "group_id": community_jid,
1427
+ "role_updates": [
1428
+ {"new_role": "SUPERADMIN_MEMBER", "user_jid": new_owner_jid}
1429
+ ],
1430
+ }
1431
+ },
1432
+ )
1433
+
1434
+ async def fetch_subgroup_suggestions(
1435
+ self, community_jid: str, hint_subgroup_jid: str
1436
+ ) -> list[WaCommunitySubGroupSuggestion]:
1437
+ """List suggested sub-groups for a community, anchored on a hint group."""
1438
+ mex_query = self._require_mex("community.fetchSubgroupSuggestions")
1439
+ data = await mex_query(
1440
+ "FetchSubgroupSuggestions",
1441
+ {
1442
+ "group_id": community_jid,
1443
+ "query_context": "INTERACTIVE",
1444
+ "sub_group_hint_id": hint_subgroup_jid,
1445
+ },
1446
+ )
1447
+ return parse_sub_group_suggestions_mex_response(data)
1448
+
1449
+ async def submit_group_suspension_appeal(
1450
+ self,
1451
+ group_jid: str,
1452
+ reason: str | None = None,
1453
+ debug_info: str = "{}",
1454
+ ) -> WaGroupSuspensionAppealResult:
1455
+ """Submit a suspension appeal for the group."""
1456
+ mex_query = self._require_mex("group.submitSuspensionAppeal")
1457
+ parsed = parse_jid_full(group_jid)
1458
+ data = await mex_query(
1459
+ "GroupSuspensionAppeal",
1460
+ {
1461
+ "input": {
1462
+ "group_jid": parsed.user,
1463
+ "appeal_reason": reason,
1464
+ "debug_info": debug_info,
1465
+ }
1466
+ },
1467
+ )
1468
+ return parse_group_suspension_appeal_mex_response(data)
1469
+
1470
+
1471
+ def create_group_coordinator(
1472
+ query_with_context: QueryWithContextFn,
1473
+ mex_query: _MexQueryFn | None = None,
1474
+ ) -> WaGroupCoordinator:
1475
+ """Create a :class:`WaGroupCoordinator` from an IQ query function."""
1476
+ return WaGroupCoordinator(
1477
+ query_with_context=query_with_context, mex_query=mex_query
1478
+ )