-
Notifications
You must be signed in to change notification settings - Fork 161
/
responses.py
1820 lines (1394 loc) · 50 KB
/
responses.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 Damir Jelić <[email protected]>
# Copyright © 2020 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.
from __future__ import unicode_literals
from builtins import str
from dataclasses import dataclass, field
from datetime import datetime
from functools import wraps
from typing import Any, Dict, List, Optional, Set, Tuple, Union
from jsonschema.exceptions import SchemaError, ValidationError
from logbook import Logger
from .event_builders import ToDeviceMessage
from .events import (AccountDataEvent, BadEventType, Event, InviteEvent,
ToDeviceEvent, EphemeralEvent)
from .events.presence import PresenceEvent
from .http import TransportResponse
from .log import logger_group
from .schemas import Schemas, validate_json
logger = Logger("nio.responses")
logger_group.add_logger(logger)
__all__ = [
"ContentRepositoryConfigResponse",
"ContentRepositoryConfigError",
"FileResponse",
"DeleteDevicesAuthResponse",
"DeleteDevicesResponse",
"DeleteDevicesError",
"Device",
"DeviceList",
"DevicesResponse",
"DevicesError",
"DeviceOneTimeKeyCount",
"DownloadResponse",
"DownloadError",
"ErrorResponse",
"InviteInfo",
"JoinResponse",
"JoinError",
"JoinedMembersResponse",
"JoinedMembersError",
"JoinedRoomsResponse",
"JoinedRoomsError",
"KeysClaimResponse",
"KeysClaimError",
"KeysQueryResponse",
"KeysQueryError",
"KeysUploadResponse",
"KeysUploadError",
"RegisterResponse",
"LoginResponse",
"LoginError",
"LoginInfoResponse",
"LoginInfoError",
"LogoutResponse",
"LogoutError",
"Response",
"RoomBanResponse",
"RoomBanError",
"RoomCreateResponse",
"RoomCreateError",
"RoomInfo",
"RoomInviteResponse",
"RoomInviteError",
"RoomKickResponse",
"RoomKickError",
"RoomLeaveResponse",
"RoomLeaveError",
"RoomForgetResponse",
"RoomForgetError",
"RoomMember",
"RoomMessagesResponse",
"RoomMessagesError",
"RoomGetStateResponse",
"RoomGetStateError",
"RoomGetStateEventResponse",
"RoomGetStateEventError",
"RoomGetEventResponse",
"RoomGetEventError",
"RoomPutStateResponse",
"RoomPutStateError",
"RoomRedactResponse",
"RoomRedactError",
"RoomResolveAliasResponse",
"RoomResolveAliasError",
"RoomSendResponse",
"RoomSendError",
"RoomSummary",
"RoomUnbanResponse",
"RoomUnbanError",
"Rooms",
"ShareGroupSessionResponse",
"ShareGroupSessionError",
"SyncResponse",
"PartialSyncResponse",
"SyncError",
"Timeline",
"UpdateDeviceResponse",
"UpdateDeviceError",
"RoomTypingResponse",
"RoomTypingError",
"RoomReadMarkersResponse",
"RoomReadMarkersError",
"UploadResponse",
"UploadError",
"ProfileGetResponse",
"ProfileGetError",
"ProfileGetDisplayNameResponse",
"ProfileGetDisplayNameError",
"ProfileSetDisplayNameResponse",
"ProfileSetDisplayNameError",
"ProfileGetAvatarResponse",
"ProfileGetAvatarError",
"ProfileSetAvatarResponse",
"ProfileSetAvatarError",
"PresenceGetResponse",
"PresenceGetError",
"PresenceSetResponse",
"PresenceSetError",
"RoomKeyRequestResponse",
"RoomKeyRequestError",
"ThumbnailResponse",
"ThumbnailError",
"ToDeviceResponse",
"ToDeviceError",
"RoomContextResponse",
"RoomContextError"
]
def verify(schema, error_class, pass_arguments=True):
def decorator(f):
@wraps(f)
def wrapper(cls, parsed_dict, *args, **kwargs):
try:
logger.info("Validating response schema")
validate_json(parsed_dict, schema)
except (SchemaError, ValidationError) as e:
logger.warn("Error validating response: " + str(e.message))
if pass_arguments:
return error_class.from_dict(parsed_dict, *args, **kwargs)
else:
return error_class.from_dict(parsed_dict)
return f(cls, parsed_dict, *args, **kwargs)
return wrapper
return decorator
@dataclass
class Rooms:
invite: Dict = field()
join: Dict = field()
leave: Dict = field()
@dataclass
class DeviceOneTimeKeyCount:
curve25519: int = field()
signed_curve25519: int = field()
@dataclass
class DeviceList:
changed: List[str] = field()
left: List[str] = field()
@dataclass
class Timeline:
events: List = field()
limited: bool = field()
prev_batch: str = field()
@dataclass
class InviteInfo:
invite_state: List = field()
@dataclass
class RoomSummary:
invited_member_count: Optional[int] = None
joined_member_count: Optional[int] = None
heroes: Optional[List[str]] = None
@dataclass
class RoomInfo:
timeline: Timeline = field()
state: List = field()
ephemeral: List = field()
account_data: List = field()
summary: Optional[RoomSummary] = None
@staticmethod
def parse_account_data(event_dict):
"""Parse the account data dictionary and produce a list of events."""
events = []
for event in event_dict:
events.append(AccountDataEvent.parse_event(event))
return events
@dataclass
class RoomMember:
user_id: str = field()
display_name: str = field()
avatar_url: str = field()
@dataclass
class Device:
id: str = field()
display_name: str = field()
last_seen_ip: str = field()
last_seen_date: datetime = field()
@classmethod
def from_dict(cls, parsed_dict):
date = None
if parsed_dict["last_seen_ts"] is not None:
date = datetime.fromtimestamp(parsed_dict["last_seen_ts"] / 1000)
return cls(
parsed_dict["device_id"],
parsed_dict["display_name"],
parsed_dict["last_seen_ip"],
date
)
@dataclass
class Response:
uuid: str = field(default="", init=False)
start_time: Optional[float] = field(default=None, init=False)
end_time: Optional[float] = field(default=None, init=False)
timeout: int = field(default=0, init=False)
transport_response: Optional[TransportResponse] = field(
init=False, default=None,
)
@property
def elapsed(self):
if not self.start_time or not self.end_time:
return 0
elapsed = self.end_time - self.start_time
return max(0, elapsed - (self.timeout / 1000))
@dataclass
class FileResponse(Response):
"""A response representing a successful file content request.
Attributes:
body (bytes): The file's content in bytes.
content_type (str): The content MIME type of the file,
e.g. "image/png".
filename (str, optional): The file's name returned by the server.
"""
body: bytes = field()
content_type: str = field()
filename: Optional[str] = field()
def __str__(self):
return "{} bytes, content type: {}, filename: {}".format(
len(self.body),
self.content_type,
self.filename
)
@classmethod
def from_data(cls, data, content_type, filename=None):
"""Create a FileResponse from file content returned by the server.
Args:
data (bytes): The file's content in bytes.
content_type (str): The content MIME type of the file,
e.g. "image/png".
"""
raise NotImplementedError()
@dataclass
class ErrorResponse(Response):
message: str = field()
status_code: Optional[int] = None
retry_after_ms: Optional[int] = None
soft_logout: bool = False
def __str__(self):
# type: () -> str
if self.status_code and self.message:
e = "{} {}".format(self.status_code, self.message)
elif self.message:
e = self.message
elif self.status_code:
e = "{} unknown error".format(self.status_code)
else:
e = "unknown error"
if self.retry_after_ms:
e = "{} - retry after {}ms".format(e, self.retry_after_ms)
return "{}: {}".format(self.__class__.__name__, e)
@classmethod
def from_dict(cls, parsed_dict):
# type: (Dict[Any, Any]) -> ErrorResponse
try:
validate_json(parsed_dict, Schemas.error)
except (SchemaError, ValidationError):
return cls("unknown error")
return cls(
parsed_dict["error"],
parsed_dict["errcode"],
parsed_dict.get("retry_after_ms"),
parsed_dict.get("soft_logout", False),
)
@dataclass
class _ErrorWithRoomId(ErrorResponse):
room_id: str = ""
@classmethod
def from_dict(cls, parsed_dict, room_id):
try:
validate_json(parsed_dict, Schemas.error)
except (SchemaError, ValidationError):
return cls("unknown error")
return cls(
parsed_dict["error"],
parsed_dict["errcode"],
parsed_dict.get("retry_after_ms"),
parsed_dict.get("soft_logout", False),
room_id
)
class LoginError(ErrorResponse):
pass
class LogoutError(ErrorResponse):
pass
class SyncError(ErrorResponse):
pass
class RoomSendError(_ErrorWithRoomId):
pass
class RoomGetStateError(_ErrorWithRoomId):
"""A response representing an unsuccessful room state query."""
pass
class RoomGetStateEventError(_ErrorWithRoomId):
"""A response representing an unsuccessful room state query."""
pass
class RoomGetEventError(ErrorResponse):
"""A response representing an unsuccessful room get event request."""
pass
class RoomPutStateError(_ErrorWithRoomId):
"""A response representing an unsuccessful room state sending request."""
pass
class RoomRedactError(_ErrorWithRoomId):
pass
class RoomResolveAliasError(ErrorResponse):
"""A response representing an unsuccessful room alias query."""
pass
class RoomTypingError(_ErrorWithRoomId):
"""A response representing a unsuccessful room typing request."""
pass
class RoomReadMarkersError(_ErrorWithRoomId):
"""A response representing a unsuccessful room read markers request."""
pass
class RoomKickError(ErrorResponse):
pass
class RoomBanError(ErrorResponse):
pass
class RoomUnbanError(ErrorResponse):
pass
class RoomInviteError(ErrorResponse):
pass
class RoomCreateError(ErrorResponse):
"""A response representing a unsuccessful create room request."""
pass
class JoinError(ErrorResponse):
pass
class RoomLeaveError(ErrorResponse):
pass
class RoomForgetError(_ErrorWithRoomId):
pass
class RoomMessagesError(_ErrorWithRoomId):
pass
class KeysUploadError(ErrorResponse):
pass
class KeysQueryError(ErrorResponse):
pass
class KeysClaimError(_ErrorWithRoomId):
pass
class ContentRepositoryConfigError(ErrorResponse):
"""A response for a unsuccessful content repository config request."""
class UploadError(ErrorResponse):
"""A response representing a unsuccessful upload request."""
class DownloadError(ErrorResponse):
"""A response representing a unsuccessful download request."""
class ThumbnailError(ErrorResponse):
"""A response representing a unsuccessful thumbnail request."""
@dataclass
class ShareGroupSessionError(_ErrorWithRoomId):
"""Response representing unsuccessful group sessions sharing request."""
users_shared_with: Set[Tuple[str, str]] = field(default_factory=set)
@classmethod
def from_dict(cls, parsed_dict, room_id, users_shared_with):
try:
validate_json(parsed_dict, Schemas.error)
except (SchemaError, ValidationError):
return cls("unknown error")
return cls(parsed_dict["error"], parsed_dict["errcode"], room_id,
users_shared_with)
class DevicesError(ErrorResponse):
pass
class DeleteDevicesError(ErrorResponse):
pass
class UpdateDeviceError(ErrorResponse):
pass
class JoinedMembersError(_ErrorWithRoomId):
pass
class JoinedRoomsError(ErrorResponse):
"""A response representing an unsuccessful joined rooms query."""
pass
class ProfileGetError(ErrorResponse):
pass
class ProfileGetDisplayNameError(ErrorResponse):
pass
class ProfileSetDisplayNameError(ErrorResponse):
pass
class ProfileGetAvatarError(ErrorResponse):
pass
class PresenceGetError(ErrorResponse):
"""Response representing a unsuccessful get presence request."""
pass
class PresenceSetError(ErrorResponse):
"""Response representing a unsuccessful set presence request."""
pass
class ProfileSetAvatarError(ErrorResponse):
pass
@dataclass
class RegisterErrorResponse(ErrorResponse):
pass
@dataclass
class RegisterResponse(Response):
user_id: str = field()
device_id: str = field()
access_token: str = field()
def __str__(self):
# type () -> str
return "Registered {}, device id {}.".format(
self.user_id, self.device_id,
)
@classmethod
@verify(Schemas.register, RegisterErrorResponse)
def from_dict(cls, parsed_dict):
return cls(
parsed_dict["user_id"],
parsed_dict["device_id"],
parsed_dict["access_token"],
)
@dataclass
class LoginInfoError(ErrorResponse):
pass
@dataclass
class LoginInfoResponse(Response):
flows: List[str] = field()
@classmethod
@verify(Schemas.login_info, LoginInfoError)
def from_dict(cls, parsed_dict):
# type: (Dict[Any, Any]) -> Union[LoginInfoResponse, ErrorResponse]
flow_types = [flow["type"] for flow in parsed_dict["flows"]]
return cls(flow_types)
@dataclass
class LoginResponse(Response):
user_id: str = field()
device_id: str = field()
access_token: str = field()
def __str__(self):
# type: () -> str
return "Logged in as {}, device id: {}.".format(
self.user_id, self.device_id
)
@classmethod
@verify(Schemas.login, LoginError)
def from_dict(cls, parsed_dict):
# type: (Dict[Any, Any]) -> Union[LoginResponse, ErrorResponse]
return cls(
parsed_dict["user_id"],
parsed_dict["device_id"],
parsed_dict["access_token"],
)
@dataclass
class LogoutResponse(Response):
def __str__(self):
# type: () -> str
return "Logged out"
@classmethod
@verify(Schemas.empty, LogoutError)
def from_dict(cls, parsed_dict):
# type: (Dict[Any, Any]) -> Union[LogoutResponse, ErrorResponse]
"""Create a response for logout response from server."""
return cls()
@dataclass
class JoinedMembersResponse(Response):
members: List[RoomMember] = field()
room_id: str = field()
@classmethod
@verify(Schemas.joined_members, JoinedMembersError)
def from_dict(
cls,
parsed_dict, # type: Dict[Any, Any]
room_id # type: str
):
# type: (...) -> Union[JoinedMembersResponse, ErrorResponse]
members = []
for user_id, user_info in parsed_dict["joined"].items():
user = RoomMember(
user_id,
user_info.get("display_name", None),
user_info.get("avatar_url", None)
)
members.append(user)
return cls(members, room_id)
@dataclass
class JoinedRoomsResponse(Response):
"""A response containing a list of joined rooms.
Attributes:
rooms (List[str]): The rooms joined by the account.
"""
rooms: List[str] = field()
@classmethod
@verify(Schemas.joined_rooms, JoinedRoomsError)
def from_dict(
cls,
parsed_dict # type: Dict[Any, Any]
):
# type: (...) -> Union[JoinedRoomsResponse, ErrorResponse]
return cls(parsed_dict["joined_rooms"])
@dataclass
class ContentRepositoryConfigResponse(Response):
"""A response for a successful content repository config request.
Attributes:
upload_size (Optional[int]): The maximum file size in bytes for an
upload. If `None`, the limit is unknown.
"""
upload_size: Optional[int] = None
@classmethod
@verify(Schemas.content_repository_config, ContentRepositoryConfigError)
def from_dict(
cls,
parsed_dict: dict,
) -> Union["ContentRepositoryConfigResponse", ErrorResponse]:
return cls(parsed_dict.get("m.upload.size"))
@dataclass
class UploadResponse(Response):
"""A response representing a successful upload request."""
content_uri: str = field()
@classmethod
@verify(Schemas.upload, UploadError)
def from_dict(cls, parsed_dict):
# type: (Dict[Any, Any]) -> Union[UploadResponse, ErrorResponse]
return cls(
parsed_dict["content_uri"],
)
@dataclass
class DownloadResponse(FileResponse):
"""A response representing a successful download request."""
@classmethod
def from_data(
cls,
data, # type: bytes
content_type, # type: str
filename=None # type: Optional[str]
):
# type: (...) -> Union[DownloadResponse, DownloadError]
if isinstance(data, bytes):
return cls(body=data, content_type=content_type, filename=filename)
if isinstance(data, dict):
return DownloadError.from_dict(data)
return DownloadError("invalid data")
@dataclass
class ThumbnailResponse(FileResponse):
"""A response representing a successful thumbnail request."""
@classmethod
def from_data(
cls,
data, # type: bytes
content_type, # type: str
filename=None # type: Optional[str]
):
# type: (...) -> Union[ThumbnailResponse, ThumbnailError]
if not content_type.startswith("image/"):
return ThumbnailError(f"invalid content type: {content_type}")
if isinstance(data, bytes):
return cls(body=data, content_type=content_type, filename=filename)
if isinstance(data, dict):
return ThumbnailError.from_dict(data)
return ThumbnailError("invalid data")
@dataclass
class RoomEventIdResponse(Response):
event_id: str = field()
room_id: str = field()
@staticmethod
def create_error(parsed_dict, _room_id):
return ErrorResponse.from_dict(parsed_dict)
@classmethod
def from_dict(
cls,
parsed_dict, # type: Dict[Any, Any]
room_id # type: str
):
# type: (...) -> Union[RoomEventIdResponse, ErrorResponse]
try:
validate_json(parsed_dict, Schemas.room_event_id)
except (SchemaError, ValidationError):
return cls.create_error(parsed_dict, room_id)
return cls(parsed_dict["event_id"], room_id)
class RoomSendResponse(RoomEventIdResponse):
@staticmethod
def create_error(parsed_dict, room_id):
return RoomSendError.from_dict(parsed_dict, room_id)
@dataclass
class RoomGetStateResponse(Response):
"""A response containing the state of a room.
Attributes:
events (List): The events making up the room state.
room_id (str): The ID of the room.
"""
events: List = field()
room_id: str = field()
@staticmethod
def create_error(parsed_dict, room_id):
return RoomGetStateError.from_dict(parsed_dict, room_id)
@classmethod
def from_dict(
cls,
parsed_dict, # type: ignore
room_id # type: str
):
# type: (...) -> Union[RoomGetStateResponse, RoomGetStateError]
try:
validate_json(parsed_dict, Schemas.room_state)
except (SchemaError, ValidationError):
return cls.create_error(parsed_dict, room_id)
return cls(parsed_dict, room_id)
@dataclass
class RoomGetStateEventResponse(Response):
"""A response containing the content of a specific bit of room state.
Attributes:
content (Dict): The content of the state event.
event_type (str): The type of the state event.
state_key (str): The key of the state event.
room_id (str): The ID of the room that the state event comes from.
"""
content: Dict = field()
event_type: str = field()
state_key: str = field()
room_id: str = field()
@staticmethod
def create_error(parsed_dict, room_id):
return RoomGetStateEventError.from_dict(parsed_dict, room_id)
@classmethod
def from_dict(
cls,
parsed_dict: Dict[str, Any],
event_type: str,
state_key: str,
room_id: str,
) -> Union["RoomGetStateEventResponse", RoomGetStateEventError] :
return cls(parsed_dict, event_type, state_key, room_id)
class RoomGetEventResponse(Response):
"""A response indicating successful room get event request.
Attributes:
event (Event): The requested event.
"""
event: Event = field()
@classmethod
@verify(
Schemas.room_event,
RoomGetEventError,
pass_arguments=False,
)
def from_dict(
cls,
parsed_dict: Dict[str, Any]
) -> Union["RoomGetEventResponse", RoomGetEventError]:
event = Event.parse_event(parsed_dict)
resp = cls()
resp.event = event
return resp
class RoomPutStateResponse(RoomEventIdResponse):
"""A response indicating successful sending of room state."""
@staticmethod
def create_error(parsed_dict, room_id):
return RoomPutStateError.from_dict(parsed_dict, room_id)
class RoomRedactResponse(RoomEventIdResponse):
@staticmethod
def create_error(parsed_dict, room_id):
return RoomRedactError.from_dict(parsed_dict, room_id)
@dataclass
class RoomResolveAliasResponse(Response):
"""A response containing the result of resolving an alias.
Attributes:
room_alias (str): The alias of the room.
room_id (str): The resolved id of the room.
servers (List[str]): Servers participating in the room.
"""
room_alias: str = field()
room_id: str = field()
servers: List[str] = field()
@classmethod
@verify(
Schemas.room_resolve_alias,
RoomResolveAliasError,
pass_arguments=False,
)
def from_dict(
cls,
parsed_dict, # type: Dict[Any, Any]
room_alias
):
# type: (...) -> Union[RoomResolveAliasResponse, ErrorResponse]
room_id = parsed_dict["room_id"]
servers = parsed_dict["servers"]
return cls(room_alias, room_id, servers)
class EmptyResponse(Response):
@staticmethod
def create_error(parsed_dict):
return ErrorResponse.from_dict(parsed_dict)
@classmethod
def from_dict(cls, parsed_dict):
# type: (Dict[Any, Any]) -> Union[Any, ErrorResponse]
try:
validate_json(parsed_dict, Schemas.empty)
except (SchemaError, ValidationError):
return cls.create_error(parsed_dict)
return cls()
@dataclass
class _EmptyResponseWithRoomId(Response):
room_id: str = field()
@staticmethod
def create_error(parsed_dict, room_id):
return _ErrorWithRoomId.from_dict(parsed_dict, room_id)
@classmethod
def from_dict(cls, parsed_dict, room_id):
# type: (Dict[Any, Any], str) -> Union[Any, ErrorResponse]
try:
validate_json(parsed_dict, Schemas.empty)
except (SchemaError, ValidationError):
return cls.create_error(parsed_dict, room_id)
return cls(room_id)
class RoomKickResponse(EmptyResponse):
@staticmethod
def create_error(parsed_dict):
return RoomKickError.from_dict(parsed_dict)
class RoomBanResponse(EmptyResponse):
@staticmethod
def create_error(parsed_dict):
return RoomBanError.from_dict(parsed_dict)
class RoomUnbanResponse(EmptyResponse):
@staticmethod
def create_error(parsed_dict):
return RoomUnbanError.from_dict(parsed_dict)
class RoomInviteResponse(EmptyResponse):
@staticmethod
def create_error(parsed_dict):
return RoomInviteError.from_dict(parsed_dict)
@dataclass
class ShareGroupSessionResponse(Response):
"""Response representing a successful group sessions sharing request.
Attributes:
room_id (str): The room id of the group session.
users_shared_with (Set[Tuple[str, str]]): A set containing a tuple of
user id device id pairs with whom we shared the group session in
this request.
"""
room_id: str = field()
users_shared_with: set = field()
@classmethod
@verify(Schemas.empty, ShareGroupSessionError)
def from_dict(
cls,