ServerAPIRequest.m 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. // _____ _
  2. // |_ _| |_ _ _ ___ ___ _ __ __ _
  3. // | | | ' \| '_/ -_) -_) ' \/ _` |_
  4. // |_| |_||_|_| \___\___|_|_|_\__,_(_)
  5. //
  6. // Threema iOS Client
  7. // Copyright (c) 2012-2020 Threema GmbH
  8. //
  9. // This program is free software: you can redistribute it and/or modify
  10. // it under the terms of the GNU Affero General Public License, version 3,
  11. // as published by the Free Software Foundation.
  12. //
  13. // This program is distributed in the hope that it will be useful,
  14. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. // GNU Affero General Public License for more details.
  17. //
  18. // You should have received a copy of the GNU Affero General Public License
  19. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  20. #import "ServerAPIRequest.h"
  21. #import "ActivityIndicatorProxy.h"
  22. #import "SSLCAHelper.h"
  23. #import "UserSettings.h"
  24. #import "ThreemaError.h"
  25. #import "BundleUtil.h"
  26. #import "LicenseStore.h"
  27. #ifdef DEBUG
  28. static const DDLogLevel ddLogLevel = DDLogLevelVerbose;
  29. #else
  30. static const DDLogLevel ddLogLevel = DDLogLevelWarning;
  31. #endif
  32. #define REQUEST_TIMEOUT 30.0
  33. @implementation ServerAPIRequest
  34. @synthesize onCompletion, onError;
  35. + (void)loadJSONFromAPIPath:(NSString*)apiPath withCachePolicy:(NSURLRequestCachePolicy)cachePolicy onCompletion:(CompletionCallback)onCompletion onError:(ErrorCallback)onError {
  36. [ServerAPIRequest loadJSONFromAPIPath:apiPath apiUrl:[ServerAPIRequest apiUrl] getParams:nil withCachePolicy:cachePolicy onCompletion:onCompletion onError:onError];
  37. }
  38. + (void)loadJSONFromWorkAPIPath:(NSString*)apiPath getParams:(NSString*)getParams withCachePolicy:(NSURLRequestCachePolicy)cachePolicy onCompletion:(CompletionCallback)onCompletion onError:(ErrorCallback)onError {
  39. [ServerAPIRequest loadJSONFromAPIPath:apiPath apiUrl:[ServerAPIRequest workApiUrl] getParams:getParams withCachePolicy:cachePolicy onCompletion:onCompletion onError:onError];
  40. }
  41. + (void)loadJSONFromAPIPath:(NSString*)apiPath apiUrl:(NSURL*)apiUrl getParams:(NSString*)getParams withCachePolicy:(NSURLRequestCachePolicy)cachePolicy onCompletion:(CompletionCallback)onCompletion onError:(ErrorCallback)onError {
  42. ServerAPIRequest *loader = [[ServerAPIRequest alloc] init];
  43. loader.onCompletion = onCompletion;
  44. loader.onError = onError;
  45. NSURL *url = [apiUrl URLByAppendingPathComponent:apiPath];
  46. if (getParams != nil) {
  47. url = [NSURL URLWithString:getParams relativeToURL:url];
  48. }
  49. [ActivityIndicatorProxy startActivity];
  50. NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:cachePolicy timeoutInterval:REQUEST_TIMEOUT];
  51. NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:loader delegateQueue:[NSOperationQueue currentQueue]];
  52. NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
  53. [self connectionCompletionHandler:data response:response error:error onCompletion:onCompletion onError:onError];
  54. }];
  55. [task resume];
  56. }
  57. + (void)postJSONToAPIPath:(NSString*)apiPath data:(id)jsonObject onCompletion:(CompletionCallback)onCompletion onError:(ErrorCallback)onError {
  58. [ServerAPIRequest postJSONToAPIPath:apiPath apiUrl:[ServerAPIRequest apiUrl] data:jsonObject onCompletion:onCompletion onError:onError];
  59. }
  60. + (void)postJSONToWorkAPIPath:(NSString*)apiPath data:(id)jsonObject onCompletion:(CompletionCallback)onCompletion onError:(ErrorCallback)onError {
  61. [ServerAPIRequest postJSONToAPIPath:apiPath apiUrl:[ServerAPIRequest workApiUrl] data:jsonObject onCompletion:onCompletion onError:onError];
  62. }
  63. + (void)postJSONToAPIPath:(NSString*)apiPath apiUrl:(NSURL*)apiUrl data:(id)jsonObject onCompletion:(CompletionCallback)onCompletion onError:(ErrorCallback)onError {
  64. ServerAPIRequest *loader = [[ServerAPIRequest alloc] init];
  65. loader.onCompletion = onCompletion;
  66. loader.onError = onError;
  67. NSURL *url = [apiUrl URLByAppendingPathComponent:apiPath];
  68. NSError *jsonError;
  69. NSData *jsonRequest = [NSJSONSerialization dataWithJSONObject:jsonObject options:0 error:&jsonError];
  70. if (jsonRequest == nil) {
  71. DDLogError(@"Could not generate JSON data: %@", jsonError);
  72. onError(jsonError);
  73. return;
  74. }
  75. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
  76. timeoutInterval:REQUEST_TIMEOUT];
  77. [request setHTTPMethod:@"POST"];
  78. [request addValue:[NSLocale currentLocale].languageCode forHTTPHeaderField:@"Accept-Language"];
  79. [request setHTTPBody:jsonRequest];
  80. DDLogVerbose(@"post JSON to %@: %@", url, jsonObject);
  81. [ActivityIndicatorProxy startActivity];
  82. NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:loader delegateQueue:[NSOperationQueue currentQueue]];
  83. NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
  84. [self connectionCompletionHandler:data response:response error:error onCompletion:onCompletion onError:onError];
  85. }];
  86. [task resume];
  87. }
  88. + (void)connectionCompletionHandler:(NSData* _Nullable)data response:(NSURLResponse* _Nullable)response error:(NSError* _Nullable)error onCompletion:(CompletionCallback)onCompletion onError:(ErrorCallback)onError {
  89. DDLogVerbose(@"JSON load succeeded - received %lu bytes", (unsigned long)[data length]);
  90. [ActivityIndicatorProxy stopActivity];
  91. // Check for client-side error (e.g. no connection to server)
  92. if (error != nil) {
  93. onError(error);
  94. return;
  95. }
  96. // Check for erroneous HTTP status code (NSURLSession does not report server-side errors in error object!)
  97. if (((NSHTTPURLResponse*)response).statusCode >= 400) {
  98. NSError *httpError = [NSError errorWithDomain:NSURLErrorDomain code:((NSHTTPURLResponse*)response).statusCode userInfo:nil];
  99. onError(httpError);
  100. return;
  101. }
  102. id jsonResult = nil;
  103. NSError *jsonError;
  104. if (data != nil) {
  105. jsonResult = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
  106. }
  107. if (jsonResult == nil) {
  108. DDLogError(@"Could not parse JSON data: %@", jsonError);
  109. onError(jsonError);
  110. return;
  111. }
  112. /* Check for "error" key in dictionary - if so, don't call onCompletion */
  113. if ([jsonResult isKindOfClass:[NSDictionary class]]) {
  114. NSDictionary *jsonDict = (NSDictionary*)jsonResult;
  115. NSString *errorStr = [jsonDict objectForKey:@"error"];
  116. if (errorStr != nil) {
  117. onError([ThreemaError threemaError:errorStr]);
  118. return;
  119. }
  120. }
  121. onCompletion(jsonResult);
  122. }
  123. + (NSURL*)apiUrl {
  124. if ([LicenseStore requiresLicenseKey]) {
  125. if ([UserSettings sharedUserSettings].enableIPv6)
  126. return [NSURL URLWithString:[BundleUtil objectForInfoDictionaryKey:@"ThreemaAPIURLv6Work"]];
  127. else
  128. return [NSURL URLWithString:[BundleUtil objectForInfoDictionaryKey:@"ThreemaAPIURLWork"]];
  129. } else {
  130. if ([UserSettings sharedUserSettings].enableIPv6)
  131. return [NSURL URLWithString:[BundleUtil objectForInfoDictionaryKey:@"ThreemaAPIURLv6"]];
  132. else
  133. return [NSURL URLWithString:[BundleUtil objectForInfoDictionaryKey:@"ThreemaAPIURL"]];
  134. }
  135. }
  136. + (NSURL*)workApiUrl {
  137. if ([UserSettings sharedUserSettings].enableIPv6) {
  138. return [NSURL URLWithString:[BundleUtil objectForInfoDictionaryKey:@"ThreemaWorkAPIURLv6"]];
  139. } else {
  140. return [NSURL URLWithString:[BundleUtil objectForInfoDictionaryKey:@"ThreemaWorkAPIURL"]];
  141. }
  142. }
  143. - (id)init
  144. {
  145. self = [super init];
  146. return self;
  147. }
  148. - (void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(nullable NSError *)error
  149. {
  150. if (error != nil) {
  151. DDLogError(@"Connection failed - error %@ %@",
  152. [error localizedDescription],
  153. [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
  154. [ActivityIndicatorProxy stopActivity];
  155. if (onError != nil)
  156. onError(error);
  157. }
  158. }
  159. - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler
  160. {
  161. [SSLCAHelper session:session didReceiveAuthenticationChallenge:challenge completion:completionHandler];
  162. }
  163. @end