mirror of
https://github.com/firebase/firebase-ios-sdk
synced 2026-11-10 22:45:59 +05:45
* AppAttestation initial public API * Run ./scripts/style.sh * Copyright * Cleanup * Cleanup * Get token forcing refresh method * Formatting * Forcing refresh samples * Interop introduced * Code samples for Interop * Run ./scripts/style.sh * Cleanup * TODOs and Copirights * Fix build * Supported iOS versions * Remove unnecessary bridging header * Run ./scripts/style.sh * [WIP] DeviceCheckAttestationProvider as a subspec * cleanup * Add memory attributes to readonly properties * Move FIRDeviceCheckAttestationProvider.h to private headers * TODO for `FirebaseAppAttestation/Core` name * Remove memory attributes from FIRAppAttestationToken properties * FIRAppAttestationTests.testSetAttestationProviderFactory introduced * FIRAppAttestationToken initializer * Basic FIRLibrary implementation and FIRAppAttestationProviderFactory ingestion. * Fix * FIRAppAttestationToken+Interop.h * TODOs * Tests: reset FIRApps * GHA for App Attestation * Run ./scripts/style.sh * Style fixes. * Run ./scripts/style.sh * TODO * Nullable initializer and type annpotations * TODOs * TODOs * TODO * Fix spec and allow warnings * AppAttestation initial public API * Run ./scripts/style.sh * Copyright * Cleanup * Cleanup * Get token forcing refresh method * Formatting * Forcing refresh samples * Interop introduced * Code samples for Interop * Run ./scripts/style.sh * Cleanup * TODOs and Copirights * Fix build * Supported iOS versions * Remove unnecessary bridging header * Run ./scripts/style.sh * [WIP] DeviceCheckAttestationProvider as a subspec * cleanup * Add memory attributes to readonly properties * Move FIRDeviceCheckAttestationProvider.h to private headers * TODO for `FirebaseAppAttestation/Core` name * Remove memory attributes from FIRAppAttestationToken properties * FIRAppAttestationTests.testSetAttestationProviderFactory introduced * FIRAppAttestationToken initializer * Basic FIRLibrary implementation and FIRAppAttestationProviderFactory ingestion. * Fix * FIRAppAttestationToken+Interop.h * TODOs * Tests: reset FIRApps * Run ./scripts/style.sh * Style fixes. * Run ./scripts/style.sh * TODO * Nullable initializer and type annpotations * TODOs * TODOs * TODO * Revert FirestoreDecoder.swift formatting. * Basic implementation of FIRDeviceCheckAttestationProvider and tests (#626) * DeviceCheck attestation provider sceleton * DeviceCheck attestation provider sceleton * Basic FIRDeviceCheckAttestationProviderTests * Run ./scripts/style.sh * FIRAppAttestStorage implementation and tests (#627) * FIRDeviceCheckAttestationProvider designated init * FIRAppAttestStorage API and basic tests. * FIRAppAttestStoredToken: NSSecureCoding implementation * WIP Storage * Add `accessGroup` param to `FIRAppAttestStorage` * FIRAppAttestStorage implementation * Use constants * FIRAppAttestStorage API doc * Coding style and typos. * Code formatting * Attestation Token caching (#630) * Storage instance and looging * AppAttestation caching * Tests and cleanup * Cleanup * Rename App Attestation -> App Check (#631) * Rename App Attestation -> App Check * Run ./scripts/style.sh * Update GHA * Default Custom Provider (#633) * AppCheck: remove not unnecessary public API (#634) * AppCheck: remove not unnecessary public API * Run ./scripts/style.sh * AppCheck: DeviceCheck token server API (#635) * Generic HTTP request handling * [draft] AppCheck: device check HTTP API and simple tests * Parse response * Cleanup * AppCheck: API errors and tests (#636) * AppCheck errors * API service tests and fixes * Cleanup * Run ./scripts/style.sh * Naming * AppCheck: Register device check provider factory as a default (#637) * AppCheck errors * API service tests and fixes * Cleanup * Run ./scripts/style.sh * AppCheck: register FIRDeviceCheckProvider as a component * Naming * Registre device check provider factory as a default * FIRDeviceCheckProvider tests * AppCheck: API communication common for all providers moved to FIRAppCheckAPIService (#640) * FIRAppCheckAPIService introduced * Move URL seession stub to FIRURLSessionOCMockStub * Run ./scripts/style.sh * Move approximate date comparing to FIRDateTestUtils * compose request in FIRAppCheckAPIService * FIRAppCheckAPIServiceTests * Use FIRAppCheckAPIService in FIRDeviceCheckProvider * Cleanup * DeviceCheck mock server integration and tests (#686) * DeviceCheck mock server integration and tests * TODO * Update FIROptions.h import * Temporary add FirebaseAppCheck to skip import validation * TestUtilities moved to SharedTestUtilities * FirebaseAppCheck.podspec: TestUtilities->SharedTestUtilities * SwiftPM: add OCMock dependency to SharedTestUtilities * FIRURLSessionOCMockStub: #import "OCMock.h" * App Check: Firebase 7 fixes (#715) * AppCheck Firebase 7 * FirebaseCore repo-relative imports * Fix FIRAppCheckStorage.m compilation * Repo relative imports * linebreak * AppCheck: debug FAC token provider (#716) * AppCheck Firebase 7 * FirebaseCore repo-relative imports * Fix FIRAppCheckStorage.m compilation * Repo relative imports * linebreak * Remove FIRAppCheckDefaultCustomProvider * FIRAppCheckDebugProvider introduced * FIRAppCheckDebugProviderTests * style * Print locally generated debug token to console * Fix imports * mullability and line breaks * typo * Comments * TODO * AppCheck: merge into single spec (package) (#717) * Standard package folder structure * Move interop header into AppCheck sources folder * Combine public headers in the standard dir * Private headers to internal * Podspec * Headers import udpdate * style * Fix header imports * Enable check_imports.swift and fix imports * AppCheck: server request adjustments (#718) * Wrap DeviceCheck token into JSON * AppChek - remove static_framework requirement * WIP * Update default base URL * Set content-type header * Check for empty response data * Fix tests * Style and formatting * Podspec - revert wrong change and remove static_framework * Assign error to error pointer safely. * AppCheck: primitive test app (#719) * Remove static_framework requirement * WIP: FIRAppCheckTestApp introduced * Delete .plist * Copyright * Remove empty test targets * pod deintegrate * Remove test targets from Podfile * formatting * Storage: integration with AppCheck (#720) * Storage: add AppCheck interop dependency * Inject AppCheck into FIRStorageTokenAuthorizer * initial AppCheck integration * Introduce AppCheck fake * AppCheck fake implementation * FIRStorageTokenAuthorizer tests and fixes * @"Authorization" header constant * Log AppCheck error. * Cleanup * FIRStorageTokenAuthorizerTests: helpers * TODO * Cleanup * AppCheck: separate 2P and 3P API (#724) * FIRAppCheckInterop: remove a convenience method. * Rename: FIRAppCheckTokenInterop->FIRAppCheckTokenResultInterop * FIRAppCheckTokenResult introduced * Update FIRAppCheckTokenHandlerInterop, FIRAppCheckTokenResultInterop and tests * style * Update token result * Update storage integration * Adjust check_imports.swift for test files * Don't use internal AppCheck classes in Storage tests * style * Rename token to tokenResult in 2P API * Add private Core headers to app check sources * Fix storage log message code format * token clarification comments in API docs * Rename token->tokenResult * AppCheck cleanup (#737) * Fix public headers import * Cleanup imported test utils * FirebaseAppCheck podspec: revert git URL * AppCheck: Debug token to AppCheck token exchange API (#739) * GUL: make NSURLSession promise extension public * Use NSURLSession+GULPromises to send requests * style * Move FIRAppCheckToken+APIResponse to Core dir * rename * FIRAppCheckDebugProviderAPIService introduced * Move async token parsing API to FIRAppCheckToken extension * Move token exchange response handling to FIRAppCheckAPIService. Tests WIP. * Move API response parsing tests to FIRAppCheckAPIServiceTests * FIRAppCheckDebugProviderAPIServiceTests * Cleanup * style * App Check debug provider: integrate with exchange API (#743) * Move FIROption validation to FIRAppCheckValidator * FIRAppCheckDebugProvider token exchange and tests * Fix FIRAppCheckDebugProviderFactoryTests * style * App Check test app debug provider fix (#747) * App Check: minor touchups (#750) * Update dummy token value * Print local debug token to logs * Require GoogleUtilities v7.2 and above * Print debug token on init * Don't print debug token again * App Check: use prod environment (#751) * App Check: use prod backend by default. * Update token expiration threshold * App Check SwiftPM support (#753) * AppCheck SwiftPM package definition * Promise header import fix * OCMock header fix * Fix fixture dependent tests * Exclude Keychain dependent tests * License * ./scripts/style.sh * Cleanup * Format with proper SwiftFormat version * `.process` resources. * Swift tests target * Cleanup and code formatting * App Check: token auto-refresh (#754) * FIRAppCheckTokenRefresher API defined * FIRAppCheckTokenRefresher implementation draft * [WIP] Token refresher integration * Token refresher integration * FIRAppCheckTests: token refresher tests * FIRAppCheckTests: additional tests cases * FIRAppCheckTimer introduced * FIRAppCheckTokenRefresher: use FIRAppCheckTimer instead of the dispatch timer. * FIRFakeTimer * FIRAppCheckTokenRefresherTests testInitialRefresh * FIRAppCheckTokenRefresherTests: testNextRefreshOnRefreshSuccess * ./scripts/style.sh * Exponential backoff * Style and comments * Move token refresh files to a separate folder * FIRAppCheckTimerTests * FIRAppCheck: use expicit class in init * FIRAppCheckDebugProviderFactory Swift name * FIRAppCheckTokenRefresher: Increment/decrement directly * App Check fixes (#755) * Fix backoff: no backoff for the initial request * Use eager initialization * FIRAppCheckTokenRefresher: don't refresh until handler set * FIRAppCheckIntegrationTests: disable token refresher * Fix testInitialRefresh test * style * FIRAppCheckIntegrationTests fix * Temporary exclude App Check from platfrom logging (#756) * App Check: send app check SDK version only in the header (#757) * App Check: store FAC token per app ID (#758) * App Check: store FAC token per app ID * update podspec * API docs * FIRAppCheck initWithApp tests * AppCheckCustomProvideApp (#760) * Functions: App Check integration (#762) * Functions: app check API added to FUNContextProvider * FUNContextProviderTests * FUNContextProvider app check support * ./scripts/style.sh * FIRFunctions: pass FAC token as HTTP header * Fix SPM * Fix Firebase-Package scheme bad merge * Cleanup * RTDB: pass FAC token to web socket (#763) * RTDB: pass FAC token to web socket * FIRAppCheckFake default init * Rename FAuthTokenProvider to FIRDatabaseConnectionContext; integrate with App Check * Pass App Check token in the HTTP header * Rename * Fix existing tests * TODO * ./scripts/style.sh * Context provider: assume separate FAC token change listener * FIRDatabaseConnectionContextProviderTests * Remove unused files * Copy NSMutableURLRequest * Cleanup * ./scripts/style.sh * FIRDatabaseConnectionContextProvider: sync callback when no auth or app check * Cleanup * Rename "authToken" leftovers to "context" * Fix renaming * Pass missing headers to NSURLSessionWebSocketTask * Cleanup * add a name to TODO * App Check: token update notifications (#764) * AppCheck: token did change API and tests * notification implementation and fixes * Run ./scripts/style.sh * Update comments * RTDB: send app check token updates to keep connection open (#765) * Pass AppCheck instance as an object into the the FAC token update notification * FIRDatabaseConnectionContext: add FAC token change listener API * formatting * Send FAC token updates to open connection * More informative empty response message * refreshAppCheckToken fixes * Remove assertion * Don't modify state * forceTokensRefresh -> forceTokenRefreshes * Call listeners on [FIRDatabaseQuery sharedQueue] * App Check API cleanup and docs (#766) * AppCheck public API and docs cleanup * More API docs * Fix compilation errors * typos and wording * Make summary different from description (pod lib lint warning) * port app check workflow changes from another branch * pod lib lint: remove --allow-warnings * App Check cleanup (#767) * Cleanup debug code and outdated TODOs * Fix FIRDeviceCheckProvider availablility for SPM * Fix availability in tests * Fix availability in tests * Make sure os requirements are consistent for tests specs * Migrate v1alpha URLs to v1beta * Migrate v1alpha URLs to v1beta * Run ./scripts/style.sh * Functions tests: fix Xcode 11 warnings (#7931) * Functions tests: fix Xcode 11 warnings * style * App Check: token auto-refresh opt-out API (#769) * FIRAppCheckSettings introduced (WIP) * FIRAppCheckSettingsTests * Style * Make FIRAppCheckSettings instance per-app. * FIRAppCheckTokenRefresher: use FIRAppCheckSettings.isTokenAutoRefreshEnabled (WIP) * Tests * Add public instance getters * Fix analyzer warnings * Fix testspec OS versions * FIRAppCheckTokenRefresher expiration date update; tests * FIRAppCheck.isTokenAutoRefreshEnabled implementation and tests * style * FIRAppCheck: Use specific types for variables in the default init * More precise comments * missing symbol * FIRAppCheckSettings: remove defensive conditions from init. Co-authored-by: Nick Cooke <nickcooke@google.com> Co-authored-by: Nick Cooke <36927374+ncooke3@users.noreply.github.com>
505 lines
17 KiB
Objective-C
505 lines
17 KiB
Objective-C
/*
|
|
* Copyright 2017 Google
|
|
*
|
|
* 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.
|
|
*/
|
|
|
|
// Targetted compilation is ONLY for testing. UIKit is weak-linked in actual
|
|
// release build.
|
|
|
|
#import <Foundation/Foundation.h>
|
|
|
|
#import "FirebaseCore/Sources/Private/FirebaseCoreInternal.h"
|
|
#import "FirebaseDatabase/Sources/Api/Private/FIRDatabase_Private.h"
|
|
#import "FirebaseDatabase/Sources/Constants/FConstants.h"
|
|
#import "FirebaseDatabase/Sources/Public/FirebaseDatabase/FIRDatabaseReference.h"
|
|
#import "FirebaseDatabase/Sources/Realtime/FWebSocketConnection.h"
|
|
#import "FirebaseDatabase/Sources/Utilities/FStringUtilities.h"
|
|
|
|
#if TARGET_OS_IOS || TARGET_OS_TV
|
|
#import <UIKit/UIKit.h>
|
|
#endif // TARGET_OS_IOS || TARGET_OS_TV
|
|
|
|
#if TARGET_OS_WATCH
|
|
#import <Network/Network.h>
|
|
#import <WatchKit/WatchKit.h>
|
|
#endif // TARGET_OS_WATCH
|
|
|
|
static NSString *const kAppCheckTokenHeader = @"X-Firebase-AppCheck";
|
|
static NSString *const kUserAgentHeader = @"User-Agent";
|
|
static NSString *const kGoogleAppIDHeader = @"X-Firebase-GMPID";
|
|
|
|
@interface FWebSocketConnection () {
|
|
NSMutableString *frame;
|
|
BOOL everConnected;
|
|
BOOL isClosed;
|
|
NSTimer *keepAlive;
|
|
}
|
|
|
|
- (void)shutdown;
|
|
- (void)onClosed;
|
|
- (void)closeIfNeverConnected;
|
|
|
|
#if TARGET_OS_WATCH
|
|
@property(nonatomic, strong) NSURLSessionWebSocketTask *webSocketTask;
|
|
#else
|
|
@property(nonatomic, strong) FSRWebSocket *webSocket;
|
|
#endif // TARGET_OS_WATCH
|
|
@property(nonatomic, strong) NSNumber *connectionId;
|
|
@property(nonatomic, readwrite) int totalFrames;
|
|
@property(nonatomic, readonly) BOOL buffering;
|
|
@property(nonatomic, readonly) NSString *userAgent;
|
|
@property(nonatomic) dispatch_queue_t dispatchQueue;
|
|
|
|
- (void)nop:(NSTimer *)timer;
|
|
|
|
@end
|
|
|
|
@implementation FWebSocketConnection
|
|
|
|
@synthesize delegate;
|
|
#if !TARGET_OS_WATCH
|
|
@synthesize webSocket;
|
|
#endif // !TARGET_OS_WATCH
|
|
@synthesize connectionId;
|
|
|
|
- (instancetype)initWith:(FRepoInfo *)repoInfo
|
|
andQueue:(dispatch_queue_t)queue
|
|
googleAppID:(NSString *)googleAppID
|
|
lastSessionID:(NSString *)lastSessionID
|
|
appCheckToken:(nullable NSString *)appCheckToken {
|
|
self = [super init];
|
|
if (self) {
|
|
everConnected = NO;
|
|
isClosed = NO;
|
|
self.connectionId = [FUtilities LUIDGenerator];
|
|
self.totalFrames = 0;
|
|
self.dispatchQueue = queue;
|
|
frame = nil;
|
|
|
|
NSString *userAgent = [self userAgent];
|
|
NSString *connectionURL =
|
|
[repoInfo connectionURLWithLastSessionID:lastSessionID];
|
|
|
|
FFLog(@"I-RDB083001", @"(wsc:%@) Connecting to: %@ as %@",
|
|
self.connectionId, connectionURL, userAgent);
|
|
|
|
NSURLRequest *req = [[self class] createRequestWithURL:connectionURL
|
|
userAgent:userAgent
|
|
googleAppID:googleAppID
|
|
appCheckToken:appCheckToken];
|
|
#if TARGET_OS_WATCH
|
|
// Regular NSURLSession websocket.
|
|
NSOperationQueue *opQueue = [[NSOperationQueue alloc] init];
|
|
opQueue.underlyingQueue = queue;
|
|
NSURLSession *session = [NSURLSession
|
|
sessionWithConfiguration:[NSURLSessionConfiguration
|
|
defaultSessionConfiguration]
|
|
delegate:self
|
|
delegateQueue:opQueue];
|
|
NSURLSessionWebSocketTask *task =
|
|
[session webSocketTaskWithRequest:req];
|
|
self.webSocketTask = task;
|
|
|
|
if (@available(watchOS 7.0, *)) {
|
|
[[NSNotificationCenter defaultCenter]
|
|
addObserverForName:WKApplicationWillResignActiveNotification
|
|
object:nil
|
|
queue:opQueue
|
|
usingBlock:^(NSNotification *_Nonnull note) {
|
|
FFLog(@"I-RDB083015",
|
|
@"Received watchOS background notification, "
|
|
@"closing web socket.");
|
|
[self onClosed];
|
|
}];
|
|
}
|
|
#else
|
|
// TODO(mmaksym): Remove googleAppID and userAgent from FSRWebSocket as
|
|
// they are passed via NSURLRequest.
|
|
self.webSocket = [[FSRWebSocket alloc] initWithURLRequest:req
|
|
queue:queue
|
|
googleAppID:googleAppID
|
|
andUserAgent:userAgent];
|
|
[self.webSocket setDelegateDispatchQueue:queue];
|
|
self.webSocket.delegate = self;
|
|
#endif // TARGET_OS_WATCH
|
|
}
|
|
return self;
|
|
}
|
|
|
|
- (NSString *)userAgent {
|
|
NSString *systemVersion;
|
|
NSString *deviceName;
|
|
BOOL hasUiDeviceClass = NO;
|
|
|
|
// Targetted compilation is ONLY for testing. UIKit is weak-linked in actual
|
|
// release build.
|
|
#if TARGET_OS_IOS || TARGET_OS_TV
|
|
Class uiDeviceClass = NSClassFromString(@"UIDevice");
|
|
if (uiDeviceClass) {
|
|
systemVersion = [uiDeviceClass currentDevice].systemVersion;
|
|
deviceName = [uiDeviceClass currentDevice].model;
|
|
hasUiDeviceClass = YES;
|
|
}
|
|
#endif // TARGET_OS_IOS || TARGET_OS_TV
|
|
|
|
if (!hasUiDeviceClass) {
|
|
NSDictionary *systemVersionDictionary = [NSDictionary
|
|
dictionaryWithContentsOfFile:
|
|
@"/System/Library/CoreServices/SystemVersion.plist"];
|
|
systemVersion =
|
|
[systemVersionDictionary objectForKey:@"ProductVersion"];
|
|
deviceName = [systemVersionDictionary objectForKey:@"ProductName"];
|
|
}
|
|
|
|
NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
|
|
|
|
// Sanitize '/'s in deviceName and bundleIdentifier for stats
|
|
deviceName = [FStringUtilities sanitizedForUserAgent:deviceName];
|
|
bundleIdentifier =
|
|
[FStringUtilities sanitizedForUserAgent:bundleIdentifier];
|
|
|
|
// Firebase/5/<semver>_<build date>_<git hash>/<os version>/{device model /
|
|
// os (Mac OS X, iPhone, etc.}_<bundle id>
|
|
NSString *ua = [NSString
|
|
stringWithFormat:@"Firebase/%@/%@/%@/%@_%@", kWebsocketProtocolVersion,
|
|
[FIRDatabase buildVersion], systemVersion, deviceName,
|
|
bundleIdentifier];
|
|
return ua;
|
|
}
|
|
|
|
- (BOOL)buffering {
|
|
return frame != nil;
|
|
}
|
|
|
|
#pragma mark -
|
|
#pragma mark Public FWebSocketConnection methods
|
|
|
|
- (void)open {
|
|
FFLog(@"I-RDB083002", @"(wsc:%@) FWebSocketConnection open.",
|
|
self.connectionId);
|
|
assert(delegate);
|
|
everConnected = NO;
|
|
// TODO Assert url
|
|
#if TARGET_OS_WATCH
|
|
[self.webSocketTask resume];
|
|
// We need to request data from the web socket in order for it to start
|
|
// sending data.
|
|
[self receiveWebSocketData];
|
|
#else
|
|
[self.webSocket open];
|
|
#endif // TARGET_OS_WATCH
|
|
dispatch_time_t when = dispatch_time(
|
|
DISPATCH_TIME_NOW, kWebsocketConnectTimeout * NSEC_PER_SEC);
|
|
dispatch_after(when, self.dispatchQueue, ^{
|
|
[self closeIfNeverConnected];
|
|
});
|
|
}
|
|
|
|
- (void)close {
|
|
FFLog(@"I-RDB083003", @"(wsc:%@) FWebSocketConnection is being closed.",
|
|
self.connectionId);
|
|
isClosed = YES;
|
|
#if TARGET_OS_WATCH
|
|
[self.webSocketTask
|
|
cancelWithCloseCode:NSURLSessionWebSocketCloseCodeNormalClosure
|
|
reason:nil];
|
|
#else
|
|
[self.webSocket close];
|
|
#endif // TARGET_OS_WATCH
|
|
}
|
|
|
|
- (void)start {
|
|
// Start is a no-op for websockets.
|
|
}
|
|
|
|
- (void)send:(NSDictionary *)dictionary {
|
|
|
|
[self resetKeepAlive];
|
|
|
|
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary
|
|
options:kNilOptions
|
|
error:nil];
|
|
|
|
NSString *data = [[NSString alloc] initWithData:jsonData
|
|
encoding:NSUTF8StringEncoding];
|
|
|
|
NSArray *dataSegs = [FUtilities splitString:data
|
|
intoMaxSize:kWebsocketMaxFrameSize];
|
|
|
|
// First send the header so the server knows how many segments are
|
|
// forthcoming
|
|
if (dataSegs.count > 1) {
|
|
NSString *formattedData =
|
|
[NSString stringWithFormat:@"%u", (unsigned int)dataSegs.count];
|
|
[self sendStringToWebSocket:formattedData];
|
|
}
|
|
|
|
// Then, actually send the segments.
|
|
for (NSString *segment in dataSegs) {
|
|
[self sendStringToWebSocket:segment];
|
|
}
|
|
}
|
|
|
|
- (void)nop:(NSTimer *)timer {
|
|
if (!isClosed) {
|
|
FFLog(@"I-RDB083004", @"(wsc:%@) nop", self.connectionId);
|
|
// Note: the backend is expecting a string "0" here, not any special
|
|
// ping/pong from build in websocket APIs.
|
|
[self sendStringToWebSocket:@"0"];
|
|
} else {
|
|
FFLog(@"I-RDB083005",
|
|
@"(wsc:%@) No more websocket; invalidating nop timer.",
|
|
self.connectionId);
|
|
[timer invalidate];
|
|
}
|
|
}
|
|
|
|
- (void)handleNewFrameCount:(int)numFrames {
|
|
self.totalFrames = numFrames;
|
|
frame = [[NSMutableString alloc] initWithString:@""];
|
|
FFLog(@"I-RDB083006", @"(wsc:%@) handleNewFrameCount: %d",
|
|
self.connectionId, self.totalFrames);
|
|
}
|
|
|
|
- (NSString *)extractFrameCount:(NSString *)message {
|
|
if ([message length] <= 4) {
|
|
int frameCount = [message intValue];
|
|
if (frameCount > 0) {
|
|
[self handleNewFrameCount:frameCount];
|
|
return nil;
|
|
}
|
|
}
|
|
[self handleNewFrameCount:1];
|
|
return message;
|
|
}
|
|
|
|
- (void)appendFrame:(NSString *)message {
|
|
[frame appendString:message];
|
|
self.totalFrames = self.totalFrames - 1;
|
|
|
|
if (self.totalFrames == 0) {
|
|
// Call delegate and pass an immutable version of the frame
|
|
NSDictionary *json = [NSJSONSerialization
|
|
JSONObjectWithData:[frame dataUsingEncoding:NSUTF8StringEncoding]
|
|
options:kNilOptions
|
|
error:nil];
|
|
frame = nil;
|
|
FFLog(@"I-RDB083007",
|
|
@"(wsc:%@) handleIncomingFrame sending complete frame: %d",
|
|
self.connectionId, self.totalFrames);
|
|
|
|
@autoreleasepool {
|
|
[self.delegate onMessage:self withMessage:json];
|
|
}
|
|
}
|
|
}
|
|
|
|
- (void)handleIncomingFrame:(NSString *)message {
|
|
[self resetKeepAlive];
|
|
if (self.buffering) {
|
|
[self appendFrame:message];
|
|
} else {
|
|
NSString *remaining = [self extractFrameCount:message];
|
|
if (remaining) {
|
|
[self appendFrame:remaining];
|
|
}
|
|
}
|
|
}
|
|
|
|
#pragma mark -
|
|
#pragma mark URLSessionWebSocketDelegate watchOS implementation
|
|
#if TARGET_OS_WATCH
|
|
|
|
- (void)URLSession:(NSURLSession *)session
|
|
webSocketTask:(NSURLSessionWebSocketTask *)webSocketTask
|
|
didOpenWithProtocol:(NSString *)protocol {
|
|
[self webSocketDidOpen];
|
|
}
|
|
|
|
- (void)URLSession:(NSURLSession *)session
|
|
webSocketTask:(NSURLSessionWebSocketTask *)webSocketTask
|
|
didCloseWithCode:(NSURLSessionWebSocketCloseCode)closeCode
|
|
reason:(NSData *)reason {
|
|
FFLog(@"I-RDB083011", @"(wsc:%@) didCloseWithCode: %ld %@",
|
|
self.connectionId, (long)closeCode, reason);
|
|
[self onClosed];
|
|
}
|
|
|
|
- (void)receiveWebSocketData {
|
|
__weak __auto_type weakSelf = self;
|
|
[self.webSocketTask receiveMessageWithCompletionHandler:^(
|
|
NSURLSessionWebSocketMessage *_Nullable message,
|
|
NSError *_Nullable error) {
|
|
__auto_type strongSelf = weakSelf;
|
|
if (strongSelf == nil) {
|
|
return;
|
|
}
|
|
|
|
if (message) {
|
|
[strongSelf handleIncomingFrame:message.string];
|
|
} else if (error && !strongSelf->isClosed) {
|
|
FFWarn(@"I-RDB083020",
|
|
@"Error received from web socket, closing the connection. %@",
|
|
error);
|
|
[strongSelf shutdown];
|
|
return;
|
|
}
|
|
|
|
[strongSelf receiveWebSocketData];
|
|
}];
|
|
}
|
|
|
|
#else
|
|
|
|
#pragma mark SRWebSocketDelegate implementation
|
|
|
|
- (void)webSocket:(FSRWebSocket *)webSocket didReceiveMessage:(id)message {
|
|
[self handleIncomingFrame:message];
|
|
}
|
|
|
|
- (void)webSocket:(FSRWebSocket *)webSocket didFailWithError:(NSError *)error {
|
|
FFLog(@"I-RDB083010", @"(wsc:%@) didFailWithError didFailWithError: %@",
|
|
self.connectionId, [error description]);
|
|
[self onClosed];
|
|
}
|
|
|
|
- (void)webSocket:(FSRWebSocket *)webSocket
|
|
didCloseWithCode:(NSInteger)code
|
|
reason:(NSString *)reason
|
|
wasClean:(BOOL)wasClean {
|
|
FFLog(@"I-RDB083011", @"(wsc:%@) didCloseWithCode: %ld %@",
|
|
self.connectionId, (long)code, reason);
|
|
[self onClosed];
|
|
}
|
|
|
|
#endif // TARGET_OS_WATCH
|
|
|
|
// Common to both SRWebSocketDelegate and URLSessionWebSocketDelegate.
|
|
|
|
- (void)webSocketDidOpen {
|
|
FFLog(@"I-RDB083008", @"(wsc:%@) webSocketDidOpen", self.connectionId);
|
|
|
|
everConnected = YES;
|
|
|
|
dispatch_async(dispatch_get_main_queue(), ^{
|
|
self->keepAlive =
|
|
[NSTimer scheduledTimerWithTimeInterval:kWebsocketKeepaliveInterval
|
|
target:self
|
|
selector:@selector(nop:)
|
|
userInfo:nil
|
|
repeats:YES];
|
|
FFLog(@"I-RDB083009", @"(wsc:%@) nop timer kicked off",
|
|
self.connectionId);
|
|
});
|
|
}
|
|
|
|
#pragma mark -
|
|
#pragma mark Private methods
|
|
|
|
/** Sends a string through the open web socket. */
|
|
- (void)sendStringToWebSocket:(NSString *)string {
|
|
#if TARGET_OS_WATCH
|
|
// Use built-in URLSessionWebSocket functionality.
|
|
[self.webSocketTask sendMessage:[[NSURLSessionWebSocketMessage alloc]
|
|
initWithString:string]
|
|
completionHandler:^(NSError *_Nullable error) {
|
|
if (error) {
|
|
FFWarn(@"I-RDB083016",
|
|
@"Error sending web socket data: %@.", error);
|
|
return;
|
|
}
|
|
}];
|
|
#else
|
|
// Use existing SocketRocket implementation.
|
|
[self.webSocket send:string];
|
|
#endif // TARGET_OS_WATCH
|
|
}
|
|
|
|
/**
|
|
* Note that the close / onClosed / shutdown cycle here is a little different
|
|
* from the javascript client. In order to properly handle deallocation, no
|
|
* close-related action is taken at a higher level until we have received
|
|
* notification from the websocket itself that it is closed. Otherwise, we end
|
|
* up deallocating this class and the FConnection class before the websocket has
|
|
* a change to call some of its delegate methods. So, since close is the
|
|
* external close handler, we just set a flag saying not to call our own
|
|
* delegate method and close the websocket. That will trigger a callback into
|
|
* this class that can then do things like clean up the keepalive timer.
|
|
*/
|
|
|
|
- (void)closeIfNeverConnected {
|
|
if (!everConnected) {
|
|
FFLog(@"I-RDB083012", @"(wsc:%@) Websocket timed out on connect",
|
|
self.connectionId);
|
|
#if TARGET_OS_WATCH
|
|
[self.webSocketTask
|
|
cancelWithCloseCode:NSURLSessionWebSocketCloseCodeNoStatusReceived
|
|
reason:nil];
|
|
#else
|
|
[self.webSocket close];
|
|
#endif // TARGET_OS_WATCH
|
|
}
|
|
}
|
|
|
|
- (void)shutdown {
|
|
isClosed = YES;
|
|
|
|
// Call delegate methods
|
|
[self.delegate onDisconnect:self wasEverConnected:everConnected];
|
|
}
|
|
|
|
- (void)onClosed {
|
|
if (!isClosed) {
|
|
FFLog(@"I-RDB083013", @"Websocket is closing itself");
|
|
[self shutdown];
|
|
}
|
|
#if TARGET_OS_WATCH
|
|
self.webSocketTask = nil;
|
|
#else
|
|
self.webSocket = nil;
|
|
#endif // TARGET_OS_WATCH
|
|
if (keepAlive.isValid) {
|
|
[keepAlive invalidate];
|
|
}
|
|
}
|
|
|
|
- (void)resetKeepAlive {
|
|
NSDate *newTime =
|
|
[NSDate dateWithTimeIntervalSinceNow:kWebsocketKeepaliveInterval];
|
|
// Calling setFireDate is actually kinda' expensive, so wait at least 5
|
|
// seconds before updating it.
|
|
if ([newTime timeIntervalSinceDate:keepAlive.fireDate] > 5) {
|
|
FFLog(@"I-RDB083014", @"(wsc:%@) resetting keepalive, to %@ ; old: %@",
|
|
self.connectionId, newTime, [keepAlive fireDate]);
|
|
[keepAlive setFireDate:newTime];
|
|
}
|
|
}
|
|
|
|
+ (NSURLRequest *)createRequestWithURL:(NSString *)connectionURL
|
|
userAgent:(NSString *)userAgent
|
|
googleAppID:(NSString *)googleAppID
|
|
appCheckToken:(nullable NSString *)appCheckToken {
|
|
|
|
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
|
|
initWithURL:[[NSURL alloc] initWithString:connectionURL]];
|
|
|
|
[request setValue:appCheckToken forHTTPHeaderField:kAppCheckTokenHeader];
|
|
[request setValue:userAgent forHTTPHeaderField:kUserAgentHeader];
|
|
[request setValue:googleAppID forHTTPHeaderField:kGoogleAppIDHeader];
|
|
|
|
return [request copy];
|
|
}
|
|
|
|
@end
|