Rework socket manager.

// FREEBIE
pull/1/head
Matthew Chen 8 years ago
parent 195d721aa6
commit effa885614

@ -140,38 +140,33 @@ static NSString *const kURLHostVerifyPrefix = @"verify";
// At this point, potentially lengthy DB locking migrations could be running. // At this point, potentially lengthy DB locking migrations could be running.
// Avoid blocking app launch by putting all further possible DB access in async thread. // Avoid blocking app launch by putting all further possible DB access in async thread.
UIApplicationState launchState = application.applicationState; [[TSAccountManager sharedInstance]
[[TSAccountManager sharedInstance] ifRegistered:YES runAsync:^{ ifRegistered:YES
if (launchState == UIApplicationStateInactive) { runAsync:^{
DDLogWarn(@"The app was launched from inactive"); [TSSocketManager requestSocketOpen];
[TSSocketManager becomeActiveFromForeground];
} else if (launchState == UIApplicationStateBackground) { RTCInitializeSSL();
DDLogWarn(@"The app was launched from being backgrounded");
[TSSocketManager becomeActiveFromBackgroundExpectMessage:NO]; [OWSSyncPushTokensJob runWithPushManager:[PushManager sharedManager]
} else { accountManager:[Environment getCurrent].accountManager
DDLogWarn(@"The app was launched in an unknown way"); preferences:[Environment preferences]]
} .then(^{
DDLogDebug(@"%@ Successfully ran syncPushTokensJob.", self.tag);
RTCInitializeSSL(); })
.catch(^(NSError *_Nonnull error) {
[OWSSyncPushTokensJob runWithPushManager:[PushManager sharedManager] DDLogDebug(@"%@ Failed to run syncPushTokensJob with error: %@", self.tag, error);
accountManager:[Environment getCurrent].accountManager });
preferences:[Environment preferences]].then(^{
DDLogDebug(@"%@ Successfully ran syncPushTokensJob.", self.tag); // Clean up any messages that expired since last launch.
}).catch(^(NSError *_Nonnull error) { [[[OWSDisappearingMessagesJob alloc] initWithStorageManager:[TSStorageManager sharedManager]] run];
DDLogDebug(@"%@ Failed to run syncPushTokensJob with error: %@", self.tag, error);
}); // Mark all "attempting out" messages as "unsent", i.e. any messages that were not successfully
// sent before the app exited should be marked as failures.
// Clean up any messages that expired since last launch. [[[OWSFailedMessagesJob alloc] initWithStorageManager:[TSStorageManager sharedManager]] run];
[[[OWSDisappearingMessagesJob alloc] initWithStorageManager:[TSStorageManager sharedManager]] run]; [[[OWSFailedAttachmentDownloadsJob alloc] initWithStorageManager:[TSStorageManager sharedManager]] run];
// Mark all "attempting out" messages as "unsent", i.e. any messages that were not successfully [AppStoreRating setupRatingLibrary];
// sent before the app exited should be marked as failures. }];
[[[OWSFailedMessagesJob alloc] initWithStorageManager:[TSStorageManager sharedManager]] run];
[[[OWSFailedAttachmentDownloadsJob alloc] initWithStorageManager:[TSStorageManager sharedManager]] run];
[AppStoreRating setupRatingLibrary];
}];
[[TSAccountManager sharedInstance] ifRegistered:NO runAsync:^{ [[TSAccountManager sharedInstance] ifRegistered:NO runAsync:^{
dispatch_async(dispatch_get_main_queue(), ^{ dispatch_async(dispatch_get_main_queue(), ^{
@ -273,7 +268,7 @@ static NSString *const kURLHostVerifyPrefix = @"verify";
// We're double checking that the app is active, to be sure since we // We're double checking that the app is active, to be sure since we
// can't verify in production env due to code // can't verify in production env due to code
// signing. // signing.
[TSSocketManager becomeActiveFromForeground]; [TSSocketManager requestSocketOpen];
[[Environment getCurrent].contactsManager verifyABPermission]; [[Environment getCurrent].contactsManager verifyABPermission];
// This will fetch new messages, if we're using domain // This will fetch new messages, if we're using domain
@ -300,7 +295,6 @@ static NSString *const kURLHostVerifyPrefix = @"verify";
dispatch_sync(dispatch_get_main_queue(), ^{ dispatch_sync(dispatch_get_main_queue(), ^{
[self protectScreen]; [self protectScreen];
[[[Environment getCurrent] signalsViewController] updateInboxCountLabel]; [[[Environment getCurrent] signalsViewController] updateInboxCountLabel];
[TSSocketManager resignActivity];
}); });
} }

@ -1,5 +1,6 @@
// Created by Michael Kirk on 12/19/16. //
// Copyright © 2016 Open Whisper Systems. All rights reserved. // Copyright (c) 2017 Open Whisper Systems. All rights reserved.
//
import Foundation import Foundation
import PromiseKit import PromiseKit
@ -27,7 +28,7 @@ class MessageFetcherJob: NSObject {
Logger.debug("\(TAG) \(#function)") Logger.debug("\(TAG) \(#function)")
guard signalService.isCensored else { guard signalService.isCensored else {
Logger.debug("\(self.TAG) delegating message fetching to SocketManager since we're using normal transport.") Logger.debug("\(self.TAG) delegating message fetching to SocketManager since we're using normal transport.")
TSSocketManager.becomeActive(fromBackgroundExpectMessage: true) TSSocketManager.requestSocketOpen()
return return
} }
@ -35,10 +36,10 @@ class MessageFetcherJob: NSObject {
let promiseId = NSDate().timeIntervalSince1970 let promiseId = NSDate().timeIntervalSince1970
Logger.debug("\(self.TAG) starting promise: \(promiseId)") Logger.debug("\(self.TAG) starting promise: \(promiseId)")
let runPromise = self.fetchUndeliveredMessages().then { (envelopes: [OWSSignalServiceProtosEnvelope], more: Bool) -> () in let runPromise = self.fetchUndeliveredMessages().then { (envelopes: [OWSSignalServiceProtosEnvelope], more: Bool) -> Void in
for envelope in envelopes { for envelope in envelopes {
Logger.info("\(self.TAG) received envelope.") Logger.info("\(self.TAG) received envelope.")
self.messagesManager.handleReceivedEnvelope(envelope); self.messagesManager.handleReceivedEnvelope(envelope)
self.acknowledgeDelivery(envelope: envelope) self.acknowledgeDelivery(envelope: envelope)
} }
@ -59,7 +60,7 @@ class MessageFetcherJob: NSObject {
// use in DEBUG or wherever you can't receive push notifications to poll for messages. // use in DEBUG or wherever you can't receive push notifications to poll for messages.
// Do not use in production. // Do not use in production.
func startRunLoop(timeInterval: Double) { func startRunLoop(timeInterval: Double) {
Logger.error("\(TAG) Starting message fetch polling. This should not be used in production."); Logger.error("\(TAG) Starting message fetch polling. This should not be used in production.")
timer = Timer.scheduledTimer(timeInterval: timeInterval, target: self, selector: #selector(runAsync), userInfo: nil, repeats: true) timer = Timer.scheduledTimer(timeInterval: timeInterval, target: self, selector: #selector(runAsync), userInfo: nil, repeats: true)
} }
@ -84,7 +85,7 @@ class MessageFetcherJob: NSObject {
return nil return nil
} }
let moreMessages = { () -> Bool in let moreMessages = { () -> Bool in
if let responseMore = responseDict["more"] as? Bool { if let responseMore = responseDict["more"] as? Bool {
return responseMore return responseMore
} else { } else {
@ -160,7 +161,7 @@ class MessageFetcherJob: NSObject {
self.networkManager.makeRequest( self.networkManager.makeRequest(
messagesRequest, messagesRequest,
success: { (task: URLSessionDataTask?, responseObject: Any?) -> () in success: { (_: URLSessionDataTask?, responseObject: Any?) -> Void in
guard let (envelopes, more) = self.parseMessagesResponse(responseObject: responseObject) else { guard let (envelopes, more) = self.parseMessagesResponse(responseObject: responseObject) else {
Logger.error("\(self.TAG) response object had unexpected content") Logger.error("\(self.TAG) response object had unexpected content")
return reject(OWSErrorMakeUnableToProcessServerResponseError()) return reject(OWSErrorMakeUnableToProcessServerResponseError())
@ -168,7 +169,7 @@ class MessageFetcherJob: NSObject {
fulfill((envelopes: envelopes, more: more)) fulfill((envelopes: envelopes, more: more))
}, },
failure: { (task: URLSessionDataTask?, error: Error?) in failure: { (_: URLSessionDataTask?, error: Error?) in
guard let error = error else { guard let error = error else {
Logger.error("\(self.TAG) error was surpringly nil. sheesh rough day.") Logger.error("\(self.TAG) error was surpringly nil. sheesh rough day.")
return reject(OWSErrorMakeUnableToProcessServerResponseError()) return reject(OWSErrorMakeUnableToProcessServerResponseError())
@ -182,10 +183,10 @@ class MessageFetcherJob: NSObject {
func acknowledgeDelivery(envelope: OWSSignalServiceProtosEnvelope) { func acknowledgeDelivery(envelope: OWSSignalServiceProtosEnvelope) {
let request = OWSAcknowledgeMessageDeliveryRequest(source: envelope.source, timestamp: envelope.timestamp) let request = OWSAcknowledgeMessageDeliveryRequest(source: envelope.source, timestamp: envelope.timestamp)
self.networkManager.makeRequest(request, self.networkManager.makeRequest(request,
success: { (task: URLSessionDataTask?, responseObject: Any?) -> () in success: { (_: URLSessionDataTask?, _: Any?) -> Void in
Logger.debug("\(self.TAG) acknowledged delivery for message at timestamp: \(envelope.timestamp)") Logger.debug("\(self.TAG) acknowledged delivery for message at timestamp: \(envelope.timestamp)")
}, },
failure: { (task: URLSessionDataTask?, error: Error?) in failure: { (_: URLSessionDataTask?, error: Error?) in
Logger.debug("\(self.TAG) acknowledging delivery for message at timestamp: \(envelope.timestamp) failed with error: \(error)") Logger.debug("\(self.TAG) acknowledging delivery for message at timestamp: \(envelope.timestamp) failed with error: \(error)")
}) })
} }

Loading…
Cancel
Save