/
AppDelegate.m
1370 lines (1129 loc) · 51.6 KB
/
AppDelegate.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 (c) 2020 Open Whisper Systems. All rights reserved.
//
#import "AppDelegate.h"
#import "ConversationListViewController.h"
#import "DebugLogger.h"
#import "MainAppContext.h"
#import "OWSBackup.h"
#import "OWSOrphanDataCleaner.h"
#import "OWSScreenLockUI.h"
#import "Pastelog.h"
#import "Signal-Swift.h"
#import "SignalApp.h"
#import "ViewControllerUtils.h"
#import "YDBLegacyMigration.h"
#import <Intents/Intents.h>
#import <PromiseKit/AnyPromise.h>
#import <SignalCoreKit/iOSVersions.h>
#import <SignalMessaging/AppSetup.h>
#import <SignalMessaging/Environment.h>
#import <SignalMessaging/OWSContactsManager.h>
#import <SignalMessaging/OWSNavigationController.h>
#import <SignalMessaging/OWSPreferences.h>
#import <SignalMessaging/OWSProfileManager.h>
#import <SignalMessaging/SignalMessaging.h>
#import <SignalMessaging/VersionMigrations.h>
#import <SignalServiceKit/AppReadiness.h>
#import <SignalServiceKit/CallKitIdStore.h>
#import <SignalServiceKit/DarwinNotificationCenter.h>
#import <SignalServiceKit/OWS2FAManager.h>
#import <SignalServiceKit/OWSBatchMessageProcessor.h>
#import <SignalServiceKit/OWSDisappearingMessagesJob.h>
#import <SignalServiceKit/OWSMath.h>
#import <SignalServiceKit/OWSMessageManager.h>
#import <SignalServiceKit/OWSMessageSender.h>
#import <SignalServiceKit/OWSReadReceiptManager.h>
#import <SignalServiceKit/SSKEnvironment.h>
#import <SignalServiceKit/SignalServiceKit-Swift.h>
#import <SignalServiceKit/StickerInfo.h>
#import <SignalServiceKit/TSAccountManager.h>
#import <SignalServiceKit/TSPreKeyManager.h>
#import <SignalServiceKit/TSSocketManager.h>
#import <UserNotifications/UserNotifications.h>
#import <WebRTC/WebRTC.h>
NSString *const AppDelegateStoryboardMain = @"Main";
static NSString *const kInitialViewControllerIdentifier = @"UserInitialViewController";
NSString *const kURLSchemeSGNLKey = @"sgnl";
static NSString *const kURLHostVerifyPrefix = @"verify";
static NSString *const kURLHostAddStickersPrefix = @"addstickers";
NSString *const kURLHostTransferPrefix = @"transfer";
static NSTimeInterval launchStartedAt;
typedef NS_ENUM(NSUInteger, LaunchFailure) {
LaunchFailure_None,
LaunchFailure_CouldNotLoadDatabase,
LaunchFailure_UnknownDatabaseVersion,
LaunchFailure_CouldNotRestoreTransferredData
};
NSString *NSStringForLaunchFailure(LaunchFailure launchFailure);
NSString *NSStringForLaunchFailure(LaunchFailure launchFailure)
{
switch (launchFailure) {
case LaunchFailure_None:
return @"LaunchFailure_None";
case LaunchFailure_CouldNotLoadDatabase:
return @"LaunchFailure_CouldNotLoadDatabase";
case LaunchFailure_UnknownDatabaseVersion:
return @"LaunchFailure_UnknownDatabaseVersion";
case LaunchFailure_CouldNotRestoreTransferredData:
return @"LaunchFailure_CouldNotRestoreTransferredData";
}
}
#if TESTABLE_BUILD
void uncaughtExceptionHandler(NSException *exception);
void uncaughtExceptionHandler(NSException *exception)
{
OWSLogError(@"exception: %@", exception);
OWSLogError(@"name: %@", exception.name);
OWSLogError(@"reason: %@", exception.reason);
OWSLogError(@"userInfo: %@", exception.userInfo);
OWSLogError(@"callStackSymbols: %@", exception.callStackSymbols);
OWSLogFlush();
}
#endif
@interface AppDelegate () <UNUserNotificationCenterDelegate>
@property (nonatomic) BOOL areVersionMigrationsComplete;
@property (nonatomic) BOOL didAppLaunchFail;
@end
#pragma mark -
@implementation AppDelegate
@synthesize window = _window;
#pragma mark - Dependencies
- (OWSProfileManager *)profileManager
{
return [OWSProfileManager sharedManager];
}
- (OWSReadReceiptManager *)readReceiptManager
{
return [OWSReadReceiptManager sharedManager];
}
- (id<OWSUDManager>)udManager
{
OWSAssertDebug(SSKEnvironment.shared.udManager);
return SSKEnvironment.shared.udManager;
}
- (nullable OWSPrimaryStorage *)primaryStorage
{
return SSKEnvironment.shared.primaryStorage;
}
- (PushRegistrationManager *)pushRegistrationManager
{
OWSAssertDebug(AppEnvironment.shared.pushRegistrationManager);
return AppEnvironment.shared.pushRegistrationManager;
}
- (TSAccountManager *)tsAccountManager
{
OWSAssertDebug(SSKEnvironment.shared.tsAccountManager);
return SSKEnvironment.shared.tsAccountManager;
}
- (OWSDisappearingMessagesJob *)disappearingMessagesJob
{
OWSAssertDebug(SSKEnvironment.shared.disappearingMessagesJob);
return SSKEnvironment.shared.disappearingMessagesJob;
}
- (TSSocketManager *)socketManager
{
OWSAssertDebug(SSKEnvironment.shared.socketManager);
return SSKEnvironment.shared.socketManager;
}
- (OWSMessageManager *)messageManager
{
OWSAssertDebug(SSKEnvironment.shared.messageManager);
return SSKEnvironment.shared.messageManager;
}
- (OWSWindowManager *)windowManager
{
return Environment.shared.windowManager;
}
- (OWSBackup *)backup
{
return AppEnvironment.shared.backup;
}
- (OWSNotificationPresenter *)notificationPresenter
{
return AppEnvironment.shared.notificationPresenter;
}
- (OWSUserNotificationActionHandler *)userNotificationActionHandler
{
return AppEnvironment.shared.userNotificationActionHandler;
}
- (SDSDatabaseStorage *)databaseStorage
{
return SDSDatabaseStorage.shared;
}
- (id<SyncManagerProtocol>)syncManager
{
OWSAssertDebug(SSKEnvironment.shared.syncManager);
return SSKEnvironment.shared.syncManager;
}
- (StorageCoordinator *)storageCoordinator
{
return SSKEnvironment.shared.storageCoordinator;
}
- (LaunchJobs *)launchJobs
{
return Environment.shared.launchJobs;
}
- (nullable MessageFetcherJob *)messageFetcherJob
{
return SSKEnvironment.shared.messageFetcherJob;
}
- (DeviceService *)deviceService
{
return DeviceService.shared;
}
#pragma mark -
- (void)applicationDidEnterBackground:(UIApplication *)application
{
OWSLogInfo(@"applicationDidEnterBackground.");
[DDLog flushLog];
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
OWSLogInfo(@"applicationWillEnterForeground.");
}
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application
{
OWSLogInfo(@"applicationDidReceiveMemoryWarning.");
}
- (void)applicationWillTerminate:(UIApplication *)application
{
OWSLogInfo(@"applicationWillTerminate.");
[SignalApp.sharedApp applicationWillTerminate];
[DDLog flushLog];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
#if TESTABLE_BUILD
NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler);
#endif
// This should be the first thing we do.
SetCurrentAppContext([MainAppContext new]);
launchStartedAt = CACurrentMediaTime();
BOOL isLoggingEnabled;
#ifdef DEBUG
// Specified at Product -> Scheme -> Edit Scheme -> Test -> Arguments -> Environment to avoid things like
// the phone directory being looked up during tests.
isLoggingEnabled = TRUE;
[DebugLogger.sharedLogger enableTTYLogging];
#elif RELEASE
isLoggingEnabled = OWSPreferences.isLoggingEnabled;
#endif
if (isLoggingEnabled) {
[DebugLogger.sharedLogger enableFileLogging];
}
if (SSKDebugFlags.audibleErrorLogging) {
[DebugLogger.sharedLogger enableErrorReporting];
}
#ifdef DEBUG
[SSKFeatureFlags logFlags];
[SSKDebugFlags logFlags];
#endif
OWSLogWarn(@"application: didFinishLaunchingWithOptions.");
[Cryptography seedRandom];
// This *must* happen before we try and access or verify the database, since we
// may be in a state where the database has been partially restored from transfer
// (e.g. the key was replaced, but the database files haven't been moved into place)
__block BOOL deviceTransferRestoreFailed = NO;
[BenchManager benchWithTitle:@"Slow device transfer service launch"
logIfLongerThan:0.01
logInProduction:YES
block:^{
deviceTransferRestoreFailed = ![DeviceTransferService.shared launchCleanup];
}];
// XXX - careful when moving this. It must happen before we load YDB and/or GRDB.
[self verifyDBKeysAvailableBeforeBackgroundLaunch];
// We need to do this _after_ we set up logging, when the keychain is unlocked,
// but before we access YapDatabase, files on disk, or NSUserDefaults
NSError *_Nullable launchError = nil;
LaunchFailure launchFailure = LaunchFailure_None;
BOOL isYdbNotReady = ![YDBLegacyMigration ensureIsYDBReadyForAppExtensions:&launchError];
if (deviceTransferRestoreFailed) {
launchFailure = LaunchFailure_CouldNotRestoreTransferredData;
} else if (isYdbNotReady || launchError != nil) {
launchFailure = LaunchFailure_CouldNotLoadDatabase;
} else if (StorageCoordinator.hasInvalidDatabaseVersion) {
// Prevent:
// * Users who have used GRDB revert to using YDB.
// * Users with an unknown GRDB schema revert to using an earlier GRDB schema.
launchFailure = LaunchFailure_UnknownDatabaseVersion;
}
if (launchFailure != LaunchFailure_None) {
OWSLogInfo(@"application: didFinishLaunchingWithOptions failed.");
[self showUIForLaunchFailure:launchFailure];
return YES;
}
#if RELEASE
// ensureIsYDBReadyForAppExtensions may change the state of the logging
// preference (due to [NSUserDefaults migrateToSharedUserDefaults]), so honor
// that change if necessary.
if (isLoggingEnabled && !OWSPreferences.isLoggingEnabled) {
[DebugLogger.sharedLogger disableFileLogging];
}
#endif
[AppVersion sharedInstance];
[self setupNSEInteroperation];
// Prevent the device from sleeping during database view async registration
// (e.g. long database upgrades).
//
// This block will be cleared in storageIsReady.
[DeviceSleepManager.sharedInstance addBlockWithBlockObject:self];
if (CurrentAppContext().isRunningTests) {
return YES;
}
[AppSetup
setupEnvironmentWithAppSpecificSingletonBlock:^{
// Create AppEnvironment.
[AppEnvironment.shared setup];
[SignalApp.sharedApp setup];
}
migrationCompletion:^{
OWSAssertIsOnMainThread();
[self versionMigrationsDidComplete];
}];
[UIUtil setupSignalAppearence];
UIWindow *mainWindow = [OWSWindow new];
self.window = mainWindow;
CurrentAppContext().mainWindow = mainWindow;
// Show LoadingViewController until the async database view registrations are complete.
mainWindow.rootViewController = [LoadingViewController new];
[mainWindow makeKeyAndVisible];
// This must happen in appDidFinishLaunching or earlier to ensure we don't
// miss notifications.
// Setting the delegate also seems to prevent us from getting the legacy notification
// notification callbacks upon launch e.g. 'didReceiveLocalNotification'
UNUserNotificationCenter.currentNotificationCenter.delegate = self;
// Accept push notification when app is not open
NSDictionary *remoteNotification = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey];
if (remoteNotification) {
OWSLogInfo(@"Application was launched by tapping a push notification.");
[self processRemoteNotification:remoteNotification completion:nil];
}
[OWSScreenLockUI.sharedManager setupWithRootWindow:self.window];
[[OWSWindowManager sharedManager] setupWithRootWindow:self.window
screenBlockingWindow:OWSScreenLockUI.sharedManager.screenBlockingWindow];
[OWSScreenLockUI.sharedManager startObserving];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(storageIsReady)
name:StorageIsReadyNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(registrationStateDidChange)
name:NSNotificationNameRegistrationStateDidChange
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(registrationLockDidChange:)
name:NSNotificationName_2FAStateDidChange
object:nil];
OWSLogInfo(@"application: didFinishLaunchingWithOptions completed.");
OWSLogInfo(@"launchOptions: %@.", launchOptions);
[OWSAnalytics appLaunchDidBegin];
return YES;
}
/**
* The user must unlock the device once after reboot before the database encryption key can be accessed.
*/
- (void)verifyDBKeysAvailableBeforeBackgroundLaunch
{
if ([UIApplication sharedApplication].applicationState != UIApplicationStateBackground) {
return;
}
// someone currently using yap
if (StorageCoordinator.hasYdbFile && !SSKPreferences.isYdbMigrated
&& OWSPrimaryStorage.isDatabasePasswordAccessible) {
return;
}
// someone who migrated from yap to grdb needs the GRDB spec
if (SSKPreferences.isYdbMigrated && GRDBDatabaseStorageAdapter.isKeyAccessible) {
return;
}
// someone who never used yap needs the GRDB spec
if (!StorageCoordinator.hasYdbFile && StorageCoordinator.hasGrdbFile
&& GRDBDatabaseStorageAdapter.isKeyAccessible) {
return;
}
OWSLogInfo(@"exiting because we are in the background and the database password is not accessible.");
UILocalNotification *notification = [UILocalNotification new];
NSString *messageFormat = NSLocalizedString(@"NOTIFICATION_BODY_PHONE_LOCKED_FORMAT",
@"Lock screen notification text presented after user powers on their device without unlocking. Embeds "
@"{{device model}} (either 'iPad' or 'iPhone')");
notification.alertBody = [NSString stringWithFormat:messageFormat, UIDevice.currentDevice.localizedModel];
// Make sure we clear any existing notifications so that they don't start stacking up
// if the user receives multiple pushes.
[UIApplication.sharedApplication cancelAllLocalNotifications];
[UIApplication.sharedApplication setApplicationIconBadgeNumber:0];
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
[UIApplication.sharedApplication setApplicationIconBadgeNumber:1];
[DDLog flushLog];
exit(0);
}
- (void)showUIForLaunchFailure:(LaunchFailure)launchFailure
{
OWSLogInfo(@"launchFailure: %@", NSStringForLaunchFailure(launchFailure));
// Disable normal functioning of app.
self.didAppLaunchFail = YES;
// We perform a subset of the [application:didFinishLaunchingWithOptions:].
[AppVersion sharedInstance];
self.window = [OWSWindow new];
// Show the launch screen
UIViewController *viewController = [[UIStoryboard storyboardWithName:@"Launch Screen"
bundle:nil] instantiateInitialViewController];
self.window.rootViewController = viewController;
[self.window makeKeyAndVisible];
NSString *alertTitle;
NSString *alertMessage
= NSLocalizedString(@"APP_LAUNCH_FAILURE_ALERT_MESSAGE", @"Message for the 'app launch failed' alert.");
switch (launchFailure) {
case LaunchFailure_CouldNotLoadDatabase:
alertTitle = NSLocalizedString(@"APP_LAUNCH_FAILURE_COULD_NOT_LOAD_DATABASE",
@"Error indicating that the app could not launch because the database could not be loaded.");
break;
case LaunchFailure_UnknownDatabaseVersion:
alertTitle = NSLocalizedString(@"APP_LAUNCH_FAILURE_INVALID_DATABASE_VERSION_TITLE",
@"Error indicating that the app could not launch without reverting unknown database migrations.");
alertMessage = NSLocalizedString(@"APP_LAUNCH_FAILURE_INVALID_DATABASE_VERSION_MESSAGE",
@"Error indicating that the app could not launch without reverting unknown database migrations.");
break;
case LaunchFailure_CouldNotRestoreTransferredData:
alertTitle = NSLocalizedString(@"APP_LAUNCH_FAILURE_RESTORE_FAILED_TITLE",
@"Error indicating that the app could not restore transferred data.");
alertMessage = NSLocalizedString(@"APP_LAUNCH_FAILURE_RESTORE_FAILED_MESSAGE",
@"Error indicating that the app could not restore transferred data.");
break;
default:
OWSFailDebug(@"Unknown launch failure.");
alertTitle
= NSLocalizedString(@"APP_LAUNCH_FAILURE_ALERT_TITLE", @"Title for the 'app launch failed' alert.");
break;
}
ActionSheetController *actionSheet = [[ActionSheetController alloc] initWithTitle:alertTitle message:alertMessage];
[actionSheet
addAction:[[ActionSheetAction alloc] initWithTitle:NSLocalizedString(@"SETTINGS_ADVANCED_SUBMIT_DEBUGLOG", nil)
style:ActionSheetActionStyleDefault
handler:^(ActionSheetAction *_Nonnull action) {
[Pastelog submitLogsWithCompletion:^{
OWSFail(@"exiting after sharing debug logs.");
}];
}]];
[viewController presentActionSheet:actionSheet];
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
OWSAssertIsOnMainThread();
if (self.didAppLaunchFail) {
OWSFailDebug(@"app launch failed");
return;
}
OWSLogInfo(@"registered vanilla push token");
[self.pushRegistrationManager didReceiveVanillaPushToken:deviceToken];
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
OWSAssertIsOnMainThread();
if (self.didAppLaunchFail) {
OWSFailDebug(@"app launch failed");
return;
}
OWSLogError(@"failed to register vanilla push token with error: %@", error);
#ifdef DEBUG
OWSLogWarn(@"We're in debug mode. Faking success for remote registration with a fake push identifier");
[self.pushRegistrationManager didReceiveVanillaPushToken:[[NSMutableData dataWithLength:32] copy]];
#else
OWSProdError([OWSAnalyticsEvents appDelegateErrorFailedToRegisterForRemoteNotifications]);
[self.pushRegistrationManager didFailToReceiveVanillaPushTokenWithError:error];
#endif
}
- (BOOL)application:(UIApplication *)app
openURL:(NSURL *)url
options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options
{
OWSAssertIsOnMainThread();
return [self tryToOpenUrl:url];
}
- (BOOL)tryToOpenUrl:(NSURL *)url
{
OWSAssertDebug(!self.didAppLaunchFail);
if (self.didAppLaunchFail) {
OWSFailDebug(@"app launch failed");
return NO;
}
if ([StickerPackInfo isStickerPackShareUrl:url]) {
StickerPackInfo *_Nullable stickerPackInfo = [StickerPackInfo parseStickerPackShareUrl:url];
if (stickerPackInfo == nil) {
OWSFailDebug(@"Could not parse sticker pack share URL: %@", url);
return NO;
}
return [self tryToShowStickerPackView:stickerPackInfo];
} else if ([url.scheme isEqualToString:kURLSchemeSGNLKey]) {
if ([url.host hasPrefix:kURLHostVerifyPrefix] && ![self.tsAccountManager isRegistered]) {
if (!AppReadiness.isAppReady) {
OWSFailDebug(@"Ignoring URL; app is not ready.");
return NO;
}
return [SignalApp.sharedApp receivedVerificationCode:[url.path substringFromIndex:1]];
} else if ([url.host hasPrefix:kURLHostAddStickersPrefix] && [self.tsAccountManager isRegistered]) {
StickerPackInfo *_Nullable stickerPackInfo = [self parseAddStickersUrl:url];
if (stickerPackInfo == nil) {
OWSFailDebug(@"Invalid URL: %@", url);
return NO;
}
return [self tryToShowStickerPackView:stickerPackInfo];
} else {
OWSLogVerbose(@"Invalid URL: %@", url);
OWSFailDebug(@"Unknown URL host: %@", url.host);
}
} else {
OWSFailDebug(@"Unknown URL scheme: %@", url.scheme);
}
return NO;
}
- (nullable StickerPackInfo *)parseAddStickersUrl:(NSURL *)url
{
NSString *_Nullable packIdHex;
NSString *_Nullable packKeyHex;
NSURLComponents *components = [NSURLComponents componentsWithString:url.absoluteString];
for (NSURLQueryItem *queryItem in [components queryItems]) {
if ([queryItem.name isEqualToString:@"pack_id"]) {
OWSAssertDebug(packIdHex == nil);
packIdHex = queryItem.value;
} else if ([queryItem.name isEqualToString:@"pack_key"]) {
OWSAssertDebug(packKeyHex == nil);
packKeyHex = queryItem.value;
} else {
OWSLogWarn(@"Unknown query item: %@", queryItem.name);
}
}
return [StickerPackInfo parsePackIdHex:packIdHex packKeyHex:packKeyHex];
}
- (BOOL)tryToShowStickerPackView:(StickerPackInfo *)stickerPackInfo
{
OWSAssertDebug(!self.didAppLaunchFail);
[AppReadiness runNowOrWhenAppDidBecomeReady:^{
if (!self.tsAccountManager.isRegistered) {
OWSFailDebug(@"Ignoring sticker pack URL; not registered.");
return;
}
StickerPackViewController *packView =
[[StickerPackViewController alloc] initWithStickerPackInfo:stickerPackInfo];
UIViewController *rootViewController = self.window.rootViewController;
if (rootViewController.presentedViewController) {
[rootViewController dismissViewControllerAnimated:NO
completion:^{
[packView presentFrom:rootViewController animated:NO];
}];
} else {
[packView presentFrom:rootViewController animated:NO];
}
}];
return YES;
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
OWSAssertIsOnMainThread();
if (self.didAppLaunchFail) {
OWSFailDebug(@"app launch failed");
return;
}
OWSLogWarn(@"applicationDidBecomeActive.");
if (CurrentAppContext().isRunningTests) {
return;
}
[SignalApp.sharedApp ensureRootViewController:launchStartedAt];
[AppReadiness runNowOrWhenAppDidBecomeReady:^{
[self handleActivation];
}];
// Clear all notifications whenever we become active.
// When opening the app from a notification,
// AppDelegate.didReceiveLocalNotification will always
// be called _before_ we become active.
[self clearAllNotificationsAndRestoreBadgeCount];
// On every activation, clear old temp directories.
ClearOldTemporaryDirectories();
// Ensure that all windows have the correct frame.
[self.windowManager updateWindowFrames];
OWSLogInfo(@"applicationDidBecomeActive completed.");
}
- (void)enableBackgroundRefreshIfNecessary
{
[AppReadiness runNowOrWhenAppDidBecomeReady:^{
if (OWS2FAManager.sharedManager.isRegistrationLockEnabled && [self.tsAccountManager isRegisteredAndReady]) {
// Ping server once a day to keep-alive reglock clients.
const NSTimeInterval kBackgroundRefreshInterval = 24 * 60 * 60;
[[UIApplication sharedApplication] setMinimumBackgroundFetchInterval:kBackgroundRefreshInterval];
} else {
[[UIApplication sharedApplication]
setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalNever];
}
}];
}
- (void)handleActivation
{
OWSAssertIsOnMainThread();
OWSLogWarn(@"handleActivation.");
// Always check prekeys after app launches, and sometimes check on app activation.
[TSPreKeyManager checkPreKeysIfNecessary];
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
RTCInitializeSSL();
if ([self.tsAccountManager isRegistered]) {
// At this point, potentially lengthy DB locking migrations could be running.
// Avoid blocking app launch by putting all further possible DB access in async block
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
OWSLogInfo(@"running post launch block for registered user: %@", [self.tsAccountManager localAddress]);
// Clean up any messages that expired since last launch immediately
// and continue cleaning in the background.
[self.disappearingMessagesJob startIfNecessary];
[self enableBackgroundRefreshIfNecessary];
});
} else {
OWSLogInfo(@"running post launch block for unregistered user.");
// Unregistered user should have no unread messages. e.g. if you delete your account.
[AppEnvironment.shared.notificationPresenter clearAllNotifications];
[self.socketManager requestSocketOpen];
}
}); // end dispatchOnce for first time we become active
// Every time we become active...
if ([self.tsAccountManager isRegistered]) {
// At this point, potentially lengthy DB locking migrations could be running.
// Avoid blocking app launch by putting all further possible DB access in async block
dispatch_async(dispatch_get_main_queue(), ^{
[self.socketManager requestSocketOpen];
[Environment.shared.contactsManager fetchSystemContactsOnceIfAlreadyAuthorized];
[self.messageFetcherJob runObjc];
if (![UIApplication sharedApplication].isRegisteredForRemoteNotifications) {
OWSLogInfo(@"Retrying to register for remote notifications since user hasn't registered yet.");
// Push tokens don't normally change while the app is launched, so checking once during launch is
// usually sufficient, but e.g. on iOS11, users who have disabled "Allow Notifications" and disabled
// "Background App Refresh" will not be able to obtain an APN token. Enabling those settings does not
// restart the app, so we check every activation for users who haven't yet registered.
[OWSSyncPushTokensJob runWithAccountManager:AppEnvironment.shared.accountManager
preferences:Environment.shared.preferences];
}
});
}
OWSLogInfo(@"handleActivation completed.");
}
- (void)applicationWillResignActive:(UIApplication *)application
{
OWSAssertIsOnMainThread();
if (self.didAppLaunchFail) {
OWSFailDebug(@"app launch failed");
return;
}
OWSLogWarn(@"applicationWillResignActive.");
[self clearAllNotificationsAndRestoreBadgeCount];
[DDLog flushLog];
}
- (void)clearAllNotificationsAndRestoreBadgeCount
{
OWSAssertIsOnMainThread();
[AppReadiness runNowOrWhenAppDidBecomeReady:^{
[AppEnvironment.shared.notificationPresenter clearAllNotifications];
[OWSMessageUtils.sharedManager updateApplicationBadgeCount];
}];
}
- (void)application:(UIApplication *)application
performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem
completionHandler:(void (^)(BOOL succeeded))completionHandler {
OWSAssertIsOnMainThread();
if (self.didAppLaunchFail) {
OWSFailDebug(@"app launch failed");
completionHandler(NO);
return;
}
[AppReadiness runNowOrWhenAppDidBecomeReady:^{
if (![self.tsAccountManager isRegisteredAndReady]) {
ActionSheetController *controller = [[ActionSheetController alloc]
initWithTitle:NSLocalizedString(@"REGISTER_CONTACTS_WELCOME", nil)
message:NSLocalizedString(@"REGISTRATION_RESTRICTED_MESSAGE", nil)];
[controller addAction:[[ActionSheetAction alloc] initWithTitle:NSLocalizedString(@"OK", nil)
style:ActionSheetActionStyleDefault
handler:^(ActionSheetAction *_Nonnull action) {
}]];
UIViewController *fromViewController = [[UIApplication sharedApplication] frontmostViewController];
[fromViewController presentViewController:controller
animated:YES
completion:^{
completionHandler(NO);
}];
return;
}
[SignalApp.sharedApp showNewConversationView];
completionHandler(YES);
}];
}
/**
* Among other things, this is used by "call back" callkit dialog and calling from native contacts app.
*
* We always return YES if we are going to try to handle the user activity since
* we never want iOS to contact us again using a URL.
*
* From https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1623072-application?language=objc:
*
* If you do not implement this method or if your implementation returns NO, iOS tries to
* create a document for your app to open using a URL.
*/
- (BOOL)application:(UIApplication *)application
continueUserActivity:(nonnull NSUserActivity *)userActivity
restorationHandler:(nonnull void (^)(NSArray *_Nullable))restorationHandler
{
OWSAssertIsOnMainThread();
if (self.didAppLaunchFail) {
OWSFailDebug(@"app launch failed");
return NO;
}
if ([userActivity.activityType isEqualToString:@"INStartVideoCallIntent"]) {
OWSLogInfo(@"got start video call intent");
INInteraction *interaction = [userActivity interaction];
INIntent *intent = interaction.intent;
if (![intent isKindOfClass:[INStartVideoCallIntent class]]) {
OWSLogError(@"unexpected class for start call video: %@", intent);
return NO;
}
INStartVideoCallIntent *startCallIntent = (INStartVideoCallIntent *)intent;
NSString *_Nullable handle = startCallIntent.contacts.firstObject.personHandle.value;
if (!handle) {
OWSLogWarn(@"unable to find handle in startCallIntent: %@", startCallIntent);
return NO;
}
[AppReadiness runNowOrWhenAppDidBecomeReady:^{
if (![self.tsAccountManager isRegisteredAndReady]) {
OWSLogInfo(@"Ignoring user activity; app not ready.");
return;
}
if (!SSKFeatureFlags.calling) {
OWSLogInfo(@"Ignoring unsupported activity.");
return;
}
SignalServiceAddress *_Nullable address = [self addressForIntentHandle:handle];
if (!address.isValid) {
OWSLogWarn(@"ignoring attempt to initiate video call to unknown user.");
return;
}
// This intent can be received from more than one user interaction.
//
// * It can be received if the user taps the "video" button in the CallKit UI for an
// an ongoing call. If so, the correct response is to try to activate the local
// video for that call.
// * It can be received if the user taps the "video" button for a contact in the
// contacts app. If so, the correct response is to try to initiate a new call
// to that user - unless there already is another call in progress.
if (AppEnvironment.shared.callService.currentCall != nil) {
if ([address isEqualToAddress:AppEnvironment.shared.callService.currentCall.remoteAddress]) {
OWSLogWarn(@"trying to upgrade ongoing call to video.");
[AppEnvironment.shared.callService handleCallKitStartVideo];
return;
} else {
OWSLogWarn(@"ignoring INStartVideoCallIntent due to ongoing WebRTC call with another party.");
return;
}
}
OutboundCallInitiator *outboundCallInitiator = AppEnvironment.shared.outboundCallInitiator;
OWSAssertDebug(outboundCallInitiator);
[outboundCallInitiator initiateCallWithAddress:address];
}];
return YES;
} else if ([userActivity.activityType isEqualToString:@"INStartAudioCallIntent"]) {
OWSLogInfo(@"got start audio call intent");
INInteraction *interaction = [userActivity interaction];
INIntent *intent = interaction.intent;
if (![intent isKindOfClass:[INStartAudioCallIntent class]]) {
OWSLogError(@"unexpected class for start call audio: %@", intent);
return NO;
}
INStartAudioCallIntent *startCallIntent = (INStartAudioCallIntent *)intent;
NSString *_Nullable handle = startCallIntent.contacts.firstObject.personHandle.value;
if (!handle) {
OWSLogWarn(@"unable to find handle in startCallIntent: %@", startCallIntent);
return NO;
}
[AppReadiness runNowOrWhenAppDidBecomeReady:^{
if (![self.tsAccountManager isRegisteredAndReady]) {
OWSLogInfo(@"Ignoring user activity; app not ready.");
return;
}
if (!SSKFeatureFlags.calling) {
OWSLogInfo(@"Ignoring unsupported activity.");
return;
}
SignalServiceAddress *_Nullable address = [self addressForIntentHandle:handle];
if (!address.isValid) {
OWSLogWarn(@"ignoring attempt to initiate audio call to unknown user.");
return;
}
if (AppEnvironment.shared.callService.currentCall != nil) {
OWSLogWarn(@"ignoring INStartAudioCallIntent due to ongoing WebRTC call.");
return;
}
OutboundCallInitiator *outboundCallInitiator = AppEnvironment.shared.outboundCallInitiator;
OWSAssertDebug(outboundCallInitiator);
[outboundCallInitiator initiateCallWithAddress:address];
}];
return YES;
// On iOS 13, all calls triggered from contacts use this intent
} else if ([userActivity.activityType isEqualToString:@"INStartCallIntent"]) {
if (!SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(13, 0)) {
OWSLogError(@"unexpectedly received INStartCallIntent pre iOS13");
return NO;
}
OWSLogInfo(@"got start call intent");
INInteraction *interaction = [userActivity interaction];
INIntent *intent = interaction.intent;
if (![intent isKindOfClass:NSClassFromString(@"INStartCallIntent")]) {
OWSLogError(@"unexpected class for start call: %@", intent);
return NO;
}
NSArray<INPerson *> *contacts = [intent performSelector:@selector(contacts)];
NSString *_Nullable handle = contacts.firstObject.personHandle.value;
if (!handle) {
OWSLogWarn(@"unable to find handle in startCallIntent: %@", intent);
return NO;
}
[AppReadiness runNowOrWhenAppDidBecomeReady:^{
if (![self.tsAccountManager isRegisteredAndReady]) {
OWSLogInfo(@"Ignoring user activity; app not ready.");
return;
}
if (!SSKFeatureFlags.calling) {
OWSLogInfo(@"Ignoring unsupported activity.");
return;
}
SignalServiceAddress *_Nullable address = [self addressForIntentHandle:handle];
if (!address.isValid) {
OWSLogWarn(@"ignoring attempt to initiate call to unknown user.");
return;
}
if (AppEnvironment.shared.callService.currentCall != nil) {
OWSLogWarn(@"ignoring INStartCallIntent due to ongoing WebRTC call.");
return;
}
OutboundCallInitiator *outboundCallInitiator = AppEnvironment.shared.outboundCallInitiator;
OWSAssertDebug(outboundCallInitiator);
[outboundCallInitiator initiateCallWithAddress:address];
}];
return YES;
} else if ([userActivity.activityType isEqualToString:NSUserActivityTypeBrowsingWeb]) {
if (userActivity.webpageURL == nil) {
OWSFailDebug(@"Missing webpageURL.");
return NO;
}
return [self tryToOpenUrl:userActivity.webpageURL];
} else {
OWSLogWarn(@"userActivity: %@, but not yet supported.", userActivity.activityType);
}
// TODO Something like...
// *phoneNumber = [[[[[[userActivity interaction] intent] contacts] firstObject] personHandle] value]
// thread = blah
// [callUIAdapter startCall:thread]
//
// Here's the Speakerbox Example for intent / NSUserActivity handling:
//
// func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool {
// guard let handle = userActivity.startCallHandle else {
// print("Could not determine start call handle from user activity: \(userActivity)")
// return false
// }
//