-
Notifications
You must be signed in to change notification settings - Fork 213
/
MXFileStore.m
2464 lines (2060 loc) · 81.9 KB
/
MXFileStore.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 2020 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 "MXFileStore.h"
#import "MXBackgroundModeHandler.h"
#import "MXEnumConstants.h"
#import "MXFileRoomStore.h"
#import "MXFileRoomOutgoingMessagesStore.h"
#import "MXFileStoreMetaData.h"
#import "MXSDKOptions.h"
#import "MXTools.h"
#import "MatrixSDKSwiftHeader.h"
#import "MXFileRoomSummaryStore.h"
static NSUInteger const kMXFileVersion = 83; // Check getUnreadRoomFromStore if you update this value. Delete this comment after
static NSString *const kMXFileStoreFolder = @"MXFileStore";
static NSString *const kMXFileStoreMedaDataFile = @"MXFileStore";
static NSString *const kMXFileStoreFiltersFile = @"filters";
static NSString *const kMXFileStoreUsersFolder = @"users";
static NSString *const kMXFileStoreGroupsFolder = @"groups";
static NSString *const kMXFileStoreBackupFolder = @"backup";
static NSString *const kMXFileStoreSavingMarker = @"savingMarker";
static NSString *const kMXFileStoreRoomsFolder = @"rooms";
static NSString *const kMXFileStoreRoomMessagesFile = @"messages";
static NSString *const kMXFileStoreRoomOutgoingMessagesFile = @"outgoingMessages";
static NSString *const kMXFileStoreRoomStateFile = @"state";
static NSString *const kMXFileStoreRoomAccountDataFile = @"accountData";
static NSString *const kMXFileStoreRoomReadReceiptsFile = @"readReceipts";
static NSString *const kMXFileStoreRoomUnreadRoomsFile = @"unreadRooms";
static NSString *const kMXFileStoreRoomThreadedReadReceiptsFile = @"threadedReadReceipts";
static NSUInteger preloadOptions;
@interface MXFileStore ()
{
// Meta data about the store. It is defined only if the passed MXCredentials contains all information.
// When nil, nothing is stored on the file system.
MXFileStoreMetaData *metaData;
// List of rooms to save on [MXStore commit]
NSMutableArray *roomsToCommitForMessages;
NSMutableArray *roomsToCommitForOutgoingMessages;
NSMutableDictionary *roomsToCommitForState;
NSMutableDictionary<NSString*, MXRoomAccountData*> *roomsToCommitForAccountData;
NSMutableArray *roomsToCommitForReceipts;
NSMutableArray *roomsToCommitForDeletion;
NSMutableDictionary *usersToCommit;
NSMutableDictionary *groupsToCommit;
NSMutableArray *groupsToCommitForDeletion;
// The path of the MXFileStore folder
NSString *storePath;
// The path of the backup folder
NSString *storeBackupPath;
// The path of the rooms folder
NSString *storeRoomsPath;
// The path of the rooms folder
NSString *storeUsersPath;
// The path of the groups folder
NSString *storeGroupsPath;
// Flag to indicate metaData needs to be stored
BOOL metaDataHasChanged;
// Flag to indicate Matrix filters need to be stored
BOOL filtersHasChanged;
// Cache used to preload room states while the store is opening.
// It is filled on the separate thread so that the UI thread will not be blocked
// when it will read rooms states.
NSMutableDictionary<NSString*, NSArray*> *preloadedRoomsStates;
// Same kind of cache for room account data.
NSMutableDictionary<NSString*, MXRoomAccountData*> *preloadedRoomAccountData;
// File reading and writing operations are dispatched to a separated thread.
// The queue invokes blocks serially in FIFO order.
// This ensures that data is stored in the expected order: MXFileStore metadata
// must be stored after messages and state events because of the event stream token it stores.
dispatch_queue_t dispatchQueue;
// The number of commits being done
NSUInteger pendingCommits;
NSDate *backgroundTaskStartDate;
// The evenst stream token that corresponds to the data being backed up.
NSString *backupEventStreamToken;
}
// The commit to file store background task
@property (nonatomic, strong) id<MXBackgroundTask> commitBackgroundTask;
@end
@implementation MXFileStore
@synthesize roomSummaryStore;
+ (void)initialize
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
// By default, we do not need to preload rooms states now
preloadOptions = MXFileStorePreloadOptionRoomAccountData;
});
}
- (instancetype)init;
{
self = [super init];
if (self)
{
roomsToCommitForMessages = [NSMutableArray array];
roomsToCommitForOutgoingMessages = [NSMutableArray array];
roomsToCommitForState = [NSMutableDictionary dictionary];
roomsToCommitForAccountData = [NSMutableDictionary dictionary];
roomsToCommitForReceipts = [NSMutableArray array];
roomsToCommitForDeletion = [NSMutableArray array];
usersToCommit = [NSMutableDictionary dictionary];
groupsToCommit = [NSMutableDictionary dictionary];
groupsToCommitForDeletion = [NSMutableArray array];
preloadedRoomsStates = [NSMutableDictionary dictionary];
preloadedRoomAccountData = [NSMutableDictionary dictionary];
metaDataHasChanged = NO;
dispatchQueue = dispatch_queue_create("MXFileStoreDispatchQueue", DISPATCH_QUEUE_SERIAL);
pendingCommits = 0;
}
return self;
}
- (instancetype)initWithCredentials:(MXCredentials *)someCredentials
{
self = [self init];
if (self)
{
credentials = someCredentials;
[self setupRoomSummaryStore];
[self setUpStoragePaths];
}
return self;
}
- (void)setupRoomSummaryStore
{
NSParameterAssert(credentials);
if (!roomSummaryStore)
{
roomSummaryStore = [[MXCoreDataRoomSummaryStore alloc] initWithCredentials:credentials];
}
}
- (void)openWithCredentials:(MXCredentials*)someCredentials onComplete:(void (^)(void))onComplete failure:(void (^)(NSError *))failure
{
credentials = someCredentials;
[self setupRoomSummaryStore];
// Create the file path where data will be stored for the user id passed in credentials
[self setUpStoragePaths];
id<MXBackgroundModeHandler> handler = [MXSDKOptions sharedInstance].backgroundModeHandler;
id<MXBackgroundTask> backgroundTask = [handler startBackgroundTaskWithName:@"[MXFileStore] openWithCredentials:onComplete:failure:"];
/*
Mount data corresponding to the account credentials.
The MXFileStore needs to prepopulate its MXMemoryStore parent data from the file system before being used.
*/
#if DEBUG
[self diskUsageWithBlock:^(NSUInteger diskUsage) {
MXLogDebug(@"[MXFileStore] diskUsage: %@", [NSByteCountFormatter stringFromByteCount:diskUsage countStyle:NSByteCountFormatterCountStyleFile]);
}];
#endif
// Load data from the file system on a separate thread
MXWeakify(self);
dispatch_async(dispatchQueue, ^(void){
@autoreleasepool
{
MXStrongifyAndReturnIfNil(self);
// Check the store and repair it if necessary
[self checkStorageValidity];
// Check store version
if (self->metaData && kMXFileVersion != self->metaData.version)
{
MXLogDebug(@"[MXFileStore] New MXFileStore version detected");
if (self->metaData.version <= 35)
{
MXLogDebug(@"[MXFileStore] Matrix SDK until the version of 35 of MXFileStore caches all NSURLRequests unnecessarily. Clear NSURLCache");
[[NSURLCache sharedURLCache] removeAllCachedResponses];
}
[self deleteAllData];
}
// If metaData is still defined, we can load rooms data
if (self->metaData)
{
MXTaskProfile *taskProfile = [MXSDKOptions.sharedInstance.profiler startMeasuringTaskWithName:MXTaskProfileNameStartupStorePreload];
MXLogDebug(@"[MXFileStore] Start data loading from files");
if (preloadOptions & MXFileStorePreloadOptionRoomMessages)
{
[self preloadRoomsMessages];
}
if (preloadOptions & MXFileStorePreloadOptionRoomState)
{
[self preloadRoomsStates];
}
if (preloadOptions & MXFileStorePreloadOptionRoomAccountData)
{
[self preloadRoomsAccountData];
}
if (preloadOptions & MXFileStorePreloadOptionReadReceipts)
{
[self preloadRoomReceipts];
}
[self loadUsers];
[self loadGroups];
[self loadUnreadRooms];
taskProfile.units = self.roomSummaryStore.countOfRooms;
[MXSDKOptions.sharedInstance.profiler stopMeasuringTaskWithProfile:taskProfile];
MXLogDebug(@"[MXFileStore] Data loaded from files in %.0fms", taskProfile.duration * 1000);
}
// Else, if credentials is valid, create and store it
if (nil == self->metaData && self->credentials.homeServer && self->credentials.userId)
{
self->metaData = [[MXFileStoreMetaData alloc] init];
self->metaData.homeServer = [self->credentials.homeServer copy];
self->metaData.userId = [self->credentials.userId copy];
self->metaData.version = kMXFileVersion;
self->metaDataHasChanged = YES;
[self saveMetaData];
}
}
dispatch_async(dispatch_get_main_queue(), ^{
[backgroundTask stop];
onComplete();
});
});
}
- (void)diskUsageWithBlock:(void (^)(NSUInteger))block
{
// The operation can take hundreds of milliseconds. Do it on a sepearate thread
MXWeakify(self);
dispatch_async(dispatchQueue, ^(void){
MXStrongifyAndReturnIfNil(self);
NSUInteger diskUsage = 0;
NSArray *contents = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:self->storePath error:nil];
NSEnumerator *contentsEnumurator = [contents objectEnumerator];
NSString *file;
while (file = [contentsEnumurator nextObject])
{
NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[self->storePath stringByAppendingPathComponent:file] error:nil];
diskUsage += [[fileAttributes objectForKey:NSFileSize] intValue];
}
// Return the result on the main thread
dispatch_async(dispatch_get_main_queue(), ^(void){
block(diskUsage);
});
});
}
- (void)logFiles
{
MXLogDebug(@"[MXFileStore] logFiles: Files in %@:", self->storePath);
NSArray *contents = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:self->storePath error:nil];
NSEnumerator *contentsEnumurator = [contents objectEnumerator];
NSUInteger fileCount = 0, diskUsage = 0;
NSString *file;
while (file = [contentsEnumurator nextObject])
{
NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[self->storePath stringByAppendingPathComponent:file] error:nil];
NSUInteger fileSize = [[fileAttributes objectForKey:NSFileSize] intValue];
MXLogDebug(@"[MXFileStore] logFiles: - %@: %@", file, [NSByteCountFormatter stringFromByteCount:fileSize countStyle:NSByteCountFormatterCountStyleFile]);
diskUsage += fileSize;
fileCount++;
}
MXLogDebug(@"[MXFileStore] logFiles: %@ files: %@", @(fileCount), [NSByteCountFormatter stringFromByteCount:diskUsage countStyle:NSByteCountFormatterCountStyleFile]);
}
+ (void)setPreloadOptions:(MXFileStorePreloadOptions)thePreloadOptions
{
preloadOptions = thePreloadOptions;
}
#pragma mark - MXStore
- (void)storeEventForRoom:(NSString*)roomId event:(MXEvent*)event direction:(MXTimelineDirection)direction
{
[super storeEventForRoom:roomId event:event direction:direction];
if (NSNotFound == [roomsToCommitForMessages indexOfObject:roomId])
{
[roomsToCommitForMessages addObject:roomId];
}
}
- (void)replaceEvent:(MXEvent*)event inRoom:(NSString*)roomId
{
[super replaceEvent:event inRoom:roomId];
if (NSNotFound == [roomsToCommitForMessages indexOfObject:roomId])
{
[roomsToCommitForMessages addObject:roomId];
}
}
- (void)deleteAllMessagesInRoom:(NSString *)roomId
{
[super deleteAllMessagesInRoom:roomId];
if (NSNotFound == [roomsToCommitForMessages indexOfObject:roomId])
{
[roomsToCommitForMessages addObject:roomId];
}
}
- (void)deleteRoom:(NSString *)roomId
{
[super deleteRoom:roomId];
if (NSNotFound == [roomsToCommitForDeletion indexOfObject:roomId])
{
[roomsToCommitForDeletion addObject:roomId];
}
// Remove this room identifier from the other arrays.
[roomsToCommitForMessages removeObject:roomId];
[roomsToCommitForState removeObjectForKey:roomId];
[roomSummaryStore removeSummaryOfRoom:roomId];
[roomsToCommitForAccountData removeObjectForKey:roomId];
[roomsToCommitForReceipts removeObject:roomId];
}
- (void)deleteAllData
{
MXLogDebug(@"[MXFileStore] Delete all data");
if (self.storeService)
{
// Clear aggregations to avoid accumulating counts.
[self.storeService resetSecondaryStoresWithSender:self];
}
else
{
MXLogError(@"[MXFileStore] deleteAllData called without an MXStoreService, aggregations may become out of sync.")
}
[super deleteAllData];
// Remove the MXFileStore and all its content
NSError *error;
[[NSFileManager defaultManager] removeItemAtPath:storePath error:&error];
// And create folders back
[[NSFileManager defaultManager] createDirectoryExcludedFromBackupAtPath:storePath error:nil];
[[NSFileManager defaultManager] createDirectoryExcludedFromBackupAtPath:storeRoomsPath error:nil];
[[NSFileManager defaultManager] createDirectoryExcludedFromBackupAtPath:storeUsersPath error:nil];
[[NSFileManager defaultManager] createDirectoryExcludedFromBackupAtPath:storeGroupsPath error:nil];
[roomSummaryStore removeAllSummaries];
// Reset data
metaData = nil;
[roomStores removeAllObjects];
self.eventStreamToken = nil;
}
- (void)storePaginationTokenOfRoom:(NSString *)roomId andToken:(NSString *)token
{
[super storePaginationTokenOfRoom:roomId andToken:token];
if (NSNotFound == [roomsToCommitForMessages indexOfObject:roomId])
{
[roomsToCommitForMessages addObject:roomId];
}
}
- (void)storeHasReachedHomeServerPaginationEndForRoom:(NSString *)roomId andValue:(BOOL)value
{
[super storeHasReachedHomeServerPaginationEndForRoom:roomId andValue:value];
if (NSNotFound == [roomsToCommitForMessages indexOfObject:roomId])
{
[roomsToCommitForMessages addObject:roomId];
}
}
- (void)storePartialAttributedTextMessageForRoom:(NSString *)roomId partialAttributedTextMessage:(NSAttributedString *)partialAttributedTextMessage
{
[super storePartialAttributedTextMessageForRoom:roomId partialAttributedTextMessage:partialAttributedTextMessage];
if (NSNotFound == [roomsToCommitForMessages indexOfObject:roomId])
{
[roomsToCommitForMessages addObject:roomId];
}
}
- (void)storeHasLoadedAllRoomMembersForRoom:(NSString *)roomId andValue:(BOOL)value
{
// XXX: To remove once https://github.com/vector-im/element-ios/issues/3807 is fixed
MXLogDebug(@"[MXFileStore] storeHasLoadedAllRoomMembersForRoom: %@ value: %@", roomId, @(value));
[super storeHasLoadedAllRoomMembersForRoom:roomId andValue:value];
if (NSNotFound == [roomsToCommitForMessages indexOfObject:roomId])
{
[roomsToCommitForMessages addObject:roomId];
}
}
- (MXWellKnown *)homeserverWellknown
{
return metaData.homeserverWellknown;
}
- (void)storeHomeserverWellknown:(nonnull MXWellKnown *)wellknown
{
if (metaData)
{
metaData.homeserverWellknown = wellknown;
metaDataHasChanged = YES;
}
}
- (MXCapabilities *)homeserverCapabilities
{
return metaData.homeserverCapabilities;
}
- (void)storeHomeserverCapabilities:(MXCapabilities *)capabilities
{
if (metaData)
{
metaData.homeserverCapabilities = capabilities;
metaDataHasChanged = YES;
}
}
- (MXMatrixVersions *)supportedMatrixVersions
{
return metaData.supportedMatrixVersions;
}
- (void)storeSupportedMatrixVersions:(MXMatrixVersions *)supportedMatrixVersions
{
if (metaData)
{
metaData.supportedMatrixVersions = supportedMatrixVersions;
metaDataHasChanged = YES;
}
}
- (NSInteger)maxUploadSize
{
return metaData.maxUploadSize;
}
- (void)storeMaxUploadSize:(NSInteger)maxUploadSize
{
if (metaData)
{
metaData.maxUploadSize = maxUploadSize;
metaDataHasChanged = YES;
}
}
- (BOOL)isPermanent
{
return YES;
}
-(void)setEventStreamToken:(NSString *)eventStreamToken
{
[super setEventStreamToken:eventStreamToken];
if (metaData)
{
metaData.eventStreamToken = eventStreamToken;
metaDataHasChanged = YES;
}
}
- (void)storeStateForRoom:(NSString*)roomId stateEvents:(NSArray*)stateEvents
{
roomsToCommitForState[roomId] = stateEvents;
}
- (void)stateOfRoom:(NSString *)roomId success:(void (^)(NSArray<MXEvent *> * _Nonnull))success failure:(void (^)(NSError * _Nonnull))failure
{
dispatch_async(dispatchQueue, ^{
NSArray<MXEvent *> *stateEvents = [self stateOfRoom:roomId];
dispatch_async(dispatch_get_main_queue(), ^{
success(stateEvents);
});
});
}
- (NSArray*)stateOfRoom:(NSString *)roomId
{
// First, try to get the state from the cache
NSArray *stateEvents = preloadedRoomsStates[roomId];
if (!stateEvents)
{
NSString *file = [self stateFileForRoom:roomId forBackup:NO];
stateEvents = [self loadRootObjectWithoutSecureCodingFromFile:file];
if (!stateEvents || !stateEvents.count)
{
MXLogWarning(@"[MXFileStore] stateOfRoom: no state was loaded for room %@", roomId);
}
if (NO == [NSThread isMainThread])
{
// If this method is called from the `dispatchQueue` thread, it means MXFileStore is preloading
// rooms states. So, fill the cache.
preloadedRoomsStates[roomId] = stateEvents;
}
}
else
{
// The cache information is valid only once
[preloadedRoomsStates removeObjectForKey:roomId];
}
return stateEvents;
}
- (void)storeAccountDataForRoom:(NSString *)roomId userData:(MXRoomAccountData *)accountData
{
roomsToCommitForAccountData[roomId] = accountData;
}
- (MXRoomAccountData *)accountDataOfRoom:(NSString *)roomId
{
// First, try to get the data from the cache
MXRoomAccountData *roomUserdData = preloadedRoomAccountData[roomId];
if (!roomUserdData)
{
roomUserdData =[NSKeyedUnarchiver unarchiveObjectWithFile:[self accountDataFileForRoom:roomId forBackup:NO]];
if (NO == [NSThread isMainThread])
{
// If this method is called from the `dispatchQueue` thread, it means MXFileStore is preloading
// data. So, fill the cache.
preloadedRoomAccountData[roomId] = roomUserdData;
}
}
else
{
// The cache information is valid only once
[preloadedRoomAccountData removeObjectForKey:roomId];
}
return roomUserdData;
}
- (void)storeUser:(MXUser *)user
{
[super storeUser:user];
usersToCommit[user.userId] = user;
}
- (void)storeGroup:(MXGroup *)group
{
[super storeGroup:group];
groupsToCommit[group.groupId] = group;
}
- (void)deleteGroup:(NSString *)groupId
{
[super deleteGroup:groupId];
if (NSNotFound == [groupsToCommitForDeletion indexOfObject:groupId])
{
[groupsToCommitForDeletion addObject:groupId];
}
// Remove this group from `groupsToCommit`.
[groupsToCommit removeObjectForKey:groupId];
}
- (void)setUserAccountData:(NSDictionary *)userAccountData
{
if (metaData)
{
metaData.userAccountData = userAccountData;
metaDataHasChanged = YES;
}
}
- (NSDictionary *)userAccountData
{
return metaData.userAccountData;
}
- (void)setAreAllIdentityServerTermsAgreed:(BOOL)areAllIdentityServerTermsAgreed
{
if (metaData)
{
metaData.areAllIdentityServerTermsAgreed = areAllIdentityServerTermsAgreed;
metaDataHasChanged = YES;
}
}
- (BOOL)areAllIdentityServerTermsAgreed
{
return metaData.areAllIdentityServerTermsAgreed;
}
- (NSArray<NSString *> *)roomIds
{
NSArray<NSString *> *roomIDs = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:self->storeRoomsPath error:nil];
NSMutableArray<NSString *> *result = [roomIDs mutableCopy];
[result removeObjectsInArray:roomsToCommitForDeletion];
return result;
}
#pragma mark - Matrix filters
- (void)setSyncFilterId:(NSString *)syncFilterId
{
MXLogDebug(@"[MXFileStore] setSyncFilterId: syncFilterId: %@", syncFilterId);
[super setSyncFilterId:syncFilterId];
if (metaData)
{
MXLogDebug(@"[MXFileStore] setSyncFilterId: metaData exists");
metaData.syncFilterId = syncFilterId;
metaDataHasChanged = YES;
}
}
- (NSString *)syncFilterId
{
return metaData.syncFilterId;
}
- (void)storeFilter:(nonnull MXFilterJSONModel*)filter withFilterId:(nonnull NSString*)filterId
{
MXLogDebug(@"[MXFileStore] storeFilter: filter: %@ with id: %@", filter.JSONDictionary, filterId);
[super storeFilter:filter withFilterId:filterId];
filtersHasChanged = YES;
}
- (void)filterWithFilterId:(nonnull NSString*)filterId
success:(nonnull void (^)(MXFilterJSONModel * _Nullable filter))success
failure:(nullable void (^)(NSError * _Nullable error))failure
{
if (filters)
{
MXLogDebug(@"[MXFileStore] filterWithFilterId: filters: %@", filters);
[super filterWithFilterId:filterId success:success failure:failure];
}
else
{
// Load filters from the store
dispatch_async(dispatchQueue, ^{
[self loadFilters];
dispatch_async(dispatch_get_main_queue(), ^{
[super filterWithFilterId:filterId success:success failure:failure];
});
});
}
}
- (void)filterIdForFilter:(nonnull MXFilterJSONModel*)filter
success:(nonnull void (^)(NSString * _Nullable filterId))success
failure:(nullable void (^)(NSError * _Nullable error))failure
{
if (filters)
{
MXLogDebug(@"[MXFileStore] filterIdForFilter: filters: %@", filters);
[super filterIdForFilter:filter success:success failure:failure];
}
else
{
// Load filters from the store
dispatch_async(dispatchQueue, ^{
[self loadFilters];
dispatch_async(dispatch_get_main_queue(), ^{
[super filterIdForFilter:filter success:success failure:failure];
});
});
}
}
- (void)commit
{
[self commitWithCompletion:nil];
}
- (void)commitWithCompletion:(void (^)(void))completion
{
// Save data only if metaData exists
if (metaData)
{
// If there are already 2 pending commits, if the data is not stored during the 1st commit operation,
// we are sure that it will be done on the second pass.
if (pendingCommits >= 2)
{
MXLogDebug(@"[MXFileStore commit] Ignore it. There are already pending commits");
return;
}
pendingCommits++;
MXWeakify(self);
NSDate *startDate = [NSDate date];
// Create a bg task if none is available
if (self.commitBackgroundTask.isRunning)
{
MXLogDebug(@"[MXFileStore commit] Background task %@ reused", self.commitBackgroundTask);
}
else
{
MXWeakify(self);
id<MXBackgroundModeHandler> handler = [MXSDKOptions sharedInstance].backgroundModeHandler;
if (handler)
{
backgroundTaskStartDate = startDate;
self.commitBackgroundTask = [handler startBackgroundTaskWithName:@"[MXFileStore commit]" expirationHandler:^{
MXStrongifyAndReturnIfNil(self);
MXLogDebug(@"[MXFileStore commit] Background task %@ is going to expire - ending it. pendingCommits: %tu", self.commitBackgroundTask, self->pendingCommits);
}];
}
}
[self saveDataToFiles];
// The data saving is completed: remove the backuped data.
// Do it on the same GCD queue
dispatch_async(dispatchQueue, ^(void){
MXStrongifyAndReturnIfNil(self);
[[NSFileManager defaultManager] removeItemAtPath:self->storeBackupPath error:nil];
// Release the background task if there is no more pending commits
dispatch_async(dispatch_get_main_queue(), ^(void){
MXLogDebug(@"[MXFileStore commit] lasted %.0fms", [[NSDate date] timeIntervalSinceDate:startDate] * 1000);
self->pendingCommits--;
if (self.commitBackgroundTask.isRunning && self->pendingCommits == 0)
{
[self.commitBackgroundTask stop];
self.commitBackgroundTask = nil;
}
else if (self.commitBackgroundTask.isRunning)
{
MXLogDebug(@"[MXFileStore commit] Background task %@ is kept - running since %.0fms", self.commitBackgroundTask, [[NSDate date] timeIntervalSinceDate:self->backgroundTaskStartDate] * 1000);
}
if (completion)
{
completion();
}
});
});
}
}
- (void)saveDataToFiles
{
// Save each component one by one
[self saveRoomsDeletion];
[self saveRoomsMessages];
[self saveRoomsOutgoingMessages];
[self saveRoomsState];
[self saveRoomsAccountData];
[self saveReceipts];
[self saveUsers];
[self saveGroupsDeletion];
[self saveGroups];
[self saveUnreadRooms];
[self saveFilters];
[self saveMetaData];
}
- (void)close
{
MXLogDebug(@"[MXFileStore] close: %tu pendingCommits", pendingCommits);
// Flush pending commits
if (pendingCommits)
{
[self saveDataToFiles];
MXWeakify(self);
dispatch_sync(dispatchQueue, ^(void){
MXStrongifyAndReturnIfNil(self);
[[NSFileManager defaultManager] removeItemAtPath:self->storeBackupPath error:nil];
});
}
// Do a dummy sync dispatch on the queue
// Once done, we are sure pending operations blocks are complete
dispatch_sync(dispatchQueue, ^(void){
});
}
#pragma mark - Protected operations
- (MXMemoryRoomStore*)getOrCreateRoomStore:(NSString*)roomId
{
MXFileRoomStore *roomStore = (MXFileRoomStore *)roomStores[roomId];
if (nil == roomStore)
{
// This object is global, which means that we will be able to open only one room at a time.
// A per-room lock might be better.
@synchronized (roomStores) {
NSString *roomFile = [self messagesFileForRoom:roomId forBackup:NO];
BOOL isMarkedForDeletion = [roomsToCommitForDeletion containsObject:roomId];
if (!isMarkedForDeletion && [[NSFileManager defaultManager] fileExistsAtPath:roomFile])
{
@try
{
NSDate *startDate = [NSDate date];
roomStore = [NSKeyedUnarchiver unarchiveObjectWithFile:roomFile];
if ([NSThread isMainThread])
{
MXLogWarning(@"[MXFileStore] Loaded room messages of room: %@ in %.0fms, in main thread", roomId, [[NSDate date] timeIntervalSinceDate:startDate] * 1000);
}
self->roomStores[roomId] = roomStore;
}
@catch (NSException *exception)
{
NSDictionary *logDetails = @{
@"roomId": roomId ?: @"unknown",
@"exception": exception ?: @"unknown"
};
MXLogErrorDetails(@"[MXFileStore] Warning: MXFileRoomStore file for room has been corrupted", logDetails);
[self logFiles];
[self deleteAllData];
}
}
else
{
// MXFileStore requires MXFileRoomStore objets
roomStore = [[MXFileRoomStore alloc] init];
self->roomStores[roomId] = roomStore;
}
}
}
return roomStore;
}
- (MXMemoryRoomOutgoingMessagesStore *)getOrCreateRoomOutgoingMessagesStore:(NSString *)roomId
{
MXMemoryRoomOutgoingMessagesStore *store = roomOutgoingMessagesStores[roomId];
if (nil == store)
{
// This object is global, which means that we will be able to open only one room at a time.
// A per-room lock might be better.
@synchronized (roomOutgoingMessagesStores) {
NSString *roomFile = [self outgoingMessagesFileForRoom:roomId forBackup:NO];
if ([[NSFileManager defaultManager] fileExistsAtPath:roomFile])
{
@try
{
NSDate *startDate = [NSDate date];
store = [NSKeyedUnarchiver unarchiveObjectWithFile:roomFile];
if ([NSThread isMainThread])
{
MXLogWarning(@"[MXFileStore] Loaded outgoing messages of room: %@ in %.0fms, in main thread", roomId, [[NSDate date] timeIntervalSinceDate:startDate] * 1000);
}
self->roomOutgoingMessagesStores[roomId] = store;
}
@catch (NSException *exception)
{
NSDictionary *logDetails = @{
@"roomId": roomId ?: @"unknown",
@"exception": exception ?: @"unknown"
};
MXLogErrorDetails(@"[MXFileStore] Warning: MXFileRoomOutgoingMessagesStore file for room as been corrupted", logDetails);
[self logFiles];
[self deleteAllData];
}
}
else
{
// MXFileStore requires MXFileRoomOutgoingMessagesStore objets
store = [MXFileRoomOutgoingMessagesStore new];
self->roomOutgoingMessagesStores[roomId] = store;
}
}
}
return store;
}
- (RoomThreadedReceiptsStore*)getOrCreateRoomThreadedReceiptsStore:(NSString*)roomId
{
RoomThreadedReceiptsStore *threadedStore = roomThreadedReceiptsStores[roomId];
if (nil == threadedStore)
{
// This object is global, which means that we will be able to open only one room at a time.
// A per-room lock might be better.
@synchronized (roomThreadedReceiptsStores) {
NSString *roomFile = [self readReceiptsFileForRoom:roomId forBackup:NO];
RoomReceiptsStore *receiptsStore = [self loadReceiptsStoreFromFileAt:roomFile forRoomWithId:roomId];
if (receiptsStore)
{
// if an old version of the receipts store exists we need first to port it to new version.
threadedStore = [RoomThreadedReceiptsStore new];
threadedStore[kMXEventTimelineMain] = receiptsStore;
// then save the new version of the receipts
NSString *newFile = [self threadedReadReceiptsFileForRoom:roomId forBackup:NO];
if ([NSKeyedArchiver archiveRootObject:threadedStore toFile:newFile])
{
// this file is not needed anymore
[[NSFileManager defaultManager] removeItemAtPath:roomFile error:nil];
}
}
else
{
roomFile = [self threadedReadReceiptsFileForRoom:roomId forBackup:NO];
threadedStore = [self loadReceiptsStoreFromFileAt:roomFile forRoomWithId:roomId];
if (!threadedStore)
{
threadedStore = [RoomThreadedReceiptsStore new];
}
}
roomThreadedReceiptsStores[roomId] = threadedStore;
}
}
return threadedStore;