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.
- shellzapy-0.1.0.dist-info/METADATA +112 -0
- shellzapy-0.1.0.dist-info/RECORD +345 -0
- shellzapy-0.1.0.dist-info/WHEEL +4 -0
- shellzapy-0.1.0.dist-info/licenses/LICENSE +21 -0
- shellzapy-0.1.0.dist-info/licenses/NOTICE +9 -0
- zapy/__init__.py +58 -0
- zapy/_appstate/__init__.py +59 -0
- zapy/_appstate/constants.py +82 -0
- zapy/_appstate/crypto/__init__.py +17 -0
- zapy/_appstate/crypto/app_state_crypto.py +401 -0
- zapy/_appstate/parsers/__init__.py +23 -0
- zapy/_appstate/parsers/encoding.py +157 -0
- zapy/_appstate/parsers/response_parser.py +135 -0
- zapy/_appstate/sync/__init__.py +11 -0
- zapy/_appstate/sync/sync_client.py +1559 -0
- zapy/_appstate/types.py +137 -0
- zapy/_appstate/utils.py +100 -0
- zapy/_auth/__init__.py +3 -0
- zapy/_auth/auth_client.py +618 -0
- zapy/_auth/credentials_flow.py +290 -0
- zapy/_auth/pairing/__init__.py +3 -0
- zapy/_auth/pairing/companion_host.py +239 -0
- zapy/_auth/pairing/flow.py +808 -0
- zapy/_auth/pairing/pairing_code_crypto.py +143 -0
- zapy/_auth/pairing/qr_flow.py +123 -0
- zapy/_auth/pairing/shortcake_crypto.py +122 -0
- zapy/_auth/pairing/shortcake_flow.py +393 -0
- zapy/_auth/types.py +110 -0
- zapy/_client/__init__.py +26 -0
- zapy/_client/client.py +972 -0
- zapy/_client/connection/__init__.py +6 -0
- zapy/_client/connection/manager.py +525 -0
- zapy/_client/connection/receipt_queue.py +74 -0
- zapy/_client/coordinators/__init__.py +81 -0
- zapy/_client/coordinators/ab_props.py +260 -0
- zapy/_client/coordinators/app_state_mutation.py +2538 -0
- zapy/_client/coordinators/bot.py +830 -0
- zapy/_client/coordinators/broadcast_list.py +101 -0
- zapy/_client/coordinators/business.py +247 -0
- zapy/_client/coordinators/email.py +158 -0
- zapy/_client/coordinators/group.py +1478 -0
- zapy/_client/coordinators/incoming_node.py +758 -0
- zapy/_client/coordinators/low_level.py +119 -0
- zapy/_client/coordinators/message.py +1153 -0
- zapy/_client/coordinators/message_dispatch.py +1637 -0
- zapy/_client/coordinators/newsletter.py +110 -0
- zapy/_client/coordinators/offline_resume.py +271 -0
- zapy/_client/coordinators/passive_tasks.py +447 -0
- zapy/_client/coordinators/presence.py +103 -0
- zapy/_client/coordinators/privacy.py +623 -0
- zapy/_client/coordinators/profile.py +1024 -0
- zapy/_client/coordinators/retry.py +1878 -0
- zapy/_client/coordinators/status.py +132 -0
- zapy/_client/coordinators/stream_control.py +260 -0
- zapy/_client/coordinators/trusted_contact_token.py +417 -0
- zapy/_client/events/__init__.py +266 -0
- zapy/_client/events/abprops.py +58 -0
- zapy/_client/events/appstate_mutation.py +248 -0
- zapy/_client/events/business.py +565 -0
- zapy/_client/events/call.py +144 -0
- zapy/_client/events/chatstate.py +41 -0
- zapy/_client/events/devices.py +122 -0
- zapy/_client/events/dirty.py +384 -0
- zapy/_client/events/group.py +655 -0
- zapy/_client/events/identity.py +40 -0
- zapy/_client/events/incoming.py +1079 -0
- zapy/_client/events/mex_notification.py +317 -0
- zapy/_client/events/offline.py +123 -0
- zapy/_client/events/picture.py +67 -0
- zapy/_client/events/presence.py +74 -0
- zapy/_client/events/privacy.py +187 -0
- zapy/_client/events/privacy_token.py +72 -0
- zapy/_client/events/receipt.py +109 -0
- zapy/_client/events/registration.py +70 -0
- zapy/_client/events/username.py +76 -0
- zapy/_client/factory.py +2020 -0
- zapy/_client/media.py +829 -0
- zapy/_client/newsletter/__init__.py +90 -0
- zapy/_client/newsletter/admin.py +323 -0
- zapy/_client/newsletter/content.py +499 -0
- zapy/_client/newsletter/discovery.py +233 -0
- zapy/_client/newsletter/messaging.py +396 -0
- zapy/_client/newsletter/mex.py +99 -0
- zapy/_client/newsletter/parse.py +406 -0
- zapy/_client/newsletter/types.py +393 -0
- zapy/_client/persistence/__init__.py +89 -0
- zapy/_client/persistence/companion_host.py +133 -0
- zapy/_client/persistence/ephemeral_setting.py +245 -0
- zapy/_client/persistence/group_history.py +361 -0
- zapy/_client/persistence/history_blob.py +169 -0
- zapy/_client/persistence/history_sync.py +646 -0
- zapy/_client/persistence/mailbox.py +232 -0
- zapy/_client/persistence/write_behind_persistence.py +368 -0
- zapy/_client/plugins/__init__.py +23 -0
- zapy/_client/plugins/define.py +44 -0
- zapy/_client/plugins/install.py +254 -0
- zapy/_client/plugins/types.py +64 -0
- zapy/_client/tokens/__init__.py +21 -0
- zapy/_client/tokens/cs_token.py +47 -0
- zapy/_client/tokens/tc_token.py +43 -0
- zapy/_client/types.py +988 -0
- zapy/_crypto/__init__.py +65 -0
- zapy/_crypto/core/__init__.py +62 -0
- zapy/_crypto/core/hkdf.py +41 -0
- zapy/_crypto/core/keys.py +51 -0
- zapy/_crypto/core/nonce.py +25 -0
- zapy/_crypto/core/primitives.py +179 -0
- zapy/_crypto/core/random.py +32 -0
- zapy/_crypto/core/xeddsa.py +72 -0
- zapy/_crypto/curves/__init__.py +3 -0
- zapy/_crypto/curves/constants.py +10 -0
- zapy/_crypto/curves/ed25519.py +61 -0
- zapy/_crypto/curves/types.py +18 -0
- zapy/_crypto/curves/x25519.py +117 -0
- zapy/_crypto/math/__init__.py +3 -0
- zapy/_crypto/math/constants.py +35 -0
- zapy/_crypto/math/edwards.py +174 -0
- zapy/_crypto/math/fe.py +120 -0
- zapy/_crypto/math/le.py +13 -0
- zapy/_crypto/math/mod.py +15 -0
- zapy/_crypto/math/prime.py +11 -0
- zapy/_crypto/math/types.py +25 -0
- zapy/_crypto/native_backend.py +40 -0
- zapy/_infra/__init__.py +3 -0
- zapy/_infra/log.py +142 -0
- zapy/_infra/perf.py +77 -0
- zapy/_media/__init__.py +64 -0
- zapy/_media/constants.py +133 -0
- zapy/_media/container.py +110 -0
- zapy/_media/crypto/__init__.py +19 -0
- zapy/_media/crypto/crypto.py +633 -0
- zapy/_media/crypto/media_retry.py +107 -0
- zapy/_media/processor.py +100 -0
- zapy/_media/sticker/__init__.py +8 -0
- zapy/_media/sticker/pack.py +188 -0
- zapy/_media/transfer/__init__.py +15 -0
- zapy/_media/transfer/client.py +635 -0
- zapy/_media/transfer/conn.py +48 -0
- zapy/_media/types.py +169 -0
- zapy/_message/__init__.py +121 -0
- zapy/_message/addons/__init__.py +5 -0
- zapy/_message/addons/link_preview/__init__.py +54 -0
- zapy/_message/addons/link_preview/builder.py +56 -0
- zapy/_message/addons/link_preview/detect.py +72 -0
- zapy/_message/addons/link_preview/fetcher.py +553 -0
- zapy/_message/addons/link_preview/types.py +100 -0
- zapy/_message/client.py +486 -0
- zapy/_message/context_info.py +424 -0
- zapy/_message/crypto/__init__.py +71 -0
- zapy/_message/crypto/addon_crypto.py +656 -0
- zapy/_message/crypto/icdc.py +138 -0
- zapy/_message/crypto/phash.py +87 -0
- zapy/_message/crypto/reporting_token.py +498 -0
- zapy/_message/crypto/use_case_secret.py +113 -0
- zapy/_message/encode/__init__.py +84 -0
- zapy/_message/encode/content.py +636 -0
- zapy/_message/encode/device_sent.py +88 -0
- zapy/_message/encode/media_payload.py +122 -0
- zapy/_message/encode/padding.py +27 -0
- zapy/_message/kinds/__init__.py +1 -0
- zapy/_message/kinds/bot.py +179 -0
- zapy/_message/kinds/group_history.py +206 -0
- zapy/_message/kinds/newsletter.py +388 -0
- zapy/_message/kinds/sticker_pack.py +74 -0
- zapy/_message/messaging/__init__.py +336 -0
- zapy/_message/messaging/companion_host.py +117 -0
- zapy/_message/messaging/fanout.py +311 -0
- zapy/_message/messaging/group_metadata.py +444 -0
- zapy/_message/messaging/ignore_key.py +264 -0
- zapy/_message/messaging/key_protocol.py +217 -0
- zapy/_message/messaging/link_preview.py +448 -0
- zapy/_message/messaging/messages.py +1429 -0
- zapy/_message/primitives/__init__.py +1 -0
- zapy/_message/primitives/ack.py +232 -0
- zapy/_message/primitives/incoming.py +1141 -0
- zapy/_message/primitives/media_retry.py +451 -0
- zapy/_message/primitives/peer_data_operation.py +271 -0
- zapy/_message/types.py +434 -0
- zapy/_proto/WAProto_pb2.py +2584 -0
- zapy/_proto/__init__.py +1 -0
- zapy/_protocol/__init__.py +3 -0
- zapy/_protocol/abprops_spec.py +6216 -0
- zapy/_protocol/auth.py +17 -0
- zapy/_protocol/browser.py +57 -0
- zapy/_protocol/defaults.py +38 -0
- zapy/_protocol/device_identity.py +54 -0
- zapy/_protocol/jid.py +241 -0
- zapy/_protocol/message.py +127 -0
- zapy/_protocol/nodes.py +144 -0
- zapy/_protocol/notification.py +18 -0
- zapy/_retry/__init__.py +77 -0
- zapy/_retry/codec.py +209 -0
- zapy/_retry/constants.py +28 -0
- zapy/_retry/parse.py +132 -0
- zapy/_retry/reason.py +65 -0
- zapy/_retry/replay.py +483 -0
- zapy/_retry/tracker.py +161 -0
- zapy/_retry/types.py +122 -0
- zapy/_signal/__init__.py +171 -0
- zapy/_signal/api/__init__.py +133 -0
- zapy/_signal/api/codec.py +164 -0
- zapy/_signal/api/constants.py +14 -0
- zapy/_signal/api/device_sync.py +915 -0
- zapy/_signal/api/digest_sync.py +363 -0
- zapy/_signal/api/identity_sync.py +250 -0
- zapy/_signal/api/missing_pre_keys_sync.py +267 -0
- zapy/_signal/api/prekeys.py +191 -0
- zapy/_signal/api/result_map.py +40 -0
- zapy/_signal/api/rotate_key.py +111 -0
- zapy/_signal/api/session_sync.py +297 -0
- zapy/_signal/attestation.py +145 -0
- zapy/_signal/constants.py +22 -0
- zapy/_signal/encoding.py +78 -0
- zapy/_signal/group/__init__.py +35 -0
- zapy/_signal/group/chain.py +139 -0
- zapy/_signal/group/codec.py +78 -0
- zapy/_signal/group/encoding.py +166 -0
- zapy/_signal/group/manager.py +361 -0
- zapy/_signal/registration/__init__.py +44 -0
- zapy/_signal/registration/keygen.py +46 -0
- zapy/_signal/registration/reg_encoding.py +66 -0
- zapy/_signal/registration/reg_utils.py +52 -0
- zapy/_signal/session/__init__.py +114 -0
- zapy/_signal/session/encoding.py +385 -0
- zapy/_signal/session/protocol.py +590 -0
- zapy/_signal/session/ratchet.py +381 -0
- zapy/_signal/session/resolver.py +630 -0
- zapy/_signal/session/serializer.py +96 -0
- zapy/_signal/session/session.py +272 -0
- zapy/_signal/types.py +214 -0
- zapy/_store/__init__.py +118 -0
- zapy/_store/cache/__init__.py +166 -0
- zapy/_store/cache/identity.py +130 -0
- zapy/_store/cache/privacy_token.py +116 -0
- zapy/_store/cache/sender_key.py +168 -0
- zapy/_store/cache/session.py +142 -0
- zapy/_store/contracts/__init__.py +84 -0
- zapy/_store/contracts/appstate.py +82 -0
- zapy/_store/contracts/auth.py +16 -0
- zapy/_store/contracts/chat_metadata.py +29 -0
- zapy/_store/contracts/contact.py +31 -0
- zapy/_store/contracts/device_list.py +35 -0
- zapy/_store/contracts/group_metadata.py +33 -0
- zapy/_store/contracts/identity.py +18 -0
- zapy/_store/contracts/message.py +36 -0
- zapy/_store/contracts/message_secret.py +41 -0
- zapy/_store/contracts/pre_key.py +32 -0
- zapy/_store/contracts/privacy_token.py +32 -0
- zapy/_store/contracts/retry.py +47 -0
- zapy/_store/contracts/sender_key.py +37 -0
- zapy/_store/contracts/session.py +21 -0
- zapy/_store/contracts/signal.py +23 -0
- zapy/_store/contracts/thread.py +35 -0
- zapy/_store/create_store.py +890 -0
- zapy/_store/locks.py +1154 -0
- zapy/_store/memory/__init__.py +40 -0
- zapy/_store/memory/appstate.py +200 -0
- zapy/_store/memory/auth.py +24 -0
- zapy/_store/memory/chat_metadata.py +124 -0
- zapy/_store/memory/contact.py +125 -0
- zapy/_store/memory/device_list.py +161 -0
- zapy/_store/memory/group_metadata.py +125 -0
- zapy/_store/memory/identity.py +86 -0
- zapy/_store/memory/message.py +85 -0
- zapy/_store/memory/message_secret.py +145 -0
- zapy/_store/memory/pre_key.py +112 -0
- zapy/_store/memory/privacy_token.py +103 -0
- zapy/_store/memory/retry.py +250 -0
- zapy/_store/memory/sender_key.py +162 -0
- zapy/_store/memory/session.py +111 -0
- zapy/_store/memory/signal.py +45 -0
- zapy/_store/memory/thread.py +66 -0
- zapy/_store/noop.py +279 -0
- zapy/_transport/__init__.py +3 -0
- zapy/_transport/binary/__init__.py +77 -0
- zapy/_transport/binary/constants.py +80 -0
- zapy/_transport/binary/decoder.py +260 -0
- zapy/_transport/binary/encoder.py +279 -0
- zapy/_transport/binary/tokens.py +1289 -0
- zapy/_transport/comms.py +759 -0
- zapy/_transport/keepalive/__init__.py +3 -0
- zapy/_transport/keepalive/keep_alive.py +252 -0
- zapy/_transport/node/__init__.py +3 -0
- zapy/_transport/node/builders/__init__.py +9 -0
- zapy/_transport/node/builders/abprops.py +33 -0
- zapy/_transport/node/builders/account_sync.py +120 -0
- zapy/_transport/node/builders/bot.py +56 -0
- zapy/_transport/node/builders/business.py +261 -0
- zapy/_transport/node/builders/chatstate.py +74 -0
- zapy/_transport/node/builders/community.py +116 -0
- zapy/_transport/node/builders/device.py +30 -0
- zapy/_transport/node/builders/email.py +181 -0
- zapy/_transport/node/builders/global_.py +74 -0
- zapy/_transport/node/builders/group.py +279 -0
- zapy/_transport/node/builders/media.py +21 -0
- zapy/_transport/node/builders/message.py +436 -0
- zapy/_transport/node/builders/mobile.py +227 -0
- zapy/_transport/node/builders/newsletter.py +293 -0
- zapy/_transport/node/builders/offline.py +20 -0
- zapy/_transport/node/builders/pairing.py +130 -0
- zapy/_transport/node/builders/passive.py +28 -0
- zapy/_transport/node/builders/prekeys.py +215 -0
- zapy/_transport/node/builders/presence.py +100 -0
- zapy/_transport/node/builders/privacy.py +243 -0
- zapy/_transport/node/builders/privacy_token.py +94 -0
- zapy/_transport/node/builders/profile.py +176 -0
- zapy/_transport/node/builders/retry.py +156 -0
- zapy/_transport/node/builders/shortcake.py +87 -0
- zapy/_transport/node/builders/tos.py +92 -0
- zapy/_transport/node/builders/usync.py +185 -0
- zapy/_transport/node/helpers.py +201 -0
- zapy/_transport/node/orchestrator.py +210 -0
- zapy/_transport/node/query.py +82 -0
- zapy/_transport/node/transport.py +105 -0
- zapy/_transport/node/usync.py +33 -0
- zapy/_transport/node/xml.py +38 -0
- zapy/_transport/noise/__init__.py +7 -0
- zapy/_transport/noise/cert.py +85 -0
- zapy/_transport/noise/client_payload.py +344 -0
- zapy/_transport/noise/constants.py +12 -0
- zapy/_transport/noise/frame_codec.py +120 -0
- zapy/_transport/noise/handshake.py +92 -0
- zapy/_transport/noise/session.py +493 -0
- zapy/_transport/noise/socket.py +45 -0
- zapy/_transport/noise/types.py +66 -0
- zapy/_transport/noise/version.json +3 -0
- zapy/_transport/proxy.py +35 -0
- zapy/_transport/types.py +19 -0
- zapy/_transport/wa_version_fetcher.py +159 -0
- zapy/_transport/web_socket.py +602 -0
- zapy/_util/__init__.py +3 -0
- zapy/_util/bytes.py +131 -0
- zapy/_util/coercion.py +29 -0
- zapy/_util/collections.py +45 -0
- zapy/_util/primitives.py +49 -0
- zapy/client.py +840 -0
- zapy/errors.py +148 -0
- zapy/events.py +564 -0
- zapy/jid.py +140 -0
- zapy/py.typed +0 -0
- zapy/stores/__init__.py +50 -0
- zapy/stores/base.py +1627 -0
- zapy/stores/json_file.py +359 -0
- zapy/stores/memory.py +322 -0
- zapy/stores/sqlite.py +343 -0
zapy/_client/client.py
ADDED
|
@@ -0,0 +1,972 @@
|
|
|
1
|
+
"""Top-level WhatsApp client (mirrors ``src/client/WaClient.ts``).
|
|
2
|
+
|
|
3
|
+
Owns the transport, auth, signal and per-feature coordinators (exposed via
|
|
4
|
+
getters) and re-emits every :data:`WA_CLIENT_EVENT_NAMES` event. Coordinator,
|
|
5
|
+
persistence, plugin and protocol-helper modules owned by sibling workers are
|
|
6
|
+
loaded lazily (see :mod:`zapy._client.factory`) so this module stays
|
|
7
|
+
importable until they land.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import asyncio
|
|
13
|
+
import importlib
|
|
14
|
+
from collections.abc import Awaitable, Callable
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
from zapy._client.plugins.install import WaClientPluginInstallInput
|
|
18
|
+
from zapy._infra.log import Logger, get_logger
|
|
19
|
+
from zapy._transport.node.query import assert_iq_result, query_with_context
|
|
20
|
+
from zapy._transport.types import BinaryNode
|
|
21
|
+
|
|
22
|
+
from zapy._client.factory import (
|
|
23
|
+
WaClientBuildRuntime,
|
|
24
|
+
WaClientDependencies,
|
|
25
|
+
build_wa_client_dependencies,
|
|
26
|
+
resolve_wa_client_base,
|
|
27
|
+
)
|
|
28
|
+
from zapy._client.types import (
|
|
29
|
+
WaClientOptions,
|
|
30
|
+
WaIgnoreKey,
|
|
31
|
+
WaIgnoreKeyPredicate,
|
|
32
|
+
WaIncomingMessageEvent,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
__all__ = ["WaClient"]
|
|
36
|
+
|
|
37
|
+
# Sync-related protocol traffic that is logged and dropped (mirrors the
|
|
38
|
+
# oracle's ``SYNC_RELATED_PROTOCOL_TYPES``; resolved from the generated
|
|
39
|
+
# protobuf enum at runtime).
|
|
40
|
+
_SYNC_RELATED_PROTOCOL_TYPE_NAMES: tuple[str, ...] = (
|
|
41
|
+
"APP_STATE_SYNC_KEY_REQUEST",
|
|
42
|
+
"APP_STATE_FATAL_EXCEPTION_NOTIFICATION",
|
|
43
|
+
"PEER_DATA_OPERATION_REQUEST_MESSAGE",
|
|
44
|
+
"PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE",
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
_HISTORY_SYNC_NOTIFICATION = "HISTORY_SYNC_NOTIFICATION"
|
|
48
|
+
_APP_STATE_SYNC_KEY_REQUEST = "APP_STATE_SYNC_KEY_REQUEST"
|
|
49
|
+
_APP_STATE_SYNC_KEY_SHARE = "APP_STATE_SYNC_KEY_SHARE"
|
|
50
|
+
_EPHEMERAL_SETTING = "EPHEMERAL_SETTING"
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _load(symbol_path: str) -> Any:
|
|
54
|
+
"""Import ``module:attr`` lazily (sibling modules land separately)."""
|
|
55
|
+
module_name, _, attr = symbol_path.partition(":")
|
|
56
|
+
return getattr(importlib.import_module(module_name), attr)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
_protocol_type_cache: dict[str, int] = {}
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _protocol_type_value(name: str) -> int | None:
|
|
63
|
+
"""Numeric ``ProtocolMessage.Type`` value, read from generated bindings."""
|
|
64
|
+
if name in _protocol_type_cache:
|
|
65
|
+
return _protocol_type_cache[name]
|
|
66
|
+
try:
|
|
67
|
+
from zapy._proto import WAProto_pb2
|
|
68
|
+
|
|
69
|
+
value = int(WAProto_pb2.Message.ProtocolMessage.Type.Value(name))
|
|
70
|
+
except Exception:
|
|
71
|
+
return None
|
|
72
|
+
_protocol_type_cache[name] = value
|
|
73
|
+
return value
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _get(obj: Any, name: str, default: Any = None) -> Any:
|
|
77
|
+
"""Read ``name`` from a dataclass/attribute object or a mapping."""
|
|
78
|
+
if isinstance(obj, dict):
|
|
79
|
+
return obj.get(name, default)
|
|
80
|
+
return getattr(obj, name, default)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _to_error(error: Any) -> Exception:
|
|
84
|
+
if isinstance(error, Exception):
|
|
85
|
+
return error
|
|
86
|
+
return Exception(str(error))
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class _EventEmitter:
|
|
90
|
+
"""Node ``EventEmitter`` semantics: sync dispatch, listener order."""
|
|
91
|
+
|
|
92
|
+
def __init__(self) -> None:
|
|
93
|
+
self._listeners: dict[str, list[Callable[..., Any]]] = {}
|
|
94
|
+
|
|
95
|
+
def on(self, event: str, listener: Callable[..., Any]) -> None:
|
|
96
|
+
self._listeners.setdefault(event, []).append(listener)
|
|
97
|
+
|
|
98
|
+
def once(self, event: str, listener: Callable[..., Any]) -> None:
|
|
99
|
+
def wrapper(*args: Any, **kwargs: Any) -> None:
|
|
100
|
+
self.off(event, wrapper)
|
|
101
|
+
listener(*args, **kwargs)
|
|
102
|
+
|
|
103
|
+
self._listeners.setdefault(event, []).append(wrapper)
|
|
104
|
+
|
|
105
|
+
def off(self, event: str, listener: Callable[..., Any]) -> None:
|
|
106
|
+
listeners = self._listeners.get(event)
|
|
107
|
+
if listeners:
|
|
108
|
+
try:
|
|
109
|
+
listeners.remove(listener)
|
|
110
|
+
except ValueError:
|
|
111
|
+
pass
|
|
112
|
+
|
|
113
|
+
def emit(self, event: str, *args: Any) -> bool:
|
|
114
|
+
listeners = list(self._listeners.get(event, ()))
|
|
115
|
+
for listener in listeners:
|
|
116
|
+
listener(*args)
|
|
117
|
+
return bool(listeners)
|
|
118
|
+
|
|
119
|
+
def listener_count(self, event: str) -> int:
|
|
120
|
+
return len(self._listeners.get(event, ()))
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
class WaClient:
|
|
124
|
+
"""Top-level WhatsApp client (mirrors ``WaClient``).
|
|
125
|
+
|
|
126
|
+
Lifecycle: construct with :class:`WaClientOptions`, call
|
|
127
|
+
:meth:`connect`, react to ``connection``/``auth_qr``/``auth_pairing_code``
|
|
128
|
+
events, then drive the session through the coordinator getters. Call
|
|
129
|
+
:meth:`disconnect` to shut down cleanly or :meth:`logout` to remove the
|
|
130
|
+
companion device.
|
|
131
|
+
"""
|
|
132
|
+
|
|
133
|
+
def __init__(self, options: WaClientOptions, logger: Logger | None = None) -> None:
|
|
134
|
+
self._emitter = _EventEmitter()
|
|
135
|
+
base = resolve_wa_client_base(options, logger or get_logger(__name__))
|
|
136
|
+
self._options: WaClientOptions = base.options
|
|
137
|
+
self._logger: Logger = base.logger
|
|
138
|
+
self._stores: Any = base.session_store
|
|
139
|
+
WriteBehindPersistence = _load(
|
|
140
|
+
"zapy._client.persistence.write_behind_persistence:WriteBehindPersistence"
|
|
141
|
+
)
|
|
142
|
+
WriteBehindStores = _load(
|
|
143
|
+
"zapy._client.persistence.write_behind_persistence:WriteBehindStores"
|
|
144
|
+
)
|
|
145
|
+
WaEphemeralObserverOptions = _load(
|
|
146
|
+
"zapy._client.persistence.ephemeral_setting:WaEphemeralObserverOptions"
|
|
147
|
+
)
|
|
148
|
+
self._write_behind: Any = WriteBehindPersistence(
|
|
149
|
+
WriteBehindStores(
|
|
150
|
+
message_store=self._stores.messages,
|
|
151
|
+
thread_store=self._stores.threads,
|
|
152
|
+
contact_store=self._stores.contacts,
|
|
153
|
+
),
|
|
154
|
+
self._logger,
|
|
155
|
+
self._options.write_behind,
|
|
156
|
+
)
|
|
157
|
+
create_ephemeral_observer = _load(
|
|
158
|
+
"zapy._client.persistence.ephemeral_setting:create_ephemeral_observer"
|
|
159
|
+
)
|
|
160
|
+
self._observe_ephemeral_setting: Callable[[Any], None] = (
|
|
161
|
+
create_ephemeral_observer(
|
|
162
|
+
WaEphemeralObserverOptions(
|
|
163
|
+
logger=self._logger,
|
|
164
|
+
chat_metadata_store=self._stores.chat_metadata,
|
|
165
|
+
)
|
|
166
|
+
)
|
|
167
|
+
)
|
|
168
|
+
self._connect_promise: asyncio.Task[None] | None = None
|
|
169
|
+
self._accepting_incoming_events = True
|
|
170
|
+
self._active_incoming_handlers = 0
|
|
171
|
+
self._incoming_handlers_drained_waiters: list[Callable[..., None]] = []
|
|
172
|
+
self._dispose_plugins: Callable[[], Awaitable[None]] | None = None
|
|
173
|
+
|
|
174
|
+
async def _send_node(node: BinaryNode) -> None:
|
|
175
|
+
await self._deps.low_level_coordinator.send_node(node)
|
|
176
|
+
|
|
177
|
+
async def _runtime_query(
|
|
178
|
+
node: BinaryNode,
|
|
179
|
+
timeout_ms: float | None = None,
|
|
180
|
+
query_options: Any = None,
|
|
181
|
+
) -> BinaryNode:
|
|
182
|
+
result: BinaryNode = await self._deps.low_level_coordinator.query(
|
|
183
|
+
node, timeout_ms, query_options
|
|
184
|
+
)
|
|
185
|
+
return result
|
|
186
|
+
|
|
187
|
+
runtime = WaClientBuildRuntime(
|
|
188
|
+
send_node=_send_node,
|
|
189
|
+
query=_runtime_query,
|
|
190
|
+
query_with_context=self._query_with_context,
|
|
191
|
+
sync_app_state=lambda: self._deps.chat_coordinator.sync(),
|
|
192
|
+
sync_app_state_with_options=lambda sync_options=None: (
|
|
193
|
+
self._deps.chat_coordinator.sync(sync_options)
|
|
194
|
+
),
|
|
195
|
+
emit_event=self.emit,
|
|
196
|
+
has_event_listener=lambda event: self.listener_count(event) > 0,
|
|
197
|
+
handle_incoming_message_event=self._handle_incoming_message_event,
|
|
198
|
+
handle_error=self._handle_error,
|
|
199
|
+
handle_incoming_frame=self._handle_incoming_frame,
|
|
200
|
+
clear_stored_state=self._clear_stored_state,
|
|
201
|
+
resume_incoming_events=self._resume_incoming_events,
|
|
202
|
+
subscribe_protocol_message=self._subscribe_protocol_message,
|
|
203
|
+
persist_contact=lambda record: self._write_behind.persist_contact(record),
|
|
204
|
+
)
|
|
205
|
+
self._deps: WaClientDependencies = build_wa_client_dependencies(base, runtime)
|
|
206
|
+
self._app_state_sync: Any = self._deps.app_state_sync
|
|
207
|
+
self._media_transfer: Any = self._deps.media_transfer
|
|
208
|
+
self._plugin_install_input = WaClientPluginInstallInput(
|
|
209
|
+
options=self._options,
|
|
210
|
+
logger=self._logger,
|
|
211
|
+
stores=self._stores,
|
|
212
|
+
deps=self._deps,
|
|
213
|
+
query_with_context=self._query_with_context,
|
|
214
|
+
)
|
|
215
|
+
self._install_plugins()
|
|
216
|
+
self._bind_node_transport_events()
|
|
217
|
+
self.on(
|
|
218
|
+
"connection",
|
|
219
|
+
lambda event: self._maybe_recover_client_too_old(event),
|
|
220
|
+
)
|
|
221
|
+
self.on(
|
|
222
|
+
"connection",
|
|
223
|
+
lambda event: self._maybe_reconcile_companions(event),
|
|
224
|
+
)
|
|
225
|
+
|
|
226
|
+
# -- events --------------------------------------------------------
|
|
227
|
+
|
|
228
|
+
def on(self, event: str, listener: Callable[..., Any]) -> WaClient:
|
|
229
|
+
"""Subscribe to an event (mirrors ``EventEmitter#on``)."""
|
|
230
|
+
self._emitter.on(event, listener)
|
|
231
|
+
return self
|
|
232
|
+
|
|
233
|
+
def once(self, event: str, listener: Callable[..., Any]) -> WaClient:
|
|
234
|
+
"""Subscribe for a single emission (mirrors ``EventEmitter#once``)."""
|
|
235
|
+
self._emitter.once(event, listener)
|
|
236
|
+
return self
|
|
237
|
+
|
|
238
|
+
def off(self, event: str, listener: Callable[..., Any]) -> WaClient:
|
|
239
|
+
"""Unsubscribe (mirrors ``EventEmitter#off``)."""
|
|
240
|
+
self._emitter.off(event, listener)
|
|
241
|
+
return self
|
|
242
|
+
|
|
243
|
+
def emit(self, event: str, *args: Any) -> bool:
|
|
244
|
+
"""Emit an event payload to local listeners synchronously."""
|
|
245
|
+
return self._emitter.emit(event, *args)
|
|
246
|
+
|
|
247
|
+
def listener_count(self, event: str) -> int:
|
|
248
|
+
"""Number of listeners registered for ``event``."""
|
|
249
|
+
return self._emitter.listener_count(event)
|
|
250
|
+
|
|
251
|
+
# -- state ---------------------------------------------------------
|
|
252
|
+
|
|
253
|
+
def get_state(self) -> Any:
|
|
254
|
+
"""Auth state snapshot (credentials, registration, connection flag)."""
|
|
255
|
+
connected = self._deps.connection_manager.is_connected()
|
|
256
|
+
self._logger.trace("wa client state requested", {"connected": connected})
|
|
257
|
+
return self._deps.auth_client.get_state(connected)
|
|
258
|
+
|
|
259
|
+
def get_credentials(self) -> Any:
|
|
260
|
+
"""Persisted credentials, or ``None`` before pairing."""
|
|
261
|
+
return self._deps.auth_client.get_current_credentials()
|
|
262
|
+
|
|
263
|
+
def get_clock_skew_ms(self) -> float | None:
|
|
264
|
+
"""Measured server clock skew in ms, or ``None`` before handshake."""
|
|
265
|
+
skew: Any = self._deps.connection_manager.get_clock_skew_ms()
|
|
266
|
+
return float(skew) if skew is not None else None
|
|
267
|
+
|
|
268
|
+
# -- lifecycle -----------------------------------------------------
|
|
269
|
+
|
|
270
|
+
async def connect(self) -> None:
|
|
271
|
+
"""Open the transport and run the noise/auth handshake.
|
|
272
|
+
|
|
273
|
+
A call in flight is reused. Pairing prompts surface via the
|
|
274
|
+
``auth_qr`` / ``auth_pairing_code`` events while this awaits.
|
|
275
|
+
"""
|
|
276
|
+
if self._connect_promise is not None:
|
|
277
|
+
self._logger.trace("wa client connect already in-flight")
|
|
278
|
+
return await self._connect_promise
|
|
279
|
+
if self._dispose_plugins is None:
|
|
280
|
+
self._install_plugins()
|
|
281
|
+
self._write_behind.restart()
|
|
282
|
+
self._accepting_incoming_events = True
|
|
283
|
+
|
|
284
|
+
async def _run() -> None:
|
|
285
|
+
await self._deps.connection_manager.connect(self._handle_incoming_frame)
|
|
286
|
+
credentials = self._deps.auth_client.get_current_credentials()
|
|
287
|
+
if _get(credentials, "me_jid") is None:
|
|
288
|
+
return
|
|
289
|
+
self.emit(
|
|
290
|
+
"connection",
|
|
291
|
+
{
|
|
292
|
+
"status": "open",
|
|
293
|
+
"reason": "connected",
|
|
294
|
+
"code": None,
|
|
295
|
+
"is_logout": False,
|
|
296
|
+
"is_new_login": False,
|
|
297
|
+
},
|
|
298
|
+
)
|
|
299
|
+
|
|
300
|
+
task = asyncio.ensure_future(_run())
|
|
301
|
+
|
|
302
|
+
def _clear(_task: asyncio.Task[None]) -> None:
|
|
303
|
+
self._connect_promise = None
|
|
304
|
+
|
|
305
|
+
task.add_done_callback(_clear)
|
|
306
|
+
self._connect_promise = task
|
|
307
|
+
await task
|
|
308
|
+
|
|
309
|
+
async def disconnect(self) -> None:
|
|
310
|
+
"""Close the transport gracefully (mirrors ``disconnect``).
|
|
311
|
+
|
|
312
|
+
Pauses incoming events, flushes write-behind persistence, disposes
|
|
313
|
+
plugins and emits ``connection`` close with reason
|
|
314
|
+
``client_disconnected``. No auto-reconnect.
|
|
315
|
+
"""
|
|
316
|
+
self._deps.privacy_coordinator.stop_account_sync_refresh()
|
|
317
|
+
await self._pause_incoming_events_and_wait_drain()
|
|
318
|
+
write_behind_options = _get(self._options, "write_behind")
|
|
319
|
+
flush_timeout = (
|
|
320
|
+
_get(write_behind_options, "flush_timeout_ms")
|
|
321
|
+
if write_behind_options is not None
|
|
322
|
+
else None
|
|
323
|
+
)
|
|
324
|
+
flush = await self._write_behind.flush(flush_timeout)
|
|
325
|
+
if _get(flush, "remaining", 0) > 0:
|
|
326
|
+
self._logger.warn(
|
|
327
|
+
"disconnect continuing with pending write-behind entries",
|
|
328
|
+
{"remaining": _get(flush, "remaining")},
|
|
329
|
+
)
|
|
330
|
+
if self._dispose_plugins is not None:
|
|
331
|
+
dispose = self._dispose_plugins
|
|
332
|
+
self._dispose_plugins = None
|
|
333
|
+
await dispose()
|
|
334
|
+
await self._deps.connection_manager.disconnect()
|
|
335
|
+
self.emit(
|
|
336
|
+
"connection",
|
|
337
|
+
{
|
|
338
|
+
"status": "close",
|
|
339
|
+
"reason": "client_disconnected",
|
|
340
|
+
"code": None,
|
|
341
|
+
"is_logout": False,
|
|
342
|
+
"is_new_login": False,
|
|
343
|
+
},
|
|
344
|
+
)
|
|
345
|
+
|
|
346
|
+
def ignore_key(
|
|
347
|
+
self, ignore: WaIgnoreKey | WaIgnoreKeyPredicate
|
|
348
|
+
) -> Callable[[], None]:
|
|
349
|
+
"""Drop matching inbound stanzas before any handler runs.
|
|
350
|
+
|
|
351
|
+
Accepts a descriptor or a predicate; ``category='peer'`` protocol
|
|
352
|
+
traffic between our own devices is never dropped. Returns an
|
|
353
|
+
``unregister`` function.
|
|
354
|
+
"""
|
|
355
|
+
create_ignore_key_filter = _load(
|
|
356
|
+
"zapy._client.messaging.ignore_key:create_ignore_key_filter"
|
|
357
|
+
)
|
|
358
|
+
validate_ignore_key = _load(
|
|
359
|
+
"zapy._client.messaging.ignore_key:validate_ignore_key"
|
|
360
|
+
)
|
|
361
|
+
if not callable(ignore):
|
|
362
|
+
validate_ignore_key(ignore)
|
|
363
|
+
key_filter = create_ignore_key_filter(
|
|
364
|
+
ignore,
|
|
365
|
+
lambda: self._deps.auth_client.get_current_credentials(),
|
|
366
|
+
)
|
|
367
|
+
unregister: Callable[[], None] = (
|
|
368
|
+
self._deps.incoming_node.register_incoming_stanza_filter(key_filter)
|
|
369
|
+
)
|
|
370
|
+
return unregister
|
|
371
|
+
|
|
372
|
+
# -- coordinator getters -------------------------------------------
|
|
373
|
+
|
|
374
|
+
@property
|
|
375
|
+
def auth(self) -> Any:
|
|
376
|
+
"""Auth client: pairing, credentials, registration state."""
|
|
377
|
+
return self._deps.auth_client
|
|
378
|
+
|
|
379
|
+
@property
|
|
380
|
+
def message(self) -> Any:
|
|
381
|
+
"""Message coordinator: send/receive, receipts, addons, media."""
|
|
382
|
+
return self._deps.message_coordinator
|
|
383
|
+
|
|
384
|
+
@property
|
|
385
|
+
def presence(self) -> Any:
|
|
386
|
+
"""Presence coordinator: own/peer presence subscriptions."""
|
|
387
|
+
return self._deps.presence_coordinator
|
|
388
|
+
|
|
389
|
+
@property
|
|
390
|
+
def lowlevel(self) -> Any:
|
|
391
|
+
"""Low-level coordinator: raw node send/query escape hatch."""
|
|
392
|
+
return self._deps.low_level_coordinator
|
|
393
|
+
|
|
394
|
+
@property
|
|
395
|
+
def chat(self) -> Any:
|
|
396
|
+
"""App-state mutation coordinator: chat-side settings."""
|
|
397
|
+
return self._deps.chat_coordinator
|
|
398
|
+
|
|
399
|
+
@property
|
|
400
|
+
def group(self) -> Any:
|
|
401
|
+
"""Group coordinator: create/query/manage groups and communities."""
|
|
402
|
+
return self._deps.group_coordinator
|
|
403
|
+
|
|
404
|
+
@property
|
|
405
|
+
def status(self) -> Any:
|
|
406
|
+
"""Status coordinator: status broadcast send and reactions."""
|
|
407
|
+
return self._deps.status_coordinator
|
|
408
|
+
|
|
409
|
+
@property
|
|
410
|
+
def broadcast_list(self) -> Any:
|
|
411
|
+
"""Broadcast-list coordinator (business-only writes)."""
|
|
412
|
+
return self._deps.broadcast_list_coordinator
|
|
413
|
+
|
|
414
|
+
@property
|
|
415
|
+
def newsletter(self) -> Any:
|
|
416
|
+
"""Newsletter coordinator: channels create/query/follow/admin/send."""
|
|
417
|
+
return self._deps.newsletter_coordinator
|
|
418
|
+
|
|
419
|
+
@property
|
|
420
|
+
def privacy(self) -> Any:
|
|
421
|
+
"""Privacy coordinator: categories, blocklist, disallowed list."""
|
|
422
|
+
return self._deps.privacy_coordinator
|
|
423
|
+
|
|
424
|
+
@property
|
|
425
|
+
def profile(self) -> Any:
|
|
426
|
+
"""Profile coordinator: own/peer profile fields."""
|
|
427
|
+
return self._deps.profile_coordinator
|
|
428
|
+
|
|
429
|
+
@property
|
|
430
|
+
def business(self) -> Any:
|
|
431
|
+
"""Business coordinator (writes are business-only)."""
|
|
432
|
+
return self._deps.business_coordinator
|
|
433
|
+
|
|
434
|
+
@property
|
|
435
|
+
def bot(self) -> Any:
|
|
436
|
+
"""Bot coordinator: Meta-AI bot profiles, prompt/chunk decryption."""
|
|
437
|
+
return self._deps.bot_coordinator
|
|
438
|
+
|
|
439
|
+
@property
|
|
440
|
+
def email(self) -> Any:
|
|
441
|
+
"""Email coordinator (mobile-only; every method throws otherwise)."""
|
|
442
|
+
return self._deps.email_coordinator
|
|
443
|
+
|
|
444
|
+
@property
|
|
445
|
+
def mobile(self) -> Any:
|
|
446
|
+
"""Mobile coordinator: host/manage linked companion devices."""
|
|
447
|
+
return self._deps.mobile_coordinator
|
|
448
|
+
|
|
449
|
+
async def logout(self, reason: str = "user_initiated") -> None:
|
|
450
|
+
"""Unpair this companion device by removing it server-side.
|
|
451
|
+
|
|
452
|
+
Throws when no ``meJid`` is present. Does not disconnect or clear
|
|
453
|
+
local stores itself; the server-initiated close (``is_logout``)
|
|
454
|
+
wipes persisted state honoring ``logout_store_clear``.
|
|
455
|
+
"""
|
|
456
|
+
credentials = self._deps.auth_client.get_current_credentials()
|
|
457
|
+
me_jid = _get(credentials, "me_jid")
|
|
458
|
+
if not me_jid:
|
|
459
|
+
raise ValueError("cannot logout: client is not authenticated")
|
|
460
|
+
normalize_device_jid = _load("zapy._protocol.jid:normalize_device_jid")
|
|
461
|
+
build_remove_companion_device_iq = _load(
|
|
462
|
+
"zapy._transport.node.builders.device:build_remove_companion_device_iq"
|
|
463
|
+
)
|
|
464
|
+
device_jid = normalize_device_jid(me_jid)
|
|
465
|
+
node = build_remove_companion_device_iq(device_jid, reason)
|
|
466
|
+
result = await self._query_with_context(
|
|
467
|
+
"client.logout", node, None, {"jid": device_jid, "reason": reason}
|
|
468
|
+
)
|
|
469
|
+
assert_iq_result(result, "client.logout")
|
|
470
|
+
|
|
471
|
+
# -- internals -----------------------------------------------------
|
|
472
|
+
|
|
473
|
+
def _install_plugins(self) -> None:
|
|
474
|
+
install_plugins = _load(
|
|
475
|
+
"zapy._client.plugins.install:install_wa_client_plugins"
|
|
476
|
+
)
|
|
477
|
+
self._dispose_plugins = install_plugins(
|
|
478
|
+
self,
|
|
479
|
+
self._plugin_install_input,
|
|
480
|
+
list(self._options.plugins),
|
|
481
|
+
)
|
|
482
|
+
|
|
483
|
+
def _maybe_recover_client_too_old(self, event: Any) -> None:
|
|
484
|
+
status = _get(event, "status")
|
|
485
|
+
reason = _get(event, "reason")
|
|
486
|
+
if status != "close" or not self._options.recover_from_client_too_old:
|
|
487
|
+
return
|
|
488
|
+
if reason != "failure_client_too_old":
|
|
489
|
+
return
|
|
490
|
+
self._logger.warn(
|
|
491
|
+
"wa rejected the connect with client_too_old: the zapy default "
|
|
492
|
+
"WA version is outdated. Auto-recovering by fetching the current "
|
|
493
|
+
"version from the public source – please upgrade zapy so the "
|
|
494
|
+
"shipped default catches up."
|
|
495
|
+
)
|
|
496
|
+
|
|
497
|
+
async def _recover() -> None:
|
|
498
|
+
try:
|
|
499
|
+
if self._connect_promise is not None:
|
|
500
|
+
try:
|
|
501
|
+
await self._connect_promise
|
|
502
|
+
except Exception:
|
|
503
|
+
pass
|
|
504
|
+
is_mobile = bool(self._deps.is_mobile_primary())
|
|
505
|
+
if is_mobile:
|
|
506
|
+
fetch_latest = _load(
|
|
507
|
+
"zapy._transport.wa_version_fetcher:"
|
|
508
|
+
"fetch_latest_wa_mobile_version"
|
|
509
|
+
)
|
|
510
|
+
else:
|
|
511
|
+
fetch_latest = _load(
|
|
512
|
+
"zapy._transport.wa_version_fetcher:fetch_latest_wa_web_version"
|
|
513
|
+
)
|
|
514
|
+
latest = await fetch_latest()
|
|
515
|
+
version = _get(latest, "version")
|
|
516
|
+
self._logger.info(
|
|
517
|
+
"client_too_old auto-recover: reconnecting",
|
|
518
|
+
{
|
|
519
|
+
"transport": "mobile" if is_mobile else "web",
|
|
520
|
+
"version": version,
|
|
521
|
+
},
|
|
522
|
+
)
|
|
523
|
+
if is_mobile:
|
|
524
|
+
self._deps.auth_client.set_next_connect_mobile_app_version(version)
|
|
525
|
+
else:
|
|
526
|
+
self._deps.auth_client.set_next_connect_version(version)
|
|
527
|
+
await self.connect()
|
|
528
|
+
except Exception as error:
|
|
529
|
+
err = _to_error(error)
|
|
530
|
+
self._logger.warn(
|
|
531
|
+
"client_too_old auto-recover failed",
|
|
532
|
+
{"message": str(err)},
|
|
533
|
+
)
|
|
534
|
+
|
|
535
|
+
asyncio.ensure_future(_recover())
|
|
536
|
+
|
|
537
|
+
def _maybe_reconcile_companions(self, event: Any) -> None:
|
|
538
|
+
if _get(event, "status") != "open":
|
|
539
|
+
return
|
|
540
|
+
|
|
541
|
+
async def _reconcile() -> None:
|
|
542
|
+
try:
|
|
543
|
+
await self._deps.mobile_coordinator.reconcile_companions()
|
|
544
|
+
except Exception as error:
|
|
545
|
+
self._logger.debug(
|
|
546
|
+
"companion reconcile on connect failed",
|
|
547
|
+
{"message": str(_to_error(error))},
|
|
548
|
+
)
|
|
549
|
+
|
|
550
|
+
asyncio.ensure_future(_reconcile())
|
|
551
|
+
|
|
552
|
+
def _bind_node_transport_events(self) -> None:
|
|
553
|
+
transport = self._deps.node_transport
|
|
554
|
+
transport.on(
|
|
555
|
+
"frame_in",
|
|
556
|
+
lambda frame: self.emit("debug_transport_frame_in", {"frame": frame}),
|
|
557
|
+
)
|
|
558
|
+
transport.on(
|
|
559
|
+
"frame_out",
|
|
560
|
+
lambda frame: self.emit("debug_transport_frame_out", {"frame": frame}),
|
|
561
|
+
)
|
|
562
|
+
transport.on(
|
|
563
|
+
"node_in",
|
|
564
|
+
lambda node, frame: self.emit(
|
|
565
|
+
"debug_transport_node_in", {"node": node, "frame": frame}
|
|
566
|
+
),
|
|
567
|
+
)
|
|
568
|
+
transport.on(
|
|
569
|
+
"node_out",
|
|
570
|
+
lambda node, frame: self.emit(
|
|
571
|
+
"debug_transport_node_out", {"node": node, "frame": frame}
|
|
572
|
+
),
|
|
573
|
+
)
|
|
574
|
+
|
|
575
|
+
def _on_decode_error(error: Exception, frame: bytes) -> None:
|
|
576
|
+
self.emit("debug_transport_decode_error", {"error": error, "frame": frame})
|
|
577
|
+
self._handle_error(error)
|
|
578
|
+
|
|
579
|
+
transport.on("decode_error", _on_decode_error)
|
|
580
|
+
|
|
581
|
+
def _subscribe_protocol_message(
|
|
582
|
+
self, handler: Callable[[Any], None]
|
|
583
|
+
) -> Callable[[], None]:
|
|
584
|
+
self.on("message_protocol", handler)
|
|
585
|
+
|
|
586
|
+
def _unsubscribe() -> None:
|
|
587
|
+
self.off("message_protocol", handler)
|
|
588
|
+
|
|
589
|
+
return _unsubscribe
|
|
590
|
+
|
|
591
|
+
def _resume_incoming_events(self) -> None:
|
|
592
|
+
self._accepting_incoming_events = True
|
|
593
|
+
|
|
594
|
+
def _try_enter_incoming_handler(self) -> bool:
|
|
595
|
+
if not self._accepting_incoming_events:
|
|
596
|
+
return False
|
|
597
|
+
self._active_incoming_handlers += 1
|
|
598
|
+
if self._accepting_incoming_events:
|
|
599
|
+
return True
|
|
600
|
+
self._leave_incoming_handler()
|
|
601
|
+
return False
|
|
602
|
+
|
|
603
|
+
def _leave_incoming_handler(self) -> None:
|
|
604
|
+
if self._active_incoming_handlers <= 0:
|
|
605
|
+
return
|
|
606
|
+
self._active_incoming_handlers -= 1
|
|
607
|
+
if self._active_incoming_handlers == 0:
|
|
608
|
+
self._notify_incoming_handlers_drained()
|
|
609
|
+
|
|
610
|
+
async def _pause_incoming_events_and_wait_drain(self) -> None:
|
|
611
|
+
self._accepting_incoming_events = False
|
|
612
|
+
if self._active_incoming_handlers == 0:
|
|
613
|
+
return
|
|
614
|
+
loop = asyncio.get_running_loop()
|
|
615
|
+
future: asyncio.Future[None] = loop.create_future()
|
|
616
|
+
self._incoming_handlers_drained_waiters.append(future.set_result)
|
|
617
|
+
await future
|
|
618
|
+
|
|
619
|
+
def _notify_incoming_handlers_drained(self) -> None:
|
|
620
|
+
waiters = self._incoming_handlers_drained_waiters
|
|
621
|
+
if not waiters:
|
|
622
|
+
return
|
|
623
|
+
self._incoming_handlers_drained_waiters = []
|
|
624
|
+
for resolve in waiters:
|
|
625
|
+
resolve(None)
|
|
626
|
+
|
|
627
|
+
def _handle_error(self, error: Exception) -> None:
|
|
628
|
+
self._logger.error("wa client error", {"message": str(error)})
|
|
629
|
+
self.emit("debug_client_error", {"error": error})
|
|
630
|
+
|
|
631
|
+
async def _query_with_context(
|
|
632
|
+
self,
|
|
633
|
+
context: str,
|
|
634
|
+
node: BinaryNode,
|
|
635
|
+
timeout_ms: float | None = None,
|
|
636
|
+
context_data: dict[str, Any] | None = None,
|
|
637
|
+
options: dict[str, Any] | None = None,
|
|
638
|
+
) -> BinaryNode:
|
|
639
|
+
resolved_timeout = timeout_ms
|
|
640
|
+
if resolved_timeout is None:
|
|
641
|
+
resolved_timeout = self._options.iq_timeout_ms
|
|
642
|
+
if resolved_timeout is None:
|
|
643
|
+
resolved_timeout = 15_000
|
|
644
|
+
|
|
645
|
+
async def _query(query_node: BinaryNode, query_timeout_ms: float) -> BinaryNode:
|
|
646
|
+
inner: BinaryNode = await self._deps.low_level_coordinator.query(
|
|
647
|
+
query_node, query_timeout_ms, options or {}
|
|
648
|
+
)
|
|
649
|
+
return inner
|
|
650
|
+
|
|
651
|
+
result: BinaryNode = await query_with_context(
|
|
652
|
+
_query,
|
|
653
|
+
self._logger,
|
|
654
|
+
context,
|
|
655
|
+
node,
|
|
656
|
+
resolved_timeout,
|
|
657
|
+
context_data,
|
|
658
|
+
)
|
|
659
|
+
return result
|
|
660
|
+
|
|
661
|
+
async def _handle_incoming_frame(self, frame: bytes) -> None:
|
|
662
|
+
try:
|
|
663
|
+
await self._deps.node_transport.dispatch_incoming_frame(
|
|
664
|
+
frame,
|
|
665
|
+
lambda node: self._deps.incoming_node.handle_incoming_node(node),
|
|
666
|
+
)
|
|
667
|
+
except Exception as error:
|
|
668
|
+
self._handle_error(_to_error(error))
|
|
669
|
+
|
|
670
|
+
async def _handle_incoming_message_event(
|
|
671
|
+
self, event: WaIncomingMessageEvent | dict[str, Any]
|
|
672
|
+
) -> None:
|
|
673
|
+
if not self._try_enter_incoming_handler():
|
|
674
|
+
return
|
|
675
|
+
try:
|
|
676
|
+
self.emit("message", event)
|
|
677
|
+
self._observe_ephemeral_setting(event)
|
|
678
|
+
persist_incoming_mailbox_entities = _load(
|
|
679
|
+
"zapy._client.persistence.mailbox:persist_incoming_mailbox_entities"
|
|
680
|
+
)
|
|
681
|
+
persist_incoming_mailbox_entities(
|
|
682
|
+
{
|
|
683
|
+
"logger": self._logger,
|
|
684
|
+
"write_behind": self._write_behind,
|
|
685
|
+
"message_secret_store": self._stores.message_secret,
|
|
686
|
+
"persist_all_secrets": bool(
|
|
687
|
+
self._options.addons is not None
|
|
688
|
+
and self._options.addons.persist_all_secrets is True
|
|
689
|
+
),
|
|
690
|
+
"event": event,
|
|
691
|
+
}
|
|
692
|
+
)
|
|
693
|
+
message = _get(event, "message")
|
|
694
|
+
addons = self._options.addons
|
|
695
|
+
if (addons is None or addons.auto_decrypt is not False) and message:
|
|
696
|
+
try:
|
|
697
|
+
await self._deps.message_coordinator.try_decrypt_addon(event)
|
|
698
|
+
except Exception as error:
|
|
699
|
+
self._logger.warn(
|
|
700
|
+
"addon auto-decrypt failed",
|
|
701
|
+
{
|
|
702
|
+
"id": _get(_get(event, "key"), "id"),
|
|
703
|
+
"message": str(_to_error(error)),
|
|
704
|
+
},
|
|
705
|
+
)
|
|
706
|
+
if message:
|
|
707
|
+
try:
|
|
708
|
+
await self._deps.bot_coordinator.try_decrypt_chunk(event)
|
|
709
|
+
except Exception as error:
|
|
710
|
+
self._logger.warn(
|
|
711
|
+
"bot chunk auto-decrypt failed",
|
|
712
|
+
{
|
|
713
|
+
"id": _get(_get(event, "key"), "id"),
|
|
714
|
+
"message": str(_to_error(error)),
|
|
715
|
+
},
|
|
716
|
+
)
|
|
717
|
+
history = self._options.history
|
|
718
|
+
key = _get(event, "key") or {}
|
|
719
|
+
if (
|
|
720
|
+
history is not None
|
|
721
|
+
and history.group_bundles is True
|
|
722
|
+
and message
|
|
723
|
+
and not _get(key, "from_me", False)
|
|
724
|
+
):
|
|
725
|
+
self._try_process_group_history_bundle(event, message, key)
|
|
726
|
+
protocol_message = _get(message, "protocol_message")
|
|
727
|
+
if protocol_message is None:
|
|
728
|
+
return
|
|
729
|
+
protocol_event = (
|
|
730
|
+
{
|
|
731
|
+
**(event if isinstance(event, dict) else {}),
|
|
732
|
+
"protocol_message": protocol_message,
|
|
733
|
+
}
|
|
734
|
+
if isinstance(event, dict)
|
|
735
|
+
else event
|
|
736
|
+
)
|
|
737
|
+
self.emit("message_protocol", protocol_event)
|
|
738
|
+
protocol_type = _get(protocol_message, "type")
|
|
739
|
+
if protocol_type is None:
|
|
740
|
+
self._logger.debug(
|
|
741
|
+
"incoming protocol message without type",
|
|
742
|
+
{
|
|
743
|
+
"id": _get(key, "id"),
|
|
744
|
+
"from": _get(key, "remote_jid"),
|
|
745
|
+
},
|
|
746
|
+
)
|
|
747
|
+
return
|
|
748
|
+
if protocol_type == _protocol_type_value(_APP_STATE_SYNC_KEY_REQUEST):
|
|
749
|
+
await self._app_state_sync.handle_incoming_key_request(
|
|
750
|
+
key, protocol_message
|
|
751
|
+
)
|
|
752
|
+
return
|
|
753
|
+
if protocol_type == _protocol_type_value(_APP_STATE_SYNC_KEY_SHARE):
|
|
754
|
+
await self._app_state_sync.handle_incoming_key_share(
|
|
755
|
+
key, protocol_message
|
|
756
|
+
)
|
|
757
|
+
return
|
|
758
|
+
if protocol_type == _protocol_type_value(_HISTORY_SYNC_NOTIFICATION):
|
|
759
|
+
history_notification = _get(
|
|
760
|
+
protocol_message, "history_sync_notification"
|
|
761
|
+
)
|
|
762
|
+
if history_notification is None:
|
|
763
|
+
return
|
|
764
|
+
await self._handle_history_sync_notification(
|
|
765
|
+
event, key, history_notification
|
|
766
|
+
)
|
|
767
|
+
return
|
|
768
|
+
if protocol_type == _protocol_type_value(_EPHEMERAL_SETTING):
|
|
769
|
+
persist_incoming_ephemeral_setting = _load(
|
|
770
|
+
"zapy._client.persistence.ephemeral_setting:"
|
|
771
|
+
"persist_incoming_ephemeral_setting"
|
|
772
|
+
)
|
|
773
|
+
persist_incoming_ephemeral_setting(
|
|
774
|
+
{
|
|
775
|
+
"logger": self._logger,
|
|
776
|
+
"write_behind": self._write_behind,
|
|
777
|
+
"chat_metadata_store": self._stores.chat_metadata,
|
|
778
|
+
"event": event,
|
|
779
|
+
"protocol_message": protocol_message,
|
|
780
|
+
}
|
|
781
|
+
)
|
|
782
|
+
return
|
|
783
|
+
sync_related = {
|
|
784
|
+
_protocol_type_value(name) for name in _SYNC_RELATED_PROTOCOL_TYPE_NAMES
|
|
785
|
+
}
|
|
786
|
+
if protocol_type in sync_related:
|
|
787
|
+
self._logger.info(
|
|
788
|
+
"incoming sync-related protocol message",
|
|
789
|
+
{
|
|
790
|
+
"id": _get(key, "id"),
|
|
791
|
+
"from": _get(key, "remote_jid"),
|
|
792
|
+
"protocol_type": protocol_type,
|
|
793
|
+
},
|
|
794
|
+
)
|
|
795
|
+
return
|
|
796
|
+
self._logger.debug(
|
|
797
|
+
"incoming protocol message received",
|
|
798
|
+
{
|
|
799
|
+
"id": _get(key, "id"),
|
|
800
|
+
"from": _get(key, "remote_jid"),
|
|
801
|
+
"protocol_type": protocol_type,
|
|
802
|
+
},
|
|
803
|
+
)
|
|
804
|
+
finally:
|
|
805
|
+
self._leave_incoming_handler()
|
|
806
|
+
|
|
807
|
+
async def _handle_history_sync_notification(
|
|
808
|
+
self, event: Any, key: Any, history_notification: Any
|
|
809
|
+
) -> None:
|
|
810
|
+
peer_remote_jid = _get(key, "remote_jid")
|
|
811
|
+
peer_stanza_id = _get(key, "id")
|
|
812
|
+
|
|
813
|
+
async def _send_receipt() -> None:
|
|
814
|
+
try:
|
|
815
|
+
await self.message.send_receipt(
|
|
816
|
+
peer_remote_jid,
|
|
817
|
+
peer_stanza_id,
|
|
818
|
+
{"type": "hist_sync"},
|
|
819
|
+
)
|
|
820
|
+
except Exception as error:
|
|
821
|
+
self._logger.warn(
|
|
822
|
+
"failed to send hist_sync receipt",
|
|
823
|
+
{
|
|
824
|
+
"id": peer_stanza_id,
|
|
825
|
+
"to": peer_remote_jid,
|
|
826
|
+
"message": str(_to_error(error)),
|
|
827
|
+
},
|
|
828
|
+
)
|
|
829
|
+
|
|
830
|
+
send_receipt = _send_receipt if peer_remote_jid and peer_stanza_id else None
|
|
831
|
+
history = self._options.history
|
|
832
|
+
if history is not None and history.enabled is False:
|
|
833
|
+
if send_receipt is not None:
|
|
834
|
+
await send_receipt()
|
|
835
|
+
return
|
|
836
|
+
run_history_sync_notification = _load(
|
|
837
|
+
"zapy._client.persistence.history_sync:run_history_sync_notification"
|
|
838
|
+
)
|
|
839
|
+
credentials = self._deps.auth_client.get_current_credentials()
|
|
840
|
+
await run_history_sync_notification(
|
|
841
|
+
{
|
|
842
|
+
"logger": self._logger,
|
|
843
|
+
"media_transfer": self._media_transfer,
|
|
844
|
+
"chat_metadata_store": self._stores.chat_metadata,
|
|
845
|
+
"write_behind": self._write_behind,
|
|
846
|
+
"chunk_id": _get(key, "id"),
|
|
847
|
+
"sink": history.sink if history is not None else None,
|
|
848
|
+
"emit_event": self.emit,
|
|
849
|
+
"on_privacy_tokens": lambda conversations: (
|
|
850
|
+
self._deps.trusted_contact_token.hydrate_from_history_sync(
|
|
851
|
+
conversations
|
|
852
|
+
)
|
|
853
|
+
),
|
|
854
|
+
"on_nct_salt": lambda salt: (
|
|
855
|
+
self._deps.trusted_contact_token.hydrate_nct_salt_from_history_sync(
|
|
856
|
+
salt
|
|
857
|
+
)
|
|
858
|
+
),
|
|
859
|
+
"on_processed": send_receipt,
|
|
860
|
+
"me_jid": _get(credentials, "me_jid"),
|
|
861
|
+
},
|
|
862
|
+
history_notification,
|
|
863
|
+
)
|
|
864
|
+
|
|
865
|
+
def _try_process_group_history_bundle(
|
|
866
|
+
self, event: Any, message: Any, key: Any
|
|
867
|
+
) -> None:
|
|
868
|
+
unwrap_message = _load("zapy._message.encode.content:unwrap_message")
|
|
869
|
+
bundle = _get(
|
|
870
|
+
unwrap_message(message if isinstance(message, dict) else {}),
|
|
871
|
+
"message_history_bundle",
|
|
872
|
+
)
|
|
873
|
+
group_jid = _get(key, "remote_jid")
|
|
874
|
+
if not bundle or not group_jid:
|
|
875
|
+
return
|
|
876
|
+
if not self._try_enter_incoming_handler():
|
|
877
|
+
return
|
|
878
|
+
credentials = self._deps.auth_client.get_current_credentials()
|
|
879
|
+
run_group_history_bundle = _load(
|
|
880
|
+
"zapy._client.persistence.group_history:run_group_history_bundle"
|
|
881
|
+
)
|
|
882
|
+
|
|
883
|
+
async def _run() -> None:
|
|
884
|
+
try:
|
|
885
|
+
get_ab_prop_number = getattr(
|
|
886
|
+
self._deps.ab_props_coordinator, "get_config_value", None
|
|
887
|
+
)
|
|
888
|
+
await run_group_history_bundle(
|
|
889
|
+
{
|
|
890
|
+
"logger": self._logger,
|
|
891
|
+
"media_transfer": self._media_transfer,
|
|
892
|
+
"write_behind": self._write_behind,
|
|
893
|
+
"emit_event": self.emit,
|
|
894
|
+
"me_jid": _get(credentials, "me_jid"),
|
|
895
|
+
"me_lid": _get(credentials, "me_lid"),
|
|
896
|
+
"get_ab_prop_number": get_ab_prop_number,
|
|
897
|
+
},
|
|
898
|
+
{
|
|
899
|
+
"bundle": bundle,
|
|
900
|
+
"group_jid": group_jid,
|
|
901
|
+
"sender_jid": _get(key, "participant"),
|
|
902
|
+
"bundle_message_id": _get(key, "id"),
|
|
903
|
+
"sent_at_seconds": _get(event, "timestamp_seconds"),
|
|
904
|
+
},
|
|
905
|
+
)
|
|
906
|
+
finally:
|
|
907
|
+
self._leave_incoming_handler()
|
|
908
|
+
|
|
909
|
+
asyncio.ensure_future(_run())
|
|
910
|
+
|
|
911
|
+
async def _clear_stored_state(self) -> None:
|
|
912
|
+
await self._pause_incoming_events_and_wait_drain()
|
|
913
|
+
write_behind_options = _get(self._options, "write_behind")
|
|
914
|
+
flush_timeout = (
|
|
915
|
+
_get(write_behind_options, "flush_timeout_ms")
|
|
916
|
+
if write_behind_options is not None
|
|
917
|
+
else None
|
|
918
|
+
)
|
|
919
|
+
destroyed = await self._write_behind.destroy(flush_timeout)
|
|
920
|
+
if _get(destroyed, "remaining", 0) > 0:
|
|
921
|
+
raise ValueError(
|
|
922
|
+
"clear stored state aborted: write-behind did not fully drain "
|
|
923
|
+
f"(remaining={_get(destroyed, 'remaining')})"
|
|
924
|
+
)
|
|
925
|
+
dangling = self._deps.receipt_queue.take()
|
|
926
|
+
if dangling:
|
|
927
|
+
self._logger.debug(
|
|
928
|
+
"cleared dangling receipts while clearing stored state",
|
|
929
|
+
{"count": len(dangling)},
|
|
930
|
+
)
|
|
931
|
+
|
|
932
|
+
def _should_clear(name: str) -> bool:
|
|
933
|
+
clear = self._options.logout_store_clear
|
|
934
|
+
if clear is None:
|
|
935
|
+
return name not in ("messages", "threads", "contacts")
|
|
936
|
+
explicit = getattr(clear, name, None)
|
|
937
|
+
if explicit is not None:
|
|
938
|
+
return bool(explicit)
|
|
939
|
+
return name not in ("messages", "threads", "contacts")
|
|
940
|
+
|
|
941
|
+
stores = self._stores
|
|
942
|
+
deps = self._deps
|
|
943
|
+
if _should_clear("auth"):
|
|
944
|
+
await deps.auth_client.clear_stored_credentials()
|
|
945
|
+
if _should_clear("app_state"):
|
|
946
|
+
await stores.app_state.clear()
|
|
947
|
+
if _should_clear("contacts"):
|
|
948
|
+
await stores.contacts.clear()
|
|
949
|
+
if _should_clear("messages"):
|
|
950
|
+
await stores.messages.clear()
|
|
951
|
+
if _should_clear("message_secret"):
|
|
952
|
+
await stores.message_secret.clear()
|
|
953
|
+
if _should_clear("group_metadata"):
|
|
954
|
+
await stores.group_metadata.clear()
|
|
955
|
+
if _should_clear("device_list"):
|
|
956
|
+
await stores.device_list.clear()
|
|
957
|
+
if _should_clear("retry"):
|
|
958
|
+
await stores.retry.clear()
|
|
959
|
+
if _should_clear("signal"):
|
|
960
|
+
await stores.signal.clear()
|
|
961
|
+
if _should_clear("pre_key"):
|
|
962
|
+
await stores.pre_key.clear()
|
|
963
|
+
if _should_clear("session"):
|
|
964
|
+
await stores.session.clear()
|
|
965
|
+
if _should_clear("identity"):
|
|
966
|
+
await stores.identity.clear()
|
|
967
|
+
if _should_clear("sender_key"):
|
|
968
|
+
await stores.sender_key.clear()
|
|
969
|
+
if _should_clear("threads"):
|
|
970
|
+
await stores.threads.clear()
|
|
971
|
+
if _should_clear("privacy_token"):
|
|
972
|
+
await stores.privacy_token.clear()
|