14
14
import itertools
15
15
import logging
16
16
from collections import defaultdict
17
- from typing import TYPE_CHECKING , Any , Callable , Dict , List , Tuple
17
+ from typing import TYPE_CHECKING , Any , Callable , Dict , List , Optional , Tuple , Union
18
18
19
19
from synapse .api .constants import Membership , PresenceState
20
20
from synapse .api .errors import Codes , StoreError , SynapseError
21
21
from synapse .api .filtering import DEFAULT_FILTER_COLLECTION , FilterCollection
22
+ from synapse .api .presence import UserPresenceState
22
23
from synapse .events .utils import (
23
24
format_event_for_client_v2_without_room_id ,
24
25
format_event_raw ,
25
26
)
26
27
from synapse .handlers .presence import format_user_presence_state
27
- from synapse .handlers .sync import KnockedSyncResult , SyncConfig
28
+ from synapse .handlers .sync import (
29
+ ArchivedSyncResult ,
30
+ InvitedSyncResult ,
31
+ JoinedSyncResult ,
32
+ KnockedSyncResult ,
33
+ SyncConfig ,
34
+ SyncResult ,
35
+ )
36
+ from synapse .http .server import HttpServer
28
37
from synapse .http .servlet import RestServlet , parse_boolean , parse_integer , parse_string
29
38
from synapse .http .site import SynapseRequest
30
39
from synapse .types import JsonDict , StreamToken
@@ -192,14 +201,22 @@ async def on_GET(self, request: SynapseRequest) -> Tuple[int, JsonDict]:
192
201
return 200 , {}
193
202
194
203
time_now = self .clock .time_msec ()
204
+ # We know that the the requester has an access token since appservices
205
+ # cannot use sync.
195
206
response_content = await self .encode_response (
196
207
time_now , sync_result , requester .access_token_id , filter_collection
197
208
)
198
209
199
210
logger .debug ("Event formatting complete" )
200
211
return 200 , response_content
201
212
202
- async def encode_response (self , time_now , sync_result , access_token_id , filter ):
213
+ async def encode_response (
214
+ self ,
215
+ time_now : int ,
216
+ sync_result : SyncResult ,
217
+ access_token_id : Optional [int ],
218
+ filter : FilterCollection ,
219
+ ) -> JsonDict :
203
220
logger .debug ("Formatting events in sync response" )
204
221
if filter .event_format == "client" :
205
222
event_formatter = format_event_for_client_v2_without_room_id
@@ -234,7 +251,7 @@ async def encode_response(self, time_now, sync_result, access_token_id, filter):
234
251
235
252
logger .debug ("building sync response dict" )
236
253
237
- response : dict = defaultdict (dict )
254
+ response : JsonDict = defaultdict (dict )
238
255
response ["next_batch" ] = await sync_result .next_batch .to_string (self .store )
239
256
240
257
if sync_result .account_data :
@@ -274,6 +291,8 @@ async def encode_response(self, time_now, sync_result, access_token_id, filter):
274
291
if archived :
275
292
response ["rooms" ][Membership .LEAVE ] = archived
276
293
294
+ # By the time we get here groups is no longer optional.
295
+ assert sync_result .groups is not None
277
296
if sync_result .groups .join :
278
297
response ["groups" ][Membership .JOIN ] = sync_result .groups .join
279
298
if sync_result .groups .invite :
@@ -284,7 +303,7 @@ async def encode_response(self, time_now, sync_result, access_token_id, filter):
284
303
return response
285
304
286
305
@staticmethod
287
- def encode_presence (events , time_now ) :
306
+ def encode_presence (events : List [ UserPresenceState ] , time_now : int ) -> JsonDict :
288
307
return {
289
308
"events" : [
290
309
{
@@ -299,25 +318,27 @@ def encode_presence(events, time_now):
299
318
}
300
319
301
320
async def encode_joined (
302
- self , rooms , time_now , token_id , event_fields , event_formatter
303
- ):
321
+ self ,
322
+ rooms : List [JoinedSyncResult ],
323
+ time_now : int ,
324
+ token_id : Optional [int ],
325
+ event_fields : List [str ],
326
+ event_formatter : Callable [[JsonDict ], JsonDict ],
327
+ ) -> JsonDict :
304
328
"""
305
329
Encode the joined rooms in a sync result
306
330
307
331
Args:
308
- rooms(list[synapse.handlers.sync.JoinedSyncResult]): list of sync
309
- results for rooms this user is joined to
310
- time_now(int): current time - used as a baseline for age
311
- calculations
312
- token_id(int): ID of the user's auth token - used for namespacing
332
+ rooms: list of sync results for rooms this user is joined to
333
+ time_now: current time - used as a baseline for age calculations
334
+ token_id: ID of the user's auth token - used for namespacing
313
335
of transaction IDs
314
- event_fields(list<str>) : List of event fields to include. If empty,
336
+ event_fields: List of event fields to include. If empty,
315
337
all fields will be returned.
316
- event_formatter (func[dict]) : function to convert from federation format
338
+ event_formatter: function to convert from federation format
317
339
to client format
318
340
Returns:
319
- dict[str, dict[str, object]]: the joined rooms list, in our
320
- response format
341
+ The joined rooms list, in our response format
321
342
"""
322
343
joined = {}
323
344
for room in rooms :
@@ -332,23 +353,26 @@ async def encode_joined(
332
353
333
354
return joined
334
355
335
- async def encode_invited (self , rooms , time_now , token_id , event_formatter ):
356
+ async def encode_invited (
357
+ self ,
358
+ rooms : List [InvitedSyncResult ],
359
+ time_now : int ,
360
+ token_id : Optional [int ],
361
+ event_formatter : Callable [[JsonDict ], JsonDict ],
362
+ ) -> JsonDict :
336
363
"""
337
364
Encode the invited rooms in a sync result
338
365
339
366
Args:
340
- rooms(list[synapse.handlers.sync.InvitedSyncResult]): list of
341
- sync results for rooms this user is invited to
342
- time_now(int): current time - used as a baseline for age
343
- calculations
344
- token_id(int): ID of the user's auth token - used for namespacing
367
+ rooms: list of sync results for rooms this user is invited to
368
+ time_now: current time - used as a baseline for age calculations
369
+ token_id: ID of the user's auth token - used for namespacing
345
370
of transaction IDs
346
- event_formatter (func[dict]) : function to convert from federation format
371
+ event_formatter: function to convert from federation format
347
372
to client format
348
373
349
374
Returns:
350
- dict[str, dict[str, object]]: the invited rooms list, in our
351
- response format
375
+ The invited rooms list, in our response format
352
376
"""
353
377
invited = {}
354
378
for room in rooms :
@@ -371,7 +395,7 @@ async def encode_knocked(
371
395
self ,
372
396
rooms : List [KnockedSyncResult ],
373
397
time_now : int ,
374
- token_id : int ,
398
+ token_id : Optional [ int ] ,
375
399
event_formatter : Callable [[Dict ], Dict ],
376
400
) -> Dict [str , Dict [str , Any ]]:
377
401
"""
@@ -422,25 +446,26 @@ async def encode_knocked(
422
446
return knocked
423
447
424
448
async def encode_archived (
425
- self , rooms , time_now , token_id , event_fields , event_formatter
426
- ):
449
+ self ,
450
+ rooms : List [ArchivedSyncResult ],
451
+ time_now : int ,
452
+ token_id : Optional [int ],
453
+ event_fields : List [str ],
454
+ event_formatter : Callable [[JsonDict ], JsonDict ],
455
+ ) -> JsonDict :
427
456
"""
428
457
Encode the archived rooms in a sync result
429
458
430
459
Args:
431
- rooms (list[synapse.handlers.sync.ArchivedSyncResult]): list of
432
- sync results for rooms this user is joined to
433
- time_now(int): current time - used as a baseline for age
434
- calculations
435
- token_id(int): ID of the user's auth token - used for namespacing
460
+ rooms: list of sync results for rooms this user is joined to
461
+ time_now: current time - used as a baseline for age calculations
462
+ token_id: ID of the user's auth token - used for namespacing
436
463
of transaction IDs
437
- event_fields(list<str>) : List of event fields to include. If empty,
464
+ event_fields: List of event fields to include. If empty,
438
465
all fields will be returned.
439
- event_formatter (func[dict]): function to convert from federation format
440
- to client format
466
+ event_formatter: function to convert from federation format to client format
441
467
Returns:
442
- dict[str, dict[str, object]]: The invited rooms list, in our
443
- response format
468
+ The archived rooms list, in our response format
444
469
"""
445
470
joined = {}
446
471
for room in rooms :
@@ -456,23 +481,27 @@ async def encode_archived(
456
481
return joined
457
482
458
483
async def encode_room (
459
- self , room , time_now , token_id , joined , only_fields , event_formatter
460
- ):
484
+ self ,
485
+ room : Union [JoinedSyncResult , ArchivedSyncResult ],
486
+ time_now : int ,
487
+ token_id : Optional [int ],
488
+ joined : bool ,
489
+ only_fields : Optional [List [str ]],
490
+ event_formatter : Callable [[JsonDict ], JsonDict ],
491
+ ) -> JsonDict :
461
492
"""
462
493
Args:
463
- room (JoinedSyncResult|ArchivedSyncResult): sync result for a
464
- single room
465
- time_now (int): current time - used as a baseline for age
466
- calculations
467
- token_id (int): ID of the user's auth token - used for namespacing
494
+ room: sync result for a single room
495
+ time_now: current time - used as a baseline for age calculations
496
+ token_id: ID of the user's auth token - used for namespacing
468
497
of transaction IDs
469
- joined (bool) : True if the user is joined to this room - will mean
498
+ joined: True if the user is joined to this room - will mean
470
499
we handle ephemeral events
471
- only_fields(list<str>) : Optional. The list of event fields to include.
472
- event_formatter (func[dict]) : function to convert from federation format
500
+ only_fields: Optional. The list of event fields to include.
501
+ event_formatter: function to convert from federation format
473
502
to client format
474
503
Returns:
475
- dict[str, object]: the room, encoded in our response format
504
+ The room, encoded in our response format
476
505
"""
477
506
478
507
def serialize (events ):
@@ -508,7 +537,7 @@ def serialize(events):
508
537
509
538
account_data = room .account_data
510
539
511
- result = {
540
+ result : JsonDict = {
512
541
"timeline" : {
513
542
"events" : serialized_timeline ,
514
543
"prev_batch" : await room .timeline .prev_batch .to_string (self .store ),
@@ -519,6 +548,7 @@ def serialize(events):
519
548
}
520
549
521
550
if joined :
551
+ assert isinstance (room , JoinedSyncResult )
522
552
ephemeral_events = room .ephemeral
523
553
result ["ephemeral" ] = {"events" : ephemeral_events }
524
554
result ["unread_notifications" ] = room .unread_notifications
@@ -528,5 +558,5 @@ def serialize(events):
528
558
return result
529
559
530
560
531
- def register_servlets (hs , http_server ) :
561
+ def register_servlets (hs : "HomeServer" , http_server : HttpServer ) -> None :
532
562
SyncRestServlet (hs ).register (http_server )
0 commit comments