|
| 1 | +/** |
| 2 | + * Copyright 2017 Beijing DiDi Infinity Technology and Development Co., Ltd. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +#import "DKMultiControlProtocol.h" |
| 18 | +#import <DoraemonKit/DKMultiControlStreamManager.h> |
| 19 | + |
| 20 | +NS_ASSUME_NONNULL_BEGIN |
| 21 | + |
| 22 | +static NSString *const ERROR_DOMAIN = @"com.didi.dokit"; |
| 23 | + |
| 24 | +static NSString *const MULTI_CONTROL_PROTOCOL_KEY = @"MULTI_CONTROL_PROTOCOL_KEY"; |
| 25 | + |
| 26 | +@interface DKMultiControlProtocol () <NSURLSessionDataDelegate> |
| 27 | + |
| 28 | +@property(nonatomic, nullable, weak) NSURLSession *urlSession; |
| 29 | + |
| 30 | +@property(nonatomic, nullable, copy) NSString *dataId; |
| 31 | + |
| 32 | +@property(nonatomic, nullable, copy) NSHTTPURLResponse *httpUrlResponse; |
| 33 | + |
| 34 | +@property(nonatomic, nullable, copy) NSString *responseBody; |
| 35 | + |
| 36 | +@end |
| 37 | + |
| 38 | +NS_ASSUME_NONNULL_END |
| 39 | + |
| 40 | +@implementation DKMultiControlProtocol |
| 41 | + |
| 42 | ++ (BOOL)canInitWithRequest:(NSURLRequest *)request { |
| 43 | + // +[NSURLProtocol canInitWithRequest:] may be called from any thread. |
| 44 | + BOOL returnValue = NO; |
| 45 | + switch (DKMultiControlStreamManager.sharedInstance.state) { |
| 46 | + case DKMultiControlStreamManagerStateMaster: |
| 47 | + if (![NSURLProtocol propertyForKey:MULTI_CONTROL_PROTOCOL_KEY inRequest:request]) { |
| 48 | + NSString *contentType = [request valueForHTTPHeaderField:@"Content-Type"]; |
| 49 | + NSString *accept = [request valueForHTTPHeaderField:@"Accept"]; |
| 50 | + if (![contentType hasPrefix:@"multipart/form-data"] && ![accept hasPrefix:@"image/"]) { |
| 51 | + returnValue = YES; |
| 52 | + } |
| 53 | + } |
| 54 | + break; |
| 55 | + case DKMultiControlStreamManagerStateSlave: |
| 56 | + returnValue = YES; |
| 57 | + break; |
| 58 | + |
| 59 | + default: |
| 60 | + break; |
| 61 | + } |
| 62 | + |
| 63 | + return returnValue; |
| 64 | +} |
| 65 | + |
| 66 | ++ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request { |
| 67 | + // +[NSURLProtocol canonicalRequestForRequest:] may be called from any thread. |
| 68 | + NSURLRequest *result = request; |
| 69 | + switch (DKMultiControlStreamManager.sharedInstance.state) { |
| 70 | + case DKMultiControlStreamManagerStateMaster: { |
| 71 | + NSMutableURLRequest *mutableUrlRequest = result.mutableCopy; |
| 72 | + [NSURLProtocol setProperty:@(YES) forKey:MULTI_CONTROL_PROTOCOL_KEY inRequest:mutableUrlRequest]; |
| 73 | + result = mutableUrlRequest.copy; |
| 74 | + } |
| 75 | + break; |
| 76 | + |
| 77 | + default: |
| 78 | + break; |
| 79 | + } |
| 80 | + |
| 81 | + return result; |
| 82 | +} |
| 83 | + |
| 84 | +- (void)startLoading { |
| 85 | + NSOperationQueue *clientOperationQueue = [[NSOperationQueue alloc] init]; |
| 86 | + clientOperationQueue.maxConcurrentOperationCount = 1; |
| 87 | + if ([NSURLProtocol propertyForKey:MULTI_CONTROL_PROTOCOL_KEY inRequest:self.request]) { |
| 88 | + self.urlSession = [NSURLSession sessionWithConfiguration:NSURLSessionConfiguration.defaultSessionConfiguration delegate:self delegateQueue:clientOperationQueue]; |
| 89 | + [[self.urlSession dataTaskWithRequest:self.request] resume]; |
| 90 | + dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); |
| 91 | + dispatch_async(dispatch_get_main_queue(), ^{ |
| 92 | + self.dataId = [DKMultiControlStreamManager.sharedInstance recordWithUrlRequest:self.request]; |
| 93 | + dispatch_semaphore_signal(semaphore); |
| 94 | + }); |
| 95 | + dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); |
| 96 | + } else { |
| 97 | + // Slave device send request through websocket. |
| 98 | + NSURLRequest *urlRequest = self.request.copy; |
| 99 | + __weak typeof(self) weakSelf = self; |
| 100 | + dispatch_async(dispatch_get_main_queue(), ^{ |
| 101 | + [DKMultiControlStreamManager.sharedInstance queryWithUrlRequest:urlRequest completionBlock:^(NSError *error, NSHTTPURLResponse *response, NSData *data) { |
| 102 | + // Main thread. |
| 103 | + [clientOperationQueue addOperationWithBlock:^{ |
| 104 | + typeof(weakSelf) self = weakSelf; |
| 105 | + if (error || !response) { |
| 106 | + [self.client URLProtocol:self didFailWithError:error ?: [NSError errorWithDomain:ERROR_DOMAIN code:0 userInfo:nil]]; |
| 107 | + |
| 108 | + return; |
| 109 | + } |
| 110 | + [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageAllowed]; |
| 111 | + if (data) { |
| 112 | + [self.client URLProtocol:self didLoadData:data]; |
| 113 | + } |
| 114 | + [self.client URLProtocolDidFinishLoading:self]; |
| 115 | + }]; |
| 116 | + }]; |
| 117 | + }); |
| 118 | + } |
| 119 | +} |
| 120 | + |
| 121 | +- (void)stopLoading { |
| 122 | + [self.urlSession invalidateAndCancel]; |
| 123 | +} |
| 124 | + |
| 125 | +- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler { |
| 126 | + [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageAllowed]; |
| 127 | + completionHandler(NSURLSessionResponseAllow); |
| 128 | + if ([response isKindOfClass:NSHTTPURLResponse.class]) { |
| 129 | + self.httpUrlResponse = (NSHTTPURLResponse *) response; |
| 130 | + } |
| 131 | +} |
| 132 | + |
| 133 | +- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data { |
| 134 | + [self.client URLProtocol:self didLoadData:data]; |
| 135 | + // TODO(ChasonTang): Append data to `self.responseData`. |
| 136 | + self.responseBody = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; |
| 137 | +} |
| 138 | + |
| 139 | +- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler { |
| 140 | + if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) { |
| 141 | + NSURLCredential *urlCredential = challenge.protectionSpace.serverTrust ? [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] : nil; |
| 142 | + completionHandler(NSURLSessionAuthChallengeUseCredential, urlCredential); |
| 143 | + } else { |
| 144 | + completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil); |
| 145 | + } |
| 146 | +} |
| 147 | + |
| 148 | +- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { |
| 149 | + if (!error) { |
| 150 | + [self.client URLProtocolDidFinishLoading:self]; |
| 151 | + if (self.httpUrlResponse && self.dataId) { |
| 152 | + NSHTTPURLResponse *httpUrlResponse = self.httpUrlResponse.copy; |
| 153 | + NSString *dataId = self.dataId.copy; |
| 154 | + NSString *responseBody = self.responseBody.copy; |
| 155 | + dispatch_async(dispatch_get_main_queue(), ^{ |
| 156 | + [DKMultiControlStreamManager.sharedInstance recordWithHTTPUrlResponse:httpUrlResponse dataId:dataId responseBody:responseBody]; |
| 157 | + }); |
| 158 | + } |
| 159 | + } else { |
| 160 | + [self.client URLProtocol:self didFailWithError:error]; |
| 161 | + } |
| 162 | +} |
| 163 | + |
| 164 | +@end |
0 commit comments