forked from matrix-org/matrix-ios-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMXSession.m
3904 lines (3224 loc) · 133 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 "MXRoomFilter.h"
#import "MXScanManager.h"
#import "MXAggregations_Private.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 kMXSessionAccountDataDidChangeNotification = @"kMXSessionAccountDataDidChangeNotification";
NSString *const kMXSessionAccountDataDidChangeIdentityServerNotification = @"kMXSessionAccountDataDidChangeIdentityServerNotification";
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*> *roomsSummaries;
/**
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;
}
/**
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;
@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];
roomsSummaries = [NSMutableDictionary dictionary];
_roomSummaryUpdateDelegate = [MXRoomSummaryUpdater roomSummaryUpdaterForSession: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];
[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,
kMXEventTypeStringCallHangup,
kMXEventTypeStringSticker
];
_unreadEventTypes = @[kMXEventTypeStringRoomName,
kMXEventTypeStringRoomTopic,
kMXEventTypeStringRoomMessage,
kMXEventTypeStringCallInvite,
kMXEventTypeStringRoomEncrypted,
kMXEventTypeStringSticker
];
_catchingUp = NO;
[[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)
{
_state = state;
if (_state != MXSessionStateSyncError)
{
// Reset the sync error
_syncError = nil;
}
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter postNotificationName:kMXSessionStateDidChangeNotification object:self userInfo:nil];
}
}
-(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);
_store = store;
// Validate the permanent implementation
if (_store.isPermanent)
{
// A permanent MXStore must implement these methods:
NSParameterAssert([_store respondsToSelector:@selector(rooms)]);
NSParameterAssert([_store respondsToSelector:@selector(storeStateForRoom:stateEvents:)]);
NSParameterAssert([_store respondsToSelector:@selector(stateOfRoom:success:failure:)]);
NSParameterAssert([_store respondsToSelector:@selector(summaryOfRoom:)]);
}
NSDate *startDate = [NSDate date];
MXWeakify(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->_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
NSLog(@"[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
self->_myUser = (MXMyUser*)myUser;
self->_myUser.mxSession = self;
// Load user account data
[self handleAccountData:self.store.userAccountData];
// Load MXRoomSummaries from the store
NSDate *startDate2 = [NSDate date];
for (NSString *roomId in self.store.rooms)
{
@autoreleasepool
{
MXRoomSummary *summary = [self.store summaryOfRoom:roomId];
[summary setMatrixSession:self];
self->roomsSummaries[roomId] = summary;
}
}
NSLog(@"[MXSession] Built %lu MXRoomSummaries in %.0fms", (unsigned long)self->roomsSummaries.allKeys.count, [[NSDate date] timeIntervalSinceDate:startDate2] * 1000);
// Create MXRooms from their states stored in the store
NSDate *startDate3 = [NSDate date];
for (NSString *roomId in self.store.rooms)
{
[self loadRoom:roomId];
}
NSLog(@"[MXSession] Built %lu MXRooms in %.0fms", (unsigned long)self->rooms.allKeys.count, [[NSDate date] timeIntervalSinceDate:startDate3] * 1000);
NSTimeInterval duration = [[NSDate date] timeIntervalSinceDate:startDate];
NSLog(@"[MXSession] Total time to mount SDK data from MXStore: %.0fms", duration * 1000);
[[MXSDKOptions sharedInstance].analyticsDelegate trackStartupMountDataDuration:duration];
[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;
NSLog(@"[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)setIdentityServer:(NSString *)identityServer andAccessToken:(NSString *)accessToken
{
NSLog(@"[MXSession] setIdentityServer: %@", identityServer);
matrixRestClient.identityServer = identityServer;
if (identityServer)
{
_identityService = [[MXIdentityService alloc] initWithIdentityServer:identityServer accessToken:accessToken andHomeserverRestClient:matrixRestClient];
}
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;
{
NSLog(@"[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);
NSLog(@"[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 == _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);
[self setState:MXSessionStateInitialSyncFailed];
failure(error);
}];
return;
}
[self setState:MXSessionStateSyncInProgress];
// Check update of the filter used for /sync requests
if (_store.syncFilterId != syncFilterId
&& ![_store.syncFilterId isEqualToString:syncFilterId])
{
if (_store.eventStreamToken)
{
NSLog(@"[MXSesssion] startWithSyncFilterId: WARNING: Changing the sync filter while there is existing data in the store is not recommended");
}
// Store the passed filter id
_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)
{
self->_syncWithLazyLoadOfRoomMembers = YES;
}
} failure:nil];
}
// Can we resume from data available in the cache
if (_store.isPermanent && self.isEventStreamInitialised && 0 < _store.rooms.count)
{
// Resume the stream (presence will be retrieved during server sync)
NSLog(@"[MXSession] Resuming the events stream from %@...", self.store.eventStreamToken);
NSDate *startDate2 = [NSDate date];
[self resume:^{
NSLog(@"[MXSession] Events stream resumed in %.0fms", [[NSDate date] timeIntervalSinceDate:startDate2] * 1000);
onServerSyncDone();
}];
// Start crypto if enabled
[self startCrypto:^{
NSLog(@"[MXSession] Crypto has been started");
} failure:^(NSError *error) {
NSLog(@"[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:^{
NSLog(@"[MXSession] Do an initial /sync");
// Initial server sync
[self serverSyncWithServerTimeout:0 success:onServerSyncDone failure:^(NSError *error) {
[self setState:MXSessionStateInitialSyncFailed];
failure(error);
} clientTimeout:CLIENT_TIMEOUT_MS setPresence:nil];
} failure:^(NSError *error) {
NSLog(@"[MXSession] Crypto failed to start. Error: %@", error);
// Check whether the token is valid
if ([self isUnknownTokenError:error])
{
// Do nothing more because without a valid access_token, the session is useless
return;
}
[self setState:MXSessionStateInitialSyncFailed];
failure(error);
}];
} failure:^(NSError *error) {
NSLog(@"[MXSession] Get the user's profile information failed");
// Check whether the token is valid
if ([self isUnknownTokenError:error])
{
// Do nothing more because without a valid access_token, the session is useless
return;
}
[self setState:MXSessionStateInitialSyncFailed];
failure(error);
}];
}
// Get wellknown data only at the login time
if (!self.homeserverWellknown)
{
[self refreshHomeserverWellknown:nil failure:nil];
}
}
- (NSString *)syncFilterId
{
return _store.syncFilterId;
}
- (void)pause
{
NSLog(@"[MXSession] pause the event stream in state %tu", _state);
if (_state == MXSessionStateRunning || _state == MXSessionStateBackgroundSyncInProgress || _state == MXSessionStatePauseRequested)
{
// Check that none required the session to keep running even if the app goes in
// background
if (_preventPauseCount)
{
NSLog(@"[MXSession pause] Prevent the session from being paused. preventPauseCount: %tu", _preventPauseCount);
id<MXBackgroundModeHandler> handler = [MXSDKOptions sharedInstance].backgroundModeHandler;
if (handler && !self.backgroundTask.isRunning)
{
MXWeakify(self);
self.backgroundTask = [handler startBackgroundTaskWithName:@"[MXSession] pause" expirationHandler:^{
MXStrongifyAndReturnIfNil(self);
// We cannot continue to run in background. Pause the session for real
self.preventPauseCount = 0;
}];
}
[self setState:MXSessionStatePauseRequested];
return;
}
// reset the callback
onResumeDone = nil;
onBackgroundSyncDone = nil;
onBackgroundSyncFail = nil;
// Cancel the current request managing the event stream
[eventStreamRequest cancel];
eventStreamRequest = nil;
for (MXPeekingRoom *peekingRoom in peekingRooms)
{
[peekingRoom pause];
}
[self setState:MXSessionStatePaused];
}
else
{
NSLog(@"[MXSession] pause skipped because of wrong state of MXSession");
}
}
- (void)resume:(void (^)(void))resumeDone
{
NSLog(@"[MXSession] resume the event stream from state %tu", _state);
if (self.backgroundTask.isRunning)
{
[self.backgroundTask stop];
self.backgroundTask = nil;
}
// Check whether no request is already in progress
if (!eventStreamRequest ||
(_state == MXSessionStateBackgroundSyncInProgress || _state == MXSessionStatePauseRequested))
{
[self setState:MXSessionStateSyncInProgress];
// Resume from the last known token
onResumeDone = resumeDone;
if (!eventStreamRequest)
{
// Relaunch live events stream (long polling)
[self serverSyncWithServerTimeout:0 success:nil failure:nil clientTimeout:CLIENT_TIMEOUT_MS setPresence:nil];
}
}
for (MXPeekingRoom *peekingRoom in peekingRooms)
{
[peekingRoom resume];
}
}
- (void)backgroundSync:(unsigned int)timeout success:(MXOnBackgroundSyncDone)backgroundSyncDone failure:(MXOnBackgroundSyncFail)backgroundSyncfails
{
// background sync considering session state
[self backgroundSync:timeout ignoreSessionState:NO success:backgroundSyncDone failure:backgroundSyncfails];
}
- (void)backgroundSync:(unsigned int)timeout ignoreSessionState:(BOOL)ignoreSessionState success:(MXOnBackgroundSyncDone)backgroundSyncDone failure:(MXOnBackgroundSyncFail)backgroundSyncfails
{
// Check whether no request is already in progress
if (!eventStreamRequest)
{
if (!ignoreSessionState && MXSessionStatePaused != _state)
{
NSLog(@"[MXSession] background Sync cannot be done in the current state %tu", _state);
dispatch_async(dispatch_get_main_queue(), ^{
backgroundSyncfails(nil);
});
}
else
{
NSLog(@"[MXSession] start a background Sync");
[self setState:MXSessionStateBackgroundSyncInProgress];
// BackgroundSync from the latest known token
onBackgroundSyncDone = backgroundSyncDone;
onBackgroundSyncFail = backgroundSyncfails;
[self serverSyncWithServerTimeout:0 success:nil failure:nil clientTimeout:timeout setPresence:@"offline"];
}
}
}
- (BOOL)reconnect
{
if (eventStreamRequest)
{
NSLog(@"[MXSession] Reconnect starts");
[eventStreamRequest cancel];
eventStreamRequest = nil;
// retrieve the available data asap
// disable the long poll to get the available data asap
[self serverSyncWithServerTimeout:0 success:nil failure:nil clientTimeout:10 setPresence:nil];
return YES;
}
else
{
NSLog(@"[MXSession] Reconnect fails.");
}
return NO;
}
- (void)close
{
// Cancel the current server request (if any)
[eventStreamRequest cancel];
eventStreamRequest = nil;
// Flush pending direct room operations
[directRoomsOperationsQueue removeAllObjects];
directRoomsOperationsQueue = nil;
// Clean MXUsers
for (MXUser *user in self.users)
{
[user removeAllListeners];
}
// Flush the store
if ([_store respondsToSelector:@selector(close)])
{
[_store close];
}
[self removeAllListeners];
// Clean MXRooms
for (MXRoom *room in rooms.allValues)
{
[room close];
}
[rooms removeAllObjects];
// Clean peeking rooms
for (MXPeekingRoom *peekingRoom in peekingRooms)
{
[peekingRoom close];
}
[peekingRooms removeAllObjects];
// Clean summaries
for (MXRoomSummary *summary in roomsSummaries.allValues)
{
[summary destroy];
}
[roomsSummaries removeAllObjects];
// Clean notification center
[_notificationCenter removeAllListeners];
_notificationCenter = nil;
// Stop calls
if (_callManager)
{
[_callManager close];
_callManager = nil;
}
// Stop crypto
if (_crypto)
{
[_crypto close:NO];
_crypto = nil;
}
publicisedGroupsByUserId = nil;
userIdsWithOutdatedPublicisedGroups = nil;
// Stop background task
if (self.backgroundTask.isRunning)
{
[self.backgroundTask stop];
self.backgroundTask = nil;
}
_myUser = nil;
mediaManager = nil;
matrixRestClient = nil;
[self setState:MXSessionStateClosed];
}
- (MXHTTPOperation*)logout:(void (^)(void))success
failure:(void (^)(NSError *error))failure
{
// Create an empty operation that will be mutated later
MXHTTPOperation *operation = [[MXHTTPOperation alloc] init];
// Clear crypto data
// For security and because it will be no more useful as we will get a new device id
// on the next log in
MXWeakify(self);
[self enableCrypto:NO success:^{
MXStrongifyAndReturnIfNil(self);
if (!operation.isCancelled)
{
MXHTTPOperation *operation2 = [self.matrixRestClient logout:success failure:failure];
[operation mutateTo:operation2];
}
} failure:nil];
return operation;
}
- (MXHTTPOperation*)deactivateAccountWithAuthParameters:(NSDictionary*)authParameters
eraseAccount:(BOOL)eraseAccount
success:(void (^)(void))success
failure:(void (^)(NSError *error))failure
{
return [self.matrixRestClient deactivateAccountWithAuthParameters:authParameters
eraseAccount:eraseAccount
success:success
failure:failure];
}
- (BOOL)isEventStreamInitialised
{
return (_store.eventStreamToken != nil);
}
#pragma mark - Invalid Token handling
- (BOOL)isUnknownTokenError:(NSError *)error
{
// Detect invalidated access token
// This can happen when the user made a forget password request for example
if ([MXError isMXError:error])
{
MXError *mxError = [[MXError alloc] initWithNSError:error];
if ([mxError.errcode isEqualToString:kMXErrCodeStringUnknownToken])
{
NSLog(@"[MXSession] isUnknownTokenError: The access token is no more valid.");
if (mxError.httpResponse.statusCode == 401
&& [mxError.userInfo[kMXErrorSoftLogoutKey] isEqual:@(YES)])
{
NSLog(@"[MXSession] isUnknownTokenError: Go to MXSessionStateSoftLogout state.");
[self setState:MXSessionStateSoftLogout];
}
else
{
NSLog(@"[MXSession] isUnknownTokenError: Go to MXSessionStateUnknownToken state.");
[self setState:MXSessionStateUnknownToken];
}
return YES;
}
}
return NO;
}
#pragma mark - MXSession pause prevention
- (void)retainPreventPause
{
// Check whether a background mode handler has been set.
if ([MXSDKOptions sharedInstance].backgroundModeHandler)
{
self.preventPauseCount++;
}
}
- (void)releasePreventPause
{
if (self.preventPauseCount > 0)
{
self.preventPauseCount--;
}
}
- (void)setPreventPauseCount:(NSUInteger)preventPauseCount
{
_preventPauseCount = preventPauseCount;
NSLog(@"[MXSession] setPreventPauseCount: %tu. MXSession state: %tu", _preventPauseCount, _state);
if (_preventPauseCount == 0)
{
// The background task can be released
if (self.backgroundTask.isRunning)
{
NSLog(@"[MXSession pause] Stop background task %@", self.backgroundTask);
[self.backgroundTask stop];
self.backgroundTask = nil;
}
// And the session can be paused for real if it was not resumed before
if (_state == MXSessionStatePauseRequested)
{
NSLog(@"[MXSession] setPreventPauseCount: Actually pause the session");
[self pause];
}
}
}
#pragma mark - Server sync
- (void)serverSyncWithServerTimeout:(NSUInteger)serverTimeout
success:(void (^)(void))success
failure:(void (^)(NSError *error))failure
clientTimeout:(NSUInteger)clientTimeout
setPresence:(NSString*)setPresence
{
NSDate *startDate = [NSDate date];
// Determine if we are catching up
_catchingUp = (0 == serverTimeout);
NSString * streamToken = _store.eventStreamToken;
NSLog(@"[MXSession] Do a server sync%@ from token: %@", _catchingUp ? @" (catching up)" : @"", streamToken);
MXWeakify(self);
eventStreamRequest = [matrixRestClient syncFromToken:streamToken serverTimeout:serverTimeout clientTimeout:clientTimeout setPresence:setPresence filter:self.syncFilterId success:^(MXSyncResponse *syncResponse) {
MXStrongifyAndReturnIfNil(self);
// Make sure [MXSession close] or [MXSession pause] has not been called before the server response
if (!self->eventStreamRequest)
{
return;
}
// By default, the next sync will be a long polling (with the default server timeout value)
NSUInteger nextServerTimeout = SERVER_TIMEOUT_MS;
NSTimeInterval duration = [[NSDate date] timeIntervalSinceDate:startDate];
NSLog(@"[MXSession] Received %tu joined rooms, %tu invited rooms, %tu left rooms, %tu toDevice events in %.0fms", syncResponse.rooms.join.count, syncResponse.rooms.invite.count, syncResponse.rooms.leave.count, syncResponse.toDevice.events.count, duration * 1000);
// Check whether this is the initial sync
BOOL isInitialSync = !self.isEventStreamInitialised;
BOOL wasfirstSync = NO;
if (!self->firstSyncDone)
{
wasfirstSync = YES;
self->firstSyncDone = YES;
[[MXSDKOptions sharedInstance].analyticsDelegate trackStartupSyncDuration:duration isInitial:isInitialSync];
}
// Handle the to device events before the room ones
// to ensure to decrypt them properly
for (MXEvent *toDeviceEvent in syncResponse.toDevice.events)
{
[self handleToDeviceEvent:toDeviceEvent];
}
if (self.catchingUp && syncResponse.toDevice.events.count)
{
// We may have not received all to-device events in a single /sync response
// Pursue /sync with short timeout
NSLog(@"[MXSession] Continue /sync with short timeout to get all to-device events (%@)", self.myUser.userId);
nextServerTimeout = 0;
}
// Handle top-level account data