Merge branch 'charlesmchen/appWillBecomeReady_'

pull/1/head
Matthew Chen 7 years ago
commit 43eda866e2

@ -550,7 +550,7 @@ static NSTimeInterval launchStartedAt;
if (!AppReadiness.isAppReady) { if (!AppReadiness.isAppReady) {
OWSLogWarn(@"Ignoring openURL: app not ready."); OWSLogWarn(@"Ignoring openURL: app not ready.");
// We don't need to use [AppReadiness runNowOrWhenAppIsReady:]; // We don't need to use [AppReadiness runNowOrWhenAppDidBecomeReady:];
// the only URLs we handle in Signal iOS at the moment are used // the only URLs we handle in Signal iOS at the moment are used
// for resuming the verification step of the registration flow. // for resuming the verification step of the registration flow.
return NO; return NO;
@ -596,7 +596,7 @@ static NSTimeInterval launchStartedAt;
[self ensureRootViewController]; [self ensureRootViewController];
[AppReadiness runNowOrWhenAppIsReady:^{ [AppReadiness runNowOrWhenAppDidBecomeReady:^{
[self handleActivation]; [self handleActivation];
}]; }];
@ -616,7 +616,7 @@ static NSTimeInterval launchStartedAt;
- (void)enableBackgroundRefreshIfNecessary - (void)enableBackgroundRefreshIfNecessary
{ {
[AppReadiness runNowOrWhenAppIsReady:^{ [AppReadiness runNowOrWhenAppDidBecomeReady:^{
if (OWS2FAManager.sharedManager.is2FAEnabled && [self.tsAccountManager isRegistered]) { if (OWS2FAManager.sharedManager.is2FAEnabled && [self.tsAccountManager isRegistered]) {
// Ping server once a day to keep-alive 2FA clients. // Ping server once a day to keep-alive 2FA clients.
const NSTimeInterval kBackgroundRefreshInterval = 24 * 60 * 60; const NSTimeInterval kBackgroundRefreshInterval = 24 * 60 * 60;
@ -732,7 +732,7 @@ static NSTimeInterval launchStartedAt;
OWSAssertIsOnMainThread(); OWSAssertIsOnMainThread();
[SignalApp clearAllNotifications]; [SignalApp clearAllNotifications];
[AppReadiness runNowOrWhenAppIsReady:^{ [AppReadiness runNowOrWhenAppDidBecomeReady:^{
[OWSMessageUtils.sharedManager updateApplicationBadgeCount]; [OWSMessageUtils.sharedManager updateApplicationBadgeCount];
}]; }];
} }
@ -747,7 +747,7 @@ static NSTimeInterval launchStartedAt;
return; return;
} }
[AppReadiness runNowOrWhenAppIsReady:^{ [AppReadiness runNowOrWhenAppDidBecomeReady:^{
if (![self.tsAccountManager isRegistered]) { if (![self.tsAccountManager isRegistered]) {
UIAlertController *controller = UIAlertController *controller =
[UIAlertController alertControllerWithTitle:NSLocalizedString(@"REGISTER_CONTACTS_WELCOME", nil) [UIAlertController alertControllerWithTitle:NSLocalizedString(@"REGISTER_CONTACTS_WELCOME", nil)
@ -818,7 +818,7 @@ static NSTimeInterval launchStartedAt;
return NO; return NO;
} }
[AppReadiness runNowOrWhenAppIsReady:^{ [AppReadiness runNowOrWhenAppDidBecomeReady:^{
NSString *_Nullable phoneNumber = handle; NSString *_Nullable phoneNumber = handle;
if ([handle hasPrefix:CallKitCallManager.kAnonymousCallHandlePrefix]) { if ([handle hasPrefix:CallKitCallManager.kAnonymousCallHandlePrefix]) {
phoneNumber = [self.primaryStorage phoneNumberForCallKitId:handle]; phoneNumber = [self.primaryStorage phoneNumberForCallKitId:handle];
@ -875,7 +875,7 @@ static NSTimeInterval launchStartedAt;
return NO; return NO;
} }
[AppReadiness runNowOrWhenAppIsReady:^{ [AppReadiness runNowOrWhenAppDidBecomeReady:^{
NSString *_Nullable phoneNumber = handle; NSString *_Nullable phoneNumber = handle;
if ([handle hasPrefix:CallKitCallManager.kAnonymousCallHandlePrefix]) { if ([handle hasPrefix:CallKitCallManager.kAnonymousCallHandlePrefix]) {
phoneNumber = [self.primaryStorage phoneNumberForCallKitId:handle]; phoneNumber = [self.primaryStorage phoneNumberForCallKitId:handle];
@ -980,7 +980,7 @@ static NSTimeInterval launchStartedAt;
} }
OWSLogInfo(@"%@", notification); OWSLogInfo(@"%@", notification);
[AppReadiness runNowOrWhenAppIsReady:^{ [AppReadiness runNowOrWhenAppDidBecomeReady:^{
[[PushManager sharedManager] application:application didReceiveLocalNotification:notification]; [[PushManager sharedManager] application:application didReceiveLocalNotification:notification];
}]; }];
} }
@ -1003,7 +1003,7 @@ static NSTimeInterval launchStartedAt;
// later, after this method returns. // later, after this method returns.
// //
// https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1623068-application?language=objc // https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1623068-application?language=objc
[AppReadiness runNowOrWhenAppIsReady:^{ [AppReadiness runNowOrWhenAppDidBecomeReady:^{
[[PushManager sharedManager] application:application [[PushManager sharedManager] application:application
handleActionWithIdentifier:identifier handleActionWithIdentifier:identifier
forLocalNotification:notification forLocalNotification:notification
@ -1032,7 +1032,7 @@ static NSTimeInterval launchStartedAt;
// later, after this method returns. // later, after this method returns.
// //
// https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1623068-application?language=objc // https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1623068-application?language=objc
[AppReadiness runNowOrWhenAppIsReady:^{ [AppReadiness runNowOrWhenAppDidBecomeReady:^{
[[PushManager sharedManager] application:application [[PushManager sharedManager] application:application
handleActionWithIdentifier:identifier handleActionWithIdentifier:identifier
forLocalNotification:notification forLocalNotification:notification
@ -1045,7 +1045,7 @@ static NSTimeInterval launchStartedAt;
performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler
{ {
OWSLogInfo(@"performing background fetch"); OWSLogInfo(@"performing background fetch");
[AppReadiness runNowOrWhenAppIsReady:^{ [AppReadiness runNowOrWhenAppDidBecomeReady:^{
__block AnyPromise *job = [AppEnvironment.shared.messageFetcherJob run].then(^{ __block AnyPromise *job = [AppEnvironment.shared.messageFetcherJob run].then(^{
// HACK: Call completion handler after n seconds. // HACK: Call completion handler after n seconds.
// //
@ -1130,17 +1130,9 @@ static NSTimeInterval launchStartedAt;
[AppVersion.sharedInstance mainAppLaunchDidComplete]; [AppVersion.sharedInstance mainAppLaunchDidComplete];
[Environment.shared.contactsManager setup];
[Environment.shared.contactsManager startObserving];
// If there were any messages in our local queue which we hadn't yet processed.
[SSKEnvironment.shared.messageReceiver handleAnyUnprocessedEnvelopesAsync];
[SSKEnvironment.shared.batchMessageProcessor handleAnyUnprocessedEnvelopesAsync];
[Environment.shared.audioSession setup]; [Environment.shared.audioSession setup];
[SSKEnvironment.shared.reachabilityManager setup]; [SSKEnvironment.shared.reachabilityManager setup];
[SSKEnvironment.shared.messageSenderJobQueue setup];
[AppEnvironment.shared.sessionResetJobQueue setup];
if (!Environment.shared.preferences.hasGeneratedThumbnails) { if (!Environment.shared.preferences.hasGeneratedThumbnails) {
[self.primaryStorage.newDatabaseConnection [self.primaryStorage.newDatabaseConnection

@ -23,6 +23,15 @@ public class SessionResetJobQueue: NSObject, JobQueue {
public let requiresInternet: Bool = true public let requiresInternet: Bool = true
public var runningOperations: [SessionResetOperation] = [] public var runningOperations: [SessionResetOperation] = []
@objc
public override init() {
super.init()
AppReadiness.runNowOrWhenAppWillBecomeReady {
self.setup()
}
}
@objc @objc
public func setup() { public func setup() {
defaultSetup() defaultSetup()

@ -105,13 +105,13 @@ NSString *const Signal_Message_MarkAsRead_Identifier = @"Signal_Message_MarkAsRe
{ {
OWSLogInfo(@"received remote notification"); OWSLogInfo(@"received remote notification");
[AppReadiness runNowOrWhenAppIsReady:^{ [AppReadiness runNowOrWhenAppDidBecomeReady:^{
[self.messageFetcherJob run]; [self.messageFetcherJob run];
}]; }];
} }
- (void)applicationDidBecomeActive { - (void)applicationDidBecomeActive {
[AppReadiness runNowOrWhenAppIsReady:^{ [AppReadiness runNowOrWhenAppDidBecomeReady:^{
[self.messageFetcherJob run]; [self.messageFetcherJob run];
}]; }];
} }
@ -130,7 +130,7 @@ NSString *const Signal_Message_MarkAsRead_Identifier = @"Signal_Message_MarkAsRe
// If we want to re-introduce silent pushes we can remove this assert. // If we want to re-introduce silent pushes we can remove this assert.
OWSFailDebug(@"Unexpected content-available push."); OWSFailDebug(@"Unexpected content-available push.");
[AppReadiness runNowOrWhenAppIsReady:^{ [AppReadiness runNowOrWhenAppDidBecomeReady:^{
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
completionHandler(UIBackgroundFetchResultNewData); completionHandler(UIBackgroundFetchResultNewData);
}); });

@ -138,7 +138,7 @@ NS_ASSUME_NONNULL_BEGIN
// //
// It's not safe to access OWSScreenLock.isScreenLockEnabled // It's not safe to access OWSScreenLock.isScreenLockEnabled
// until the app is ready. // until the app is ready.
[AppReadiness runNowOrWhenAppIsReady:^{ [AppReadiness runNowOrWhenAppWillBecomeReady:^{
self.isScreenLockLocked = OWSScreenLock.sharedManager.isScreenLockEnabled; self.isScreenLockLocked = OWSScreenLock.sharedManager.isScreenLockEnabled;
[self ensureUI]; [self ensureUI];
@ -251,7 +251,7 @@ NS_ASSUME_NONNULL_BEGIN
OWSAssertIsOnMainThread(); OWSAssertIsOnMainThread();
if (!AppReadiness.isAppReady) { if (!AppReadiness.isAppReady) {
[AppReadiness runNowOrWhenAppIsReady:^{ [AppReadiness runNowOrWhenAppWillBecomeReady:^{
[self ensureUI]; [self ensureUI];
}]; }];
return; return;

@ -25,8 +25,6 @@ extern NSString *const OWSContactsManagerSignalAccountsDidChangeNotification;
- (id)initWithPrimaryStorage:(OWSPrimaryStorage *)primaryStorage; - (id)initWithPrimaryStorage:(OWSPrimaryStorage *)primaryStorage;
- (void)startObserving;
#pragma mark - Accessors #pragma mark - Accessors
@property (nonnull, readonly) ImageCache *avatarCache; @property (nonnull, readonly) ImageCache *avatarCache;
@ -44,8 +42,6 @@ extern NSString *const OWSContactsManagerSignalAccountsDidChangeNotification;
- (SignalAccount *)fetchOrBuildSignalAccountForRecipientId:(NSString *)recipientId; - (SignalAccount *)fetchOrBuildSignalAccountForRecipientId:(NSString *)recipientId;
- (BOOL)hasSignalAccountForRecipientId:(NSString *)recipientId; - (BOOL)hasSignalAccountForRecipientId:(NSString *)recipientId;
- (void)setup;
#pragma mark - System Contact Fetching #pragma mark - System Contact Fetching
// Must call `requestSystemContactsOnce` before accessing this method // Must call `requestSystemContactsOnce` before accessing this method

@ -82,6 +82,12 @@ NSString *const OWSContactsManagerKeyNextFullIntersectionDate = @"OWSContactsMan
OWSSingletonAssert(); OWSSingletonAssert();
[AppReadiness runNowOrWhenAppWillBecomeReady:^{
[self setup];
[self startObserving];
}];
return self; return self;
} }
@ -402,10 +408,12 @@ NSString *const OWSContactsManagerKeyNextFullIntersectionDate = @"OWSContactsMan
{ {
OWSAssertIsOnMainThread(); OWSAssertIsOnMainThread();
NSString *recipientId = notification.userInfo[kNSNotificationKey_ProfileRecipientId]; [AppReadiness runNowOrWhenAppDidBecomeReady:^{
OWSAssertDebug(recipientId.length > 0); NSString *recipientId = notification.userInfo[kNSNotificationKey_ProfileRecipientId];
OWSAssertDebug(recipientId.length > 0);
[self.avatarCache removeAllImagesForKey:recipientId]; [self.avatarCache removeAllImagesForKey:recipientId];
}];
} }
- (void)updateWithContacts:(NSArray<Contact *> *)contacts - (void)updateWithContacts:(NSArray<Contact *> *)contacts

@ -214,7 +214,7 @@ NSString *const kSyncManagerLastContactSyncKey = @"kTSStorageManagerOWSSyncManag
} }
- (void)sendConfigurationSyncMessage { - (void)sendConfigurationSyncMessage {
[AppReadiness runNowOrWhenAppIsReady:^{ [AppReadiness runNowOrWhenAppDidBecomeReady:^{
[self sendConfigurationSyncMessage_AppReady]; [self sendConfigurationSyncMessage_AppReady];
}]; }];
} }

@ -64,7 +64,7 @@ class ContactsFrameworkContactStoreAdaptee: NSObject, ContactStoreAdaptee {
@objc @objc
func didBecomeActive() { func didBecomeActive() {
AppReadiness.runNowOrWhenAppIsReady { AppReadiness.runNowOrWhenAppDidBecomeReady {
let currentSortOrder = CNContactsUserDefaults.shared().sortOrder let currentSortOrder = CNContactsUserDefaults.shared().sortOrder
guard currentSortOrder != self.lastSortOrder else { guard currentSortOrder != self.lastSortOrder else {

@ -94,7 +94,7 @@ typedef void (^ProfileManagerFailureBlock)(NSError *error);
OWSSingletonAssert(); OWSSingletonAssert();
[AppReadiness runNowOrWhenAppIsReady:^{ [AppReadiness runNowOrWhenAppDidBecomeReady:^{
[self rotateLocalProfileKeyIfNecessary]; [self rotateLocalProfileKeyIfNecessary];
}]; }];
@ -1479,7 +1479,7 @@ typedef void (^ProfileManagerFailureBlock)(NSError *error);
- (void)blockListDidChange:(NSNotification *)notification { - (void)blockListDidChange:(NSNotification *)notification {
OWSAssertIsOnMainThread(); OWSAssertIsOnMainThread();
[AppReadiness runNowOrWhenAppIsReady:^{ [AppReadiness runNowOrWhenAppDidBecomeReady:^{
[self rotateLocalProfileKeyIfNecessary]; [self rotateLocalProfileKeyIfNecessary];
}]; }];
} }

@ -85,7 +85,7 @@ NSString *const TSAccountManager_NeedsAccountAttributesUpdateKey = @"TSAccountMa
object:nil]; object:nil];
} }
[AppReadiness runNowOrWhenAppIsReady:^{ [AppReadiness runNowOrWhenAppDidBecomeReady:^{
[self updateAccountAttributesIfNecessary]; [self updateAccountAttributesIfNecessary];
}]; }];
@ -683,7 +683,7 @@ NSString *const TSAccountManager_NeedsAccountAttributesUpdateKey = @"TSAccountMa
- (void)reachabilityChanged { - (void)reachabilityChanged {
OWSAssertIsOnMainThread(); OWSAssertIsOnMainThread();
[AppReadiness runNowOrWhenAppIsReady:^{ [AppReadiness runNowOrWhenAppDidBecomeReady:^{
[self updateAccountAttributesIfNecessary]; [self updateAccountAttributesIfNecessary];
}]; }];
} }

@ -24,8 +24,6 @@ NS_ASSUME_NONNULL_BEGIN
plaintextData:(NSData *_Nullable)plaintextData plaintextData:(NSData *_Nullable)plaintextData
transaction:(YapDatabaseReadWriteTransaction *)transaction; transaction:(YapDatabaseReadWriteTransaction *)transaction;
- (void)handleAnyUnprocessedEnvelopesAsync;
@end @end
NS_ASSUME_NONNULL_END NS_ASSUME_NONNULL_END

@ -269,8 +269,10 @@ NSString *const OWSMessageContentJobFinderExtensionGroup = @"OWSMessageContentJo
object:nil]; object:nil];
// Start processing. // Start processing.
[AppReadiness runNowOrWhenAppIsReady:^{ [AppReadiness runNowOrWhenAppDidBecomeReady:^{
[self drainQueue]; if (CurrentAppContext().isMainApp) {
[self drainQueue];
}
}]; }];
return self; return self;
@ -458,6 +460,12 @@ NSString *const OWSMessageContentJobFinderExtensionGroup = @"OWSMessageContentJo
_processingQueue = processingQueue; _processingQueue = processingQueue;
[AppReadiness runNowOrWhenAppDidBecomeReady:^{
if (CurrentAppContext().isMainApp) {
[self.processingQueue drainQueue];
}
}];
return self; return self;
} }
@ -475,11 +483,6 @@ NSString *const OWSMessageContentJobFinderExtensionGroup = @"OWSMessageContentJo
#pragma mark - instance methods #pragma mark - instance methods
- (void)handleAnyUnprocessedEnvelopesAsync
{
[self.processingQueue drainQueue];
}
- (void)enqueueEnvelopeData:(NSData *)envelopeData - (void)enqueueEnvelopeData:(NSData *)envelopeData
plaintextData:(NSData *_Nullable)plaintextData plaintextData:(NSData *_Nullable)plaintextData
transaction:(YapDatabaseReadWriteTransaction *)transaction transaction:(YapDatabaseReadWriteTransaction *)transaction

@ -422,7 +422,7 @@ NSString *const kOWSBlockingManager_SyncedBlockedGroupIdsKey = @"kOWSBlockingMan
{ {
OWSAssertIsOnMainThread(); OWSAssertIsOnMainThread();
[AppReadiness runNowOrWhenAppIsReady:^{ [AppReadiness runNowOrWhenAppDidBecomeReady:^{
@synchronized(self) @synchronized(self)
{ {
[self syncBlockListIfNecessary]; [self syncBlockListIfNecessary];

@ -69,7 +69,7 @@ void AssertIsOnDisappearingMessagesQueue()
// suspenders in case a deletion schedule is missed. // suspenders in case a deletion schedule is missed.
NSTimeInterval kFallBackTimerInterval = 5 * kMinuteInterval; NSTimeInterval kFallBackTimerInterval = 5 * kMinuteInterval;
[AppReadiness runNowOrWhenAppIsReady:^{ [AppReadiness runNowOrWhenAppDidBecomeReady:^{
if (CurrentAppContext().isMainApp) { if (CurrentAppContext().isMainApp) {
self.fallbackTimer = [NSTimer weakScheduledTimerWithTimeInterval:kFallBackTimerInterval self.fallbackTimer = [NSTimer weakScheduledTimerWithTimeInterval:kFallBackTimerInterval
target:self target:self
@ -405,7 +405,7 @@ void AssertIsOnDisappearingMessagesQueue()
{ {
OWSAssertIsOnMainThread(); OWSAssertIsOnMainThread();
[AppReadiness runNowOrWhenAppIsReady:^{ [AppReadiness runNowOrWhenAppDidBecomeReady:^{
dispatch_async(OWSDisappearingMessagesJob.serialQueue, ^{ dispatch_async(OWSDisappearingMessagesJob.serialQueue, ^{
[self runLoop]; [self runLoop];
}); });

@ -569,7 +569,7 @@ NSString *const kNSNotificationName_IdentityStateDidChange = @"kNSNotificationNa
{ {
OWSAssertIsOnMainThread(); OWSAssertIsOnMainThread();
[AppReadiness runNowOrWhenAppIsReady:^{ [AppReadiness runNowOrWhenAppDidBecomeReady:^{
[self syncQueuedVerificationStates]; [self syncQueuedVerificationStates];
}]; }];
} }

@ -185,7 +185,7 @@ NS_ASSUME_NONNULL_BEGIN
} else { } else {
static dispatch_once_t onceToken; static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{ dispatch_once(&onceToken, ^{
[AppReadiness runNowOrWhenAppIsReady:^{ [AppReadiness runNowOrWhenAppDidBecomeReady:^{
[OWSMessageUtils.sharedManager updateApplicationBadgeCount]; [OWSMessageUtils.sharedManager updateApplicationBadgeCount];
}]; }];
}); });

@ -20,7 +20,6 @@ NS_ASSUME_NONNULL_BEGIN
+ (void)asyncRegisterDatabaseExtension:(OWSStorage *)storage; + (void)asyncRegisterDatabaseExtension:(OWSStorage *)storage;
- (void)handleReceivedEnvelopeData:(NSData *)envelopeData; - (void)handleReceivedEnvelopeData:(NSData *)envelopeData;
- (void)handleAnyUnprocessedEnvelopesAsync;
@end @end

@ -248,8 +248,10 @@ NSString *const OWSMessageDecryptJobFinderExtensionGroup = @"OWSMessageProcessin
_finder = finder; _finder = finder;
_isDrainingQueue = NO; _isDrainingQueue = NO;
[AppReadiness runNowOrWhenAppIsReady:^{ [AppReadiness runNowOrWhenAppDidBecomeReady:^{
[self drainQueue]; if (CurrentAppContext().isMainApp) {
[self drainQueue];
}
}]; }];
return self; return self;
@ -414,6 +416,12 @@ NSString *const OWSMessageDecryptJobFinderExtensionGroup = @"OWSMessageProcessin
_processingQueue = processingQueue; _processingQueue = processingQueue;
[AppReadiness runNowOrWhenAppDidBecomeReady:^{
if (CurrentAppContext().isMainApp) {
[self.processingQueue drainQueue];
}
}];
return self; return self;
} }
@ -431,11 +439,6 @@ NSString *const OWSMessageDecryptJobFinderExtensionGroup = @"OWSMessageProcessin
#pragma mark - instance methods #pragma mark - instance methods
- (void)handleAnyUnprocessedEnvelopesAsync
{
[self.processingQueue drainQueue];
}
- (void)handleReceivedEnvelopeData:(NSData *)envelopeData - (void)handleReceivedEnvelopeData:(NSData *)envelopeData
{ {
if (envelopeData.length < 1) { if (envelopeData.length < 1) {

@ -65,7 +65,7 @@ NSString *const kOutgoingReadReceiptManagerCollection = @"kOutgoingReadReceiptMa
object:nil]; object:nil];
// Start processing. // Start processing.
[AppReadiness runNowOrWhenAppIsReady:^{ [AppReadiness runNowOrWhenAppDidBecomeReady:^{
[self process]; [self process];
}]; }];

@ -157,7 +157,7 @@ NSString *const OWSReadReceiptManagerAreReadReceiptsEnabled = @"areReadReceiptsE
OWSSingletonAssert(); OWSSingletonAssert();
// Start processing. // Start processing.
[AppReadiness runNowOrWhenAppIsReady:^{ [AppReadiness runNowOrWhenAppDidBecomeReady:^{
[self scheduleProcessing]; [self scheduleProcessing];
}]; }];

@ -122,7 +122,7 @@ public class OWSUDManagerImpl: NSObject, OWSUDManager {
} }
@objc public func setup() { @objc public func setup() {
AppReadiness.runNowOrWhenAppIsReady { AppReadiness.runNowOrWhenAppDidBecomeReady {
guard TSAccountManager.isRegistered() else { guard TSAccountManager.isRegistered() else {
return return
} }

@ -25,6 +25,15 @@ import Foundation
@objc(SSKMessageSenderJobQueue) @objc(SSKMessageSenderJobQueue)
public class MessageSenderJobQueue: NSObject, JobQueue { public class MessageSenderJobQueue: NSObject, JobQueue {
@objc
public override init() {
super.init()
AppReadiness.runNowOrWhenAppWillBecomeReady {
self.setup()
}
}
// MARK: // MARK:
@objc(addMessage:transaction:) @objc(addMessage:transaction:)
@ -56,6 +65,8 @@ public class MessageSenderJobQueue: NSObject, JobQueue {
} }
private func add(message: TSOutgoingMessage, removeMessageAfterSending: Bool, transaction: YapDatabaseReadWriteTransaction) { private func add(message: TSOutgoingMessage, removeMessageAfterSending: Bool, transaction: YapDatabaseReadWriteTransaction) {
assert(AppReadiness.isAppReady())
let jobRecord: SSKMessageSenderJobRecord let jobRecord: SSKMessageSenderJobRecord
do { do {
jobRecord = try SSKMessageSenderJobRecord(message: message, removeMessageAfterSending: false, label: self.jobRecordLabel) jobRecord = try SSKMessageSenderJobRecord(message: message, removeMessageAfterSending: false, label: self.jobRecordLabel)

@ -1048,7 +1048,7 @@ NSString *NSStringFromOWSWebSocketType(OWSWebSocketType type)
if (!AppReadiness.isAppReady) { if (!AppReadiness.isAppReady) {
static dispatch_once_t onceToken; static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{ dispatch_once(&onceToken, ^{
[AppReadiness runNowOrWhenAppIsReady:^{ [AppReadiness runNowOrWhenAppDidBecomeReady:^{
[self applyDesiredSocketState]; [self applyDesiredSocketState];
}]; }];
}); });

@ -21,7 +21,15 @@ typedef void (^AppReadyBlock)(void);
// //
// This method should only be called on the main thread. // This method should only be called on the main thread.
// The block will always be called on the main thread. // The block will always be called on the main thread.
+ (void)runNowOrWhenAppIsReady:(AppReadyBlock)block NS_SWIFT_NAME(runNowOrWhenAppIsReady(_:)); //
// * The "will become ready" blocks are called before the "did become ready" blocks.
// * The "will become ready" blocks should be used for internal setup of components
// so that they are ready to interact with other components of the system.
// * The "did become ready" blocks should be used for any work that should be done
// on app launch, especially work that uses other components.
// * We should usually use "did become ready" blocks since they are safer.
+ (void)runNowOrWhenAppWillBecomeReady:(AppReadyBlock)block NS_SWIFT_NAME(runNowOrWhenAppWillBecomeReady(_:));
+ (void)runNowOrWhenAppDidBecomeReady:(AppReadyBlock)block NS_SWIFT_NAME(runNowOrWhenAppDidBecomeReady(_:));
@end @end

@ -11,7 +11,8 @@ NS_ASSUME_NONNULL_BEGIN
@property (atomic) BOOL isAppReady; @property (atomic) BOOL isAppReady;
@property (nonatomic) NSMutableArray<AppReadyBlock> *appReadyBlocks; @property (nonatomic) NSMutableArray<AppReadyBlock> *appWillBecomeReadyBlocks;
@property (nonatomic) NSMutableArray<AppReadyBlock> *appDidBecomeReadyBlocks;
@end @end
@ -39,7 +40,8 @@ NS_ASSUME_NONNULL_BEGIN
OWSSingletonAssert(); OWSSingletonAssert();
self.appReadyBlocks = [NSMutableArray new]; self.appWillBecomeReadyBlocks = [NSMutableArray new];
self.appDidBecomeReadyBlocks = [NSMutableArray new];
return self; return self;
} }
@ -49,21 +51,20 @@ NS_ASSUME_NONNULL_BEGIN
return [self.sharedManager isAppReady]; return [self.sharedManager isAppReady];
} }
+ (void)runNowOrWhenAppIsReady:(AppReadyBlock)block + (void)runNowOrWhenAppWillBecomeReady:(AppReadyBlock)block
{ {
DispatchMainThreadSafe(^{ DispatchMainThreadSafe(^{
[self.sharedManager runNowOrWhenAppIsReady:block]; [self.sharedManager runNowOrWhenAppWillBecomeReady:block];
}); });
} }
- (void)runNowOrWhenAppIsReady:(AppReadyBlock)block - (void)runNowOrWhenAppWillBecomeReady:(AppReadyBlock)block
{ {
OWSAssertIsOnMainThread(); OWSAssertIsOnMainThread();
OWSAssertDebug(block); OWSAssertDebug(block);
if (CurrentAppContext().isRunningTests) { if (CurrentAppContext().isRunningTests) {
// We don't need to an any "on app ready" work // We don't need to do any "on app ready" work in the tests.
// in the tests.
return; return;
} }
@ -72,7 +73,32 @@ NS_ASSUME_NONNULL_BEGIN
return; return;
} }
[self.appReadyBlocks addObject:block]; [self.appWillBecomeReadyBlocks addObject:block];
}
+ (void)runNowOrWhenAppDidBecomeReady:(AppReadyBlock)block
{
DispatchMainThreadSafe(^{
[self.sharedManager runNowOrWhenAppDidBecomeReady:block];
});
}
- (void)runNowOrWhenAppDidBecomeReady:(AppReadyBlock)block
{
OWSAssertIsOnMainThread();
OWSAssertDebug(block);
if (CurrentAppContext().isRunningTests) {
// We don't need to do any "on app ready" work in the tests.
return;
}
if (self.isAppReady) {
block();
return;
}
[self.appDidBecomeReadyBlocks addObject:block];
} }
+ (void)setAppIsReady + (void)setAppIsReady
@ -97,10 +123,16 @@ NS_ASSUME_NONNULL_BEGIN
OWSAssertIsOnMainThread(); OWSAssertIsOnMainThread();
OWSAssertDebug(self.isAppReady); OWSAssertDebug(self.isAppReady);
NSArray<AppReadyBlock> *appReadyBlocks = [self.appReadyBlocks copy]; NSArray<AppReadyBlock> *appWillBecomeReadyBlocks = [self.appWillBecomeReadyBlocks copy];
[self.appReadyBlocks removeAllObjects]; [self.appWillBecomeReadyBlocks removeAllObjects];
NSArray<AppReadyBlock> *appDidBecomeReadyBlocks = [self.appDidBecomeReadyBlocks copy];
[self.appDidBecomeReadyBlocks removeAllObjects];
for (AppReadyBlock block in appReadyBlocks) { // We invoke the _will become_ blocks before the _did become_ blocks.
for (AppReadyBlock block in appWillBecomeReadyBlocks) {
block();
}
for (AppReadyBlock block in appDidBecomeReadyBlocks) {
block(); block();
} }
} }

@ -88,7 +88,7 @@ public protocol JobQueue: DurableOperationDelegate {
public extension JobQueue { public extension JobQueue {
// MARK: Depenencies // MARK: Dependencies
var dbConnection: YapDatabaseConnection { var dbConnection: YapDatabaseConnection {
return SSKEnvironment.shared.primaryStorage.dbReadWriteConnection return SSKEnvironment.shared.primaryStorage.dbReadWriteConnection
@ -106,10 +106,15 @@ public extension JobQueue {
func add(jobRecord: JobRecordType, transaction: YapDatabaseReadWriteTransaction) { func add(jobRecord: JobRecordType, transaction: YapDatabaseReadWriteTransaction) {
assert(jobRecord.status == .ready) assert(jobRecord.status == .ready)
jobRecord.save(with: transaction) jobRecord.save(with: transaction)
transaction.addCompletionQueue(.global()) { transaction.addCompletionQueue(.global()) {
self.workStep() AppReadiness.runNowOrWhenAppDidBecomeReady {
DispatchQueue.global().async {
self.workStep()
}
}
} }
} }
@ -283,7 +288,7 @@ public class JobRecordFinder: NSObject, Finder {
func allRecords(label: String, status: SSKJobRecordStatus, transaction: YapDatabaseReadTransaction) -> [SSKJobRecord] { func allRecords(label: String, status: SSKJobRecordStatus, transaction: YapDatabaseReadTransaction) -> [SSKJobRecord] {
var result: [SSKJobRecord] = [] var result: [SSKJobRecord] = []
self.enumerateJobRecords(label: label, status: status, transaction: transaction) { jobRecord, stopPointer in self.enumerateJobRecords(label: label, status: status, transaction: transaction) { jobRecord, _ in
result.append(jobRecord) result.append(jobRecord)
} }
return result return result
@ -293,7 +298,7 @@ public class JobRecordFinder: NSObject, Finder {
let queryFormat = String(format: "WHERE %@ = ? AND %@ = ? ORDER BY %@", JobRecordField.status.rawValue, JobRecordField.label.rawValue, JobRecordField.sortId.rawValue) let queryFormat = String(format: "WHERE %@ = ? AND %@ = ? ORDER BY %@", JobRecordField.status.rawValue, JobRecordField.label.rawValue, JobRecordField.sortId.rawValue)
let query = YapDatabaseQuery(string: queryFormat, parameters: [status.rawValue, label]) let query = YapDatabaseQuery(string: queryFormat, parameters: [status.rawValue, label])
self.ext(transaction: transaction).enumerateKeysAndObjects(matching: query) { collection, key, object, stopPointer in self.ext(transaction: transaction).enumerateKeysAndObjects(matching: query) { _, _, object, stopPointer in
guard let jobRecord = object as? SSKJobRecord else { guard let jobRecord = object as? SSKJobRecord else {
owsFailDebug("expecting jobRecord but found: \(object)") owsFailDebug("expecting jobRecord but found: \(object)")
return return

@ -56,7 +56,7 @@ public class TypingIndicatorsImpl: NSObject, TypingIndicators {
public override init() { public override init() {
super.init() super.init()
AppReadiness.runNowOrWhenAppIsReady { AppReadiness.runNowOrWhenAppWillBecomeReady {
self.setup() self.setup()
} }
} }

@ -262,9 +262,6 @@ public class ShareViewController: UIViewController, ShareViewDelegate, SAEFailed
AppVersion.sharedInstance().saeLaunchDidComplete() AppVersion.sharedInstance().saeLaunchDidComplete()
Environment.shared.contactsManager.setup()
Environment.shared.contactsManager.startObserving()
ensureRootViewController() ensureRootViewController()
// We don't need to use OWSMessageReceiver in the SAE. // We don't need to use OWSMessageReceiver in the SAE.
@ -402,7 +399,7 @@ public class ShareViewController: UIViewController, ShareViewDelegate, SAEFailed
Logger.debug("") Logger.debug("")
if isReadyForAppExtensions { if isReadyForAppExtensions {
AppReadiness.runNowOrWhenAppIsReady { [weak self] in AppReadiness.runNowOrWhenAppDidBecomeReady { [weak self] in
AssertIsOnMainThread() AssertIsOnMainThread()
guard let strongSelf = self else { return } guard let strongSelf = self else { return }
strongSelf.activate() strongSelf.activate()

Loading…
Cancel
Save