This repository has been archived by the owner on Dec 12, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 71
/
MXKAccountManager.m
550 lines (451 loc) · 17.1 KB
/
MXKAccountManager.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
/*
Copyright 2015 OpenMarket Ltd
Copyright 2017 Vector Creations Ltd
Copyright 2018 New Vector Ltd
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 "MXKAccountManager.h"
#import "MXKAppSettings.h"
static NSString *const kMXKAccountsKey = @"accounts";
NSString *const kMXKAccountManagerDidAddAccountNotification = @"kMXKAccountManagerDidAddAccountNotification";
NSString *const kMXKAccountManagerDidRemoveAccountNotification = @"kMXKAccountManagerDidRemoveAccountNotification";
@interface MXKAccountManager()
{
/**
The list of all accounts (enabled and disabled). Each value is a `MXKAccount` instance.
*/
NSMutableArray<MXKAccount *> *mxAccounts;
}
@end
@implementation MXKAccountManager
+ (MXKAccountManager *)sharedManager
{
static MXKAccountManager *sharedAccountManager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedAccountManager = [[super allocWithZone:NULL] init];
});
return sharedAccountManager;
}
- (instancetype)init
{
self = [super init];
if (self)
{
_storeClass = [MXFileStore class];
// Load existing accounts from local storage
[self loadAccounts];
}
return self;
}
- (void)dealloc
{
mxAccounts = nil;
}
#pragma mark -
- (void)prepareSessionForActiveAccounts
{
for (MXKAccount *account in mxAccounts)
{
// Check whether the account is enabled. Open a new matrix session if none.
if (!account.isDisabled && !account.mxSession)
{
NSLog(@"[MXKAccountManager] openSession for %@ account", account.mxCredentials.userId);
id<MXStore> store = [[_storeClass alloc] init];
[account openSessionWithStore:store];
}
}
}
- (void)saveAccounts
{
NSDate *startDate = [NSDate date];
NSLog(@"[MXKAccountManager] saveAccounts...");
BOOL result = [NSKeyedArchiver archiveRootObject:mxAccounts toFile:[self accountFile]];
NSLog(@"[MXKAccountManager] saveAccounts. Done (result: %@) in %.0fms", @(result), [[NSDate date] timeIntervalSinceDate:startDate] * 1000);
}
- (void)addAccount:(MXKAccount *)account andOpenSession:(BOOL)openSession
{
NSLog(@"[MXKAccountManager] login (%@)", account.mxCredentials.userId);
[mxAccounts addObject:account];
[self saveAccounts];
// Check conditions to open a matrix session
if (openSession && !account.disabled)
{
// Open a new matrix session by default
NSLog(@"[MXKAccountManager] openSession for %@ account", account.mxCredentials.userId);
id<MXStore> store = [[_storeClass alloc] init];
[account openSessionWithStore:store];
}
// Post notification
[[NSNotificationCenter defaultCenter] postNotificationName:kMXKAccountManagerDidAddAccountNotification object:account userInfo:nil];
}
- (void)removeAccount:(MXKAccount*)theAccount completion:(void (^)(void))completion
{
[self removeAccount:theAccount sendLogoutRequest:YES completion:completion];
}
- (void)removeAccount:(MXKAccount*)theAccount
sendLogoutRequest:(BOOL)sendLogoutRequest
completion:(void (^)(void))completion
{
NSLog(@"[MXKAccountManager] logout (%@), send logout request to home server: %d", theAccount.mxCredentials.userId, sendLogoutRequest);
// Close session and clear associated store.
[theAccount logoutSendingServerRequest:sendLogoutRequest completion:^{
// Retrieve the corresponding account in the internal array
MXKAccount* removedAccount = nil;
for (MXKAccount *account in mxAccounts)
{
if ([account.mxCredentials.userId isEqualToString:theAccount.mxCredentials.userId])
{
removedAccount = account;
break;
}
}
if (removedAccount)
{
[mxAccounts removeObject:removedAccount];
[self saveAccounts];
// Post notification
[[NSNotificationCenter defaultCenter] postNotificationName:kMXKAccountManagerDidRemoveAccountNotification object:removedAccount userInfo:nil];
}
if (completion)
{
completion();
}
}];
}
- (void)logoutWithCompletion:(void (^)(void))completion
{
// Logout one by one the existing accounts
if (mxAccounts.count)
{
[self removeAccount:mxAccounts.lastObject completion:^{
// loop: logout the next existing account (if any)
[self logoutWithCompletion:completion];
}];
return;
}
NSUserDefaults *sharedUserDefaults = [MXKAppSettings standardAppSettings].sharedUserDefaults;
// Remove APNS device token
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"apnsDeviceToken"];
// Remove Push device token
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"pushDeviceToken"];
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"pushOptions"];
// Be sure that no account survive in local storage
[[NSUserDefaults standardUserDefaults] removeObjectForKey:kMXKAccountsKey];
[sharedUserDefaults removeObjectForKey:kMXKAccountsKey];
[[NSFileManager defaultManager] removeItemAtPath:[self accountFile] error:nil];
if (completion)
{
completion();
}
}
- (MXKAccount *)accountForUserId:(NSString *)userId
{
for (MXKAccount *account in mxAccounts)
{
if ([account.mxCredentials.userId isEqualToString:userId])
{
return account;
}
}
return nil;
}
- (MXKAccount *)accountKnowingRoomWithRoomIdOrAlias:(NSString *)roomIdOrAlias
{
MXKAccount *theAccount = nil;
NSArray *activeAccounts = self.activeAccounts;
for (MXKAccount *account in activeAccounts)
{
if ([roomIdOrAlias hasPrefix:@"#"])
{
if ([account.mxSession roomWithAlias:roomIdOrAlias])
{
theAccount = account;
break;
}
}
else
{
if ([account.mxSession roomWithRoomId:roomIdOrAlias])
{
theAccount = account;
break;
}
}
}
return theAccount;
}
- (MXKAccount *)accountKnowingUserWithUserId:(NSString *)userId
{
MXKAccount *theAccount = nil;
NSArray *activeAccounts = self.activeAccounts;
for (MXKAccount *account in activeAccounts)
{
if ([account.mxSession userWithUserId:userId])
{
theAccount = account;
break;
}
}
return theAccount;
}
#pragma mark -
- (void)setStoreClass:(Class)storeClass
{
// Sanity check
NSAssert([storeClass conformsToProtocol:@protocol(MXStore)], @"MXKAccountManager only manages store class that conforms to MXStore protocol");
_storeClass = storeClass;
}
- (NSArray<MXKAccount *> *)accounts
{
return [mxAccounts copy];
}
- (NSArray<MXKAccount *> *)activeAccounts
{
NSMutableArray *activeAccounts = [NSMutableArray arrayWithCapacity:mxAccounts.count];
for (MXKAccount *account in mxAccounts)
{
if (!account.disabled)
{
[activeAccounts addObject:account];
}
}
return activeAccounts;
}
- (NSData *)apnsDeviceToken
{
NSData *token = [[NSUserDefaults standardUserDefaults] objectForKey:@"apnsDeviceToken"];
if (!token.length)
{
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"apnsDeviceToken"];
token = nil;
}
return token;
}
- (void)setApnsDeviceToken:(NSData *)apnsDeviceToken
{
NSData *oldToken = self.apnsDeviceToken;
if (!apnsDeviceToken.length)
{
NSLog(@"[MXKAccountManager] reset APNS device token");
if (oldToken)
{
// turn off the Apns flag for all accounts if any
for (MXKAccount *account in mxAccounts)
{
account.enablePushNotifications = NO;
}
}
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"apnsDeviceToken"];
}
else
{
NSArray *activeAccounts = self.activeAccounts;
if (!oldToken)
{
NSLog(@"[MXKAccountManager] set APNS device token");
[[NSUserDefaults standardUserDefaults] setObject:apnsDeviceToken forKey:@"apnsDeviceToken"];
// turn on the Apns flag for all accounts, when the Apns registration succeeds for the first time
for (MXKAccount *account in activeAccounts)
{
account.enablePushNotifications = YES;
}
}
else if (![oldToken isEqualToData:apnsDeviceToken])
{
NSLog(@"[MXKAccountManager] update APNS device token");
// Delete the pushers related to the old token
for (MXKAccount *account in activeAccounts)
{
[account deletePusher];
}
// Update the token
[[NSUserDefaults standardUserDefaults] setObject:apnsDeviceToken forKey:@"apnsDeviceToken"];
// Refresh pushers with the new token.
for (MXKAccount *account in activeAccounts)
{
if (account.pushNotificationServiceIsActive)
{
NSLog(@"[MXKAccountManager] Resync APNS for %@ account", account.mxCredentials.userId);
account.enablePushNotifications = YES;
}
}
}
}
}
- (BOOL)isAPNSAvailable
{
// [UIApplication isRegisteredForRemoteNotifications] tells whether your app can receive
// remote notifications or not. However receiving remote notifications does not mean it
// will also display them to the user.
// To check whether the user allowed or denied remote notification or in fact changed
// the notifications permissions later in iOS setting, we have to call
// [UIApplication currentUserNotificationSettings].
BOOL isRemoteNotificationsAllowed = NO;
UIApplication *sharedApplication = [UIApplication performSelector:@selector(sharedApplication)];
if (sharedApplication)
{
UIUserNotificationSettings *settings = [sharedApplication currentUserNotificationSettings];
isRemoteNotificationsAllowed = (settings.types != UIUserNotificationTypeNone);
NSLog(@"[MXKAccountManager] the user %@ remote notification", (isRemoteNotificationsAllowed ? @"allowed" : @"denied"));
}
return (isRemoteNotificationsAllowed && self.apnsDeviceToken);
}
- (NSData *)pushDeviceToken
{
NSData *token = [[NSUserDefaults standardUserDefaults] objectForKey:@"pushDeviceToken"];
if (!token.length)
{
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"pushDeviceToken"];
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"pushOptions"];
token = nil;
}
return token;
}
- (NSDictionary *)pushOptions
{
return [[NSUserDefaults standardUserDefaults] objectForKey:@"pushOptions"];
}
- (void)setPushDeviceToken:(NSData *)pushDeviceToken withPushOptions:(NSDictionary *)pushOptions
{
NSData *oldToken = self.pushDeviceToken;
if (!pushDeviceToken.length)
{
NSLog(@"[MXKAccountManager] reset Push device token");
if (oldToken)
{
// turn off the Push flag for all accounts if any
for (MXKAccount *account in mxAccounts)
{
account.enablePushKitNotifications = NO;
}
}
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"pushDeviceToken"];
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"pushOptions"];
}
else
{
NSArray *activeAccounts = self.activeAccounts;
if (!oldToken)
{
NSLog(@"[MXKAccountManager] set Push device token");
[[NSUserDefaults standardUserDefaults] setObject:pushDeviceToken forKey:@"pushDeviceToken"];
if (pushOptions)
{
[[NSUserDefaults standardUserDefaults] setObject:pushOptions forKey:@"pushOptions"];
}
else
{
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"pushOptions"];
}
// turn on the Push flag for all accounts
for (MXKAccount *account in activeAccounts)
{
account.enablePushKitNotifications = YES;
}
}
else if (![oldToken isEqualToData:pushDeviceToken])
{
NSLog(@"[MXKAccountManager] update Push device token");
// Delete the pushers related to the old token
for (MXKAccount *account in activeAccounts)
{
[account deletePushKitPusher];
}
// Update the token
[[NSUserDefaults standardUserDefaults] setObject:pushDeviceToken forKey:@"pushDeviceToken"];
if (pushOptions)
{
[[NSUserDefaults standardUserDefaults] setObject:pushOptions forKey:@"pushOptions"];
}
else
{
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"pushOptions"];
}
// Refresh pushers with the new token.
for (MXKAccount *account in activeAccounts)
{
if (account.isPushKitNotificationActive)
{
NSLog(@"[MXKAccountManager] Resync Push for %@ account", account.mxCredentials.userId);
account.enablePushKitNotifications = YES;
}
}
}
}
}
- (BOOL)isPushAvailable
{
// [UIApplication isRegisteredForRemoteNotifications] tells whether your app can receive
// remote notifications or not. However receiving remote notifications does not mean it
// will also display them to the user.
// To check whether the user allowed or denied remote notification or in fact changed
// the notifications permissions later in iOS setting, we have to call
// [UIApplication currentUserNotificationSettings].
BOOL isRemoteNotificationsAllowed = NO;
UIApplication *sharedApplication = [UIApplication performSelector:@selector(sharedApplication)];
if (sharedApplication)
{
UIUserNotificationSettings *settings = [sharedApplication currentUserNotificationSettings];
isRemoteNotificationsAllowed = (settings.types != UIUserNotificationTypeNone);
NSLog(@"[MXKAccountManager] the user %@ remote notification", (isRemoteNotificationsAllowed ? @"allowed" : @"denied"));
}
return (isRemoteNotificationsAllowed && self.pushDeviceToken);
}
#pragma mark -
// Return the path of the file containing stored MXAccounts array
- (NSString*)accountFile
{
NSString *matrixKitCacheFolder = [MXKAppSettings cacheFolder];
return [matrixKitCacheFolder stringByAppendingPathComponent:kMXKAccountsKey];
}
- (void)loadAccounts
{
NSLog(@"[MXKAccountManager] loadAccounts");
NSString *accountFile = [self accountFile];
if ([[NSFileManager defaultManager] fileExistsAtPath:accountFile])
{
NSDate *startDate = [NSDate date];
mxAccounts = [NSKeyedUnarchiver unarchiveObjectWithFile:accountFile];
NSLog(@"[MXKAccountManager] loadAccounts. %tu accounts loaded in %.0fms", mxAccounts.count, [[NSDate date] timeIntervalSinceDate:startDate] * 1000);
}
else
{
// Migration of accountData from sharedUserDefaults to a file
NSUserDefaults *sharedDefaults = [MXKAppSettings standardAppSettings].sharedUserDefaults;
NSData *accountData = [sharedDefaults objectForKey:kMXKAccountsKey];
if (!accountData)
{
// Migration of accountData from [NSUserDefaults standardUserDefaults], the first location storage
accountData = [[NSUserDefaults standardUserDefaults] objectForKey:kMXKAccountsKey];
}
if (accountData)
{
mxAccounts = [NSMutableArray arrayWithArray:[NSKeyedUnarchiver unarchiveObjectWithData:accountData]];
[self saveAccounts];
NSLog(@"[MXKAccountManager] loadAccounts: performed data migration");
// Now that data has been migrated, erase old location of accountData
[[NSUserDefaults standardUserDefaults] removeObjectForKey:kMXKAccountsKey];
[sharedDefaults removeObjectForKey:kMXKAccountsKey];
}
}
if (!mxAccounts)
{
NSLog(@"[MXKAccountManager] loadAccounts. No accounts");
mxAccounts = [NSMutableArray array];
}
}
- (void)forceReloadAccounts
{
NSLog(@"[MXKAccountManager] Force reload existing accounts from local storage");
[self loadAccounts];
}
@end