forked from matrix-org/matrix-ios-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMXSession.m
5045 lines (4191 loc) · 181 KB
/
MXSession.m
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
/*
Copyright 2014 OpenMarket Ltd
Copyright 2017 Vector Creations Ltd
Copyright 2018 New Vector Ltd
Copyright 2019 The Matrix.org Foundation C.I.C
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import "MXSession.h"
#import "MatrixSDK.h"
#import <AFNetworking/AFNetworking.h>
#import "MXSessionEventListener.h"
#import "MXTools.h"
#import "MXHTTPClient.h"
#import "MXNoStore.h"
#import "MXMemoryStore.h"
#import "MXFileStore.h"
#import "MXDecryptionResult.h"
#import "MXAccountData.h"
#import "MXSDKOptions.h"
#import "MXBackgroundModeHandler.h"
#import "MXRoomSummaryUpdater.h"
#import "MXRoomAccountDataUpdater.h"
#import "MXRoomFilter.h"
#import "MXScanManager.h"
#import "MXAggregations_Private.h"
#import "MatrixSDKSwiftHeader.h"
#import "MXRoomSummaryProtocol.h"
#pragma mark - Constants definitions
NSString *const kMXSessionStateDidChangeNotification = @"kMXSessionStateDidChangeNotification";
NSString *const kMXSessionNewRoomNotification = @"kMXSessionNewRoomNotification";
NSString *const kMXSessionWillLeaveRoomNotification = @"kMXSessionWillLeaveRoomNotification";
NSString *const kMXSessionDidLeaveRoomNotification = @"kMXSessionDidLeaveRoomNotification";
NSString *const kMXSessionDidSyncNotification = @"kMXSessionDidSyncNotification";
NSString *const kMXSessionInvitedRoomsDidChangeNotification = @"kMXSessionInvitedRoomsDidChangeNotification";
NSString *const kMXSessionOnToDeviceEventNotification = @"kMXSessionOnToDeviceEventNotification";
NSString *const kMXSessionIgnoredUsersDidChangeNotification = @"kMXSessionIgnoredUsersDidChangeNotification";
NSString *const kMXSessionDirectRoomsDidChangeNotification = @"kMXSessionDirectRoomsDidChangeNotification";
NSString *const kMXSessionVirtualRoomsDidChangeNotification = @"kMXSessionVirtualRoomsDidChangeNotification";
NSString *const kMXSessionAccountDataDidChangeNotification = @"kMXSessionAccountDataDidChangeNotification";
NSString *const kMXSessionAccountDataDidChangeIdentityServerNotification = @"kMXSessionAccountDataDidChangeIdentityServerNotification";
NSString *const kMXSessionAccountDataDidChangeBreadcrumbsNotification = @"kMXSessionAccountDataDidChangeBreadcrumbsNotification";
NSString *const kMXSessionDidCorruptDataNotification = @"kMXSessionDidCorruptDataNotification";
NSString *const kMXSessionCryptoDidCorruptDataNotification = @"kMXSessionCryptoDidCorruptDataNotification";
NSString *const kMXSessionNewGroupInviteNotification = @"kMXSessionNewGroupInviteNotification";
NSString *const kMXSessionDidJoinGroupNotification = @"kMXSessionDidJoinGroupNotification";
NSString *const kMXSessionDidLeaveGroupNotification = @"kMXSessionDidLeaveGroupNotification";
NSString *const kMXSessionDidUpdateGroupSummaryNotification = @"kMXSessionDidUpdateGroupSummaryNotification";
NSString *const kMXSessionDidUpdateGroupRoomsNotification = @"kMXSessionDidUpdateGroupRoomsNotification";
NSString *const kMXSessionDidUpdateGroupUsersNotification = @"kMXSessionDidUpdateGroupUsersNotification";
NSString *const kMXSessionDidUpdatePublicisedGroupsForUsersNotification = @"kMXSessionDidUpdatePublicisedGroupsForUsersNotification";
NSString *const kMXSessionNotificationRoomIdKey = @"roomId";
NSString *const kMXSessionNotificationGroupKey = @"group";
NSString *const kMXSessionNotificationGroupIdKey = @"groupId";
NSString *const kMXSessionNotificationEventKey = @"event";
NSString *const kMXSessionNotificationSyncResponseKey = @"syncResponse";
NSString *const kMXSessionNotificationErrorKey = @"error";
NSString *const kMXSessionNotificationUserIdsArrayKey = @"userIds";
NSString *const kMXSessionNoRoomTag = @"m.recent"; // Use the same value as matrix-react-sdk
/**
Default timeouts used by the events streams.
*/
#define SERVER_TIMEOUT_MS 30000
#define CLIENT_TIMEOUT_MS 120000
/**
Time before retrying in case of `MXSessionStateSyncError`.
*/
#define RETRY_SYNC_AFTER_MXERROR_MS 5000
// Block called when MSSession resume is complete
typedef void (^MXOnResumeDone)(void);
@interface MXSession ()
{
/**
Rooms data
Each key is a room id. Each value, the MXRoom instance.
*/
NSMutableDictionary<NSString*, MXRoom*> *rooms;
/**
Rooms summaries
Each key is a room id. Each value, the MXRoomSummary instance.
*/
NSMutableDictionary<NSString*, MXRoomSummary*> *roomSummaries;
/**
The current request of the event stream.
*/
MXHTTPOperation *eventStreamRequest;
/**
The list of global events listeners (`MXSessionEventListener`).
*/
NSMutableArray *globalEventListeners;
/**
The block to call when MSSession resume is complete.
*/
MXOnResumeDone onResumeDone;
/**
The block to call when MSSession backgroundSync is successfully done.
*/
MXOnBackgroundSyncDone onBackgroundSyncDone;
/**
The block to call when MSSession backgroundSync fails.
*/
MXOnBackgroundSyncFail onBackgroundSyncFail;
/**
The maintained list of rooms where the user has a pending invitation.
*/
NSMutableArray<MXRoom *> *invitedRooms;
/**
The rooms being peeked.
*/
NSMutableArray<MXPeekingRoom *> *peekingRooms;
/**
For debug, indicate if the first sync after the MXSession startup is done.
*/
BOOL firstSyncDone;
/**
The tool to refresh the homeserver wellknown data.
*/
MXAutoDiscovery *autoDiscovery;
/**
Queue of requested direct room change operations ([MXSession setRoom:directWithUserId:]
or [MXSession uploadDirectRooms:])
*/
NSMutableArray<dispatch_block_t> *directRoomsOperationsQueue;
/**
The current publicised groups list by userId dictionary.
The key is the user id; the value, the list of the group ids that the user enabled in his profile.
*/
NSMutableDictionary <NSString*, NSArray<NSString*>*> *publicisedGroupsByUserId;
/**
The list of users for who a publicised groups list is available but outdated.
*/
NSMutableArray <NSString*> *userIdsWithOutdatedPublicisedGroups;
/**
Native -> virtual rooms ids map.
Each key is a native room id. Each value is the virtual room id.
*/
NSMutableDictionary<NSString*, NSString*> *nativeToVirtualRoomIds;
/**
Async queue to run a single task at a time.
*/
MXAsyncTaskQueue *asyncTaskQueue;
/**
Flag to indicate whether a fixRoomsLastMessage execution is ongoing.
*/
BOOL fixingRoomsLastMessages;
}
/**
The count of prevent pause tokens.
*/
@property (nonatomic) NSUInteger preventPauseCount;
@property (nonatomic, readwrite) MXScanManager *scanManager;
/**
The background task used when the session continue to run the events stream when
the app goes in background.
*/
@property (nonatomic, strong) id<MXBackgroundTask> backgroundTask;
@property (nonatomic, strong) id<MXSyncResponseStore> initialSyncResponseCache;
@property (atomic, copy, readwrite) NSDictionary<NSString*, NSArray<NSString*>*> *directRooms;
@property (nonatomic, readwrite) id<MXRoomListDataManager> roomListDataManager;
@property (nonatomic, readonly) MXStoreService *storeService;
@end
@implementation MXSession
@synthesize matrixRestClient, mediaManager;
- (id)initWithMatrixRestClient:(MXRestClient*)mxRestClient
{
self = [super init];
if (self)
{
matrixRestClient = mxRestClient;
_threePidAddManager = [[MX3PidAddManager alloc] initWithMatrixSession:self];
mediaManager = [[MXMediaManager alloc] initWithHomeServer:matrixRestClient.homeserver];
rooms = [NSMutableDictionary dictionary];
roomSummaries = [NSMutableDictionary dictionary];
_roomSummaryUpdateDelegate = [MXRoomSummaryUpdater roomSummaryUpdaterForSession:self];
_roomAccountDataUpdateDelegate = [MXRoomAccountDataUpdater roomAccountDataUpdaterForSession:self];
globalEventListeners = [NSMutableArray array];
_notificationCenter = [[MXNotificationCenter alloc] initWithMatrixSession:self];
_accountData = [[MXAccountData alloc] init];
peekingRooms = [NSMutableArray array];
_preventPauseCount = 0;
directRoomsOperationsQueue = [NSMutableArray array];
publicisedGroupsByUserId = [[NSMutableDictionary alloc] init];
nativeToVirtualRoomIds = [NSMutableDictionary dictionary];
asyncTaskQueue = [[MXAsyncTaskQueue alloc] initWithDispatchQueue:dispatch_get_main_queue() label:@"MXAsyncTaskQueue-MXSession"];
_spaceService = [[MXSpaceService alloc] initWithSession:self];
// add did build graph notification
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(spaceServiceDidBuildSpaceGraph:)
name:MXSpaceService.didBuildSpaceGraph
object:_spaceService];
_threadingService = [[MXThreadingService alloc] initWithSession:self];
_eventStreamService = [[MXEventStreamService alloc] init];
_preferredSyncPresence = MXPresenceOnline;
_locationService = [[MXLocationService alloc] initWithSession:self];
[self setIdentityServer:mxRestClient.identityServer andAccessToken:mxRestClient.credentials.identityServerAccessToken];
firstSyncDone = NO;
_acknowledgableEventTypes = @[kMXEventTypeStringRoomName,
kMXEventTypeStringRoomTopic,
kMXEventTypeStringRoomAvatar,
kMXEventTypeStringRoomMember,
kMXEventTypeStringRoomCreate,
kMXEventTypeStringRoomEncrypted,
kMXEventTypeStringRoomJoinRules,
kMXEventTypeStringRoomPowerLevels,
kMXEventTypeStringRoomAliases,
kMXEventTypeStringRoomCanonicalAlias,
kMXEventTypeStringRoomGuestAccess,
kMXEventTypeStringRoomHistoryVisibility,
kMXEventTypeStringRoomMessage,
kMXEventTypeStringRoomMessageFeedback,
kMXEventTypeStringRoomRedaction,
kMXEventTypeStringRoomThirdPartyInvite,
kMXEventTypeStringRoomRelatedGroups,
kMXEventTypeStringReaction,
kMXEventTypeStringCallInvite,
kMXEventTypeStringCallCandidates,
kMXEventTypeStringCallAnswer,
kMXEventTypeStringCallSelectAnswer,
kMXEventTypeStringCallHangup,
kMXEventTypeStringCallReject,
kMXEventTypeStringCallNegotiate,
kMXEventTypeStringSticker
];
_unreadEventTypes = @[kMXEventTypeStringRoomName,
kMXEventTypeStringRoomTopic,
kMXEventTypeStringRoomMessage,
kMXEventTypeStringCallInvite,
kMXEventTypeStringRoomEncrypted,
kMXEventTypeStringSticker
];
_catchingUp = NO;
MXCredentials *initialSyncCredentials = [MXCredentials initialSyncCacheCredentialsFrom:mxRestClient.credentials];
_initialSyncResponseCache = [[MXSyncResponseFileStore alloc] initWithCredentials:initialSyncCredentials];
_homeserverCapabilitiesService = [[MXHomeserverCapabilitiesService alloc] initWithSession: self];
[_homeserverCapabilitiesService updateWithCompletion:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onDidDecryptEvent:) name:kMXEventDidDecryptNotification object:nil];
[self setState:MXSessionStateInitialised];
}
return self;
}
- (MXCredentials *)credentials
{
return matrixRestClient.credentials;
}
- (NSString *)myUserId
{
return matrixRestClient.credentials.userId;
}
- (NSString *)myDeviceId
{
return matrixRestClient.credentials.deviceId;
}
- (void)setState:(MXSessionState)state
{
if (_state != state)
{
MXLogDebug(@"[MXSession] setState: %@ (was %@)", [MXTools readableSessionState:state], [MXTools readableSessionState:_state]);
_state = state;
if (_state != MXSessionStateSyncError)
{
// Reset the sync error
_syncError = nil;
}
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter postNotificationName:kMXSessionStateDidChangeNotification object:self userInfo:nil];
[_eventStreamService dispatchSessionStateChangedWithState:state];
}
}
- (id<MXStore>)store
{
return self.storeService.mainStore;
}
-(void)setStore:(id<MXStore>)store success:(void (^)(void))onStoreDataReady failure:(void (^)(NSError *))failure
{
NSAssert(MXSessionStateInitialised == _state, @"Store can be set only just after initialisation");
NSParameterAssert(store);
_storeService = [[MXStoreService alloc] initWithStore:store credentials:matrixRestClient.credentials];
// Validate the permanent implementation
if (self.store.isPermanent)
{
// A permanent MXStore must implement these methods:
NSParameterAssert([self.store respondsToSelector:@selector(storeStateForRoom:stateEvents:)]);
NSParameterAssert([self.store respondsToSelector:@selector(stateOfRoom:success:failure:)]);
}
self.roomListDataManager = [[MXSDKOptions.sharedInstance.roomListDataManagerClass alloc] init];
NSDate *startDate = [NSDate date];
MXTaskProfile *taskProfile = [MXSDKOptions.sharedInstance.profiler startMeasuringTaskWithName:MXTaskProfileNameStartupMountData];
MXWeakify(self);
[self.store openWithCredentials:matrixRestClient.credentials onComplete:^{
MXStrongifyAndReturnIfNil(self);
// Sanity check: The session may be closed before the end of store opening.
if (!self->matrixRestClient)
{
return;
}
self.storeService.aggregations = [[MXAggregations alloc] initWithMatrixSession:self];
// Check if the user has enabled crypto
MXWeakify(self);
[MXCrypto checkCryptoWithMatrixSession:self complete:^(MXCrypto *crypto) {
MXStrongifyAndReturnIfNil(self);
self->_crypto = crypto;
// Sanity check: The session may be closed before the end of this operation.
if (!self->matrixRestClient)
{
return;
}
// Can we start on data from the MXStore?
if (self.store.isPermanent && self.isEventStreamInitialised)
{
// Mount data from the permanent store
MXLogDebug(@"[MXSession] Loading room state events to build MXRoom objects...");
// Create myUser from the store
MXUser *myUser = [self.store userWithUserId:self->matrixRestClient.credentials.userId];
// My user is a MXMyUser object
if ([myUser isKindOfClass:[MXMyUser class]])
{
self->_myUser = (MXMyUser *)myUser;
}
else
{
self->_myUser = [[MXMyUser alloc] initWithUserId:myUser.userId andDisplayname:myUser.displayname andAvatarUrl:myUser.avatarUrl];
}
self->_myUser.mxSession = self;
// Use the cached agreement to identity server terms.
if (self.identityService)
{
self.identityService.areAllTermsAgreed = self.store.areAllIdentityServerTermsAgreed;
}
// Load user account data
[self handleAccountData:self.store.userAccountData];
// Refresh identity server terms with complete account data
[self refreshIdentityServerServiceTerms];
// Load MXRoomSummaries from the store
NSDate *startDate2 = [NSDate date];
dispatch_group_t dispatchGroupRooms = dispatch_group_create();
NSUInteger numberOfSummaries = self.store.roomSummaryStore.countOfRooms;
taskProfile.units = numberOfSummaries;
NSArray<NSString *> *roomIDs = self.store.roomIds;
BOOL fixSummariesLastMessages = NO;
if (numberOfSummaries < roomIDs.count)
{
MXLogWarning(@"[MXFileStore] Detected missing rooms, expected: %tu, got: %tu", roomIDs.count, numberOfSummaries);
fixSummariesLastMessages = YES;
// remove all room summaries
[self.store.roomSummaryStore removeAllSummaries];
// recreate room summaries
for (NSString *roomID in roomIDs)
{
dispatch_group_enter(dispatchGroupRooms);
[MXRoomState loadRoomStateFromStore:self.store
withRoomId:roomID
matrixSession:self
onComplete:^(MXRoomState *roomState) {
MXRoomSummary *summary = [self getOrCreateRoomSummary:roomID];
[self.roomSummaryUpdateDelegate session:self
updateRoomSummary:summary
withStateEvents:roomState.stateEvents
roomState:roomState];
[summary save:YES];
dispatch_group_leave(dispatchGroupRooms);
}];
}
}
dispatch_group_notify(dispatchGroupRooms, dispatch_get_main_queue(), ^{
NSArray<NSString*> *roomIds = self.store.roomSummaryStore.rooms;
MXLogDebug(@"[MXSession] Read %lu room ids in %.0fms", (unsigned long)roomIds.count, [[NSDate date] timeIntervalSinceDate:startDate2] * 1000);
// Create MXRooms from their states stored in the store
NSDate *startDate3 = [NSDate date];
for (NSString *roomId in roomIds)
{
[self loadRoom:roomId];
}
MXLogDebug(@"[MXSession] Built %lu MXRooms in %.0fms", (unsigned long)self->rooms.count, [[NSDate date] timeIntervalSinceDate:startDate3] * 1000);
if (fixSummariesLastMessages)
{
[self fixRoomsSummariesLastMessageWithMaxServerPaginationCount:MXRoomSummaryPaginationChunkSize
force:YES
completion:nil];
}
taskProfile.units = self->rooms.count;
[MXSDKOptions.sharedInstance.profiler stopMeasuringTaskWithProfile:taskProfile];
MXLogDebug(@"[MXSession] Total time to mount SDK data from MXStore: %.0fms", taskProfile.duration * 1000);
[self setState:MXSessionStateStoreDataReady];
// The SDK client can use this data
onStoreDataReady();
});
}
else
{
// Create self.myUser instance to expose the user id as soon as possible
self->_myUser = [[MXMyUser alloc] initWithUserId:self->matrixRestClient.credentials.userId];
self->_myUser.mxSession = self;
MXLogDebug(@"[MXSession] Total time to mount SDK data from MXStore: %.0fms", [[NSDate date] timeIntervalSinceDate:startDate] * 1000);
[self setState:MXSessionStateStoreDataReady];
// The SDK client can use this data
onStoreDataReady();
}
}];
} failure:^(NSError *error) {
[self setState:MXSessionStateInitialised];
if (failure)
{
failure(error);
}
}];
}
- (void)setRoomListDataManager:(id<MXRoomListDataManager>)roomListDataManager
{
NSParameterAssert(_roomListDataManager == nil);
_roomListDataManager = roomListDataManager;
[_roomListDataManager configureWithSession:self];
}
/// Handle a sync response and decide serverTimeout for the next sync request.
/// @param syncResponse The sync response object
/// @param completion Completion block to be called at the end of the process. Will be called on the caller thread.
/// @param storeCompletion Completion block to be called when the process completed at store level, i.e sync response is stored. Will be called on main thread.
- (void)handleSyncResponse:(MXSyncResponse *)syncResponse
completion:(void (^)(void))completion
storeCompletion:(void (^)(void))storeCompletion
{
MXLogDebug(@"[MXSession] handleSyncResponse: Received %tu joined rooms, %tu invited rooms, %tu left rooms, %tu toDevice events.", syncResponse.rooms.join.count, syncResponse.rooms.invite.count, syncResponse.rooms.leave.count, syncResponse.toDevice.events.count);
[self.crypto handleSyncResponse:syncResponse];
// Check whether this is the initial sync
BOOL isInitialSync = !self.isEventStreamInitialised;
// Handle to_device events before everything else to make future decryptions work
[self handleToDeviceEvents:syncResponse.toDevice.events onComplete:^{
dispatch_group_t dispatchGroup = dispatch_group_create();
// Handle top-level account data
if (syncResponse.accountData)
{
[self handleAccountData:syncResponse.accountData];
}
// Handle first joined rooms
for (NSString *roomId in syncResponse.rooms.join)
{
MXRoomSync *roomSync = syncResponse.rooms.join[roomId];
@autoreleasepool {
// Retrieve existing room or create a new one
MXRoom *room = [self getOrCreateRoom:roomId notify:!isInitialSync];
// Sync room
dispatch_group_enter(dispatchGroup);
[room handleJoinedRoomSync:roomSync onComplete:^{
[room.summary handleJoinedRoomSync:roomSync onComplete:^{
// Make sure the last message has been decrypted
// In case of an initial sync, we save decryptions to save time. Only unread messages are decrypted.
// We need to decrypt already read last message.
if (isInitialSync && room.summary.lastMessage.isEncrypted)
{
[self eventWithEventId:room.summary.lastMessage.eventId
inRoom:room.roomId
success:^(MXEvent *event) {
if (event.eventType == MXEventTypeRoomEncrypted)
{
[room.summary resetLastMessage:^{
dispatch_group_leave(dispatchGroup);
} failure:^(NSError *error) {
dispatch_group_leave(dispatchGroup);
} commit:NO];
}
else
{
dispatch_group_leave(dispatchGroup);
}
} failure:^(NSError *error) {
MXLogError(@"[MXSession] handleSyncResponse: event fetch failed: %@", error);
dispatch_group_leave(dispatchGroup);
}];
}
else
{
dispatch_group_leave(dispatchGroup);
}
}];
}];
for (MXEvent *event in roomSync.accountData.events)
{
if ([event.type isEqualToString:kRoomIsVirtualJSONKey])
{
MXVirtualRoomInfo *virtualRoomInfo = [MXVirtualRoomInfo modelFromJSON:event.content];
if (virtualRoomInfo.isVirtual)
{
// cache this info
[self.roomAccountDataUpdateDelegate updateAccountDataIfRequiredForRoom:room
withNativeRoomId:virtualRoomInfo.nativeRoomId
completion:nil];
}
}
}
[self.threadingService handleJoinedRoomSync:roomSync forRoom:roomId];
}
}
// Handle invited rooms
for (NSString *roomId in syncResponse.rooms.invite)
{
MXInvitedRoomSync *invitedRoomSync = syncResponse.rooms.invite[roomId];
@autoreleasepool {
// Retrieve existing room or create a new one
MXRoom *room = [self getOrCreateRoom:roomId notify:!isInitialSync];
// Prepare invited room
dispatch_group_enter(dispatchGroup);
[room handleInvitedRoomSync:invitedRoomSync onComplete:^{
[room.summary handleInvitedRoomSync:invitedRoomSync];
dispatch_group_leave(dispatchGroup);
}];
}
}
// Handle archived rooms
for (NSString *roomId in syncResponse.rooms.leave)
{
MXRoomSync *leftRoomSync = syncResponse.rooms.leave[roomId];
@autoreleasepool {
// Presently we remove the existing room from the rooms list.
// FIXME SYNCV2 Archive/Display the left rooms!
// For that create 'handleArchivedRoomSync' method
// Retrieve existing room
MXRoom *room = [self roomWithRoomId:roomId];
if (room)
{
// FIXME SYNCV2: While 'handleArchivedRoomSync' is not available,
// use 'handleJoinedRoomSync' to pass the last events to the room before leaving it.
// The room will then able to notify its listeners.
dispatch_group_enter(dispatchGroup);
[room handleJoinedRoomSync:leftRoomSync onComplete:^{
[room.summary handleJoinedRoomSync:leftRoomSync onComplete:^{
// Look for the last room member event
MXEvent *roomMemberEvent;
NSInteger index = leftRoomSync.timeline.events.count;
while (index--)
{
MXEvent *event = leftRoomSync.timeline.events[index];
if ([event.type isEqualToString:kMXEventTypeStringRoomMember])
{
roomMemberEvent = event;
break;
}
}
// Notify the room is going to disappear
NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithObject:room.roomId forKey:kMXSessionNotificationRoomIdKey];
if (roomMemberEvent)
{
userInfo[kMXSessionNotificationEventKey] = roomMemberEvent;
}
[[NSNotificationCenter defaultCenter] postNotificationName:kMXSessionWillLeaveRoomNotification
object:self
userInfo:userInfo];
// Remove the room from the rooms list
[self removeRoom:room.roomId];
dispatch_group_leave(dispatchGroup);
}];
}];
}
}
}
// Check the conditions to update summaries direct user ids for retrieved rooms (We have to do it
// when we receive some invites to handle correctly a new invite to a direct chat that the user has left).
if (isInitialSync || syncResponse.rooms.invite.count)
{
[self updateSummaryDirectUserIdForRooms:[self directRoomIds]];
}
// Handle invited groups
for (NSString *groupId in syncResponse.groups.invite)
{
// Create a new group for each invite
MXInvitedGroupSync *invitedGroupSync = syncResponse.groups.invite[groupId];
[self createGroupInviteWithId:groupId profile:invitedGroupSync.profile andInviter:invitedGroupSync.inviter notify:!isInitialSync];
}
// Handle joined groups
for (NSString *groupId in syncResponse.groups.join)
{
// Join an existing group or create a new one
[self didJoinGroupWithId:groupId notify:!isInitialSync];
}
// Handle left groups
for (NSString *groupId in syncResponse.groups.leave)
{
// Remove the group from the group list
[self removeGroup:groupId];
}
// Handle presence of other users
for (MXEvent *presenceEvent in syncResponse.presence.events)
{
[self handlePresenceEvent:presenceEvent direction:MXTimelineDirectionForwards];
}
// Sync point: wait that all rooms in the /sync response have been loaded
// and their /sync response has been processed
dispatch_group_notify(dispatchGroup, dispatch_get_main_queue(), ^{
if (self.crypto)
{
// Handle device list updates
if (syncResponse.deviceLists)
{
[self.crypto handleDeviceListsChanges:syncResponse.deviceLists];
}
// Handle one_time_keys_count
if (syncResponse.deviceOneTimeKeysCount)
{
[self.crypto handleDeviceOneTimeKeysCount:syncResponse.deviceOneTimeKeysCount];
}
[self.crypto handleDeviceUnusedFallbackKeys:syncResponse.unusedFallbackKeys];
// Tell the crypto module to do its processing
[self.crypto onSyncCompleted:self.store.eventStreamToken
nextSyncToken:syncResponse.nextBatch
catchingUp:self.catchingUp];
}
// Update live event stream token
MXLogDebug(@"[MXSession] Next sync token: %@", syncResponse.nextBatch);
self.store.eventStreamToken = syncResponse.nextBatch;
// Propagate sync response to the associated space service
[self.spaceService handleSyncResponse:syncResponse];
if (!self.homeserverCapabilitiesService.isInitialised)
{
[self.homeserverCapabilitiesService updateWithCompletion:nil];
}
if (completion)
{
completion();
}
// Broadcast that a server sync has been processed.
[[NSNotificationCenter defaultCenter] postNotificationName:kMXSessionDidSyncNotification
object:self
userInfo:@{
kMXSessionNotificationSyncResponseKey: syncResponse
}];
// Commit store changes
if ([self.store respondsToSelector:@selector(commitWithCompletion:)])
{
[self.store commitWithCompletion:storeCompletion];
}
});
}];
}
- (void)setIdentityServer:(NSString *)identityServer andAccessToken:(NSString *)accessToken
{
MXLogDebug(@"[MXSession] setIdentityServer: %@", identityServer);
matrixRestClient.identityServer = identityServer;
if (identityServer)
{
_identityService = [[MXIdentityService alloc] initWithIdentityServer:identityServer accessToken:accessToken andHomeserverRestClient:matrixRestClient];
// Only refresh the terms after the first sync to
// avoid multiple requests from -setStore:success:failure:
if (firstSyncDone)
{
[self refreshIdentityServerServiceTerms];
}
}
else
{
_identityService = nil;
}
MXWeakify(self);
matrixRestClient.identityServerAccessTokenHandler = ^MXHTTPOperation *(void (^success)(NSString *accessToken), void (^failure)(NSError *error)) {
MXStrongifyAndReturnValueIfNil(self, nil);
return [self.identityService accessTokenWithSuccess:success failure:failure];
};
}
- (void)start:(void (^)(void))onServerSyncDone
failure:(void (^)(NSError *error))failure
{
[self startWithSyncFilter:nil onServerSyncDone:onServerSyncDone failure:failure];
}
- (void)startWithSyncFilter:(MXFilterJSONModel*)syncFilter
onServerSyncDone:(void (^)(void))onServerSyncDone
failure:(void (^)(NSError *error))failure;
{
MXLogDebug(@"[MXSession] startWithSyncFilter: %@", syncFilter);
if (syncFilter)
{
// Build or retrieve the filter before launching the event stream
MXWeakify(self);
[self setFilter:syncFilter success:^(NSString *filterId) {
MXStrongifyAndReturnIfNil(self);
[self startWithSyncFilterId:filterId onServerSyncDone:onServerSyncDone failure:failure];
} failure:^(NSError *error) {
MXStrongifyAndReturnIfNil(self);
MXLogDebug(@"[MXSession] startWithSyncFilter: WARNING: Impossible to create the filter. Use no filter in /sync");
[self startWithSyncFilterId:nil onServerSyncDone:onServerSyncDone failure:failure];
}];
}
else
{
[self startWithSyncFilterId:nil onServerSyncDone:onServerSyncDone failure:failure];
}
}
- (void)startWithSyncFilterId:(NSString *)syncFilterId onServerSyncDone:(void (^)(void))onServerSyncDone failure:(void (^)(NSError *))failure
{
if (nil == self.store)
{
// The user did not set a MXStore, use MXNoStore as default
MXNoStore *store = [[MXNoStore alloc] init];
// Set the store before going further
MXWeakify(self);
[self setStore:store success:^{
MXStrongifyAndReturnIfNil(self);
// Then, start again
[self startWithSyncFilterId:syncFilterId onServerSyncDone:onServerSyncDone failure:failure];
} failure:^(NSError *error) {
MXStrongifyAndReturnIfNil(self);
MXLogError(@"[MXSession] startWithSyncFilterId: setStore failed with error: %@", error);
[self setState:MXSessionStateInitialSyncFailed];
failure(error);
}];
return;
}
// Check update of the filter used for /sync requests
if (![self.store.syncFilterId isEqualToString:syncFilterId])
{
if (self.store.eventStreamToken)
{
MXLogDebug(@"[MXSesssion] startWithSyncFilterId: WARNING: Changing the sync filter while there is existing data in the store is not recommended");
}
// Store the passed filter id
self.store.syncFilterId = syncFilterId;
}
// Determine if this filter implies lazy loading of room members
if (syncFilterId)
{
MXWeakify(self);
[self filterWithFilterId:syncFilterId success:^(MXFilterJSONModel *filter) {
MXStrongifyAndReturnIfNil(self);
if (filter.room.state.lazyLoadMembers)
{
MXLogDebug(@"[MXSession] Set syncWithLazyLoadOfRoomMembers to YES");
self->_syncWithLazyLoadOfRoomMembers = YES;
}
} failure:nil];
}
[self handleBackgroundSyncCacheIfRequiredWithCompletion:^{
[self _startWithSyncFilterId:syncFilterId onServerSyncDone:onServerSyncDone failure:failure];
}];
}
- (void)_startWithSyncFilterId:(NSString *)syncFilterId onServerSyncDone:(void (^)(void))onServerSyncDone failure:(void (^)(NSError *))failure
{
[self setState:MXSessionStateSyncInProgress];
// Can we resume from data available in the cache
if (self.store.isPermanent && self.isEventStreamInitialised && 0 < self.store.roomSummaryStore.countOfRooms)
{
// Resume the stream (presence will be retrieved during server sync)
MXLogDebug(@"[MXSession] Resuming the events stream from %@...", self.store.eventStreamToken);
NSDate *startDate2 = [NSDate date];
[self _resume:^{
MXLogDebug(@"[MXSession] Events stream resumed in %.0fms", [[NSDate date] timeIntervalSinceDate:startDate2] * 1000);
onServerSyncDone();
}];
// Start crypto if enabled
[self startCrypto:^{
MXLogDebug(@"[MXSession] Crypto has been started");
} failure:^(NSError *error) {
MXLogDebug(@"[MXSession] Crypto failed to start. Error: %@", error);
}];
}
else
{
// Get data from the home server
// First of all, retrieve the user's profile information
MXWeakify(self);
[_myUser updateFromHomeserverOfMatrixSession:self success:^{
MXStrongifyAndReturnIfNil(self);
// Stop here if [MXSession close] has been triggered.
if (nil == self.myUser)
{
return;
}
// And store him as a common MXUser
[self.store storeUser:self.myUser];
// Start crypto if enabled
[self startCrypto:^{
MXLogDebug(@"[MXSession] Do an initial /sync");
// Initial server sync
[self serverSyncWithServerTimeout:0 success:onServerSyncDone failure:^(NSError *error) {
MXLogError(@"[MXSession] _startWithSyncFilterId: Failed with error %@", error);
[self setState:MXSessionStateInitialSyncFailed];
failure(error);
} clientTimeout:CLIENT_TIMEOUT_MS setPresence:self.preferredSyncPresenceString];
} failure:^(NSError *error) {
MXLogError(@"[MXSession] Crypto failed to start. Error: %@", error);
[self setState:MXSessionStateInitialSyncFailed];
failure(error);
}];
} failure:^(NSError *error) {
MXLogError(@"[MXSession] Get the user's profile information failed with error %@", error);
[self setState:MXSessionStateInitialSyncFailed];
failure(error);
}];
}
// Refresh wellknown data
[self refreshHomeserverWellknown:nil failure:nil];
// Refresh homeserver capabilities
[self refreshHomeserverCapabilities:nil failure:nil];
// Refresh supported Matrix versions
[self refreshSupportedMatrixVersions:nil failure:nil];
// Get the maximum file size allowed for uploading media
[self.matrixRestClient maxUploadSize:^(NSInteger maxUploadSize) {
[self.store storeMaxUploadSize:maxUploadSize];
} failure:^(NSError *error) {
MXLogError(@"[MXSession] Failed to get maximum upload size.");
}];
}
- (NSString *)syncFilterId
{
return self.store.syncFilterId;
}