OCNetworking.m 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820
  1. //
  2. // OCnetworking.m
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 10/05/15.
  6. // Copyright (c) 2017 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "OCNetworking.h"
  24. #import "CCUtility.h"
  25. #import "CCGraphics.h"
  26. #import "NSString+Encode.h"
  27. #import "NCBridgeSwift.h"
  28. #import "NCXMLGetAppPasswordParser.h"
  29. @implementation OCNetworking
  30. + (OCNetworking *)sharedManager {
  31. static OCNetworking *sharedManager;
  32. @synchronized(self)
  33. {
  34. if (!sharedManager) {
  35. sharedManager = [OCNetworking new];
  36. sharedManager.checkRemoteUserInProgress = false;
  37. }
  38. return sharedManager;
  39. }
  40. }
  41. - (id)init
  42. {
  43. self = [super init];
  44. [self sharedOCCommunication];
  45. return self;
  46. }
  47. #pragma --------------------------------------------------------------------------------------------
  48. #pragma mark ===== OCCommunication =====
  49. #pragma --------------------------------------------------------------------------------------------
  50. - (OCCommunication *)sharedOCCommunication
  51. {
  52. static OCCommunication* sharedOCCommunication = nil;
  53. if (sharedOCCommunication == nil)
  54. {
  55. // Network
  56. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  57. configuration.allowsCellularAccess = YES;
  58. configuration.discretionary = NO;
  59. configuration.HTTPMaximumConnectionsPerHost = k_maxConcurrentOperation;
  60. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  61. OCURLSessionManager *networkSessionManager = [[OCURLSessionManager alloc] initWithSessionConfiguration:configuration];
  62. [networkSessionManager.operationQueue setMaxConcurrentOperationCount: k_maxConcurrentOperation];
  63. networkSessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
  64. // Download
  65. NSURLSessionConfiguration *configurationDownload = [NSURLSessionConfiguration defaultSessionConfiguration];
  66. configurationDownload.allowsCellularAccess = YES;
  67. configurationDownload.discretionary = NO;
  68. configurationDownload.HTTPMaximumConnectionsPerHost = k_maxHTTPConnectionsPerHost;
  69. configurationDownload.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  70. configurationDownload.timeoutIntervalForRequest = k_timeout_upload;
  71. OCURLSessionManager *downloadSessionManager = [[OCURLSessionManager alloc] initWithSessionConfiguration:configurationDownload];
  72. [downloadSessionManager.operationQueue setMaxConcurrentOperationCount:k_maxHTTPConnectionsPerHost];
  73. [downloadSessionManager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition (NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential) {
  74. return NSURLSessionAuthChallengePerformDefaultHandling;
  75. }];
  76. // Upload
  77. NSURLSessionConfiguration *configurationUpload = [NSURLSessionConfiguration defaultSessionConfiguration];
  78. configurationUpload.allowsCellularAccess = YES;
  79. configurationUpload.discretionary = NO;
  80. configurationUpload.HTTPMaximumConnectionsPerHost = k_maxHTTPConnectionsPerHost;
  81. configurationUpload.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  82. configurationUpload.timeoutIntervalForRequest = k_timeout_upload;
  83. OCURLSessionManager *uploadSessionManager = [[OCURLSessionManager alloc] initWithSessionConfiguration:configurationUpload];
  84. [uploadSessionManager.operationQueue setMaxConcurrentOperationCount:k_maxHTTPConnectionsPerHost];
  85. [uploadSessionManager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition (NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential) {
  86. return NSURLSessionAuthChallengePerformDefaultHandling;
  87. }];
  88. sharedOCCommunication = [[OCCommunication alloc] initWithUploadSessionManager:uploadSessionManager andDownloadSessionManager:downloadSessionManager andNetworkSessionManager:networkSessionManager];
  89. }
  90. return sharedOCCommunication;
  91. }
  92. #pragma --------------------------------------------------------------------------------------------
  93. #pragma mark ===== Share =====
  94. #pragma --------------------------------------------------------------------------------------------
  95. - (void)readShareWithAccount:(NSString *)account completion:(void (^)(NSString *account, NSArray *items, NSString *message, NSInteger errorCode))completion
  96. {
  97. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  98. if (tableAccount == nil) {
  99. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  100. } else if ([CCUtility getPassword:account].length == 0) {
  101. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  102. } else if ([CCUtility getCertificateError:account]) {
  103. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  104. }
  105. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  106. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  107. [communication setUserAgent:[CCUtility getUserAgent]];
  108. [communication readSharedByServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  109. completion(account, items, nil, 0);
  110. } failureRequest :^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  111. NSString *message;
  112. NSInteger errorCode = response.statusCode;
  113. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  114. errorCode = error.code;
  115. // Error
  116. if (errorCode == 503) {
  117. message = NSLocalizedString(@"_server_error_retry_", nil);
  118. } else {
  119. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  120. }
  121. completion(account, nil, message, errorCode);
  122. }];
  123. }
  124. - (void)readShareWithAccount:(NSString *)account path:(NSString *)path completion:(void (^)(NSString *account, NSArray *items, NSString *message, NSInteger errorCode))completion
  125. {
  126. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  127. if (tableAccount == nil) {
  128. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  129. } else if ([CCUtility getPassword:account].length == 0) {
  130. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  131. } else if ([CCUtility getCertificateError:account]) {
  132. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  133. }
  134. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  135. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  136. [communication setUserAgent:[CCUtility getUserAgent]];
  137. [communication readSharedByServer:[tableAccount.url stringByAppendingString:@"/"] andPath:path onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfShared, NSString *redirectedServer) {
  138. completion(account, listOfShared, nil, 0);
  139. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  140. NSString *message;
  141. NSInteger errorCode = response.statusCode;
  142. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  143. errorCode = error.code;
  144. // Error
  145. if (errorCode == 503) {
  146. message = NSLocalizedString(@"_server_error_retry_", nil);
  147. } else {
  148. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  149. }
  150. completion(account, nil, message, errorCode);
  151. }];
  152. }
  153. - (void)shareWithAccount:(NSString *)account fileName:(NSString *)fileName password:(NSString *)password permission:(NSInteger)permission hideDownload:(BOOL)hideDownload completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  154. {
  155. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  156. if (tableAccount == nil) {
  157. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  158. } else if ([CCUtility getPassword:account].length == 0) {
  159. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  160. } else if ([CCUtility getCertificateError:account]) {
  161. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  162. }
  163. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  164. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  165. [communication setUserAgent:[CCUtility getUserAgent]];
  166. [communication shareFileOrFolderByServer:[tableAccount.url stringByAppendingString:@"/"] andFileOrFolderPath:[fileName encodeString:NSUTF8StringEncoding] andPassword:[password encodeString:NSUTF8StringEncoding] andPermission:permission andHideDownload:hideDownload onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *token, NSString *redirectedServer) {
  167. completion(account, nil, 0);
  168. } failureRequest :^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  169. NSString *message;
  170. NSInteger errorCode = response.statusCode;
  171. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  172. errorCode = error.code;
  173. // Error
  174. if (errorCode == 503) {
  175. message = NSLocalizedString(@"_server_error_retry_", nil);
  176. } else {
  177. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  178. }
  179. completion(account, message, errorCode);
  180. }];
  181. }
  182. // * @param shareeType -> NSInteger: to set the type of sharee (user/group/federated)
  183. - (void)shareUserGroupWithAccount:(NSString *)account userOrGroup:(NSString *)userOrGroup fileName:(NSString *)fileName permission:(NSInteger)permission shareeType:(NSInteger)shareeType completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  184. {
  185. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  186. if (tableAccount == nil) {
  187. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  188. } else if ([CCUtility getPassword:account].length == 0) {
  189. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  190. } else if ([CCUtility getCertificateError:account]) {
  191. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  192. }
  193. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  194. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  195. [communication setUserAgent:[CCUtility getUserAgent]];
  196. [communication shareWith:userOrGroup shareeType:shareeType inServer:[tableAccount.url stringByAppendingString:@"/"] andFileOrFolderPath:[fileName encodeString:NSUTF8StringEncoding] andPermissions:permission onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  197. completion(account, nil, 0);
  198. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  199. NSString *message;
  200. NSInteger errorCode = response.statusCode;
  201. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  202. errorCode = error.code;
  203. // Error
  204. if (errorCode == 503) {
  205. message = NSLocalizedString(@"_server_error_retry_", nil);
  206. } else {
  207. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  208. }
  209. completion(account, message, errorCode);
  210. }];
  211. }
  212. - (void)shareUpdateAccount:(NSString *)account shareID:(NSInteger)shareID password:(NSString *)password note:(NSString *)note permission:(NSInteger)permission expirationTime:(NSString *)expirationTime hideDownload:(BOOL)hideDownload completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  213. {
  214. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  215. if (tableAccount == nil) {
  216. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  217. } else if ([CCUtility getPassword:account].length == 0) {
  218. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  219. } else if ([CCUtility getCertificateError:account]) {
  220. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  221. }
  222. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  223. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  224. [communication setUserAgent:[CCUtility getUserAgent]];
  225. [communication updateShare:shareID ofServerPath:[tableAccount.url stringByAppendingString:@"/"] withPasswordProtect:[password encodeString:NSUTF8StringEncoding] andNote:note andExpirationTime:expirationTime andPermissions:permission andHideDownload:hideDownload onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  226. completion(account, nil, 0);
  227. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  228. NSString *message;
  229. NSInteger errorCode = response.statusCode;
  230. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  231. errorCode = error.code;
  232. // Error
  233. if (errorCode == 503) {
  234. message = NSLocalizedString(@"_server_error_retry_", nil);
  235. } else {
  236. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  237. }
  238. completion(account, message, errorCode);
  239. }];
  240. }
  241. - (void)unshareAccount:(NSString *)account shareID:(NSInteger)shareID completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  242. {
  243. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  244. if (tableAccount == nil) {
  245. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  246. } else if ([CCUtility getPassword:account].length == 0) {
  247. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  248. } else if ([CCUtility getCertificateError:account]) {
  249. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  250. }
  251. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  252. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  253. [communication setUserAgent:[CCUtility getUserAgent]];
  254. [communication unShareFileOrFolderByServer:[tableAccount.url stringByAppendingString:@"/"] andIdRemoteShared:shareID onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  255. completion(account, nil, 0);
  256. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  257. NSString *message;
  258. NSInteger errorCode = response.statusCode;
  259. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  260. errorCode = error.code;
  261. // Error
  262. if (errorCode == 503) {
  263. message = NSLocalizedString(@"_server_error_retry_", nil);
  264. } else {
  265. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  266. }
  267. completion(account, message, errorCode);
  268. }];
  269. }
  270. - (void)getUserGroupWithAccount:(NSString *)account searchString:(NSString *)searchString completion:(void (^)(NSString *account, NSArray *item, NSString *message, NSInteger errorCode))completion
  271. {
  272. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  273. if (tableAccount == nil) {
  274. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  275. } else if ([CCUtility getPassword:account].length == 0) {
  276. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  277. } else if ([CCUtility getCertificateError:account]) {
  278. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  279. }
  280. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  281. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  282. [communication setUserAgent:[CCUtility getUserAgent]];
  283. [communication searchUsersAndGroupsWith:searchString forPage:1 with:50 ofServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *itemList, NSString *redirectedServer) {
  284. completion(account, itemList, nil, 0);
  285. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  286. NSString *message;
  287. NSInteger errorCode = response.statusCode;
  288. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  289. errorCode = error.code;
  290. // Error
  291. if (errorCode == 503) {
  292. message = NSLocalizedString(@"_server_error_retry_", nil);
  293. } else {
  294. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  295. }
  296. completion(account, nil, message, errorCode);
  297. }];
  298. }
  299. #pragma --------------------------------------------------------------------------------------------
  300. #pragma mark ===== Push Notification =====
  301. #pragma --------------------------------------------------------------------------------------------
  302. - (void)subscribingPushNotificationWithAccount:(NSString *)account url:(NSString *)url pushToken:(NSString *)pushToken Hash:(NSString *)pushTokenHash devicePublicKey:(NSString *)devicePublicKey completion:(void(^)(NSString *account, NSString *deviceIdentifier, NSString *deviceIdentifierSignature, NSString *publicKey, NSString *message, NSInteger errorCode))completion
  303. {
  304. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  305. if (tableAccount == nil) {
  306. completion(account, nil, nil, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  307. } else if ([CCUtility getPassword:account].length == 0) {
  308. completion(account, nil, nil, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  309. } else if ([CCUtility getCertificateError:account]) {
  310. completion(account, nil, nil, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  311. }
  312. devicePublicKey = [CCUtility URLEncodeStringFromString:devicePublicKey];
  313. NSString *proxyServerPath = [NCBrandOptions sharedInstance].pushNotificationServerProxy;
  314. NSString *proxyServer = [NCBrandOptions sharedInstance].pushNotificationServerProxy;
  315. #ifdef DEBUG
  316. // proxyServerPath = @"http://127.0.0.1:8088";
  317. // proxyServer = @"https://10.132.0.37:8443/pushnotifications";
  318. #endif
  319. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  320. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  321. [communication setUserAgent:[CCUtility getUserAgent]];
  322. [communication subscribingNextcloudServerPush:url pushTokenHash:pushTokenHash devicePublicKey:devicePublicKey proxyServerPath: proxyServerPath onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *publicKey, NSString *deviceIdentifier, NSString *signature, NSString *redirectedServer) {
  323. deviceIdentifier = [CCUtility URLEncodeStringFromString:deviceIdentifier];
  324. signature = [CCUtility URLEncodeStringFromString:signature];
  325. publicKey = [CCUtility URLEncodeStringFromString:publicKey];
  326. [communication subscribingPushProxy:proxyServer pushToken:pushToken deviceIdentifier:deviceIdentifier deviceIdentifierSignature:signature publicKey:publicKey onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  327. completion(account, deviceIdentifier, signature, publicKey, nil, 0);
  328. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  329. NSString *message;
  330. NSInteger errorCode = response.statusCode;
  331. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  332. errorCode = error.code;
  333. // Error
  334. if (errorCode == 503)
  335. message = NSLocalizedString(@"_server_error_retry_", nil);
  336. else
  337. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  338. completion(account, nil, nil, nil, message, errorCode);
  339. }];
  340. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  341. NSString *message;
  342. NSInteger errorCode = response.statusCode;
  343. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  344. errorCode = error.code;
  345. // Error
  346. if (errorCode == 503)
  347. message = NSLocalizedString(@"_server_error_retry_", nil);
  348. else
  349. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  350. completion(account, nil, nil, nil, message, errorCode);
  351. }];
  352. }
  353. - (void)unsubscribingPushNotificationWithAccount:(NSString *)account url:(NSString *)url deviceIdentifier:(NSString *)deviceIdentifier deviceIdentifierSignature:(NSString *)deviceIdentifierSignature publicKey:(NSString *)publicKey completion:(void (^)(NSString *account ,NSString *message, NSInteger errorCode))completion {
  354. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  355. if (tableAccount == nil) {
  356. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  357. } else if ([CCUtility getPassword:account].length == 0) {
  358. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  359. } else if ([CCUtility getCertificateError:account]) {
  360. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  361. }
  362. NSString *proxyServer = [NCBrandOptions sharedInstance].pushNotificationServerProxy;
  363. #ifdef DEBUG
  364. // proxyServer = @"https://10.132.0.37:8443/pushnotifications";
  365. #endif
  366. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  367. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  368. [communication setUserAgent:[CCUtility getUserAgent]];
  369. [communication unsubscribingNextcloudServerPush:url onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  370. [communication unsubscribingPushProxy:proxyServer deviceIdentifier:deviceIdentifier deviceIdentifierSignature:deviceIdentifierSignature publicKey:publicKey onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  371. completion(account, nil, 0);
  372. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  373. NSString *message;
  374. NSInteger errorCode = response.statusCode;
  375. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  376. errorCode = error.code;
  377. // Error
  378. if (errorCode == 503)
  379. message = NSLocalizedString(@"_server_error_retry_", nil);
  380. else
  381. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  382. completion(account, message, errorCode);
  383. }];
  384. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  385. NSString *message;
  386. NSInteger errorCode = response.statusCode;
  387. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  388. errorCode = error.code;
  389. // Error
  390. if (errorCode == 503)
  391. message = NSLocalizedString(@"_server_error_retry_", nil);
  392. else
  393. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  394. completion(account, message, errorCode);
  395. }];
  396. }
  397. - (void)getServerNotification:(NSString *)serverUrl notificationId:(NSInteger)notificationId completion:(void(^)(NSDictionary*jsongParsed, NSString *message, NSInteger errorCode))completion
  398. {
  399. NSString *URLString = [NSString stringWithFormat:@"%@/ocs/v2.php/apps/notifications/api/v2/notifications/%ld?format=json", serverUrl, (long)notificationId];
  400. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URLString] cachePolicy:0 timeoutInterval:20.0];
  401. [request addValue:[CCUtility getUserAgent] forHTTPHeaderField:@"User-Agent"];
  402. [request addValue:@"true" forHTTPHeaderField:@"OCS-APIRequest"];
  403. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  404. NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  405. NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler: ^(NSData *data, NSURLResponse *response, NSError *error) {
  406. if (error) {
  407. NSString *message;
  408. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
  409. NSInteger errorCode = httpResponse.statusCode;
  410. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  411. errorCode = error.code;
  412. // Error
  413. if (errorCode == 503)
  414. message = NSLocalizedString(@"_server_error_retry_", nil);
  415. else
  416. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  417. completion(nil, message, errorCode);
  418. } else {
  419. NSDictionary *jsongParsed = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
  420. completion(jsongParsed, nil, 0);
  421. }
  422. }];
  423. [task resume];
  424. }
  425. - (void)deletingServerNotification:(NSString *)serverUrl notificationId:(NSInteger)notificationId completion:(void(^)(NSString *message, NSInteger errorCode))completion
  426. {
  427. // NSData *authData = [[NSString stringWithFormat:@"%@:%@", tableAccount.user, [CCUtility getPassword:tableAccount.account]] dataUsingEncoding:NSUTF8StringEncoding];
  428. // NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];
  429. // Delete
  430. NSString *URLString = [NSString stringWithFormat:@"%@/ocs/v2.php/apps/notifications/api/v2/notifications/%ld", serverUrl, (long)notificationId];
  431. // Delete-all
  432. if (notificationId == 0) {
  433. URLString = [NSString stringWithFormat:@"%@/ocs/v2.php/apps/notifications/api/v2/notifications", serverUrl];
  434. }
  435. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URLString] cachePolicy:0 timeoutInterval:20.0];
  436. // [request setValue:authValue forHTTPHeaderField:@"Authorization"];
  437. [request addValue:[CCUtility getUserAgent] forHTTPHeaderField:@"User-Agent"];
  438. [request addValue:@"true" forHTTPHeaderField:@"OCS-APIRequest"];
  439. [request setHTTPMethod: @"DELETE"];
  440. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  441. NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  442. NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler: ^(NSData *data, NSURLResponse *response, NSError *error) {
  443. if (error) {
  444. NSString *message;
  445. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
  446. NSInteger errorCode = httpResponse.statusCode;
  447. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  448. errorCode = error.code;
  449. // Error
  450. if (errorCode == 503)
  451. message = NSLocalizedString(@"_server_error_retry_", nil);
  452. else
  453. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  454. completion(message, errorCode);
  455. } else {
  456. completion(nil, 0);
  457. }
  458. }];
  459. [task resume];
  460. }
  461. #pragma --------------------------------------------------------------------------------------------
  462. #pragma mark ===== Third Parts =====
  463. #pragma --------------------------------------------------------------------------------------------
  464. - (void)getHCUserProfileWithAccount:(NSString *)account serverUrl:(NSString *)serverUrl completion:(void (^)(NSString *account, OCUserProfile *userProfile, NSString *message, NSInteger errorCode))completion
  465. {
  466. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  467. if (tableAccount == nil) {
  468. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  469. } else if ([CCUtility getPassword:account].length == 0) {
  470. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  471. } else if ([CCUtility getCertificateError:account]) {
  472. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  473. }
  474. NSString *serverPath = [NSString stringWithFormat:@"%@/ocs/v2.php/apps/handwerkcloud/api/v1/settings/%@", serverUrl, tableAccount.userID];
  475. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  476. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  477. [communication setUserAgent:[CCUtility getUserAgent]];
  478. [communication getHCUserProfile:serverPath onCommunication:communication successRequest:^(NSHTTPURLResponse *response, OCUserProfile *userProfile, NSString *redirectedServer) {
  479. completion(account, userProfile, nil, 0);
  480. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  481. NSString *message;
  482. NSInteger errorCode = response.statusCode;
  483. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  484. errorCode = error.code;
  485. // Server Unauthorized
  486. if (errorCode == kOCErrorServerUnauthorized || errorCode == kOCErrorServerForbidden) {
  487. #ifndef EXTENSION
  488. [[NCNetworkingCheckRemoteUser shared] checkRemoteUserWithAccount:account];
  489. #endif
  490. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  491. [CCUtility setCertificateError:account error:YES];
  492. }
  493. // Error
  494. if (errorCode == 503)
  495. message = NSLocalizedString(@"_server_error_retry_", nil);
  496. else
  497. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  498. completion(account, nil,message, errorCode);
  499. }];
  500. }
  501. - (void)putHCUserProfileWithAccount:(NSString *)account serverUrl:(NSString *)serverUrl address:(NSString *)address businesssize:(NSString *)businesssize businesstype:(NSString *)businesstype city:(NSString *)city company:(NSString *)company country:(NSString *)country displayname:(NSString *)displayname email:(NSString *)email phone:(NSString *)phone role_:(NSString *)role_ twitter:(NSString *)twitter website:(NSString *)website zip:(NSString *)zip completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  502. {
  503. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  504. if (tableAccount == nil) {
  505. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  506. } else if ([CCUtility getPassword:account].length == 0) {
  507. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  508. } else if ([CCUtility getCertificateError:account]) {
  509. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  510. }
  511. // Create JSON
  512. NSMutableDictionary *dataDic = [NSMutableDictionary new];
  513. if (address) [dataDic setValue:address forKey:@"address"];
  514. if (businesssize) {
  515. if ([businesssize isEqualToString:@"1-4"]) { [dataDic setValue:[NSNumber numberWithInt:1] forKey:@"businesssize"]; }
  516. else if ([businesssize isEqualToString:@"5-9"]) { [dataDic setValue:[NSNumber numberWithInt:5] forKey:@"businesssize"]; }
  517. else if ([businesssize isEqualToString:@"10-19"]) { [dataDic setValue:[NSNumber numberWithInt:10] forKey:@"businesssize"]; }
  518. else if ([businesssize isEqualToString:@"20-49"]) { [dataDic setValue:[NSNumber numberWithInt:20] forKey:@"businesssize"]; }
  519. else if ([businesssize isEqualToString:@"50-99"]) { [dataDic setValue:[NSNumber numberWithInt:50] forKey:@"businesssize"]; }
  520. else if ([businesssize isEqualToString:@"100-249"]) { [dataDic setValue:[NSNumber numberWithInt:100] forKey:@"businesssize"]; }
  521. else if ([businesssize isEqualToString:@"250-499"]) { [dataDic setValue:[NSNumber numberWithInt:250] forKey:@"businesssize"]; }
  522. else if ([businesssize isEqualToString:@"500-999"]) { [dataDic setValue:[NSNumber numberWithInt:500] forKey:@"businesssize"]; }
  523. else if ([businesssize isEqualToString:@"1000+"]) { [dataDic setValue:[NSNumber numberWithInt:1000] forKey:@"businesssize"]; }
  524. }
  525. if (businesstype) [dataDic setValue:businesstype forKey:@"businesstype"];
  526. if (city) [dataDic setValue:city forKey:@"city"];
  527. if (company) [dataDic setValue:company forKey:@"company"];
  528. if (country) [dataDic setValue:country forKey:@"country"];
  529. if (displayname) [dataDic setValue:displayname forKey:@"displayname"];
  530. if (email) [dataDic setValue:email forKey:@"email"];
  531. if (phone) [dataDic setValue:phone forKey:@"phone"];
  532. if (role_) [dataDic setValue:role_ forKey:@"role"];
  533. if (twitter) [dataDic setValue:twitter forKey:@"twitter"];
  534. if (website) [dataDic setValue:website forKey:@"website"];
  535. if (zip) [dataDic setValue:zip forKey:@"zip"];
  536. NSString *data = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:dataDic options:0 error:nil] encoding:NSUTF8StringEncoding];
  537. NSString *serverPath = [NSString stringWithFormat:@"%@/ocs/v2.php/apps/handwerkcloud/api/v1/settings/%@", serverUrl, tableAccount.userID];
  538. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  539. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  540. [communication setUserAgent:[CCUtility getUserAgent]];
  541. [communication putHCUserProfile:serverPath data:data onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  542. completion(account, nil, 0);
  543. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  544. NSString *message;
  545. NSInteger errorCode = response.statusCode;
  546. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  547. errorCode = error.code;
  548. // Server Unauthorized
  549. if (errorCode == kOCErrorServerUnauthorized || errorCode == kOCErrorServerForbidden) {
  550. #ifndef EXTENSION
  551. [[NCNetworkingCheckRemoteUser shared] checkRemoteUserWithAccount:account];
  552. #endif
  553. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  554. [CCUtility setCertificateError:account error:YES];
  555. }
  556. // Error
  557. if (errorCode == 503)
  558. message = NSLocalizedString(@"_server_error_retry_", nil);
  559. else
  560. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  561. completion(account, message, errorCode);
  562. }];
  563. }
  564. - (void)getHCFeaturesWithAccount:(NSString *)account serverUrl:(NSString *)serverUrl completion:(void (^)(NSString *account, HCFeatures *features, NSString *message, NSInteger errorCode))completion
  565. {
  566. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  567. if (tableAccount == nil) {
  568. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  569. } else if ([CCUtility getPassword:account].length == 0) {
  570. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  571. } else if ([CCUtility getCertificateError:account]) {
  572. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  573. }
  574. NSString *serverPath = [NSString stringWithFormat:@"%@/ocs/v2.php/apps/handwerkcloud/api/v1/features/%@", serverUrl, tableAccount.userID];
  575. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  576. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  577. [communication setUserAgent:[CCUtility getUserAgent]];
  578. [communication getHCFeatures:serverPath onCommunication:communication successRequest:^(NSHTTPURLResponse *response, HCFeatures *features, NSString *redirectedServer) {
  579. completion(account, features, nil, 0);
  580. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  581. NSString *message;
  582. NSInteger errorCode = response.statusCode;
  583. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  584. errorCode = error.code;
  585. // Server Unauthorized
  586. if (errorCode == kOCErrorServerUnauthorized || errorCode == kOCErrorServerForbidden) {
  587. #ifndef EXTENSION
  588. [[NCNetworkingCheckRemoteUser shared] checkRemoteUserWithAccount:account];
  589. #endif
  590. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  591. [CCUtility setCertificateError:account error:YES];
  592. }
  593. // Error
  594. if (errorCode == 503)
  595. message = NSLocalizedString(@"_server_error_retry_", nil);
  596. else
  597. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  598. completion(account, nil,message, errorCode);
  599. }];
  600. }
  601. #pragma --------------------------------------------------------------------------------------------
  602. #pragma mark ===== didReceiveChallenge =====
  603. #pragma --------------------------------------------------------------------------------------------
  604. -(void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler
  605. {
  606. // The pinnning check
  607. if ([[NCNetworking sharedInstance] checkTrustedChallengeWithChallenge:challenge directoryCertificate:[CCUtility getDirectoryCerificates]]) {
  608. completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  609. } else {
  610. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  611. }
  612. }
  613. @end
  614. #pragma --------------------------------------------------------------------------------------------
  615. #pragma mark ===== OCURLSessionManager =====
  616. #pragma --------------------------------------------------------------------------------------------
  617. @implementation OCURLSessionManager
  618. - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
  619. {
  620. // The pinnning check
  621. if ([[NCNetworking sharedInstance] checkTrustedChallengeWithChallenge:challenge directoryCertificate:[CCUtility getDirectoryCerificates]]) {
  622. completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  623. } else {
  624. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  625. }
  626. }
  627. @end