zapind 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.
- zapind/__init__.py +148 -0
- zapind/client.py +532 -0
- zapind/core.py +376 -0
- zapind/errors.py +195 -0
- zapind/mappers.py +285 -0
- zapind/models.py +613 -0
- zapind/py.typed +0 -0
- zapind/services.py +672 -0
- zapind/storage.py +214 -0
- zapind/transport.py +558 -0
- zapind-0.1.0.dist-info/METADATA +91 -0
- zapind-0.1.0.dist-info/RECORD +14 -0
- zapind-0.1.0.dist-info/WHEEL +4 -0
- zapind-0.1.0.dist-info/licenses/LICENSE +166 -0
zapind/__init__.py
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
from .client import DEFAULT_USER_AGENT, EventsNamespace, Zapind
|
|
2
|
+
from .core import RateLimiter, RedactingLogger, RetryOptions, redact_sensitive
|
|
3
|
+
from .errors import (
|
|
4
|
+
APIError,
|
|
5
|
+
AuthenticationError,
|
|
6
|
+
NetworkError,
|
|
7
|
+
NotFoundError,
|
|
8
|
+
PermissionError,
|
|
9
|
+
RateLimitError,
|
|
10
|
+
SessionError,
|
|
11
|
+
ValidationError,
|
|
12
|
+
ZapindError,
|
|
13
|
+
)
|
|
14
|
+
from .models import (
|
|
15
|
+
AccountSettings,
|
|
16
|
+
Attachment,
|
|
17
|
+
AuthRequiredEvent,
|
|
18
|
+
ClientStatus,
|
|
19
|
+
CloseReason,
|
|
20
|
+
ConnectionEvent,
|
|
21
|
+
Contact,
|
|
22
|
+
Conversation,
|
|
23
|
+
Gender,
|
|
24
|
+
Group,
|
|
25
|
+
GroupMember,
|
|
26
|
+
GroupSettings,
|
|
27
|
+
GroupSummary,
|
|
28
|
+
GroupType,
|
|
29
|
+
GroupUpdateEvent,
|
|
30
|
+
LastOnlineInfo,
|
|
31
|
+
MediaBuffer,
|
|
32
|
+
MediaInput,
|
|
33
|
+
Mention,
|
|
34
|
+
Message,
|
|
35
|
+
MessagePage,
|
|
36
|
+
MessageQuote,
|
|
37
|
+
MessageSenderRef,
|
|
38
|
+
MessageStyle,
|
|
39
|
+
OnlineStatus,
|
|
40
|
+
PinnedConversations,
|
|
41
|
+
Profile,
|
|
42
|
+
QRCodeData,
|
|
43
|
+
QRScannedData,
|
|
44
|
+
Reaction,
|
|
45
|
+
ReactionEvent,
|
|
46
|
+
SeenEvent,
|
|
47
|
+
SendMessageContent,
|
|
48
|
+
SendMessagePayload,
|
|
49
|
+
SendMessageReceipt,
|
|
50
|
+
SessionCredentials,
|
|
51
|
+
SessionInfo,
|
|
52
|
+
StoredSessionRecord,
|
|
53
|
+
TextStyle,
|
|
54
|
+
ThreadTarget,
|
|
55
|
+
ThreadType,
|
|
56
|
+
TypingEvent,
|
|
57
|
+
UndoEvent,
|
|
58
|
+
UnreadMark,
|
|
59
|
+
UnreadMarks,
|
|
60
|
+
UploadedMedia,
|
|
61
|
+
Urgency,
|
|
62
|
+
User,
|
|
63
|
+
UserUpdateEvent,
|
|
64
|
+
)
|
|
65
|
+
from .storage import (
|
|
66
|
+
EncryptedFileSessionStore,
|
|
67
|
+
FileSessionStore,
|
|
68
|
+
MemorySessionStore,
|
|
69
|
+
SessionStore,
|
|
70
|
+
)
|
|
71
|
+
from .transport import NodeBridgeTransport, TransportAdapter
|
|
72
|
+
|
|
73
|
+
__version__ = "0.1.0"
|
|
74
|
+
|
|
75
|
+
__all__ = [
|
|
76
|
+
"__version__",
|
|
77
|
+
"DEFAULT_USER_AGENT",
|
|
78
|
+
"Zapind",
|
|
79
|
+
"EventsNamespace",
|
|
80
|
+
"ZapindError",
|
|
81
|
+
"AuthenticationError",
|
|
82
|
+
"SessionError",
|
|
83
|
+
"NetworkError",
|
|
84
|
+
"RateLimitError",
|
|
85
|
+
"ValidationError",
|
|
86
|
+
"PermissionError",
|
|
87
|
+
"NotFoundError",
|
|
88
|
+
"APIError",
|
|
89
|
+
"ThreadType",
|
|
90
|
+
"ClientStatus",
|
|
91
|
+
"Gender",
|
|
92
|
+
"GroupType",
|
|
93
|
+
"CloseReason",
|
|
94
|
+
"TextStyle",
|
|
95
|
+
"Urgency",
|
|
96
|
+
"Reaction",
|
|
97
|
+
"User",
|
|
98
|
+
"Profile",
|
|
99
|
+
"Contact",
|
|
100
|
+
"Group",
|
|
101
|
+
"Conversation",
|
|
102
|
+
"Message",
|
|
103
|
+
"SessionCredentials",
|
|
104
|
+
"SessionInfo",
|
|
105
|
+
"StoredSessionRecord",
|
|
106
|
+
"QRCodeData",
|
|
107
|
+
"QRScannedData",
|
|
108
|
+
"MediaBuffer",
|
|
109
|
+
"MediaInput",
|
|
110
|
+
"UploadedMedia",
|
|
111
|
+
"Attachment",
|
|
112
|
+
"Mention",
|
|
113
|
+
"MessageStyle",
|
|
114
|
+
"MessageQuote",
|
|
115
|
+
"SendMessagePayload",
|
|
116
|
+
"SendMessageContent",
|
|
117
|
+
"SendMessageReceipt",
|
|
118
|
+
"MessagePage",
|
|
119
|
+
"MessageSenderRef",
|
|
120
|
+
"GroupSummary",
|
|
121
|
+
"GroupSettings",
|
|
122
|
+
"GroupMember",
|
|
123
|
+
"OnlineStatus",
|
|
124
|
+
"LastOnlineInfo",
|
|
125
|
+
"AccountSettings",
|
|
126
|
+
"PinnedConversations",
|
|
127
|
+
"UnreadMark",
|
|
128
|
+
"UnreadMarks",
|
|
129
|
+
"ThreadTarget",
|
|
130
|
+
"ConnectionEvent",
|
|
131
|
+
"ReactionEvent",
|
|
132
|
+
"TypingEvent",
|
|
133
|
+
"SeenEvent",
|
|
134
|
+
"UndoEvent",
|
|
135
|
+
"GroupUpdateEvent",
|
|
136
|
+
"UserUpdateEvent",
|
|
137
|
+
"AuthRequiredEvent",
|
|
138
|
+
"SessionStore",
|
|
139
|
+
"MemorySessionStore",
|
|
140
|
+
"FileSessionStore",
|
|
141
|
+
"EncryptedFileSessionStore",
|
|
142
|
+
"RetryOptions",
|
|
143
|
+
"RateLimiter",
|
|
144
|
+
"RedactingLogger",
|
|
145
|
+
"redact_sensitive",
|
|
146
|
+
"TransportAdapter",
|
|
147
|
+
"NodeBridgeTransport",
|
|
148
|
+
]
|
zapind/client.py
ADDED
|
@@ -0,0 +1,532 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
import time
|
|
5
|
+
from datetime import datetime, timezone
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any, Callable
|
|
8
|
+
|
|
9
|
+
from .core import (
|
|
10
|
+
EventBus,
|
|
11
|
+
InFlightDeduplicator,
|
|
12
|
+
PolicyExecutor,
|
|
13
|
+
RateLimiter,
|
|
14
|
+
RedactingLogger,
|
|
15
|
+
RetryOptions,
|
|
16
|
+
ThreadTypeRegistry,
|
|
17
|
+
TTLCache,
|
|
18
|
+
)
|
|
19
|
+
from .errors import AuthenticationError, SessionError, ValidationError, normalize_error
|
|
20
|
+
from .mappers import map_message_kwargs, map_profile_kwargs
|
|
21
|
+
from .models import (
|
|
22
|
+
AuthRequiredEvent,
|
|
23
|
+
ClientStatus,
|
|
24
|
+
CloseReason,
|
|
25
|
+
ConnectionEvent,
|
|
26
|
+
Conversation,
|
|
27
|
+
EventHandler,
|
|
28
|
+
Group,
|
|
29
|
+
GroupUpdateEvent,
|
|
30
|
+
Message,
|
|
31
|
+
MessagePage,
|
|
32
|
+
QRCodeData,
|
|
33
|
+
QRScannedData,
|
|
34
|
+
Reaction,
|
|
35
|
+
ReactionEvent,
|
|
36
|
+
SeenEvent,
|
|
37
|
+
SendMessageContent,
|
|
38
|
+
SendMessageReceipt,
|
|
39
|
+
SessionCredentials,
|
|
40
|
+
SessionInfo,
|
|
41
|
+
StoredSessionRecord,
|
|
42
|
+
ThreadType,
|
|
43
|
+
TypingEvent,
|
|
44
|
+
UndoEvent,
|
|
45
|
+
UnsubscribeFn,
|
|
46
|
+
User,
|
|
47
|
+
UserUpdateEvent,
|
|
48
|
+
)
|
|
49
|
+
from .services import (
|
|
50
|
+
AccountService,
|
|
51
|
+
ContactsService,
|
|
52
|
+
ConversationsService,
|
|
53
|
+
GroupsService,
|
|
54
|
+
MediaService,
|
|
55
|
+
MessagesService,
|
|
56
|
+
ServiceDeps,
|
|
57
|
+
SettingsService,
|
|
58
|
+
UsersService,
|
|
59
|
+
)
|
|
60
|
+
from .storage import FileSessionStore, MemorySessionStore, SessionStore
|
|
61
|
+
from .transport import NodeBridgeTransport, TransportAdapter
|
|
62
|
+
|
|
63
|
+
DEFAULT_USER_AGENT = (
|
|
64
|
+
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:133.0) Gecko/20100101 Firefox/133.0"
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class _ClientModelActions:
|
|
69
|
+
def __init__(self, client: Zapind) -> None:
|
|
70
|
+
self._client = client
|
|
71
|
+
|
|
72
|
+
async def send_message(
|
|
73
|
+
self, target_id: str, content: SendMessageContent, thread_type: ThreadType
|
|
74
|
+
) -> SendMessageReceipt:
|
|
75
|
+
return await self._client.messages.send(target_id, content, thread_type=thread_type)
|
|
76
|
+
|
|
77
|
+
async def reply_message(
|
|
78
|
+
self, message: Message, content: SendMessageContent
|
|
79
|
+
) -> SendMessageReceipt:
|
|
80
|
+
return await self._client.messages.reply(message, content)
|
|
81
|
+
|
|
82
|
+
async def react_message(self, message: Message, reaction: Reaction | str) -> None:
|
|
83
|
+
await self._client.messages.react(message, reaction)
|
|
84
|
+
|
|
85
|
+
async def undo_message(self, message: Message) -> None:
|
|
86
|
+
await self._client.messages.undo(message)
|
|
87
|
+
|
|
88
|
+
async def delete_message(self, message: Message, only_me: bool = True) -> None:
|
|
89
|
+
await self._client.messages.delete(message, only_me=only_me)
|
|
90
|
+
|
|
91
|
+
async def mark_seen(self, messages: list[Message]) -> None:
|
|
92
|
+
await self._client.messages.mark_seen(messages)
|
|
93
|
+
|
|
94
|
+
async def get_group_messages(self, group_id: str, count: int | None = None) -> MessagePage:
|
|
95
|
+
return await self._client.conversations.get_messages(group_id, count)
|
|
96
|
+
|
|
97
|
+
async def send_typing(self, thread_id: str, thread_type: ThreadType) -> None:
|
|
98
|
+
await self._client.conversations.send_typing(Conversation(thread_id, thread_type, self))
|
|
99
|
+
|
|
100
|
+
async def pin_conversation(
|
|
101
|
+
self, thread_id: str, pinned: bool, thread_type: ThreadType
|
|
102
|
+
) -> None:
|
|
103
|
+
await self._client.conversations.pin(Conversation(thread_id, thread_type, self), pinned)
|
|
104
|
+
|
|
105
|
+
async def mute_conversation(
|
|
106
|
+
self, thread_id: str, duration_seconds: int, thread_type: ThreadType
|
|
107
|
+
) -> None:
|
|
108
|
+
await self._client.conversations.mute(
|
|
109
|
+
Conversation(thread_id, thread_type, self), duration_seconds
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
async def send_friend_request(self, user_id: str, message: str) -> None:
|
|
113
|
+
await self._client.contacts.send_request(user_id, message)
|
|
114
|
+
|
|
115
|
+
async def block_user(self, user_id: str) -> None:
|
|
116
|
+
await self._client.contacts.block(user_id)
|
|
117
|
+
|
|
118
|
+
async def unblock_user(self, user_id: str) -> None:
|
|
119
|
+
await self._client.contacts.unblock(user_id)
|
|
120
|
+
|
|
121
|
+
async def set_friend_alias(self, user_id: str, alias: str) -> None:
|
|
122
|
+
await self._client.contacts.set_alias(user_id, alias)
|
|
123
|
+
|
|
124
|
+
async def remove_friend(self, user_id: str) -> None:
|
|
125
|
+
await self._client.contacts.remove(user_id)
|
|
126
|
+
|
|
127
|
+
async def add_group_members(self, group_id: str, user_ids: list[str]) -> None:
|
|
128
|
+
await self._client.groups.add_members(group_id, user_ids)
|
|
129
|
+
|
|
130
|
+
async def remove_group_members(self, group_id: str, user_ids: list[str]) -> None:
|
|
131
|
+
await self._client.groups.remove_members(group_id, user_ids)
|
|
132
|
+
|
|
133
|
+
async def rename_group(self, group_id: str, name: str) -> None:
|
|
134
|
+
await self._client.groups.rename(group_id, name)
|
|
135
|
+
|
|
136
|
+
async def leave_group(self, group_id: str) -> None:
|
|
137
|
+
await self._client.groups.leave(group_id)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
class EventsNamespace:
|
|
141
|
+
def __init__(self, client: Zapind) -> None:
|
|
142
|
+
self._client = client
|
|
143
|
+
|
|
144
|
+
def on(self, event: str, handler: EventHandler | None = None) -> Any:
|
|
145
|
+
return self._client.on(event, handler)
|
|
146
|
+
|
|
147
|
+
def once(self, event: str, handler: EventHandler) -> UnsubscribeFn:
|
|
148
|
+
return self._client.once(event, handler)
|
|
149
|
+
|
|
150
|
+
def off(self, event: str, handler: EventHandler) -> None:
|
|
151
|
+
self._client.off(event, handler)
|
|
152
|
+
|
|
153
|
+
async def start(self, *, retry_on_close: bool = False) -> None:
|
|
154
|
+
await self._client.start_listening(retry_on_close=retry_on_close)
|
|
155
|
+
|
|
156
|
+
async def stop(self) -> None:
|
|
157
|
+
await self._client.stop_listening()
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
class Zapind:
|
|
161
|
+
"""Async-first, multi-account, contextual Zalo SDK client for Python."""
|
|
162
|
+
|
|
163
|
+
def __init__(
|
|
164
|
+
self,
|
|
165
|
+
*,
|
|
166
|
+
session: str | Path | SessionStore | None = None,
|
|
167
|
+
timeout: float = 15.0,
|
|
168
|
+
qr_timeout: float = 180.0,
|
|
169
|
+
retry: RetryOptions | None = None,
|
|
170
|
+
rate_limit: RateLimiter | bool = True,
|
|
171
|
+
cache_ttl: float = 60.0,
|
|
172
|
+
max_cache_entries: int = 500,
|
|
173
|
+
logger: logging.Logger | None = None,
|
|
174
|
+
debug: bool = False,
|
|
175
|
+
self_listen: bool = False,
|
|
176
|
+
user_agent: str = DEFAULT_USER_AGENT,
|
|
177
|
+
language: str = "vi",
|
|
178
|
+
transport: TransportAdapter | None = None,
|
|
179
|
+
) -> None:
|
|
180
|
+
if timeout <= 0:
|
|
181
|
+
raise ValidationError("timeout must be a positive number")
|
|
182
|
+
if qr_timeout <= 0:
|
|
183
|
+
raise ValidationError("qr_timeout must be a positive number")
|
|
184
|
+
|
|
185
|
+
self._qr_timeout = qr_timeout
|
|
186
|
+
self._self_listen = self_listen
|
|
187
|
+
self._user_agent = user_agent
|
|
188
|
+
self._language = language
|
|
189
|
+
self._logger = RedactingLogger(logger, debug=debug)
|
|
190
|
+
|
|
191
|
+
if isinstance(session, (str, Path)):
|
|
192
|
+
self._store: SessionStore = FileSessionStore(session)
|
|
193
|
+
elif session is not None:
|
|
194
|
+
self._store = session
|
|
195
|
+
else:
|
|
196
|
+
self._store = MemorySessionStore()
|
|
197
|
+
|
|
198
|
+
self._transport: TransportAdapter = transport or NodeBridgeTransport()
|
|
199
|
+
limiter: RateLimiter | None
|
|
200
|
+
if rate_limit is False:
|
|
201
|
+
limiter = None
|
|
202
|
+
elif isinstance(rate_limit, RateLimiter):
|
|
203
|
+
limiter = rate_limit
|
|
204
|
+
else:
|
|
205
|
+
limiter = RateLimiter(max_requests_per_second=5.0, burst=10)
|
|
206
|
+
|
|
207
|
+
self._executor = PolicyExecutor(
|
|
208
|
+
default_timeout=timeout,
|
|
209
|
+
retry_options=retry or RetryOptions(),
|
|
210
|
+
rate_limiter=limiter,
|
|
211
|
+
logger=self._logger,
|
|
212
|
+
)
|
|
213
|
+
self._event_bus = EventBus(self._logger)
|
|
214
|
+
self._registry = ThreadTypeRegistry(groups_ttl=max(cache_ttl, 300.0))
|
|
215
|
+
self._user_cache: TTLCache[str, User] = TTLCache(
|
|
216
|
+
max_entries=max_cache_entries, default_ttl=cache_ttl
|
|
217
|
+
)
|
|
218
|
+
self._group_cache: TTLCache[str, Group] = TTLCache(
|
|
219
|
+
max_entries=max(1, max_cache_entries // 2), default_ttl=cache_ttl
|
|
220
|
+
)
|
|
221
|
+
self._dedup = InFlightDeduplicator()
|
|
222
|
+
self._actions = _ClientModelActions(self)
|
|
223
|
+
|
|
224
|
+
deps = ServiceDeps(
|
|
225
|
+
transport=self._transport,
|
|
226
|
+
executor=self._executor,
|
|
227
|
+
registry=self._registry,
|
|
228
|
+
actions=self._actions,
|
|
229
|
+
user_cache=self._user_cache,
|
|
230
|
+
group_cache=self._group_cache,
|
|
231
|
+
dedup=self._dedup,
|
|
232
|
+
)
|
|
233
|
+
|
|
234
|
+
self.account = AccountService(deps)
|
|
235
|
+
self.users = UsersService(deps)
|
|
236
|
+
self.contacts = ContactsService(deps)
|
|
237
|
+
self.groups = GroupsService(deps)
|
|
238
|
+
self.conversations = ConversationsService(deps)
|
|
239
|
+
self.messages = MessagesService(deps)
|
|
240
|
+
self.media = MediaService(deps, self.messages)
|
|
241
|
+
self.settings = SettingsService(deps)
|
|
242
|
+
self.events = EventsNamespace(self)
|
|
243
|
+
|
|
244
|
+
self._status = ClientStatus.IDLE
|
|
245
|
+
self._session_info: SessionInfo | None = None
|
|
246
|
+
self._listening = False
|
|
247
|
+
|
|
248
|
+
async def __aenter__(self) -> Zapind:
|
|
249
|
+
return self
|
|
250
|
+
|
|
251
|
+
async def __aexit__(self, exc_type: Any, exc: Any, tb: Any) -> None:
|
|
252
|
+
await self.logout(clear_session=False)
|
|
253
|
+
|
|
254
|
+
def get_status(self) -> ClientStatus:
|
|
255
|
+
return self._status
|
|
256
|
+
|
|
257
|
+
def get_session(self) -> SessionInfo | None:
|
|
258
|
+
return self._session_info
|
|
259
|
+
|
|
260
|
+
def is_authenticated(self) -> bool:
|
|
261
|
+
return (
|
|
262
|
+
self._status == ClientStatus.CONNECTED
|
|
263
|
+
and self._transport.is_connected()
|
|
264
|
+
and self._session_info is not None
|
|
265
|
+
)
|
|
266
|
+
|
|
267
|
+
async def login(
|
|
268
|
+
self,
|
|
269
|
+
*,
|
|
270
|
+
credentials: SessionCredentials | None = None,
|
|
271
|
+
on_qr_code: Callable[[QRCodeData], Any] | None = None,
|
|
272
|
+
on_scanned: Callable[[QRScannedData], Any] | None = None,
|
|
273
|
+
on_expired: Callable[[], Any] | None = None,
|
|
274
|
+
on_declined: Callable[[], Any] | None = None,
|
|
275
|
+
timeout: float | None = None,
|
|
276
|
+
force_qr: bool = False,
|
|
277
|
+
) -> SessionInfo:
|
|
278
|
+
if credentials is not None:
|
|
279
|
+
return await self._auth_with_credentials(credentials)
|
|
280
|
+
|
|
281
|
+
if not force_qr:
|
|
282
|
+
stored = await self._store.load()
|
|
283
|
+
if stored and stored.credentials.cookie:
|
|
284
|
+
try:
|
|
285
|
+
return await self._auth_with_credentials(stored.credentials)
|
|
286
|
+
except Exception as err:
|
|
287
|
+
normalized = normalize_error(err, "Saved session expired or invalid")
|
|
288
|
+
self._event_bus.emit(
|
|
289
|
+
"auth.required",
|
|
290
|
+
AuthRequiredEvent(reason="session_expired", error=normalized),
|
|
291
|
+
)
|
|
292
|
+
else:
|
|
293
|
+
self._event_bus.emit("auth.required", AuthRequiredEvent(reason="no_session"))
|
|
294
|
+
|
|
295
|
+
return await self._login_with_qr(
|
|
296
|
+
on_qr_code=on_qr_code,
|
|
297
|
+
on_scanned=on_scanned,
|
|
298
|
+
on_expired=on_expired,
|
|
299
|
+
on_declined=on_declined,
|
|
300
|
+
timeout=timeout,
|
|
301
|
+
)
|
|
302
|
+
|
|
303
|
+
async def _build_and_persist_session(self, credentials: SessionCredentials) -> SessionInfo:
|
|
304
|
+
account_id = ""
|
|
305
|
+
display_name = ""
|
|
306
|
+
avatar_url = ""
|
|
307
|
+
try:
|
|
308
|
+
raw = await self._executor.execute(
|
|
309
|
+
self._transport.fetch_account_info,
|
|
310
|
+
operation="auth.fetch_profile",
|
|
311
|
+
idempotent=True,
|
|
312
|
+
)
|
|
313
|
+
if raw:
|
|
314
|
+
p = map_profile_kwargs(raw)
|
|
315
|
+
account_id = p["id"]
|
|
316
|
+
display_name = p["display_name"]
|
|
317
|
+
avatar_url = p["avatar_url"]
|
|
318
|
+
except Exception:
|
|
319
|
+
pass
|
|
320
|
+
|
|
321
|
+
if not account_id:
|
|
322
|
+
account_id = self._transport.get_own_id()
|
|
323
|
+
|
|
324
|
+
info = SessionInfo(
|
|
325
|
+
account_id=account_id,
|
|
326
|
+
display_name=display_name,
|
|
327
|
+
avatar_url=avatar_url,
|
|
328
|
+
status=ClientStatus.CONNECTED,
|
|
329
|
+
authenticated_at=datetime.now(tz=timezone.utc),
|
|
330
|
+
)
|
|
331
|
+
self._session_info = info
|
|
332
|
+
self._status = ClientStatus.CONNECTED
|
|
333
|
+
self._registry.register_user(account_id)
|
|
334
|
+
|
|
335
|
+
await self._store.save(
|
|
336
|
+
StoredSessionRecord(
|
|
337
|
+
version=1,
|
|
338
|
+
saved_at=int(time.time() * 1000),
|
|
339
|
+
credentials=credentials,
|
|
340
|
+
account={
|
|
341
|
+
"accountId": account_id,
|
|
342
|
+
"displayName": display_name,
|
|
343
|
+
"avatarUrl": avatar_url,
|
|
344
|
+
},
|
|
345
|
+
)
|
|
346
|
+
)
|
|
347
|
+
return info
|
|
348
|
+
|
|
349
|
+
async def _auth_with_credentials(self, credentials: SessionCredentials) -> SessionInfo:
|
|
350
|
+
if not credentials.cookie or not credentials.imei:
|
|
351
|
+
raise ValidationError("credentials must include non-empty cookie and imei")
|
|
352
|
+
self._status = ClientStatus.STARTING
|
|
353
|
+
try:
|
|
354
|
+
await self._executor.execute(
|
|
355
|
+
lambda: self._transport.login_with_credentials(credentials),
|
|
356
|
+
operation="auth.login_with_credentials",
|
|
357
|
+
idempotent=False,
|
|
358
|
+
)
|
|
359
|
+
return await self._build_and_persist_session(credentials)
|
|
360
|
+
except Exception as err:
|
|
361
|
+
self._status = ClientStatus.ERROR
|
|
362
|
+
self._session_info = None
|
|
363
|
+
raise normalize_error(err, "Session authentication failed") from err
|
|
364
|
+
|
|
365
|
+
async def _login_with_qr(
|
|
366
|
+
self,
|
|
367
|
+
*,
|
|
368
|
+
on_qr_code: Callable[[QRCodeData], Any] | None = None,
|
|
369
|
+
on_scanned: Callable[[QRScannedData], Any] | None = None,
|
|
370
|
+
on_expired: Callable[[], Any] | None = None,
|
|
371
|
+
on_declined: Callable[[], Any] | None = None,
|
|
372
|
+
timeout: float | None = None,
|
|
373
|
+
) -> SessionInfo:
|
|
374
|
+
self._status = ClientStatus.QR_PENDING
|
|
375
|
+
effective_timeout = timeout if timeout is not None else self._qr_timeout
|
|
376
|
+
|
|
377
|
+
def _handle_qr(qr: QRCodeData) -> None:
|
|
378
|
+
self._status = ClientStatus.QR_PENDING
|
|
379
|
+
if on_qr_code:
|
|
380
|
+
on_qr_code(qr)
|
|
381
|
+
|
|
382
|
+
def _handle_scanned(info: QRScannedData) -> None:
|
|
383
|
+
self._status = ClientStatus.SCANNED
|
|
384
|
+
if on_scanned:
|
|
385
|
+
on_scanned(info)
|
|
386
|
+
|
|
387
|
+
def _handle_expired() -> None:
|
|
388
|
+
self._status = ClientStatus.IDLE
|
|
389
|
+
if on_expired:
|
|
390
|
+
on_expired()
|
|
391
|
+
|
|
392
|
+
def _handle_declined() -> None:
|
|
393
|
+
self._status = ClientStatus.IDLE
|
|
394
|
+
if on_declined:
|
|
395
|
+
on_declined()
|
|
396
|
+
|
|
397
|
+
try:
|
|
398
|
+
creds = await self._executor.execute(
|
|
399
|
+
lambda: self._transport.login_with_qr(
|
|
400
|
+
user_agent=self._user_agent,
|
|
401
|
+
language=self._language,
|
|
402
|
+
on_qr_code=_handle_qr,
|
|
403
|
+
on_scanned=_handle_scanned,
|
|
404
|
+
on_expired=_handle_expired,
|
|
405
|
+
on_declined=_handle_declined,
|
|
406
|
+
),
|
|
407
|
+
operation="auth.login_with_qr",
|
|
408
|
+
timeout=effective_timeout,
|
|
409
|
+
idempotent=False,
|
|
410
|
+
)
|
|
411
|
+
return await self._build_and_persist_session(creds)
|
|
412
|
+
except Exception as err:
|
|
413
|
+
self._status = ClientStatus.ERROR
|
|
414
|
+
self._session_info = None
|
|
415
|
+
raise normalize_error(err, "QR login failed") from err
|
|
416
|
+
|
|
417
|
+
async def logout(self, *, clear_session: bool = True) -> None:
|
|
418
|
+
await self.stop_listening()
|
|
419
|
+
await self._transport.disconnect()
|
|
420
|
+
self._session_info = None
|
|
421
|
+
self._status = ClientStatus.IDLE
|
|
422
|
+
self._user_cache.clear()
|
|
423
|
+
self._group_cache.clear()
|
|
424
|
+
self._registry.clear()
|
|
425
|
+
self._dedup.clear()
|
|
426
|
+
if clear_session:
|
|
427
|
+
await self._store.clear()
|
|
428
|
+
|
|
429
|
+
def on(self, event: str, handler: EventHandler | None = None) -> Any:
|
|
430
|
+
"""Register an event listener directly or as a decorator (`@client.on("message")`)."""
|
|
431
|
+
if handler is not None:
|
|
432
|
+
return self._event_bus.on(event, handler)
|
|
433
|
+
|
|
434
|
+
def _decorator(fn: EventHandler) -> EventHandler:
|
|
435
|
+
self._event_bus.on(event, fn)
|
|
436
|
+
return fn
|
|
437
|
+
|
|
438
|
+
return _decorator
|
|
439
|
+
|
|
440
|
+
def once(self, event: str, handler: EventHandler) -> UnsubscribeFn:
|
|
441
|
+
return self._event_bus.once(event, handler)
|
|
442
|
+
|
|
443
|
+
def off(self, event: str, handler: EventHandler) -> None:
|
|
444
|
+
self._event_bus.off(event, handler)
|
|
445
|
+
|
|
446
|
+
async def start_listening(self, *, retry_on_close: bool = False) -> None:
|
|
447
|
+
if not self.is_authenticated():
|
|
448
|
+
raise AuthenticationError("Cannot start listening before login()")
|
|
449
|
+
if self._listening:
|
|
450
|
+
return
|
|
451
|
+
self._listening = True
|
|
452
|
+
|
|
453
|
+
def _on_message(raw: dict[str, Any]) -> None:
|
|
454
|
+
kwargs = map_message_kwargs(raw)
|
|
455
|
+
if kwargs["thread_type"] == ThreadType.GROUP:
|
|
456
|
+
self._registry.register_group(kwargs["thread_id"])
|
|
457
|
+
else:
|
|
458
|
+
self._registry.register_user(kwargs["thread_id"])
|
|
459
|
+
if kwargs["is_self"] and not self._self_listen:
|
|
460
|
+
return
|
|
461
|
+
self._event_bus.emit("message", Message(actions=self._actions, **kwargs))
|
|
462
|
+
|
|
463
|
+
def _on_reaction(evt: ReactionEvent) -> None:
|
|
464
|
+
if evt.is_self and not self._self_listen:
|
|
465
|
+
return
|
|
466
|
+
self._event_bus.emit("reaction", evt)
|
|
467
|
+
|
|
468
|
+
def _on_group_update(evt: GroupUpdateEvent) -> None:
|
|
469
|
+
if evt.group_id:
|
|
470
|
+
self._registry.register_group(evt.group_id)
|
|
471
|
+
self._group_cache.delete(evt.group_id)
|
|
472
|
+
self._event_bus.emit("group.update", evt)
|
|
473
|
+
|
|
474
|
+
def _on_user_update(evt: UserUpdateEvent) -> None:
|
|
475
|
+
if evt.user_id:
|
|
476
|
+
self._registry.register_user(evt.user_id)
|
|
477
|
+
self._user_cache.delete(evt.user_id)
|
|
478
|
+
self._event_bus.emit("user.update", evt)
|
|
479
|
+
|
|
480
|
+
def _on_typing(evt: TypingEvent) -> None:
|
|
481
|
+
if evt.is_self and not self._self_listen:
|
|
482
|
+
return
|
|
483
|
+
self._event_bus.emit("typing", evt)
|
|
484
|
+
|
|
485
|
+
def _on_seen(evt: SeenEvent) -> None:
|
|
486
|
+
self._event_bus.emit("seen", evt)
|
|
487
|
+
|
|
488
|
+
def _on_undo(evt: UndoEvent) -> None:
|
|
489
|
+
if evt.is_self and not self._self_listen:
|
|
490
|
+
return
|
|
491
|
+
self._event_bus.emit("undo", evt)
|
|
492
|
+
|
|
493
|
+
def _on_connected(evt: ConnectionEvent) -> None:
|
|
494
|
+
self._event_bus.emit("connected", evt)
|
|
495
|
+
|
|
496
|
+
def _on_disconnected(evt: ConnectionEvent) -> None:
|
|
497
|
+
self._listening = False
|
|
498
|
+
self._event_bus.emit("disconnected", evt)
|
|
499
|
+
if evt.code in (CloseReason.KICK_CONNECTION, CloseReason.DUPLICATE_CONNECTION):
|
|
500
|
+
err = SessionError(
|
|
501
|
+
f"Realtime connection closed with code {evt.code}", raw_code=evt.code
|
|
502
|
+
)
|
|
503
|
+
self._status = ClientStatus.ERROR
|
|
504
|
+
self._session_info = None
|
|
505
|
+
self._event_bus.emit(
|
|
506
|
+
"auth.required", AuthRequiredEvent(reason="session_expired", error=err)
|
|
507
|
+
)
|
|
508
|
+
|
|
509
|
+
def _on_error(err: Any) -> None:
|
|
510
|
+
self._event_bus.emit("error", normalize_error(err, "Realtime listener error"))
|
|
511
|
+
|
|
512
|
+
await self._transport.start_listening(
|
|
513
|
+
{
|
|
514
|
+
"message": _on_message,
|
|
515
|
+
"reaction": _on_reaction,
|
|
516
|
+
"group.update": _on_group_update,
|
|
517
|
+
"user.update": _on_user_update,
|
|
518
|
+
"typing": _on_typing,
|
|
519
|
+
"seen": _on_seen,
|
|
520
|
+
"undo": _on_undo,
|
|
521
|
+
"connected": _on_connected,
|
|
522
|
+
"disconnected": _on_disconnected,
|
|
523
|
+
"error": _on_error,
|
|
524
|
+
},
|
|
525
|
+
retry_on_close=retry_on_close,
|
|
526
|
+
)
|
|
527
|
+
|
|
528
|
+
async def stop_listening(self) -> None:
|
|
529
|
+
if not self._listening:
|
|
530
|
+
return
|
|
531
|
+
self._listening = False
|
|
532
|
+
await self._transport.stop_listening()
|