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
|
@@ -0,0 +1,915 @@
|
|
|
1
|
+
"""Device-list and LID-mapping sync over usync (mirrors ``SignalDeviceSyncApi``).
|
|
2
|
+
|
|
3
|
+
JID helpers now come from :mod:`zapy._protocol.jid`; usync IQ builders, the
|
|
4
|
+
SID generator, the protocol-error logger and ``_PromiseDedup`` below are
|
|
5
|
+
verbatim ports of ``src/transport/node/builders/usync.ts``,
|
|
6
|
+
``src/transport/node/usync.ts`` and ``src/infra/perf/PromiseDedup.ts``. They
|
|
7
|
+
move to their canonical modules once those land.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import asyncio
|
|
13
|
+
import time
|
|
14
|
+
from collections.abc import Awaitable, Callable, Sequence
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
from typing import Any, Literal, TypeVar, cast
|
|
17
|
+
|
|
18
|
+
from zapy._infra.log import Logger
|
|
19
|
+
from zapy._protocol import defaults as _defaults
|
|
20
|
+
from zapy._protocol.jid import (
|
|
21
|
+
is_lid_jid as _is_lid_jid,
|
|
22
|
+
is_user_jid as _is_user_jid,
|
|
23
|
+
parse_phone_jid,
|
|
24
|
+
split_jid as _split_jid,
|
|
25
|
+
to_user_jid as _to_user_jid,
|
|
26
|
+
)
|
|
27
|
+
from zapy._protocol.nodes import WA_IQ_TYPES, WA_NODE_TAGS, WA_XMLNS
|
|
28
|
+
from zapy._store.contracts.device_list import WaDeviceListStore
|
|
29
|
+
from zapy._store.contracts.device_list import WaDeviceListSnapshot
|
|
30
|
+
from zapy._transport.node.helpers import (
|
|
31
|
+
create_node_id_generator,
|
|
32
|
+
find_node_child,
|
|
33
|
+
get_node_children_by_tag,
|
|
34
|
+
get_node_text_content,
|
|
35
|
+
)
|
|
36
|
+
from zapy._transport.node.query import assert_iq_result
|
|
37
|
+
from zapy._transport.types import BinaryNode
|
|
38
|
+
from zapy._util.primitives import parse_optional_int, to_error
|
|
39
|
+
|
|
40
|
+
T = TypeVar("T")
|
|
41
|
+
|
|
42
|
+
QueryFn = Callable[[BinaryNode, float | None], Awaitable[BinaryNode]]
|
|
43
|
+
|
|
44
|
+
_SIGNAL_FETCH_KEY_BUNDLES_TIMEOUT_MS: float = 20_000
|
|
45
|
+
|
|
46
|
+
_USYNC_CONTEXT_INTERACTIVE: str = "interactive"
|
|
47
|
+
_USYNC_MODE_QUERY: str = "query"
|
|
48
|
+
_USYNC_INDEX: str = "0"
|
|
49
|
+
_USYNC_LAST: str = "true"
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _now_ms() -> int:
|
|
53
|
+
"""Wall-clock milliseconds (mirrors ``Date.now()``)."""
|
|
54
|
+
return int(time.time() * 1000)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _parse_js_int(text: str) -> int | None:
|
|
58
|
+
"""Leading-digit integer like ``Number.parseInt(text, 10)``, else ``None``."""
|
|
59
|
+
stripped = text.lstrip()
|
|
60
|
+
sign = 1
|
|
61
|
+
if stripped.startswith(("+", "-")):
|
|
62
|
+
if stripped.startswith("-"):
|
|
63
|
+
sign = -1
|
|
64
|
+
stripped = stripped[1:]
|
|
65
|
+
digits = ""
|
|
66
|
+
for char in stripped:
|
|
67
|
+
if "0" <= char <= "9":
|
|
68
|
+
digits += char
|
|
69
|
+
else:
|
|
70
|
+
break
|
|
71
|
+
if not digits:
|
|
72
|
+
return None
|
|
73
|
+
value = sign * int(digits, 10)
|
|
74
|
+
return value if abs(value) <= 2**53 - 1 else None
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _build_device_jid(
|
|
78
|
+
user: str,
|
|
79
|
+
normalized_server: str,
|
|
80
|
+
device_id: int,
|
|
81
|
+
raw_server: str | None = None,
|
|
82
|
+
is_hosted: bool = False,
|
|
83
|
+
) -> str:
|
|
84
|
+
"""Build a device JID from its parts, preserving the hosted variant."""
|
|
85
|
+
if is_hosted:
|
|
86
|
+
if device_id != _defaults.HOSTED_DEVICE_ID:
|
|
87
|
+
return f"{user}:{device_id}@{normalized_server}"
|
|
88
|
+
hosted_server = (
|
|
89
|
+
_defaults.HOSTED_LID_SERVER
|
|
90
|
+
if raw_server == _defaults.HOSTED_LID_SERVER
|
|
91
|
+
or normalized_server == _defaults.LID_SERVER
|
|
92
|
+
else _defaults.HOSTED_SERVER
|
|
93
|
+
)
|
|
94
|
+
return f"{user}:{_defaults.HOSTED_DEVICE_ID}@{hosted_server}"
|
|
95
|
+
if device_id == 0:
|
|
96
|
+
return f"{user}@{normalized_server}"
|
|
97
|
+
return f"{user}:{device_id}@{normalized_server}"
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
@dataclass(frozen=True, slots=True)
|
|
101
|
+
class _WaUsyncProtocolError:
|
|
102
|
+
"""Per-protocol ``code / text / backoff`` envelope of a usync result."""
|
|
103
|
+
|
|
104
|
+
code: int | None
|
|
105
|
+
text: str | None
|
|
106
|
+
backoff_seconds: int | None
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
@dataclass(frozen=True, slots=True)
|
|
110
|
+
class _WaUsyncResultEnvelope:
|
|
111
|
+
"""Per-protocol errors plus ``refresh`` hints of a usync IQ result."""
|
|
112
|
+
|
|
113
|
+
errors: dict[str, _WaUsyncProtocolError]
|
|
114
|
+
refresh: dict[str, int]
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _parse_usync_result_envelope(result: BinaryNode) -> _WaUsyncResultEnvelope:
|
|
118
|
+
"""Extract per-protocol error envelopes and ``refresh`` hints."""
|
|
119
|
+
usync_node = find_node_child(result, WA_NODE_TAGS["USYNC"])
|
|
120
|
+
if usync_node is None:
|
|
121
|
+
return _WaUsyncResultEnvelope(errors={}, refresh={})
|
|
122
|
+
result_node = find_node_child(usync_node, "result")
|
|
123
|
+
if result_node is None or not isinstance(result_node.content, list):
|
|
124
|
+
return _WaUsyncResultEnvelope(errors={}, refresh={})
|
|
125
|
+
errors: dict[str, _WaUsyncProtocolError] = {}
|
|
126
|
+
refresh: dict[str, int] = {}
|
|
127
|
+
for proto_node in result_node.content:
|
|
128
|
+
error_node = find_node_child(proto_node, WA_NODE_TAGS["ERROR"])
|
|
129
|
+
if error_node is not None:
|
|
130
|
+
errors[proto_node.tag] = _WaUsyncProtocolError(
|
|
131
|
+
code=parse_optional_int(error_node.attrs.get("code")),
|
|
132
|
+
text=error_node.attrs.get("text"),
|
|
133
|
+
backoff_seconds=parse_optional_int(error_node.attrs.get("backoff")),
|
|
134
|
+
)
|
|
135
|
+
continue
|
|
136
|
+
refresh_seconds = parse_optional_int(proto_node.attrs.get("refresh"))
|
|
137
|
+
if refresh_seconds is not None:
|
|
138
|
+
refresh[proto_node.tag] = refresh_seconds
|
|
139
|
+
return _WaUsyncResultEnvelope(errors=errors, refresh=refresh)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _iterate_usync_users(result: BinaryNode) -> list[BinaryNode] | None:
|
|
143
|
+
"""User nodes of a usync IQ result, or ``None`` without a usync envelope."""
|
|
144
|
+
usync_node = find_node_child(result, WA_NODE_TAGS["USYNC"])
|
|
145
|
+
if usync_node is None:
|
|
146
|
+
return None
|
|
147
|
+
list_node = find_node_child(usync_node, WA_NODE_TAGS["LIST"])
|
|
148
|
+
if list_node is None:
|
|
149
|
+
return None
|
|
150
|
+
return get_node_children_by_tag(list_node, WA_NODE_TAGS["USER"])
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _build_usync_iq(
|
|
154
|
+
sid: str,
|
|
155
|
+
query_protocol_nodes: list[BinaryNode],
|
|
156
|
+
users: list[BinaryNode],
|
|
157
|
+
host_domain: str,
|
|
158
|
+
) -> BinaryNode:
|
|
159
|
+
"""``<iq type=get xmlns=usync>`` wrapping the query protocols and users."""
|
|
160
|
+
if not query_protocol_nodes:
|
|
161
|
+
raise ValueError("usync query must include at least one protocol node")
|
|
162
|
+
return BinaryNode(
|
|
163
|
+
tag=WA_NODE_TAGS["IQ"],
|
|
164
|
+
attrs={
|
|
165
|
+
"to": host_domain,
|
|
166
|
+
"type": WA_IQ_TYPES["GET"],
|
|
167
|
+
"xmlns": WA_XMLNS["USYNC"],
|
|
168
|
+
},
|
|
169
|
+
content=[
|
|
170
|
+
BinaryNode(
|
|
171
|
+
tag=WA_NODE_TAGS["USYNC"],
|
|
172
|
+
attrs={
|
|
173
|
+
"sid": sid,
|
|
174
|
+
"index": _USYNC_INDEX,
|
|
175
|
+
"last": _USYNC_LAST,
|
|
176
|
+
"mode": _USYNC_MODE_QUERY,
|
|
177
|
+
"context": _USYNC_CONTEXT_INTERACTIVE,
|
|
178
|
+
},
|
|
179
|
+
content=[
|
|
180
|
+
BinaryNode(
|
|
181
|
+
tag=WA_NODE_TAGS["QUERY"],
|
|
182
|
+
attrs={},
|
|
183
|
+
content=query_protocol_nodes,
|
|
184
|
+
),
|
|
185
|
+
BinaryNode(
|
|
186
|
+
tag=WA_NODE_TAGS["LIST"],
|
|
187
|
+
attrs={},
|
|
188
|
+
content=users,
|
|
189
|
+
),
|
|
190
|
+
],
|
|
191
|
+
)
|
|
192
|
+
],
|
|
193
|
+
)
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _create_usync_sid_generator() -> Callable[[], Awaitable[str]]:
|
|
197
|
+
"""SID generator backed by the stanza id generator (mirrors the oracle)."""
|
|
198
|
+
generator = create_node_id_generator()
|
|
199
|
+
|
|
200
|
+
async def generate_sid() -> str:
|
|
201
|
+
return generator.next()
|
|
202
|
+
|
|
203
|
+
return generate_sid
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _log_usync_protocol_errors(
|
|
207
|
+
envelope: _WaUsyncResultEnvelope, logger: Logger, context: str
|
|
208
|
+
) -> None:
|
|
209
|
+
"""Warn once per errored usync protocol."""
|
|
210
|
+
for protocol, error in envelope.errors.items():
|
|
211
|
+
logger.warn(
|
|
212
|
+
"usync protocol error",
|
|
213
|
+
{
|
|
214
|
+
"context": context,
|
|
215
|
+
"protocol": protocol,
|
|
216
|
+
"code": error.code,
|
|
217
|
+
"text": error.text,
|
|
218
|
+
"backoffSeconds": error.backoff_seconds,
|
|
219
|
+
},
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
class _PromiseDedup:
|
|
224
|
+
"""Deduplicates concurrent async work by key (mirrors ``PromiseDedup``)."""
|
|
225
|
+
|
|
226
|
+
def __init__(self) -> None:
|
|
227
|
+
self._in_flight: dict[str, asyncio.Future[Any]] = {}
|
|
228
|
+
|
|
229
|
+
async def run(self, key: str, task: Callable[[], Awaitable[T]]) -> T:
|
|
230
|
+
existing = self._in_flight.get(key)
|
|
231
|
+
if existing is not None:
|
|
232
|
+
return cast(T, await existing)
|
|
233
|
+
future: asyncio.Future[Any] = asyncio.get_running_loop().create_future()
|
|
234
|
+
self._in_flight[key] = future
|
|
235
|
+
try:
|
|
236
|
+
result = await task()
|
|
237
|
+
except Exception as error:
|
|
238
|
+
if not future.done():
|
|
239
|
+
future.set_exception(error)
|
|
240
|
+
raise
|
|
241
|
+
else:
|
|
242
|
+
if not future.done():
|
|
243
|
+
future.set_result(result)
|
|
244
|
+
return result
|
|
245
|
+
finally:
|
|
246
|
+
self._in_flight.pop(key, None)
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
SignalLidSyncStatus = Literal["in", "out", "invalid", "error", "unanswered"]
|
|
250
|
+
"""Outcome of a LID sync lookup for one phone number."""
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
@dataclass(frozen=True, slots=True)
|
|
254
|
+
class SignalLidSyncError:
|
|
255
|
+
"""Server error behind an ``error`` or ``unanswered`` LID lookup."""
|
|
256
|
+
|
|
257
|
+
code: str | None = None
|
|
258
|
+
text: str | None = None
|
|
259
|
+
backoff_seconds: int | None = None
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
@dataclass(frozen=True, slots=True)
|
|
263
|
+
class SignalLidSyncResult:
|
|
264
|
+
"""One LID lookup: the queried/corrected phone JID plus the verdict."""
|
|
265
|
+
|
|
266
|
+
queried_jid: str
|
|
267
|
+
phone_jid: str
|
|
268
|
+
lid_jid: str | None
|
|
269
|
+
exists: bool
|
|
270
|
+
invalid: bool
|
|
271
|
+
status: SignalLidSyncStatus
|
|
272
|
+
error: SignalLidSyncError | None = None
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
@dataclass(frozen=True, slots=True)
|
|
276
|
+
class SignalDeviceListEntry:
|
|
277
|
+
"""Resolved per-user device JIDs (matches the on-store snapshot)."""
|
|
278
|
+
|
|
279
|
+
jid: str
|
|
280
|
+
device_jids: Sequence[str]
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
@dataclass(frozen=True, slots=True)
|
|
284
|
+
class SignalUserJidPair:
|
|
285
|
+
"""Both addressing forms of a 1:1 user, as far as they could be resolved."""
|
|
286
|
+
|
|
287
|
+
lid_jid: str | None
|
|
288
|
+
pn_jid: str | None
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
@dataclass(frozen=True, slots=True)
|
|
292
|
+
class _ParsedLidSyncEntry:
|
|
293
|
+
"""One raw LID row before it is joined back to the queried JID."""
|
|
294
|
+
|
|
295
|
+
jid: str
|
|
296
|
+
lid_jid: str | None
|
|
297
|
+
phone_jid: str | None
|
|
298
|
+
status: SignalLidSyncStatus
|
|
299
|
+
error: SignalLidSyncError | None = None
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def _error_message(error: Exception | object) -> str:
|
|
303
|
+
"""Readable message for a caught failure (mirrors ``toError().message``)."""
|
|
304
|
+
normalized = to_error(error)
|
|
305
|
+
return str(normalized.args[0]) if normalized.args else str(normalized)
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def _to_lid_sync_error(error_node: BinaryNode) -> SignalLidSyncError:
|
|
309
|
+
code = error_node.attrs.get("code")
|
|
310
|
+
text = error_node.attrs.get("text")
|
|
311
|
+
return SignalLidSyncError(
|
|
312
|
+
code=code if code is not None else None,
|
|
313
|
+
text=text if text is not None else None,
|
|
314
|
+
)
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def _to_lid_sync_protocol_error(
|
|
318
|
+
error: _WaUsyncProtocolError,
|
|
319
|
+
) -> SignalLidSyncError:
|
|
320
|
+
return SignalLidSyncError(
|
|
321
|
+
code=str(error.code) if error.code is not None else None,
|
|
322
|
+
text=error.text,
|
|
323
|
+
backoff_seconds=error.backoff_seconds,
|
|
324
|
+
)
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
class SignalDeviceSyncApi:
|
|
328
|
+
"""Resolves device lists and LID mappings via usync.
|
|
329
|
+
|
|
330
|
+
Concurrent calls for the same JIDs share one server query.
|
|
331
|
+
|
|
332
|
+
Example:
|
|
333
|
+
>>> api = SignalDeviceSyncApi(logger=logger, query=send_iq)
|
|
334
|
+
>>> await api.sync_device_list(["5511999999999@s.whatsapp.net"])
|
|
335
|
+
"""
|
|
336
|
+
|
|
337
|
+
def __init__(
|
|
338
|
+
self,
|
|
339
|
+
logger: Logger,
|
|
340
|
+
query: QueryFn,
|
|
341
|
+
device_list_store: WaDeviceListStore | None = None,
|
|
342
|
+
default_timeout_ms: float | None = None,
|
|
343
|
+
host_domain: str | None = None,
|
|
344
|
+
generate_sid: Callable[[], Awaitable[str]] | None = None,
|
|
345
|
+
) -> None:
|
|
346
|
+
self._logger = logger
|
|
347
|
+
self._query = query
|
|
348
|
+
self._device_list_store = device_list_store
|
|
349
|
+
self._default_timeout_ms = (
|
|
350
|
+
_SIGNAL_FETCH_KEY_BUNDLES_TIMEOUT_MS
|
|
351
|
+
if default_timeout_ms is None
|
|
352
|
+
else default_timeout_ms
|
|
353
|
+
)
|
|
354
|
+
self._host_domain = (
|
|
355
|
+
_defaults.HOST_DOMAIN if host_domain is None else host_domain
|
|
356
|
+
)
|
|
357
|
+
self._generate_sid = (
|
|
358
|
+
_create_usync_sid_generator() if generate_sid is None else generate_sid
|
|
359
|
+
)
|
|
360
|
+
self._sync_dedup = _PromiseDedup()
|
|
361
|
+
|
|
362
|
+
async def sync_device_list(
|
|
363
|
+
self,
|
|
364
|
+
user_jids: Sequence[str],
|
|
365
|
+
timeout_ms: float | None = None,
|
|
366
|
+
) -> list[SignalDeviceListEntry]:
|
|
367
|
+
"""Refresh the device list for every JID; returns per-user device JIDs."""
|
|
368
|
+
effective_timeout = (
|
|
369
|
+
self._default_timeout_ms if timeout_ms is None else timeout_ms
|
|
370
|
+
)
|
|
371
|
+
normalized_users = self._normalize_users(user_jids)
|
|
372
|
+
if not normalized_users:
|
|
373
|
+
return []
|
|
374
|
+
dedup_key = ",".join(normalized_users)
|
|
375
|
+
|
|
376
|
+
async def run() -> list[SignalDeviceListEntry]:
|
|
377
|
+
return await self._sync_device_list_internal(
|
|
378
|
+
normalized_users, effective_timeout
|
|
379
|
+
)
|
|
380
|
+
|
|
381
|
+
return await self._sync_dedup.run(dedup_key, run)
|
|
382
|
+
|
|
383
|
+
async def _sync_device_list_internal(
|
|
384
|
+
self, normalized_users: list[str], timeout_ms: float
|
|
385
|
+
) -> list[SignalDeviceListEntry]:
|
|
386
|
+
now_ms = _now_ms()
|
|
387
|
+
cached_by_user: dict[str, Sequence[str]] = {}
|
|
388
|
+
if self._device_list_store is not None:
|
|
389
|
+
users_to_query = await self._collect_users_to_query(
|
|
390
|
+
normalized_users, now_ms, cached_by_user, self._device_list_store
|
|
391
|
+
)
|
|
392
|
+
else:
|
|
393
|
+
users_to_query = list(normalized_users)
|
|
394
|
+
|
|
395
|
+
if not users_to_query:
|
|
396
|
+
return [
|
|
397
|
+
SignalDeviceListEntry(jid=jid, device_jids=cached_by_user.get(jid, []))
|
|
398
|
+
for jid in normalized_users
|
|
399
|
+
]
|
|
400
|
+
|
|
401
|
+
sid = await self._generate_sid()
|
|
402
|
+
request = self._make_device_sync_request(users_to_query, sid)
|
|
403
|
+
self._logger.debug(
|
|
404
|
+
"signal device sync request",
|
|
405
|
+
{"users": len(users_to_query), "timeoutMs": timeout_ms},
|
|
406
|
+
)
|
|
407
|
+
response = await self._query(request, timeout_ms)
|
|
408
|
+
parsed = self._parse_device_sync_response(response, users_to_query)
|
|
409
|
+
if self._device_list_store is not None:
|
|
410
|
+
updated_at_ms = _now_ms()
|
|
411
|
+
await self._device_list_store.upsert_user_devices_batch(
|
|
412
|
+
[
|
|
413
|
+
WaDeviceListSnapshot(
|
|
414
|
+
user_jid=entry.jid,
|
|
415
|
+
device_jids=entry.device_jids,
|
|
416
|
+
updated_at_ms=updated_at_ms,
|
|
417
|
+
)
|
|
418
|
+
for entry in parsed
|
|
419
|
+
]
|
|
420
|
+
)
|
|
421
|
+
parsed_by_user = {entry.jid: entry.device_jids for entry in parsed}
|
|
422
|
+
merged: list[SignalDeviceListEntry] = []
|
|
423
|
+
total_devices = 0
|
|
424
|
+
for jid in normalized_users:
|
|
425
|
+
device_jids = parsed_by_user.get(jid, cached_by_user.get(jid, []))
|
|
426
|
+
total_devices += len(device_jids)
|
|
427
|
+
merged.append(SignalDeviceListEntry(jid=jid, device_jids=device_jids))
|
|
428
|
+
self._logger.debug(
|
|
429
|
+
"signal device sync success",
|
|
430
|
+
{"users": len(merged), "devices": total_devices},
|
|
431
|
+
)
|
|
432
|
+
return merged
|
|
433
|
+
|
|
434
|
+
async def query_lids_by_phone_jids(
|
|
435
|
+
self,
|
|
436
|
+
phone_jids: Sequence[str],
|
|
437
|
+
timeout_ms: float | None = None,
|
|
438
|
+
) -> list[SignalLidSyncResult]:
|
|
439
|
+
"""Look up LIDs for phone JIDs; one entry per input with the verdict."""
|
|
440
|
+
effective_timeout = (
|
|
441
|
+
self._default_timeout_ms if timeout_ms is None else timeout_ms
|
|
442
|
+
)
|
|
443
|
+
normalized_phone_jids = self._normalize_users(phone_jids)
|
|
444
|
+
if not normalized_phone_jids:
|
|
445
|
+
return []
|
|
446
|
+
sid = await self._generate_sid()
|
|
447
|
+
request = self._make_lid_sync_request(normalized_phone_jids, sid)
|
|
448
|
+
self._logger.debug(
|
|
449
|
+
"signal lid sync request",
|
|
450
|
+
{"users": len(normalized_phone_jids), "timeoutMs": effective_timeout},
|
|
451
|
+
)
|
|
452
|
+
response = await self._query(request, effective_timeout)
|
|
453
|
+
entries, protocol_error = self._parse_lid_sync_response(
|
|
454
|
+
response, normalized_phone_jids
|
|
455
|
+
)
|
|
456
|
+
entry_by_phone_jid = {entry.jid: entry for entry in entries}
|
|
457
|
+
result: list[SignalLidSyncResult] = []
|
|
458
|
+
found = 0
|
|
459
|
+
for queried_jid in normalized_phone_jids:
|
|
460
|
+
hit = entry_by_phone_jid.get(queried_jid)
|
|
461
|
+
status = hit.status if hit is not None else "unanswered"
|
|
462
|
+
own_error = (
|
|
463
|
+
hit is not None
|
|
464
|
+
and hit.error is not None
|
|
465
|
+
and (hit.error.code is not None or hit.error.text is not None)
|
|
466
|
+
)
|
|
467
|
+
if own_error and hit is not None and hit.error is not None:
|
|
468
|
+
error: SignalLidSyncError | None = hit.error
|
|
469
|
+
elif status == "unanswered" or status == "error":
|
|
470
|
+
error = protocol_error
|
|
471
|
+
else:
|
|
472
|
+
error = None
|
|
473
|
+
phone_jid = queried_jid
|
|
474
|
+
if hit is not None and hit.phone_jid is not None:
|
|
475
|
+
phone_jid = hit.phone_jid
|
|
476
|
+
resolved = SignalLidSyncResult(
|
|
477
|
+
queried_jid=queried_jid,
|
|
478
|
+
phone_jid=phone_jid,
|
|
479
|
+
lid_jid=hit.lid_jid if hit is not None else None,
|
|
480
|
+
exists=status == "in",
|
|
481
|
+
invalid=status == "invalid",
|
|
482
|
+
status=status,
|
|
483
|
+
error=error,
|
|
484
|
+
)
|
|
485
|
+
if resolved.exists:
|
|
486
|
+
found += 1
|
|
487
|
+
result.append(resolved)
|
|
488
|
+
self._logger.debug(
|
|
489
|
+
"signal lid sync success", {"users": len(result), "found": found}
|
|
490
|
+
)
|
|
491
|
+
await self._propagate_alt_user_jids(result)
|
|
492
|
+
return result
|
|
493
|
+
|
|
494
|
+
async def resolve_user_jid_pair(
|
|
495
|
+
self,
|
|
496
|
+
user_jid: str,
|
|
497
|
+
timeout_ms: float | None = None,
|
|
498
|
+
) -> SignalUserJidPair:
|
|
499
|
+
"""Resolve both addressing forms for a 1:1 user JID.
|
|
500
|
+
|
|
501
|
+
Cache-first via the device-list store with a one-shot usync fallback
|
|
502
|
+
for PN inputs. LID inputs have no reverse lookup; unknown forms
|
|
503
|
+
resolve to ``(None, None)``.
|
|
504
|
+
"""
|
|
505
|
+
effective_timeout = (
|
|
506
|
+
self._default_timeout_ms if timeout_ms is None else timeout_ms
|
|
507
|
+
)
|
|
508
|
+
if _is_lid_jid(user_jid):
|
|
509
|
+
return SignalUserJidPair(
|
|
510
|
+
lid_jid=user_jid,
|
|
511
|
+
pn_jid=await self._find_cached_alt_form(user_jid, _is_user_jid),
|
|
512
|
+
)
|
|
513
|
+
if not _is_user_jid(user_jid):
|
|
514
|
+
return SignalUserJidPair(lid_jid=None, pn_jid=None)
|
|
515
|
+
cached_lid = await self._find_cached_alt_form(user_jid, _is_lid_jid)
|
|
516
|
+
if cached_lid is not None:
|
|
517
|
+
return SignalUserJidPair(lid_jid=cached_lid, pn_jid=user_jid)
|
|
518
|
+
try:
|
|
519
|
+
results = await self.query_lids_by_phone_jids([user_jid], effective_timeout)
|
|
520
|
+
match = next(
|
|
521
|
+
(entry for entry in results if entry.queried_jid == user_jid), None
|
|
522
|
+
)
|
|
523
|
+
if match is not None and match.lid_jid is not None:
|
|
524
|
+
return SignalUserJidPair(lid_jid=match.lid_jid, pn_jid=match.phone_jid)
|
|
525
|
+
except Exception as error:
|
|
526
|
+
self._logger.debug(
|
|
527
|
+
"lid usync resolution failed for jid pair",
|
|
528
|
+
{"jid": user_jid, "message": _error_message(error)},
|
|
529
|
+
)
|
|
530
|
+
return SignalUserJidPair(lid_jid=None, pn_jid=user_jid)
|
|
531
|
+
|
|
532
|
+
async def _find_cached_alt_form(
|
|
533
|
+
self, user_jid: str, matches: Callable[[str], bool]
|
|
534
|
+
) -> str | None:
|
|
535
|
+
"""Device-list snapshot form of ``user_jid`` satisfying ``matches``."""
|
|
536
|
+
if self._device_list_store is None:
|
|
537
|
+
return None
|
|
538
|
+
try:
|
|
539
|
+
snapshot = await self._device_list_store.find_by_any_user_jid(user_jid)
|
|
540
|
+
if snapshot is not None:
|
|
541
|
+
if matches(snapshot.user_jid):
|
|
542
|
+
return snapshot.user_jid
|
|
543
|
+
if snapshot.alt_user_jid is not None and matches(snapshot.alt_user_jid):
|
|
544
|
+
return snapshot.alt_user_jid
|
|
545
|
+
except Exception as error:
|
|
546
|
+
self._logger.debug(
|
|
547
|
+
"device-list lookup failed for jid pair",
|
|
548
|
+
{"jid": user_jid, "message": _error_message(error)},
|
|
549
|
+
)
|
|
550
|
+
return None
|
|
551
|
+
|
|
552
|
+
async def _propagate_alt_user_jids(
|
|
553
|
+
self, results: Sequence[SignalLidSyncResult]
|
|
554
|
+
) -> None:
|
|
555
|
+
"""Record resolved LID equivalents on cached device-list snapshots."""
|
|
556
|
+
if self._device_list_store is None or not results:
|
|
557
|
+
return
|
|
558
|
+
now_ms = _now_ms()
|
|
559
|
+
lid_by_queried_jid: dict[str, str] = {}
|
|
560
|
+
queried_jids: list[str] = []
|
|
561
|
+
for entry in results:
|
|
562
|
+
if entry.lid_jid is not None:
|
|
563
|
+
lid_by_queried_jid[entry.queried_jid] = entry.lid_jid
|
|
564
|
+
queried_jids.append(entry.queried_jid)
|
|
565
|
+
if not queried_jids:
|
|
566
|
+
return
|
|
567
|
+
existing = await self._device_list_store.get_user_devices_batch(
|
|
568
|
+
queried_jids, now_ms
|
|
569
|
+
)
|
|
570
|
+
updates: list[WaDeviceListSnapshot] = []
|
|
571
|
+
for index, queried_jid in enumerate(queried_jids):
|
|
572
|
+
snapshot = existing[index]
|
|
573
|
+
if snapshot is None:
|
|
574
|
+
continue
|
|
575
|
+
lid_jid = lid_by_queried_jid.get(queried_jid)
|
|
576
|
+
if lid_jid is None or snapshot.alt_user_jid == lid_jid:
|
|
577
|
+
continue
|
|
578
|
+
updates.append(
|
|
579
|
+
WaDeviceListSnapshot(
|
|
580
|
+
user_jid=snapshot.user_jid,
|
|
581
|
+
device_jids=snapshot.device_jids,
|
|
582
|
+
updated_at_ms=now_ms,
|
|
583
|
+
alt_user_jid=lid_jid,
|
|
584
|
+
)
|
|
585
|
+
)
|
|
586
|
+
if updates:
|
|
587
|
+
await self._device_list_store.upsert_user_devices_batch(updates)
|
|
588
|
+
|
|
589
|
+
async def _collect_users_to_query(
|
|
590
|
+
self,
|
|
591
|
+
normalized_users: list[str],
|
|
592
|
+
now_ms: int,
|
|
593
|
+
cached_by_user: dict[str, Sequence[str]],
|
|
594
|
+
store: WaDeviceListStore,
|
|
595
|
+
) -> list[str]:
|
|
596
|
+
records = await store.get_user_devices_batch(normalized_users, now_ms)
|
|
597
|
+
users_to_query: list[str] = []
|
|
598
|
+
for index, user_jid in enumerate(normalized_users):
|
|
599
|
+
record = records[index]
|
|
600
|
+
if record is None:
|
|
601
|
+
users_to_query.append(user_jid)
|
|
602
|
+
continue
|
|
603
|
+
cached_by_user[user_jid] = record.device_jids
|
|
604
|
+
return users_to_query
|
|
605
|
+
|
|
606
|
+
def _make_device_sync_request(
|
|
607
|
+
self, user_jids: Sequence[str], sid: str
|
|
608
|
+
) -> BinaryNode:
|
|
609
|
+
users = [
|
|
610
|
+
BinaryNode(tag=WA_NODE_TAGS["USER"], attrs={"jid": jid})
|
|
611
|
+
for jid in user_jids
|
|
612
|
+
]
|
|
613
|
+
return _build_usync_iq(
|
|
614
|
+
sid,
|
|
615
|
+
[BinaryNode(tag=WA_NODE_TAGS["DEVICES"], attrs={"version": "2"})],
|
|
616
|
+
users,
|
|
617
|
+
self._host_domain,
|
|
618
|
+
)
|
|
619
|
+
|
|
620
|
+
def _make_lid_sync_request(self, user_jids: Sequence[str], sid: str) -> BinaryNode:
|
|
621
|
+
users: list[BinaryNode] = []
|
|
622
|
+
for jid in user_jids:
|
|
623
|
+
user, _ = _split_jid(jid)
|
|
624
|
+
users.append(
|
|
625
|
+
BinaryNode(
|
|
626
|
+
tag=WA_NODE_TAGS["USER"],
|
|
627
|
+
attrs={"jid": jid},
|
|
628
|
+
content=[
|
|
629
|
+
BinaryNode(
|
|
630
|
+
tag=WA_NODE_TAGS["CONTACT"],
|
|
631
|
+
attrs={},
|
|
632
|
+
content=f"+{user}",
|
|
633
|
+
)
|
|
634
|
+
],
|
|
635
|
+
)
|
|
636
|
+
)
|
|
637
|
+
return _build_usync_iq(
|
|
638
|
+
sid,
|
|
639
|
+
[
|
|
640
|
+
BinaryNode(tag=WA_NODE_TAGS["CONTACT"], attrs={}),
|
|
641
|
+
BinaryNode(tag=WA_NODE_TAGS["LID"], attrs={}),
|
|
642
|
+
],
|
|
643
|
+
users,
|
|
644
|
+
self._host_domain,
|
|
645
|
+
)
|
|
646
|
+
|
|
647
|
+
def _parse_device_sync_response(
|
|
648
|
+
self, node: BinaryNode, requested_users: Sequence[str]
|
|
649
|
+
) -> list[SignalDeviceListEntry]:
|
|
650
|
+
assert_iq_result(node, "signal device sync")
|
|
651
|
+
_log_usync_protocol_errors(
|
|
652
|
+
_parse_usync_result_envelope(node), self._logger, "signal.deviceSync"
|
|
653
|
+
)
|
|
654
|
+
user_nodes = _iterate_usync_users(node)
|
|
655
|
+
if user_nodes is None:
|
|
656
|
+
raise ValueError("signal device sync response missing usync envelope")
|
|
657
|
+
|
|
658
|
+
requested_set = set(requested_users)
|
|
659
|
+
parsed: list[SignalDeviceListEntry] = []
|
|
660
|
+
for user_node in user_nodes:
|
|
661
|
+
user_jid = user_node.attrs.get("jid")
|
|
662
|
+
if not user_jid:
|
|
663
|
+
continue
|
|
664
|
+
normalized_user_jid = self._try_normalize_user_jid(user_jid)
|
|
665
|
+
if normalized_user_jid is None:
|
|
666
|
+
self._logger.debug(
|
|
667
|
+
"signal device sync skipping user node with invalid jid",
|
|
668
|
+
{"jid": user_jid},
|
|
669
|
+
)
|
|
670
|
+
continue
|
|
671
|
+
if normalized_user_jid not in requested_set:
|
|
672
|
+
continue
|
|
673
|
+
parsed.append(
|
|
674
|
+
SignalDeviceListEntry(
|
|
675
|
+
jid=normalized_user_jid,
|
|
676
|
+
device_jids=self._parse_user_device_jids(
|
|
677
|
+
user_node, user_jid, normalized_user_jid
|
|
678
|
+
),
|
|
679
|
+
)
|
|
680
|
+
)
|
|
681
|
+
return parsed
|
|
682
|
+
|
|
683
|
+
def _parse_lid_sync_response(
|
|
684
|
+
self, node: BinaryNode, requested_users: Sequence[str]
|
|
685
|
+
) -> tuple[list[_ParsedLidSyncEntry], SignalLidSyncError | None]:
|
|
686
|
+
assert_iq_result(node, "signal lid sync")
|
|
687
|
+
envelope = _parse_usync_result_envelope(node)
|
|
688
|
+
_log_usync_protocol_errors(envelope, self._logger, "signal.lidSync")
|
|
689
|
+
user_nodes = _iterate_usync_users(node)
|
|
690
|
+
if user_nodes is None:
|
|
691
|
+
raise ValueError("signal lid sync response missing usync envelope")
|
|
692
|
+
|
|
693
|
+
requested_set = set(requested_users)
|
|
694
|
+
parsed: list[_ParsedLidSyncEntry] = []
|
|
695
|
+
lid_user_errors: list[dict[str, str | None]] = []
|
|
696
|
+
for user_node in user_nodes:
|
|
697
|
+
raw_user_jid = user_node.attrs.get("jid")
|
|
698
|
+
resolved_jid = (
|
|
699
|
+
self._try_normalize_user_jid(raw_user_jid)
|
|
700
|
+
if raw_user_jid is not None
|
|
701
|
+
else None
|
|
702
|
+
)
|
|
703
|
+
pn_attr = user_node.attrs.get("pn_jid")
|
|
704
|
+
pn_jid = (
|
|
705
|
+
self._try_normalize_user_jid(pn_attr) if pn_attr is not None else None
|
|
706
|
+
)
|
|
707
|
+
phone_jid = pn_jid if pn_jid is not None else resolved_jid
|
|
708
|
+
|
|
709
|
+
lid_node = find_node_child(user_node, WA_NODE_TAGS["LID"])
|
|
710
|
+
lid_error_node = (
|
|
711
|
+
find_node_child(lid_node, WA_NODE_TAGS["ERROR"])
|
|
712
|
+
if lid_node is not None
|
|
713
|
+
else None
|
|
714
|
+
)
|
|
715
|
+
if lid_error_node is not None:
|
|
716
|
+
error_jid = resolved_jid if resolved_jid is not None else raw_user_jid
|
|
717
|
+
lid_user_errors.append(
|
|
718
|
+
{
|
|
719
|
+
"jid": error_jid,
|
|
720
|
+
"code": lid_error_node.attrs.get("code"),
|
|
721
|
+
"text": lid_error_node.attrs.get("text"),
|
|
722
|
+
}
|
|
723
|
+
)
|
|
724
|
+
lid_error = (
|
|
725
|
+
_to_lid_sync_error(lid_error_node)
|
|
726
|
+
if lid_error_node is not None
|
|
727
|
+
else None
|
|
728
|
+
)
|
|
729
|
+
lid_jid: str | None = None
|
|
730
|
+
if lid_error_node is None and lid_node is not None:
|
|
731
|
+
lid_val = lid_node.attrs.get("val")
|
|
732
|
+
if lid_val is not None:
|
|
733
|
+
lid_jid = self._try_normalize_user_jid(lid_val)
|
|
734
|
+
|
|
735
|
+
contact_nodes = get_node_children_by_tag(user_node, WA_NODE_TAGS["CONTACT"])
|
|
736
|
+
matched = False
|
|
737
|
+
for contact_node in contact_nodes:
|
|
738
|
+
input_jid = self._recover_contact_jid(contact_node)
|
|
739
|
+
if input_jid is None or input_jid not in requested_set:
|
|
740
|
+
continue
|
|
741
|
+
matched = True
|
|
742
|
+
status, outcome_error = self._resolve_lid_sync_outcome(
|
|
743
|
+
contact_node, input_jid, lid_jid, lid_error
|
|
744
|
+
)
|
|
745
|
+
parsed.append(
|
|
746
|
+
_ParsedLidSyncEntry(
|
|
747
|
+
jid=input_jid,
|
|
748
|
+
lid_jid=lid_jid,
|
|
749
|
+
phone_jid=phone_jid if phone_jid is not None else input_jid,
|
|
750
|
+
status=status,
|
|
751
|
+
error=outcome_error,
|
|
752
|
+
)
|
|
753
|
+
)
|
|
754
|
+
if matched:
|
|
755
|
+
continue
|
|
756
|
+
|
|
757
|
+
if resolved_jid is None:
|
|
758
|
+
self._logger.debug(
|
|
759
|
+
"signal lid sync skipping user node with invalid jid",
|
|
760
|
+
{"jid": raw_user_jid},
|
|
761
|
+
)
|
|
762
|
+
continue
|
|
763
|
+
requested_key: str | None = None
|
|
764
|
+
if resolved_jid in requested_set:
|
|
765
|
+
requested_key = resolved_jid
|
|
766
|
+
elif pn_jid is not None and pn_jid in requested_set:
|
|
767
|
+
requested_key = pn_jid
|
|
768
|
+
if requested_key is None:
|
|
769
|
+
self._logger.debug(
|
|
770
|
+
"signal lid sync unmatched user (no contact echo)",
|
|
771
|
+
{"jid": resolved_jid, "pnJid": pn_jid},
|
|
772
|
+
)
|
|
773
|
+
continue
|
|
774
|
+
fallback_contact_node = find_node_child(user_node, WA_NODE_TAGS["CONTACT"])
|
|
775
|
+
status, outcome_error = self._resolve_lid_sync_outcome(
|
|
776
|
+
fallback_contact_node, requested_key, lid_jid, lid_error
|
|
777
|
+
)
|
|
778
|
+
parsed.append(
|
|
779
|
+
_ParsedLidSyncEntry(
|
|
780
|
+
jid=requested_key,
|
|
781
|
+
lid_jid=lid_jid,
|
|
782
|
+
phone_jid=phone_jid if phone_jid is not None else requested_key,
|
|
783
|
+
status=status,
|
|
784
|
+
error=outcome_error,
|
|
785
|
+
)
|
|
786
|
+
)
|
|
787
|
+
if lid_user_errors:
|
|
788
|
+
self._logger.warn(
|
|
789
|
+
"signal lid sync user errors",
|
|
790
|
+
{
|
|
791
|
+
"droppedCount": len(lid_user_errors),
|
|
792
|
+
"totalExpected": len(requested_users),
|
|
793
|
+
"sample": lid_user_errors[:3],
|
|
794
|
+
},
|
|
795
|
+
)
|
|
796
|
+
contact_protocol_error = envelope.errors.get(WA_NODE_TAGS["CONTACT"])
|
|
797
|
+
if contact_protocol_error is None:
|
|
798
|
+
contact_protocol_error = envelope.errors.get(WA_NODE_TAGS["LID"])
|
|
799
|
+
protocol_error = (
|
|
800
|
+
_to_lid_sync_protocol_error(contact_protocol_error)
|
|
801
|
+
if contact_protocol_error is not None
|
|
802
|
+
else None
|
|
803
|
+
)
|
|
804
|
+
return (parsed, protocol_error)
|
|
805
|
+
|
|
806
|
+
def _recover_contact_jid(self, contact_node: BinaryNode) -> str | None:
|
|
807
|
+
"""Recover the queried phone JID from a ``<contact>`` echo."""
|
|
808
|
+
echoed = get_node_text_content(contact_node)
|
|
809
|
+
if not echoed:
|
|
810
|
+
return None
|
|
811
|
+
try:
|
|
812
|
+
return parse_phone_jid(echoed)
|
|
813
|
+
except ValueError:
|
|
814
|
+
return None
|
|
815
|
+
|
|
816
|
+
def _resolve_lid_sync_outcome(
|
|
817
|
+
self,
|
|
818
|
+
contact_node: BinaryNode | None,
|
|
819
|
+
user_jid: str,
|
|
820
|
+
lid_jid: str | None,
|
|
821
|
+
lid_error: SignalLidSyncError | None,
|
|
822
|
+
) -> tuple[SignalLidSyncStatus, SignalLidSyncError | None]:
|
|
823
|
+
"""Classify one lookup from its ``<contact>`` node."""
|
|
824
|
+
if contact_node is None:
|
|
825
|
+
if lid_jid is not None:
|
|
826
|
+
return ("in", None)
|
|
827
|
+
return (
|
|
828
|
+
("error", lid_error) if lid_error is not None else ("unanswered", None)
|
|
829
|
+
)
|
|
830
|
+
if contact_node.attrs.get("type") == "invalid":
|
|
831
|
+
return ("invalid", None)
|
|
832
|
+
error_node = find_node_child(contact_node, WA_NODE_TAGS["ERROR"])
|
|
833
|
+
if error_node is not None:
|
|
834
|
+
self._logger.warn(
|
|
835
|
+
"signal lid sync contact error",
|
|
836
|
+
{
|
|
837
|
+
"jid": user_jid,
|
|
838
|
+
"code": error_node.attrs.get("code"),
|
|
839
|
+
"text": error_node.attrs.get("text"),
|
|
840
|
+
},
|
|
841
|
+
)
|
|
842
|
+
return ("error", _to_lid_sync_error(error_node))
|
|
843
|
+
if contact_node.attrs.get("type") == "in":
|
|
844
|
+
return ("in", lid_error)
|
|
845
|
+
if contact_node.attrs.get("type") == "out":
|
|
846
|
+
return ("out", None)
|
|
847
|
+
return ("error", lid_error) if lid_error is not None else ("unanswered", None)
|
|
848
|
+
|
|
849
|
+
def _parse_user_device_jids(
|
|
850
|
+
self, user_node: BinaryNode, raw_user_jid: str, normalized_user_jid: str
|
|
851
|
+
) -> list[str]:
|
|
852
|
+
devices_node = find_node_child(user_node, WA_NODE_TAGS["DEVICES"])
|
|
853
|
+
if devices_node is None:
|
|
854
|
+
return []
|
|
855
|
+
error_node = find_node_child(devices_node, WA_NODE_TAGS["ERROR"])
|
|
856
|
+
if error_node is not None:
|
|
857
|
+
self._logger.warn(
|
|
858
|
+
"signal device sync user error",
|
|
859
|
+
{
|
|
860
|
+
"jid": normalized_user_jid,
|
|
861
|
+
"code": error_node.attrs.get("code"),
|
|
862
|
+
"text": error_node.attrs.get("text"),
|
|
863
|
+
},
|
|
864
|
+
)
|
|
865
|
+
return []
|
|
866
|
+
|
|
867
|
+
device_list_node = find_node_child(devices_node, "device-list")
|
|
868
|
+
if device_list_node is None:
|
|
869
|
+
return []
|
|
870
|
+
|
|
871
|
+
parsed_user, parsed_server = _split_jid(normalized_user_jid)
|
|
872
|
+
raw_at_index = raw_user_jid.find("@")
|
|
873
|
+
raw_server = (
|
|
874
|
+
raw_user_jid[raw_at_index + 1 :]
|
|
875
|
+
if 1 <= raw_at_index < len(raw_user_jid) - 1
|
|
876
|
+
else parsed_server
|
|
877
|
+
)
|
|
878
|
+
device_jids: list[str] = []
|
|
879
|
+
seen: set[str] = set()
|
|
880
|
+
for device_node in get_node_children_by_tag(
|
|
881
|
+
device_list_node, WA_NODE_TAGS["DEVICE"]
|
|
882
|
+
):
|
|
883
|
+
device_id = _parse_js_int(device_node.attrs.get("id", ""))
|
|
884
|
+
if device_id is None or device_id < 0 or abs(device_id) > 2**53 - 1:
|
|
885
|
+
continue
|
|
886
|
+
is_hosted = device_id == _defaults.HOSTED_DEVICE_ID or (
|
|
887
|
+
device_node.attrs.get("is_hosted") == "true"
|
|
888
|
+
)
|
|
889
|
+
device_jid = _build_device_jid(
|
|
890
|
+
parsed_user, parsed_server, device_id, raw_server, is_hosted
|
|
891
|
+
)
|
|
892
|
+
if device_jid not in seen:
|
|
893
|
+
seen.add(device_jid)
|
|
894
|
+
device_jids.append(device_jid)
|
|
895
|
+
return device_jids
|
|
896
|
+
|
|
897
|
+
def _normalize_users(self, user_jids: Sequence[str]) -> list[str]:
|
|
898
|
+
normalized: list[str] = []
|
|
899
|
+
dedup: set[str] = set()
|
|
900
|
+
for jid in user_jids:
|
|
901
|
+
normalized_jid = _to_user_jid(
|
|
902
|
+
jid, canonicalize=True, host_domain=self._host_domain
|
|
903
|
+
)
|
|
904
|
+
if normalized_jid in dedup:
|
|
905
|
+
continue
|
|
906
|
+
dedup.add(normalized_jid)
|
|
907
|
+
normalized.append(normalized_jid)
|
|
908
|
+
return normalized
|
|
909
|
+
|
|
910
|
+
def _try_normalize_user_jid(self, jid: str) -> str | None:
|
|
911
|
+
"""Canonicalize a user JID, returning ``None`` for malformed input."""
|
|
912
|
+
try:
|
|
913
|
+
return _to_user_jid(jid, canonicalize=True, host_domain=self._host_domain)
|
|
914
|
+
except ValueError:
|
|
915
|
+
return None
|