Split out second web socket.

This commit is contained in:
Matthew Chen 2018-10-04 16:42:05 -04:00
parent c137e95ae5
commit 3b06434d4f
11 changed files with 1259 additions and 1082 deletions

View File

@ -595,7 +595,7 @@ static NSTimeInterval launchStartedAt;
// Unregistered user should have no unread messages. e.g. if you delete your account.
[SignalApp clearAllNotifications];
[TSSocketManager requestSocketOpen];
[TSSocketManager.shared requestSocketOpen];
UITapGestureRecognizer *gesture =
[[UITapGestureRecognizer alloc] initWithTarget:[Pastelog class] action:@selector(submitLogs)];
@ -609,7 +609,7 @@ static NSTimeInterval launchStartedAt;
// 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(), ^{
[TSSocketManager requestSocketOpen];
[TSSocketManager.shared requestSocketOpen];
[Environment.shared.contactsManager fetchSystemContactsOnceIfAlreadyAuthorized];
// This will fetch new messages, if we're using domain fronting.
[[PushManager sharedManager] applicationDidBecomeActive];

View File

@ -40,7 +40,7 @@ public class MessageFetcherJob: NSObject {
guard signalService.isCensorshipCircumventionActive else {
Logger.debug("delegating message fetching to SocketManager since we're using normal transport.")
TSSocketManager.requestSocketOpen()
TSSocketManager.shared.requestSocketOpen()
return Promise(value: ())
}

View File

@ -45,7 +45,7 @@ NS_ASSUME_NONNULL_BEGIN
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(socketStateDidChange)
name:kNSNotification_SocketManagerStateDidChange
name:kNSNotification_OWSWebSocketStateDidChange
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(reachabilityChanged)
@ -128,12 +128,13 @@ NS_ASSUME_NONNULL_BEGIN
OWSTableSection *censorshipSection = [OWSTableSection new];
censorshipSection.headerTitle = NSLocalizedString(@"SETTINGS_ADVANCED_CENSORSHIP_CIRCUMVENTION_HEADER",
@"Table header for the 'censorship circumvention' section.");
BOOL isAnySocketOpen = TSSocketManager.shared.highestSocketState == OWSWebSocketStateOpen;
if (OWSSignalService.sharedInstance.hasCensoredPhoneNumber) {
censorshipSection.footerTitle
= NSLocalizedString(@"SETTINGS_ADVANCED_CENSORSHIP_CIRCUMVENTION_FOOTER_AUTO_ENABLED",
@"Table footer for the 'censorship circumvention' section shown when censorship circumvention has been "
@"auto-enabled based on local phone number.");
} else if (TSSocketManager.shared.state == SocketManagerStateOpen) {
} else if (isAnySocketOpen) {
censorshipSection.footerTitle
= NSLocalizedString(@"SETTINGS_ADVANCED_CENSORSHIP_CIRCUMVENTION_FOOTER_WEBSOCKET_CONNECTED",
@"Table footer for the 'censorship circumvention' section shown when the app is connected to the "
@ -162,8 +163,8 @@ NS_ASSUME_NONNULL_BEGIN
// internet connection.
BOOL isManualCensorshipCircumventionOnEnabled
= (OWSSignalService.sharedInstance.isCensorshipCircumventionManuallyActivated
|| (!OWSSignalService.sharedInstance.hasCensoredPhoneNumber
&& TSSocketManager.shared.state != SocketManagerStateOpen && weakSelf.reachability.isReachable));
|| (!OWSSignalService.sharedInstance.hasCensoredPhoneNumber && !isAnySocketOpen
&& weakSelf.reachability.isReachable));
BOOL isCensorshipCircumventionOn = NO;
if (OWSSignalService.sharedInstance.hasCensoredPhoneNumber) {
isCensorshipCircumventionOn = YES;

View File

@ -148,16 +148,16 @@
@"Error indicating that this device is no longer registered.");
accessoryLabel.textColor = [UIColor ows_redColor];
} else {
switch (TSSocketManager.shared.state) {
case SocketManagerStateClosed:
switch (TSSocketManager.shared.highestSocketState) {
case OWSWebSocketStateClosed:
accessoryLabel.text = NSLocalizedString(@"NETWORK_STATUS_OFFLINE", @"");
accessoryLabel.textColor = [UIColor ows_redColor];
break;
case SocketManagerStateConnecting:
case OWSWebSocketStateConnecting:
accessoryLabel.text = NSLocalizedString(@"NETWORK_STATUS_CONNECTING", @"");
accessoryLabel.textColor = [UIColor ows_yellowColor];
break;
case SocketManagerStateOpen:
case OWSWebSocketStateOpen:
accessoryLabel.text = NSLocalizedString(@"NETWORK_STATUS_CONNECTED", @"");
accessoryLabel.textColor = [UIColor ows_greenColor];
break;
@ -473,7 +473,7 @@
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(socketStateDidChange)
name:kNSNotification_SocketManagerStateDidChange
name:kNSNotification_OWSWebSocketStateDidChange
object:nil];
}

View File

@ -54,8 +54,8 @@ static double const STALLED_PROGRESS = 0.9;
- (void)initializeObserver {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(socketManagerStateDidChange)
name:kNSNotification_SocketManagerStateDidChange
selector:@selector(OWSWebSocketStateDidChange)
name:kNSNotification_OWSWebSocketStateDidChange
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(isCensorshipCircumventionActiveDidChange:)
@ -70,7 +70,8 @@ static double const STALLED_PROGRESS = 0.9;
[self updateSocketStatusView];
}
- (void)socketManagerStateDidChange {
- (void)OWSWebSocketStateDidChange
{
OWSAssertIsOnMainThread();
[self updateSocketStatusView];
@ -86,8 +87,8 @@ static double const STALLED_PROGRESS = 0.9;
return;
}
switch (TSSocketManager.shared.state) {
case SocketManagerStateClosed:
switch (TSSocketManager.shared.highestSocketState) {
case OWSWebSocketStateClosed:
if (_socketStatusView == nil) {
[self initializeSocketStatusBar];
[_updateStatusTimer invalidate];
@ -101,10 +102,10 @@ static double const STALLED_PROGRESS = 0.9;
[_updateStatusTimer invalidate];
}
break;
case SocketManagerStateConnecting:
case OWSWebSocketStateConnecting:
// Do nothing.
break;
case SocketManagerStateOpen:
case OWSWebSocketStateOpen:
[_updateStatusTimer invalidate];
[_socketStatusView removeFromSuperview];
_socketStatusView = nil;

View File

@ -37,7 +37,7 @@ public class ProfileFetcherJob: NSObject {
}
private var socketManager: TSSocketManager {
return TSSocketManager.shared()
return TSSocketManager.shared
}
private var primaryStorage: OWSPrimaryStorage {
@ -48,6 +48,14 @@ public class ProfileFetcherJob: NSObject {
return SSKEnvironment.shared.udManager
}
private var profileManager: OWSProfileManager {
return OWSProfileManager.shared()
}
private var identityManager: OWSIdentityManager {
return SSKEnvironment.shared.identityManager
}
// MARK: -
public func run(recipientIds: [String]) {
@ -126,8 +134,10 @@ public class ProfileFetcherJob: NSObject {
let (promise, fulfill, reject) = Promise<SignalServiceProfile>.pending()
if TSSocketManager.canMakeRequests() {
// TODO: Use UD socket for some profile gets.
if socketManager.canMakeRequests(of: .default) {
self.socketManager.make(request,
webSocketType: .default,
success: { (responseObject: Any?) -> Void in
do {
let profile = try SignalServiceProfile(recipientId: recipientId, responseObject: responseObject)
@ -165,7 +175,7 @@ public class ProfileFetcherJob: NSObject {
private func updateProfile(signalServiceProfile: SignalServiceProfile) {
verifyIdentityUpToDateAsync(recipientId: signalServiceProfile.recipientId, latestIdentityKey: signalServiceProfile.identityKey)
OWSProfileManager.shared().updateProfile(forRecipientId: signalServiceProfile.recipientId,
profileManager.updateProfile(forRecipientId: signalServiceProfile.recipientId,
profileNameEncrypted: signalServiceProfile.profileNameEncrypted,
avatarUrlPath: signalServiceProfile.avatarUrlPath)
@ -179,7 +189,7 @@ public class ProfileFetcherJob: NSObject {
private func verifyIdentityUpToDateAsync(recipientId: String, latestIdentityKey: Data) {
primaryStorage.newDatabaseConnection().asyncReadWrite { (transaction) in
if OWSIdentityManager.shared().saveRemoteIdentity(latestIdentityKey, recipientId: recipientId, protocolContext: transaction) {
if self.identityManager.saveRemoteIdentity(latestIdentityKey, recipientId: recipientId, protocolContext: transaction) {
Logger.info("updated identity key with fetched profile for recipient: \(recipientId)")
self.primaryStorage.archiveAllSessions(forContact: recipientId, protocolContext: transaction)
} else {

View File

@ -1005,8 +1005,11 @@ NSString *const OWSMessageSenderRateLimitedException = @"RateLimitedException";
}
// TODO: UD sends over websocket.
if (!messageSend.hasWebsocketSendFailed && TSSocketManager.canMakeRequests && !messageSend.isUDSend) {
OWSWebSocketType webSocketType = (isUDSend ? OWSWebSocketTypeUD : OWSWebSocketTypeDefault);
BOOL canMakeWebsocketRequests = [TSSocketManager.shared canMakeRequestsOfType:webSocketType];
if (!messageSend.hasWebsocketSendFailed && canMakeWebsocketRequests && !messageSend..isUDSend) {
[TSSocketManager.shared makeRequest:request
webSocketType:webSocketType
success:^(id _Nullable responseObject) {
[self messageSendDidSucceed:messageSend deviceMessages:deviceMessages];
}

View File

@ -0,0 +1,59 @@
//
// Copyright (c) 2018 Open Whisper Systems. All rights reserved.
//
NS_ASSUME_NONNULL_BEGIN
static void *OWSWebSocketStateObservationContext = &OWSWebSocketStateObservationContext;
extern NSString *const kNSNotification_OWSWebSocketStateDidChange;
typedef NS_ENUM(NSUInteger, OWSWebSocketType) {
OWSWebSocketTypeDefault,
OWSWebSocketTypeUD,
};
typedef NS_ENUM(NSUInteger, OWSWebSocketState) {
OWSWebSocketStateClosed,
OWSWebSocketStateConnecting,
OWSWebSocketStateOpen,
};
typedef void (^TSSocketMessageSuccess)(id _Nullable responseObject);
// statusCode is zero by default, if request never made or failed.
typedef void (^TSSocketMessageFailure)(NSInteger statusCode, NSData *_Nullable responseData, NSError *error);
@class TSRequest;
@interface OWSWebSocket : NSObject
@property (nonatomic, readonly) OWSWebSocketState state;
- (instancetype)init NS_UNAVAILABLE;
- (instancetype)initWithWebSocketType:(OWSWebSocketType)webSocketType NS_DESIGNATED_INITIALIZER;
// If the app is in the foreground, we'll try to open the socket unless it's already
// open or connecting.
//
// If the app is in the background, we'll try to open the socket unless it's already
// open or connecting _and_ keep it open for at least N seconds.
// If the app is in the background and the socket is already open or connecting this
// might prolong how long we keep the socket open.
//
// This method can be called from any thread.
- (void)requestSocketOpen;
// This can be used to force the socket to close and re-open, if it is open.
- (void)cycleSocket;
#pragma mark - Message Sending
@property (atomic, readonly) BOOL canMakeRequests;
- (void)makeRequest:(TSRequest *)request
success:(TSSocketMessageSuccess)success
failure:(TSSocketMessageFailure)failure;
@end
NS_ASSUME_NONNULL_END

File diff suppressed because it is too large Load Diff

View File

@ -2,34 +2,27 @@
// Copyright (c) 2018 Open Whisper Systems. All rights reserved.
//
#import <SocketRocket/SRWebSocket.h>
#import "OWSWebSocket.h"
NS_ASSUME_NONNULL_BEGIN
static void *SocketManagerStateObservationContext = &SocketManagerStateObservationContext;
extern NSString *const kNSNotification_SocketManagerStateDidChange;
typedef NS_ENUM(NSUInteger, SocketManagerState) {
SocketManagerStateClosed,
SocketManagerStateConnecting,
SocketManagerStateOpen,
};
typedef void (^TSSocketMessageSuccess)(id _Nullable responseObject);
// statusCode is zero by default, if request never made or failed.
typedef void (^TSSocketMessageFailure)(NSInteger statusCode, NSData *_Nullable responseData, NSError *error);
@class TSRequest;
@interface TSSocketManager : NSObject <SRWebSocketDelegate>
@interface TSSocketManager : NSObject
@property (nonatomic, readonly) SocketManagerState state;
+ (instancetype)shared;
@property (class, readonly, nonatomic) TSSocketManager *shared;
- (instancetype)init NS_DESIGNATED_INITIALIZER;
// Returns the "best" state of any of the sockets.
//
// We surface the socket state in various places in the UI.
// We generally are trying to indicate/help resolve network
// connectivity issues. We want to show the "best" or "highest"
// socket state of the sockets. e.g. the UI should reflect
// "open" if any of the sockets is open.
- (OWSWebSocketState)highestSocketState;
// If the app is in the foreground, we'll try to open the socket unless it's already
// open or connecting.
//
@ -39,16 +32,17 @@ typedef void (^TSSocketMessageFailure)(NSInteger statusCode, NSData *_Nullable r
// might prolong how long we keep the socket open.
//
// This method can be called from any thread.
+ (void)requestSocketOpen;
- (void)requestSocketOpen;
// This can be used to force the socket to close and re-open, if it is open.
- (void)cycleSocket;
#pragma mark - Message Sending
+ (BOOL)canMakeRequests;
- (BOOL)canMakeRequestsOfType:(OWSWebSocketType)webSocketType;
- (void)makeRequest:(TSRequest *)request
webSocketType:(OWSWebSocketType)webSocketType
success:(TSSocketMessageSuccess)success
failure:(TSSocketMessageFailure)failure;

File diff suppressed because it is too large Load Diff