-
Notifications
You must be signed in to change notification settings - Fork 164
/
Copy pathasync_client.py
3663 lines (2972 loc) · 130 KB
/
async_client.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# Copyright © 2018, 2019 Damir Jelić <poljar@termina.org.uk>
# Copyright © 2020-2021 Famedly GmbH
#
# Permission to use, copy, modify, and/or distribute this software for
# any purpose with or without fee is hereby granted, provided that the
# above copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
# SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
# RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
# CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
import asyncio
import io
import json
import warnings
from asyncio import Event as AsyncioEvent
from dataclasses import dataclass, field
from functools import partial, wraps
from json.decoder import JSONDecodeError
from pathlib import Path
from typing import (
Any,
AsyncIterable,
BinaryIO,
Callable,
Coroutine,
Dict,
Iterable,
List,
Optional,
Sequence,
Set,
Tuple,
Type,
Union,
)
from urllib.parse import urlparse
from uuid import UUID, uuid4
from aiofiles.threadpool.binary import AsyncBufferedReader
from aiofiles.threadpool.text import AsyncTextIOWrapper
from aiohttp import (
ClientResponse,
ClientSession,
ClientTimeout,
ContentTypeError,
TraceConfig,
)
from aiohttp.client_exceptions import ClientConnectionError
from aiohttp.connector import Connection
from aiohttp_socks import ProxyConnector
from ..api import (
Api,
EventFormat,
MessageDirection,
PushRuleKind,
ResizingMethod,
RoomPreset,
RoomVisibility,
_FilterT,
)
from ..crypto import (
AsyncDataT,
OlmDevice,
async_encrypt_attachment,
async_generator_from_data,
)
from ..event_builders import ToDeviceMessage
from ..events import (
BadEventType,
Event,
MegolmEvent,
PushAction,
PushCondition,
RoomKeyRequest,
RoomKeyRequestCancellation,
ToDeviceEvent,
)
from ..exceptions import (
GroupEncryptionError,
LocalProtocolError,
MembersSyncError,
SendRetryError,
TransferCancelledError,
)
from ..monitors import TransferMonitor
from ..responses import (
ContentRepositoryConfigError,
ContentRepositoryConfigResponse,
DeleteAliasError,
DeleteAliasResponse,
DeleteDevicesAuthResponse,
DeleteDevicesError,
DeleteDevicesResponse,
DeletePushRuleError,
DeletePushRuleResponse,
DevicesError,
DevicesResponse,
DiscoveryInfoError,
DiscoveryInfoResponse,
DownloadError,
DownloadResponse,
EnablePushRuleError,
EnablePushRuleResponse,
ErrorResponse,
FileResponse,
GetOpenIDTokenError,
GetOpenIDTokenResponse,
JoinedMembersError,
JoinedMembersResponse,
JoinedRoomsError,
JoinedRoomsResponse,
JoinError,
JoinResponse,
KeysClaimError,
KeysClaimResponse,
KeysQueryError,
KeysQueryResponse,
KeysUploadError,
KeysUploadResponse,
LoginError,
LoginInfoError,
LoginInfoResponse,
LoginResponse,
LogoutError,
LogoutResponse,
PresenceGetError,
PresenceGetResponse,
PresenceSetError,
PresenceSetResponse,
ProfileGetAvatarError,
ProfileGetAvatarResponse,
ProfileGetDisplayNameError,
ProfileGetDisplayNameResponse,
ProfileGetError,
ProfileGetResponse,
ProfileSetAvatarError,
ProfileSetAvatarResponse,
ProfileSetDisplayNameError,
ProfileSetDisplayNameResponse,
PutAliasError,
PutAliasResponse,
RegisterResponse,
Response,
RoomBanError,
RoomBanResponse,
RoomContextError,
RoomContextResponse,
RoomCreateError,
RoomCreateResponse,
RoomDeleteAliasError,
RoomDeleteAliasResponse,
RoomForgetError,
RoomForgetResponse,
RoomGetEventError,
RoomGetEventResponse,
RoomGetStateError,
RoomGetStateEventError,
RoomGetStateEventResponse,
RoomGetStateResponse,
RoomGetVisibilityError,
RoomGetVisibilityResponse,
RoomInviteError,
RoomInviteResponse,
RoomKeyRequestError,
RoomKeyRequestResponse,
RoomKickError,
RoomKickResponse,
RoomLeaveError,
RoomLeaveResponse,
RoomMessagesError,
RoomMessagesResponse,
RoomPutAliasError,
RoomPutAliasResponse,
RoomPutStateError,
RoomPutStateResponse,
RoomReadMarkersError,
RoomReadMarkersResponse,
RoomRedactError,
RoomRedactResponse,
RoomResolveAliasError,
RoomResolveAliasResponse,
RoomSendResponse,
RoomTypingError,
RoomTypingResponse,
RoomUnbanError,
RoomUnbanResponse,
RoomUpdateAliasError,
RoomUpdateAliasResponse,
RoomUpgradeError,
RoomUpgradeResponse,
SetPushRuleActionsError,
SetPushRuleActionsResponse,
SetPushRuleError,
SetPushRuleResponse,
ShareGroupSessionError,
ShareGroupSessionResponse,
SyncError,
SyncResponse,
ThumbnailError,
ThumbnailResponse,
ToDeviceError,
ToDeviceResponse,
UpdateDeviceError,
UpdateDeviceResponse,
UpdateReceiptMarkerResponse,
UploadError,
UploadFilterError,
UploadFilterResponse,
UploadResponse,
WhoamiError,
WhoamiResponse,
)
from . import Client, ClientConfig
from .base_client import logged_in, store_loaded
_ShareGroupSessionT = Union[ShareGroupSessionError, ShareGroupSessionResponse]
_ProfileGetDisplayNameT = Union[
ProfileGetDisplayNameResponse, ProfileGetDisplayNameError
]
_ProfileSetDisplayNameT = Union[
ProfileSetDisplayNameResponse, ProfileSetDisplayNameError
]
DataProvider = Callable[[int, int], AsyncDataT]
SynchronousFile = (
io.TextIOBase,
io.BufferedReader,
io.BufferedRandom,
io.BytesIO,
io.FileIO,
)
AsyncFile = (AsyncBufferedReader, AsyncTextIOWrapper)
@dataclass
class ResponseCb:
"""Response callback."""
func: Callable = field()
filter: Union[Tuple[Type], Type, None] = None
async def on_request_chunk_sent(session, context, params):
"""TraceConfig callback to run when a chunk is sent for client uploads."""
context_obj = context.trace_request_ctx
if isinstance(context_obj, TransferMonitor):
context_obj.transferred += len(params.chunk)
async def connect_wrapper(self, *args, **kwargs) -> Connection:
connection = await type(self).connect(self, *args, **kwargs)
connection.transport.set_write_buffer_limits(16 * 1024)
return connection
def client_session(func):
"""Ensure that the Async client has a valid client session."""
@wraps(func)
async def wrapper(self, *args, **kwargs):
if not self.client_session:
trace = TraceConfig()
trace.on_request_chunk_sent.append(on_request_chunk_sent)
connector = ProxyConnector.from_url(self.proxy) if self.proxy else None
self.client_session = ClientSession(
timeout=ClientTimeout(total=self.config.request_timeout),
trace_configs=[trace],
connector=connector,
)
self.client_session.connector.connect = partial(
connect_wrapper,
self.client_session.connector,
)
return await func(self, *args, **kwargs)
return wrapper
@dataclass(frozen=True)
class AsyncClientConfig(ClientConfig):
"""Async nio client configuration.
Attributes:
max_limit_exceeded (int, optional): How many 429 (Too many requests)
errors can a request encounter before giving up and returning
an ErrorResponse.
Default is None for unlimited.
max_timeouts (int, optional): How many timeout connection errors can
a request encounter before giving up and raising the error:
a ClientConnectionError, TimeoutError, or asyncio.TimeoutError.
Default is None for unlimited.
backoff_factor (float): A backoff factor to apply between retries
for timeouts, starting from the second try.
nio will sleep for `backoff_factor * (2 ** (total_retries - 1))`
seconds.
For example, with the default backoff_factor of 0.1,
nio will sleep for 0.0, 0.2, 0.4, ... seconds between retries.
max_timeout_retry_wait_time (float): The maximum time in seconds to
wait between retries for timeouts, by default 60.
request_timeout (float): How many seconds a request has to finish,
before it is retried or raise an `asycio.TimeoutError` depending
on `max_timeouts`.
Defaults to 60 seconds, and can be disabled with `0`.
`AsyncClient.sync()` overrides this option with its
`timeout` argument.
The `download()`, `thumbnail()` and `upload()` methods ignore
this option and use `0`.
"""
max_limit_exceeded: Optional[int] = None
max_timeouts: Optional[int] = None
backoff_factor: float = 0.1
max_timeout_retry_wait_time: float = 60
request_timeout: float = 60
class AsyncClient(Client):
"""An async IO matrix client.
Args:
homeserver (str): The URL of the homeserver which we want to connect
to.
user (str, optional): The user which will be used when we log in to the
homeserver.
device_id (str, optional): An unique identifier that distinguishes
this client instance. If not set the server will provide one after
log in.
store_path (str, optional): The directory that should be used for state
storage.
config (AsyncClientConfig, optional): Configuration for the client.
ssl (bool/ssl.SSLContext, optional): SSL validation mode. None for
default SSL check (ssl.create_default_context() is used), False
for skip SSL certificate validation connection.
proxy (str, optional): The proxy that should be used for the HTTP
connection. Supports SOCKS4(a), SOCKS5, HTTP (tunneling) via an
URL like e.g. 'socks5://user:password@127.0.0.1:1080'.
Attributes:
synced (Event): An asyncio event that is fired every time the client
successfully syncs with the server. Note, this event will only be
fired if the `sync_forever()` method is used.
A simple example can be found bellow.
Example:
>>> client = AsyncClient("https://example.org", "example")
>>> login_response = loop.run_until_complete(
>>> client.login("hunter1")
>>> )
>>> asyncio.run(client.sync_forever(30000))
This example assumes a full sync on every run. If a sync token is provided
for the `since` parameter of the `sync_forever` method `full_state` should
be set to `True` as well.
Example:
>>> asyncio.run(
>>> client.sync_forever(30000, since="token123",
>>> full_state=True)
>>> )
The client can also be configured to store and restore the sync token
automatically. The `full_state` argument should be set to `True` in that
case as well.
Example:
>>> config = ClientConfig(store_sync_tokens=True)
>>> client = AsyncClient("https://example.org", "example",
>>> store_path="/home/example",
>>> config=config)
>>> login_response = loop.run_until_complete(
>>> client.login("hunter1")
>>> )
>>> asyncio.run(client.sync_forever(30000, full_state=True))
"""
def __init__(
self,
homeserver: str,
user: str = "",
device_id: Optional[str] = "",
store_path: Optional[str] = "",
config: Optional[AsyncClientConfig] = None,
ssl: Optional[bool] = None,
proxy: Optional[str] = None,
):
self.homeserver = homeserver
self.client_session: Optional[ClientSession] = None
self.ssl = ssl
self.proxy = proxy
self._presence: Optional[str] = None
self.synced = AsyncioEvent()
self.response_callbacks: List[ResponseCb] = []
self.sharing_session: Dict[str, AsyncioEvent] = dict()
is_config = isinstance(config, ClientConfig)
is_async_config = isinstance(config, AsyncClientConfig)
if is_config and not is_async_config:
warnings.warn(
"Pass an AsyncClientConfig instead of ClientConfig.",
DeprecationWarning,
)
config = AsyncClientConfig(**config.__dict__)
self.config: AsyncClientConfig = config or AsyncClientConfig()
super().__init__(user, device_id, store_path, self.config)
def add_response_callback(
self,
func: Coroutine[Any, Any, Response],
cb_filter: Union[Tuple[Type], Type, None] = None,
):
"""Add a coroutine that will be called if a response is received.
Args:
func (Coroutine): The coroutine that will be called with the
response as the argument.
cb_filter (Type, optional): A type or a tuple of types for which
the callback should be called.
Example:
>>> # A callback that will be called every time our `sync_forever`
>>> # method succesfully syncs with the server.
>>> async def sync_cb(response):
... print(f"We synced, token: {response.next_batch}")
...
>>> client.add_response_callback(sync_cb, SyncResponse)
>>> await client.sync_forever(30000)
"""
cb = ResponseCb(func, cb_filter) # type: ignore
self.response_callbacks.append(cb)
async def parse_body(self, transport_response: ClientResponse) -> Dict[Any, Any]:
"""Parse the body of the response.
Low-level function which is normally only used by other methods of
this class.
Args:
transport_response(ClientResponse): The transport response that
contains the body of the response.
Returns a dictionary representing the response.
"""
try:
return await transport_response.json()
except (JSONDecodeError, ContentTypeError):
try:
# matrix.org return an incorrect content-type for .well-known
# API requests, which leads to .text() working but not .json()
return json.loads(await transport_response.text())
except (JSONDecodeError, ContentTypeError):
pass
return {}
async def create_matrix_response(
self,
response_class: Type,
transport_response: ClientResponse,
data: Tuple[Any, ...] = None,
) -> Response:
"""Transform a transport response into a nio matrix response.
Low-level function which is normally only used by other methods of
this class.
Args:
response_class (Type): The class that the requests belongs to.
transport_response (ClientResponse): The underlying transport
response that contains our response body.
data (Tuple, optional): Extra data that is required to instantiate
the response class.
Returns a subclass of `Response` depending on the type of the
response_class argument.
"""
data = data or ()
content_type = transport_response.content_type
is_json = content_type == "application/json"
name = None
if transport_response.content_disposition:
name = transport_response.content_disposition.filename
if issubclass(response_class, FileResponse) and is_json:
parsed_dict = await self.parse_body(transport_response)
resp = response_class.from_data(parsed_dict, content_type, name)
elif issubclass(response_class, FileResponse):
body = await transport_response.read()
resp = response_class.from_data(body, content_type, name)
elif (
issubclass(response_class, RoomGetStateEventResponse)
and transport_response.status == 404
):
parsed_dict = await self.parse_body(transport_response)
resp = response_class.create_error(parsed_dict, data[-1])
elif (
transport_response.status == 401 and response_class == DeleteDevicesResponse
):
parsed_dict = await self.parse_body(transport_response)
resp = DeleteDevicesAuthResponse.from_dict(parsed_dict)
else:
parsed_dict = await self.parse_body(transport_response)
resp = response_class.from_dict(parsed_dict, *data)
resp.transport_response = transport_response
return resp
async def _run_to_device_callbacks(self, event: Union[ToDeviceEvent]):
for cb in self.to_device_callbacks:
if cb.filter is None or isinstance(event, cb.filter):
await asyncio.coroutine(cb.func)(event)
async def _handle_to_device(self, response: SyncResponse):
decrypted_to_device = []
for index, to_device_event in enumerate(response.to_device_events):
decrypted_event = self._handle_decrypt_to_device(to_device_event)
if decrypted_event:
decrypted_to_device.append((index, decrypted_event))
to_device_event = decrypted_event
# Do not pass room key request events to our user here. We don't
# want to notify them about requests that get automatically handled
# or canceled right away.
if isinstance(
to_device_event, (RoomKeyRequest, RoomKeyRequestCancellation)
):
continue
await self._run_to_device_callbacks(to_device_event)
self._replace_decrypted_to_device(decrypted_to_device, response)
async def _handle_invited_rooms(self, response: SyncResponse):
for room_id, info in response.rooms.invite.items():
room = self._get_invited_room(room_id)
for event in info.invite_state:
room.handle_event(event)
for cb in self.event_callbacks:
if cb.filter is None or isinstance(event, cb.filter):
await asyncio.coroutine(cb.func)(room, event)
async def _handle_joined_rooms(self, response: SyncResponse) -> None:
encrypted_rooms: Set[str] = set()
for room_id, join_info in response.rooms.join.items():
self._handle_joined_state(room_id, join_info, encrypted_rooms)
room = self.rooms[room_id]
decrypted_events: List[Tuple[int, Union[Event, BadEventType]]] = []
for index, event in enumerate(join_info.timeline.events):
decrypted_event = self._handle_timeline_event(
event, room_id, room, encrypted_rooms
)
if decrypted_event:
event = decrypted_event
decrypted_events.append((index, decrypted_event))
for cb in self.event_callbacks:
if cb.filter is None or isinstance(event, cb.filter):
await asyncio.coroutine(cb.func)(room, event)
# Replace the Megolm events with decrypted ones
for index, event in decrypted_events:
join_info.timeline.events[index] = event
for event in join_info.ephemeral:
room.handle_ephemeral_event(event)
for cb in self.ephemeral_callbacks:
if cb.filter is None or isinstance(event, cb.filter):
await asyncio.coroutine(cb.func)(room, event)
for event in join_info.account_data:
room.handle_account_data(event)
for cb in self.room_account_data_callbacks:
if cb.filter is None or isinstance(event, cb.filter):
await asyncio.coroutine(cb.func)(room, event)
if room.encrypted and self.olm is not None:
self.olm.update_tracked_users(room)
self.encrypted_rooms.update(encrypted_rooms)
if self.store:
self.store.save_encrypted_rooms(encrypted_rooms)
async def _handle_presence_events(self, response: SyncResponse):
for event in response.presence_events:
for room_id in self.rooms.keys():
if event.user_id not in self.rooms[room_id].users:
continue
self.rooms[room_id].users[event.user_id].presence = event.presence
self.rooms[room_id].users[
event.user_id
].last_active_ago = event.last_active_ago
self.rooms[room_id].users[
event.user_id
].currently_active = event.currently_active
self.rooms[room_id].users[event.user_id].status_msg = event.status_msg
for cb in self.presence_callbacks:
if cb.filter is None or isinstance(event, cb.filter):
await asyncio.coroutine(cb.func)(event)
async def _handle_global_account_data_events( # type: ignore
self,
response: SyncResponse,
) -> None:
for event in response.account_data_events:
for cb in self.global_account_data_callbacks:
if cb.filter is None or isinstance(event, cb.filter):
await asyncio.coroutine(cb.func)(event)
async def _handle_expired_verifications(self):
expired_verifications = self.olm.clear_verifications()
for event in expired_verifications:
for cb in self.to_device_callbacks:
if cb.filter is None or isinstance(event, cb.filter):
await asyncio.coroutine(cb.func)(event)
async def _handle_sync(self, response: SyncResponse) -> None:
# We already recieved such a sync response, do nothing in that case.
if self.next_batch == response.next_batch:
return
self.next_batch = response.next_batch
if self.config.store_sync_tokens and self.store:
self.store.save_sync_token(self.next_batch)
await self._handle_to_device(response)
await self._handle_invited_rooms(response)
await self._handle_joined_rooms(response)
await self._handle_presence_events(response)
await self._handle_global_account_data_events(response)
if self.olm:
await self._handle_expired_verifications()
self._handle_olm_events(response)
await self._collect_key_requests()
async def _collect_key_requests(self):
events = self.olm.collect_key_requests()
for event in events:
await self._run_to_device_callbacks(event)
async def receive_response(self, response: Response) -> None:
"""Receive a Matrix Response and change the client state accordingly.
Automatically called for all "high-level" methods of this API (each
function documents calling it).
Some responses will get edited for the callers convenience e.g. sync
responses that contain encrypted messages. The encrypted messages will
be replaced by decrypted ones if decryption is possible.
Args:
response (Response): the response that we wish the client to handle
"""
if not isinstance(response, Response):
raise ValueError("Invalid response received")
if isinstance(response, SyncResponse):
await self._handle_sync(response)
else:
super().receive_response(response)
async def get_timeout_retry_wait_time(self, got_timeouts: int) -> float:
if got_timeouts < 2:
return 0.0
return min(
self.config.backoff_factor * (2 ** (min(got_timeouts, 1000) - 1)),
self.config.max_timeout_retry_wait_time,
)
async def _send(
self,
response_class: Type,
method: str,
path: str,
data: Union[None, str, AsyncDataT] = None,
response_data: Optional[Tuple[Any, ...]] = None,
content_type: Optional[str] = None,
trace_context: Optional[Any] = None,
data_provider: Optional[DataProvider] = None,
timeout: Optional[float] = None,
content_length: Optional[int] = None,
):
headers = (
{"Content-Type": content_type}
if content_type
else {"Content-Type": "application/json"}
)
if content_length is not None:
headers["Content-Length"] = str(content_length)
if self.config.custom_headers is not None:
headers.update(self.config.custom_headers)
got_429 = 0
max_429 = self.config.max_limit_exceeded
got_timeouts = 0
max_timeouts = self.config.max_timeouts
while True:
if data_provider:
# mypy expects an "Awaitable[Any]" but data_provider is a
# method generated during runtime that may or may not be
# Awaitable. The actual type is a union of the types that we
# can receive from reading files.
data = await data_provider(got_429, got_timeouts) # type: ignore
try:
transport_resp = await self.send(
method,
path,
data,
headers,
trace_context,
timeout,
)
resp = await self.create_matrix_response(
response_class,
transport_resp,
response_data,
)
if transport_resp.status == 429 or (
isinstance(resp, ErrorResponse)
and resp.status_code in ("M_LIMIT_EXCEEDED", 429)
):
got_429 += 1
if max_429 is not None and got_429 > max_429:
break
await self.run_response_callbacks([resp])
retry_after_ms = getattr(resp, "retry_after_ms", 0) or 5000
await asyncio.sleep(retry_after_ms / 1000)
else:
break
except (ClientConnectionError, TimeoutError, asyncio.TimeoutError):
got_timeouts += 1
if max_timeouts is not None and got_timeouts > max_timeouts:
raise
wait = await self.get_timeout_retry_wait_time(got_timeouts)
await asyncio.sleep(wait)
await self.receive_response(resp)
return resp
@client_session
async def send(
self,
method: str,
path: str,
data: Union[None, str, AsyncDataT] = None,
headers: Optional[Dict[str, str]] = None,
trace_context: Any = None,
timeout: Optional[float] = None,
) -> ClientResponse:
"""Send a request to the homeserver.
This function does not call receive_response().
Args:
method (str): The request method that should be used. One of get,
post, put, delete.
path (str): The URL path of the request.
data (str, optional): Data that will be posted with the request.
headers (Dict[str,str] , optional): Additional request headers that
should be used with the request.
trace_context (Any, optional): An object to use for the
ClientSession TraceConfig context
timeout (int, optional): How many seconds the request has before
raising `asyncio.TimeoutError`.
Overrides `AsyncClient.config.request_timeout` if not `None`.
"""
assert self.client_session
return await self.client_session.request(
method,
self.homeserver + path,
data=data,
ssl=self.ssl,
headers=headers,
trace_request_ctx=trace_context,
timeout=self.config.request_timeout if timeout is None else timeout,
)
async def mxc_to_http(
self,
mxc: str,
homeserver: Optional[str] = None,
) -> Optional[str]:
"""Convert a matrix content URI to a HTTP URI."""
return Api.mxc_to_http(mxc, homeserver or self.homeserver)
async def login_raw(
self, auth_dict: Dict[str, Any]
) -> Union[LoginResponse, LoginError]:
"""Login to the homeserver using a raw dictionary.
Calls receive_response() to update the client state if necessary.
Args:
auth_dict (Dict[str, Any]): The auth dictionary.
See the example below and here
https://matrix.org/docs/spec/client_server/r0.6.0#authentication-types
for detailed documentation
Example:
>>> auth_dict = {
>>> "type": "m.login.password",
>>> "identifier": {
>>> "type": "m.id.thirdparty",
>>> "medium": "email",
>>> "address": "testemail@mail.org"
>>> },
>>> "password": "PASSWORDABCD",
>>> "initial_device_display_name": "Test user"
>>> }
Returns either a `LoginResponse` if the request was successful or
a `LoginError` if there was an error with the request.
"""
if auth_dict is None or auth_dict == {}:
raise ValueError("Auth dictionary shall not be empty")
method, path, data = Api.login_raw(auth_dict)
return await self._send(LoginResponse, method, path, data)
async def register(self, username, password, device_name=""):
"""Register with homeserver.
Calls receive_response() to update the client state if necessary.
Args:
username (str): Username to register the new user as.
password (str): New password for the user.
device_name (str): A display name to assign to a newly-created
device. Ignored if the logged in device corresponds to a
known device.
Returns a 'RegisterResponse' if successful.
"""
method, path, data = Api.register(
user=username,
password=password,
device_name=device_name,
device_id=self.device_id,
)
return await self._send(RegisterResponse, method, path, data)
async def discovery_info(
self,
) -> Union[DiscoveryInfoResponse, DiscoveryInfoError]:
"""Get discovery information about current `AsyncClient.homeserver`.
Returns either a `DiscoveryInfoResponse` if the request was successful
or a `DiscoveryInfoError` if there was an error with the request.
Some homeservers do not redirect requests to their main domain and
instead require clients to use a specific URL for communication.
If the domain specified by the `AsyncClient.homeserver` URL
implements the
[.well-known](https://matrix.org/docs/spec/client_server/latest#id178),
discovery mechanism, this method can be used to retrieve the
actual homeserver URL from it.
Example:
>>> client = AsyncClient(homeserver="https://example.org")
>>> response = await client.discovery_info()
>>> if isinstance(response, DiscoveryInfoResponse):
>>> client.homeserver = response.homeserver_url
"""
method, path = Api.discovery_info()
return await self._send(DiscoveryInfoResponse, method, path)
async def login_info(self) -> Union[LoginInfoResponse, LoginInfoError]:
"""Get the available login methods from the server
Returns either a `LoginInfoResponse` if the request was successful or
a `LoginInfoError` if there was an error with the request.
"""
method, path = Api.login_info()
return await self._send(LoginInfoResponse, method, path)
async def login(
self,
password: Optional[str] = None,
device_name: Optional[str] = "",
token: Optional[str] = None,
) -> Union[LoginResponse, LoginError]:
"""Login to the homeserver.
Calls receive_response() to update the client state if necessary.
Args:
password (str, optional): The user's password.
device_name (str): A display name to assign to a newly-created
device. Ignored if the logged in device corresponds to a
known device.
token (str, optional): A login token, for example provided by a
single sign-on service.
Either a password or a token needs to be provided.
Returns either a `LoginResponse` if the request was successful or
a `LoginError` if there was an error with the request.
"""
if password is None and token is None:
raise ValueError("Either a password or a token needs to be provided")
method, path, data = Api.login(
self.user,
password=password,
device_name=device_name,
device_id=self.device_id,
token=token,
)
return await self._send(LoginResponse, method, path, data)
@logged_in
async def logout(
self, all_devices: bool = False
) -> Union[LogoutResponse, LogoutError]:
"""Logout from the homeserver.
Calls receive_response() to update the client state if necessary.
Returns either 'LogoutResponse' if the request was successful or
a `Logouterror` if there was an error with the request.
"""
method, path, data = Api.logout(self.access_token, all_devices)
return await self._send(LogoutResponse, method, path, data)
@logged_in