OCNetworking.m 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122
  1. //
  2. // OCnetworking.m
  3. // Crypto Cloud Technology Nextcloud
  4. //
  5. // Created by Marino Faggiana on 10/05/15.
  6. // Copyright (c) 2014 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  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 "AppDelegate.h"
  25. #import "CCGraphics.h"
  26. #import "CCCertificate.h"
  27. #import "NSString+Encode.h"
  28. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  29. @interface OCnetworking ()
  30. {
  31. NSString *_activeUser;
  32. NSString *_activePassword;
  33. NSString *_activeUrl;
  34. NSString *_typeCloud;
  35. NSURLSessionDownloadTask *_downloadTask;
  36. NSURLSessionUploadTask *_uploadTask;
  37. BOOL _activityIndicator;
  38. }
  39. @end
  40. @implementation OCnetworking
  41. - (id)initWithDelegate:(id <OCNetworkingDelegate>)delegate metadataNet:(CCMetadataNet *)metadataNet withUser:(NSString *)withUser withPassword:(NSString *)withPassword withUrl:(NSString *)withUrl withTypeCloud:(NSString *)withTypeCloud activityIndicator:(BOOL)activityIndicator
  42. {
  43. self = [super init];
  44. if (self) {
  45. _delegate = delegate;
  46. _metadataNet = [[CCMetadataNet alloc] init];
  47. _metadataNet = [metadataNet copy];
  48. _activeUser = withUser;
  49. _activePassword = withPassword;
  50. _activeUrl = withUrl;
  51. _typeCloud = withTypeCloud;
  52. _activityIndicator = activityIndicator;
  53. }
  54. return self;
  55. }
  56. - (void)start
  57. {
  58. if (![NSThread isMainThread]) {
  59. [self performSelectorOnMainThread:@selector(start) withObject:nil waitUntilDone:NO];
  60. return;
  61. }
  62. [self willChangeValueForKey:@"isExecuting"];
  63. _isExecuting = YES;
  64. [self didChangeValueForKey:@"isExecuting"];
  65. if (self.isCancelled) {
  66. [self finish];
  67. } else {
  68. [self poolNetworking];
  69. }
  70. }
  71. - (void)finish
  72. {
  73. [self willChangeValueForKey:@"isExecuting"];
  74. [self willChangeValueForKey:@"isFinished"];
  75. _isExecuting = NO;
  76. _isFinished = YES;
  77. [self didChangeValueForKey:@"isExecuting"];
  78. [self didChangeValueForKey:@"isFinished"];
  79. }
  80. - (void)cancel
  81. {
  82. if (_isExecuting) {
  83. if (_downloadTask)
  84. [_downloadTask cancel];
  85. if (_uploadTask)
  86. [_uploadTask cancel];
  87. [self complete];
  88. }
  89. [super cancel];
  90. }
  91. - (void)poolNetworking
  92. {
  93. #ifndef EXTENSION
  94. // Animation network
  95. if (_activityIndicator) {
  96. dispatch_async(dispatch_get_main_queue(), ^{
  97. [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
  98. [[NSNotificationCenter defaultCenter] postNotificationName:@"setTitleCCMainYESAnimation" object:nil];
  99. });
  100. }
  101. #endif
  102. if([self respondsToSelector:NSSelectorFromString(_metadataNet.action)])
  103. [self performSelector:NSSelectorFromString(_metadataNet.action)];
  104. }
  105. #pragma --------------------------------------------------------------------------------------------
  106. #pragma mark ===== Delegate =====
  107. #pragma --------------------------------------------------------------------------------------------
  108. - (void)complete
  109. {
  110. #ifndef EXTENSION
  111. // Animation network
  112. if (_activityIndicator) {
  113. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  114. [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
  115. [[NSNotificationCenter defaultCenter] postNotificationName:@"setTitleCCMainNOAnimation" object:nil];
  116. });
  117. }
  118. #endif
  119. [self finish];
  120. }
  121. #pragma --------------------------------------------------------------------------------------------
  122. #pragma mark ===== downloadFile =====
  123. #pragma --------------------------------------------------------------------------------------------
  124. - (void)downloadFile
  125. {
  126. [[CCNetworking sharedNetworking] downloadFile:_metadataNet.metadata serverUrl:_metadataNet.serverUrl downloadData:_metadataNet.downloadData downloadPlist:_metadataNet.downloadPlist selector:_metadataNet.selector selectorPost:_metadataNet.selectorPost session:_metadataNet.session taskStatus:_metadataNet.taskStatus delegate:self];
  127. }
  128. - (void)downloadTaskSave:(NSURLSessionDownloadTask *)downloadTask
  129. {
  130. _downloadTask= downloadTask;
  131. if ([self.delegate respondsToSelector:@selector(downloadTaskSave:)])
  132. [self.delegate downloadTaskSave:downloadTask];
  133. }
  134. - (void)downloadFileSuccess:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  135. {
  136. [self complete];
  137. if ([self.delegate respondsToSelector:@selector(downloadFileSuccess:serverUrl:selector:selectorPost:)])
  138. [self.delegate downloadFileSuccess:fileID serverUrl:serverUrl selector:selector selectorPost:selectorPost];
  139. }
  140. - (void)downloadFileFailure:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  141. {
  142. [self complete];
  143. if ([self.delegate respondsToSelector:@selector(downloadFileFailure:serverUrl:selector:message:errorCode:)])
  144. [self.delegate downloadFileFailure:fileID serverUrl:serverUrl selector:selector message:message errorCode:errorCode];
  145. }
  146. #pragma --------------------------------------------------------------------------------------------
  147. #pragma mark ===== uploadFile =====
  148. #pragma --------------------------------------------------------------------------------------------
  149. - (void)uploadFile
  150. {
  151. [[CCNetworking sharedNetworking] uploadFile:_metadataNet.fileName serverUrl:_metadataNet.serverUrl cryptated:_metadataNet.cryptated onlyPlist:NO session:_metadataNet.session taskStatus:_metadataNet.taskStatus selector:_metadataNet.selector selectorPost:_metadataNet.selectorPost parentRev:nil errorCode:_metadataNet.errorCode delegate:self];
  152. }
  153. - (void)uploadOnlyPlist
  154. {
  155. [[CCNetworking sharedNetworking] uploadFile:_metadataNet.fileName serverUrl:_metadataNet.serverUrl cryptated:YES onlyPlist:YES session:_metadataNet.session taskStatus:_metadataNet.taskStatus selector:_metadataNet.selector selectorPost:_metadataNet.selectorPost parentRev:nil errorCode:_metadataNet.errorCode delegate:self];
  156. }
  157. - (void)uploadAsset
  158. {
  159. [[CCNetworking sharedNetworking] uploadFileFromAssetLocalIdentifier:_metadataNet.identifier fileName:_metadataNet.fileName serverUrl:_metadataNet.serverUrl cryptated:_metadataNet.cryptated session:_metadataNet.session taskStatus:_metadataNet.taskStatus selector:_metadataNet.selector selectorPost:_metadataNet.selectorPost parentRev:nil errorCode:_metadataNet.errorCode delegate:self];
  160. }
  161. - (void)uploadTemplate
  162. {
  163. [[CCNetworking sharedNetworking] uploadTemplate:_metadataNet.fileNamePrint fileNameCrypto:_metadataNet.fileName serverUrl:_metadataNet.serverUrl session:_metadataNet.session taskStatus:_metadataNet.taskStatus selector:_metadataNet.selector selectorPost:_metadataNet.selectorPost parentRev:nil errorCode:_metadataNet.errorCode delegate:self];
  164. }
  165. - (void)uploadTaskSave:(NSURLSessionUploadTask *)uploadTask
  166. {
  167. _uploadTask = uploadTask;
  168. if ([self.delegate respondsToSelector:@selector(uploadTaskSave:)])
  169. [self.delegate uploadTaskSave:uploadTask];
  170. }
  171. - (void)uploadFileSuccess:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  172. {
  173. [self complete];
  174. if ([self.delegate respondsToSelector:@selector(uploadFileSuccess:serverUrl:selector:selectorPost:)])
  175. [self.delegate uploadFileSuccess:fileID serverUrl:serverUrl selector:selector selectorPost:selectorPost];
  176. }
  177. - (void)uploadFileFailure:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  178. {
  179. [self complete];
  180. if ([self.delegate respondsToSelector:@selector(uploadFileFailure:serverUrl:selector:message:errorCode:)])
  181. [self.delegate uploadFileFailure:fileID serverUrl:serverUrl selector:selector message:message errorCode:errorCode];
  182. }
  183. #pragma --------------------------------------------------------------------------------------------
  184. #pragma mark ===== downloadThumbnail =====
  185. #pragma --------------------------------------------------------------------------------------------
  186. - (void)downloadThumbnail
  187. {
  188. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  189. __block NSString *ext;
  190. NSInteger width = 0, height = 0;
  191. NSString *directoryUser = [CCUtility getDirectoryActiveUser:_activeUser activeUrl:_activeUrl];
  192. if ([_metadataNet.options.lowercaseString isEqualToString:@"xs"]) { width = 32; height = 32; ext = @"ico"; }
  193. else if ([_metadataNet.options.lowercaseString isEqualToString:@"s"]) { width = 64; height = 64; ext = @"ico"; }
  194. else if ([_metadataNet.options.lowercaseString isEqualToString:@"m"]) { width = 128; height = 128; ext = @"ico"; }
  195. else if ([_metadataNet.options.lowercaseString isEqualToString:@"l"]) { width = 640; height = 640; ext = @"pvw"; }
  196. else if ([_metadataNet.options.lowercaseString isEqualToString:@"xl"]) { width = 1024; height = 1024; ext = @"pvw"; }
  197. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.%@", directoryUser, _metadataNet.fileNameLocal, ext]]) {
  198. [self.delegate downloadThumbnailSuccess:_metadataNet];
  199. [self complete];
  200. return;
  201. }
  202. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  203. [communication setUserAgent:[CCUtility getUserAgent:_typeCloud]];
  204. [communication getRemoteThumbnailByServer:[_activeUrl stringByAppendingString:@"/"] ofFilePath:_metadataNet.fileName withWidth:width andHeight:height onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSData *thumbnail, NSString *redirectedServer) {
  205. TableAccount *recordAccount = [CCCoreData getActiveAccount];
  206. if ([recordAccount.account isEqualToString:_metadataNet.account]) {
  207. UIImage *thumbnailImage = [UIImage imageWithData:thumbnail];
  208. NSString *directoryUser = [CCUtility getDirectoryActiveUser:_activeUser activeUrl:_activeUrl];
  209. [CCGraphics saveIcoWithFileID:_metadataNet.fileNameLocal image:thumbnailImage writeToFile:[NSString stringWithFormat:@"%@/%@.%@", directoryUser, _metadataNet.fileNameLocal, ext] copy:NO move:NO fromPath:nil toPath:nil];
  210. if ([self.delegate respondsToSelector:@selector(downloadThumbnailSuccess:)] && [_metadataNet.action isEqualToString:actionDownloadThumbnail])
  211. [self.delegate downloadThumbnailSuccess:_metadataNet];
  212. }
  213. [self complete];
  214. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  215. NSInteger errorCode = response.statusCode;
  216. if (errorCode == 0)
  217. errorCode = error.code;
  218. if ([self.delegate respondsToSelector:@selector(downloadThumbnailFailure:message:errorCode:)] && [_metadataNet.action isEqualToString:actionDownloadThumbnail])
  219. [self.delegate downloadThumbnailFailure:_metadataNet message:[CCError manageErrorOC:response.statusCode error:error] errorCode:errorCode];
  220. [self complete];
  221. }];
  222. }
  223. #pragma --------------------------------------------------------------------------------------------
  224. #pragma mark ===== Read Folder =====
  225. #pragma --------------------------------------------------------------------------------------------
  226. - (void)readFolder
  227. {
  228. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  229. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  230. [communication setUserAgent:[CCUtility getUserAgent:_typeCloud]];
  231. [communication readFolder:_metadataNet.serverUrl withUserSessionToken:nil onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer, NSString *token) {
  232. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  233. // Check items > 0
  234. if ([items count] == 0) {
  235. #ifndef EXTENSION
  236. [app messageNotification:@"Server error" description:@"Read Folder WebDAV : [items NULL] please fix" visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeError];
  237. #endif
  238. dispatch_async(dispatch_get_main_queue(), ^{
  239. if ([self.delegate respondsToSelector:@selector(readFolderSuccess:permissions:rev:metadatas:)])
  240. [self.delegate readFolderSuccess:_metadataNet permissions:@"" rev:@"" metadatas:metadatas];
  241. });
  242. [self complete];
  243. return;
  244. }
  245. // directory [0]
  246. OCFileDto *itemDtoDirectory = [items objectAtIndex:0];
  247. NSString *permissions = itemDtoDirectory.permissions;
  248. NSString *rev = itemDtoDirectory.etag;
  249. NSDate *date = [NSDate dateWithTimeIntervalSince1970:itemDtoDirectory.date];
  250. NSString *directoryID = [CCCoreData addDirectory:_metadataNet.serverUrl date:date permissions:permissions activeAccount:_metadataNet.account];
  251. NSString *cameraFolderName = [CCCoreData getCameraUploadFolderNameActiveAccount:_metadataNet.account];
  252. NSString *cameraFolderPath = [CCCoreData getCameraUploadFolderPathActiveAccount:_metadataNet.account activeUrl:_activeUrl typeCloud:_typeCloud];
  253. NSString *directoryUser = [CCUtility getDirectoryActiveUser:_activeUser activeUrl:_activeUrl];
  254. // Update metadataNet.directoryID
  255. _metadataNet.directoryID = directoryID;
  256. #ifndef EXTENSION
  257. NSString *home = [CCUtility getHomeServerUrlActiveUrl:_activeUrl typeCloud:_typeCloud];
  258. if ([home isEqualToString:_metadataNet.serverUrl]) {
  259. app.quotaUsed = itemDtoDirectory.quotaUsed;
  260. app.quotaAvailable = itemDtoDirectory.quotaAvailable;
  261. }
  262. #endif
  263. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  264. NSArray *itemsSortedArray = [items sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
  265. NSString *first = [(OCFileDto*)a fileName];
  266. NSString *second = [(OCFileDto*)b fileName];
  267. return [[first lowercaseString] compare:[second lowercaseString]];
  268. }];
  269. for (NSUInteger i=1; i < [itemsSortedArray count]; i++) {
  270. OCFileDto *itemDto = [itemsSortedArray objectAtIndex:i];
  271. itemDto.fileName = [itemDto.fileName stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  272. // ----- BUG #942 ---------
  273. if ([itemDto.etag length] == 0) {
  274. #ifndef EXTENSION
  275. [app messageNotification:@"Server error" description:@"Metadata etag absent, record excluded, please fix" visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeError];
  276. #endif
  277. continue;
  278. }
  279. // ------------------------
  280. [metadatas addObject:[CCUtility trasformedOCFileToCCMetadata:itemDto fileNamePrint:itemDto.fileName serverUrl:_metadataNet.serverUrl directoryID:directoryID cameraFolderName:cameraFolderName cameraFolderPath:cameraFolderPath activeAccount:_metadataNet.account directoryUser:directoryUser typeCloud:_typeCloud]];
  281. }
  282. dispatch_async(dispatch_get_main_queue(), ^{
  283. if ([self.delegate respondsToSelector:@selector(readFolderSuccess:permissions:rev:metadatas:)])
  284. [self.delegate readFolderSuccess:_metadataNet permissions:permissions rev:rev metadatas:metadatas];
  285. });
  286. });
  287. [self complete];
  288. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) {
  289. NSInteger errorCode = response.statusCode;
  290. if (errorCode == 0)
  291. errorCode = error.code;
  292. if ([self.delegate respondsToSelector:@selector(readFolderFailure:message:errorCode:)])
  293. [self.delegate readFolderFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  294. // Request trusted certificated
  295. if ([error code] == NSURLErrorServerCertificateUntrusted)
  296. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  297. [self complete];
  298. }];
  299. }
  300. #pragma --------------------------------------------------------------------------------------------
  301. #pragma mark ===== Create Folder =====
  302. #pragma --------------------------------------------------------------------------------------------
  303. - (void)createFolder
  304. {
  305. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  306. BOOL hasServerForbiddenCharactersSupport;
  307. NSString *nameFolderURL = [NSString stringWithFormat:@"%@/%@", _metadataNet.serverUrl, _metadataNet.fileName];
  308. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  309. [communication setUserAgent:[CCUtility getUserAgent:_typeCloud]];
  310. [communication createFolder:nameFolderURL onCommunication:communication withForbiddenCharactersSupported:hasServerForbiddenCharactersSupport successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  311. if ([self.delegate respondsToSelector:@selector(createFolderSuccess:)])
  312. [self.delegate createFolderSuccess:_metadataNet];
  313. [self complete];
  314. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  315. NSString *message;
  316. if (([_metadataNet.fileName isEqualToString:[CCCoreData getCameraUploadFolderNameActiveAccount:_metadataNet.account]] == YES && [_metadataNet.serverUrl isEqualToString:[CCCoreData getCameraUploadFolderPathActiveAccount:_metadataNet.account activeUrl:_activeUrl typeCloud:_typeCloud]] == YES))
  317. message = nil;
  318. else
  319. message = [CCError manageErrorOC:response.statusCode error:error];
  320. NSInteger errorCode = response.statusCode;
  321. if (errorCode == 0)
  322. errorCode = error.code;
  323. if ([self.delegate respondsToSelector:@selector(createFolderFailure:message:errorCode:)])
  324. [self.delegate createFolderFailure:_metadataNet message:message errorCode:errorCode];
  325. // Request trusted certificated
  326. if ([error code] == NSURLErrorServerCertificateUntrusted)
  327. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  328. [self complete];
  329. } errorBeforeRequest:^(NSError *error) {
  330. NSString *message;
  331. if (([_metadataNet.fileName isEqualToString:[CCCoreData getCameraUploadFolderNameActiveAccount:_metadataNet.account]] == YES && [_metadataNet.serverUrl isEqualToString:[CCCoreData getCameraUploadFolderPathActiveAccount:_metadataNet.account activeUrl:_activeUrl typeCloud:_typeCloud]] == YES))
  332. message = nil;
  333. else {
  334. if (error.code == OCErrorForbidenCharacters)
  335. message = NSLocalizedStringFromTable(@"_forbidden_characters_from_server_", @"Error", nil);
  336. else
  337. message = NSLocalizedStringFromTable(@"_unknow_response_server_", @"Error", nil);
  338. }
  339. if ([self.delegate respondsToSelector:@selector(createFolderFailure:message:errorCode:)])
  340. [self.delegate createFolderFailure:_metadataNet message:message errorCode:error.code];
  341. [self complete];
  342. }];
  343. }
  344. - (NSError *)createFolderSync:(NSString *)folderPathName
  345. {
  346. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  347. BOOL hasServerForbiddenCharactersSupport;
  348. __block NSError *returnError;
  349. dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
  350. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  351. [communication setUserAgent:[CCUtility getUserAgent:_typeCloud]];
  352. [communication createFolder:folderPathName onCommunication:communication withForbiddenCharactersSupported:hasServerForbiddenCharactersSupport successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  353. dispatch_semaphore_signal(semaphore);
  354. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  355. // Request trusted certificated
  356. if ([error code] == NSURLErrorServerCertificateUntrusted)
  357. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  358. returnError = error;
  359. dispatch_semaphore_signal(semaphore);
  360. } errorBeforeRequest:^(NSError *error) {
  361. returnError = error;
  362. dispatch_semaphore_signal(semaphore);
  363. }];
  364. while (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_NOW))
  365. [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:k_timeout_webdav]];
  366. return returnError;
  367. }
  368. #pragma --------------------------------------------------------------------------------------------
  369. #pragma mark ===== Delete =====
  370. #pragma --------------------------------------------------------------------------------------------
  371. - (void)deleteFileOrFolder
  372. {
  373. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  374. NSString *serverFileUrl = [NSString stringWithFormat:@"%@/%@", _metadataNet.serverUrl, _metadataNet.fileName];
  375. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  376. [communication setUserAgent:[CCUtility getUserAgent:_typeCloud]];
  377. [communication deleteFileOrFolder:serverFileUrl onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  378. if ([_metadataNet.selector rangeOfString:selectorDelete].location != NSNotFound && [self.delegate respondsToSelector:@selector(deleteFileOrFolderSuccess:)])
  379. [self.delegate deleteFileOrFolderSuccess:_metadataNet];
  380. [self complete];
  381. } failureRquest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  382. NSInteger errorCode = response.statusCode;
  383. if (errorCode == 0)
  384. errorCode = error.code;
  385. if ([self.delegate respondsToSelector:@selector(deleteFileOrFolderFailure:message:errorCode:)])
  386. [self.delegate deleteFileOrFolderFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  387. // Request trusted certificated
  388. if ([error code] == NSURLErrorServerCertificateUntrusted)
  389. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  390. [self complete];
  391. }];
  392. }
  393. #pragma --------------------------------------------------------------------------------------------
  394. #pragma mark ===== Move =====
  395. #pragma --------------------------------------------------------------------------------------------
  396. - (void)moveFileOrFolder
  397. {
  398. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  399. BOOL hasServerForbiddenCharactersSupport;
  400. NSString *origineURL = [NSString stringWithFormat:@"%@/%@", _metadataNet.serverUrl, _metadataNet.fileName];
  401. NSString *destinazioneURL = [NSString stringWithFormat:@"%@/%@", _metadataNet.serverUrlTo, _metadataNet.fileNameTo];
  402. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  403. [communication setUserAgent:[CCUtility getUserAgent:_typeCloud]];
  404. [communication moveFileOrFolder:origineURL toDestiny:destinazioneURL onCommunication:communication withForbiddenCharactersSupported:hasServerForbiddenCharactersSupport successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  405. if ([_metadataNet.selector isEqualToString:selectorRename] && [self.delegate respondsToSelector:@selector(renameSuccess:revTo:)])
  406. [self.delegate renameSuccess:_metadataNet revTo:nil];
  407. if ([_metadataNet.selector rangeOfString:selectorMove].location != NSNotFound && [self.delegate respondsToSelector:@selector(moveSuccess:revTo:)])
  408. [self.delegate moveSuccess:_metadataNet revTo:nil];
  409. [self complete];
  410. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  411. NSInteger errorCode = response.statusCode;
  412. if (errorCode == 0)
  413. errorCode = error.code;
  414. if ([self.delegate respondsToSelector:@selector(moveFileOrFolderFailure:message:errorCode:)])
  415. [self.delegate moveFileOrFolderFailure:_metadataNet message:[CCError manageErrorOC:response.statusCode error:error] errorCode:errorCode];
  416. // Request trusted certificated
  417. if ([error code] == NSURLErrorServerCertificateUntrusted)
  418. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  419. [self complete];
  420. } errorBeforeRequest:^(NSError *error) {
  421. NSString *message;
  422. if (error.code == OCErrorMovingTheDestinyAndOriginAreTheSame) {
  423. message = NSLocalizedStringFromTable(@"_error_folder_destiny_is_the_same_", @"Error", nil);
  424. } else if (error.code == OCErrorMovingFolderInsideHimself) {
  425. message = NSLocalizedStringFromTable(@"_error_folder_destiny_is_the_same_", @"Error", nil);
  426. } else if (error.code == OCErrorMovingDestinyNameHaveForbiddenCharacters) {
  427. message = NSLocalizedStringFromTable(@"_forbidden_characters_from_server_", @"Error", nil);
  428. } else {
  429. message = NSLocalizedStringFromTable(@"_unknow_response_server_", @"Error", nil);
  430. }
  431. if ([self.delegate respondsToSelector:@selector(moveFileOrFolderFailure:message:errorCode:)])
  432. [self.delegate moveFileOrFolderFailure:_metadataNet message:message errorCode:error.code];
  433. [self complete];
  434. }];
  435. }
  436. #pragma --------------------------------------------------------------------------------------------
  437. #pragma mark ===== ReadFile =====
  438. #pragma --------------------------------------------------------------------------------------------
  439. - (void)readFile
  440. {
  441. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  442. NSString *fileName;
  443. if (_metadataNet.fileName)
  444. fileName = [NSString stringWithFormat:@"%@/%@", _metadataNet.serverUrl, _metadataNet.fileName];
  445. else
  446. fileName = _metadataNet.serverUrl;
  447. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  448. [communication setUserAgent:[CCUtility getUserAgent:_typeCloud]];
  449. [communication readFile:fileName onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  450. TableAccount *recordAccount = [CCCoreData getActiveAccount];
  451. if ([recordAccount.account isEqualToString:_metadataNet.account] && [items count] > 0) {
  452. CCMetadata *metadata = [[CCMetadata alloc] init];
  453. OCFileDto *itemDto = [items objectAtIndex:0];
  454. itemDto.fileName = _metadataNet.fileName;
  455. NSString *directoryID = [CCCoreData getDirectoryIDFromServerUrl:_metadataNet.serverUrl activeAccount:_metadataNet.account];
  456. NSString *cameraFolderName = [CCCoreData getCameraUploadFolderNameActiveAccount:_metadataNet.account];
  457. NSString *cameraFolderPath = [CCCoreData getCameraUploadFolderPathActiveAccount:_metadataNet.account activeUrl:_activeUrl typeCloud:_typeCloud];
  458. NSString *directoryUser = [CCUtility getDirectoryActiveUser:_activeUser activeUrl:_activeUrl];
  459. metadata = [CCUtility trasformedOCFileToCCMetadata:itemDto fileNamePrint:_metadataNet.fileNamePrint serverUrl:_metadataNet.serverUrl directoryID:directoryID cameraFolderName:cameraFolderName cameraFolderPath:cameraFolderPath activeAccount:_metadataNet.account directoryUser:directoryUser typeCloud:_typeCloud];
  460. #ifndef EXTENSION
  461. NSString *home = [CCUtility getHomeServerUrlActiveUrl:_activeUrl typeCloud:_typeCloud];
  462. if ([home isEqualToString:fileName]) {
  463. app.quotaUsed = itemDto.quotaUsed;
  464. app.quotaAvailable = itemDto.quotaAvailable;
  465. }
  466. #endif
  467. if([self.delegate respondsToSelector:@selector(readFileSuccess:metadata:)])
  468. [self.delegate readFileSuccess:_metadataNet metadata:metadata];
  469. }
  470. // BUG 1038
  471. if ([items count] == 0) {
  472. #ifndef EXTENSION
  473. [app messageNotification:@"Server error" description:@"Read File WebDAV : [items NULL] please fix" visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeError];
  474. #endif
  475. }
  476. [self complete];
  477. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  478. TableAccount *recordAccount = [CCCoreData getActiveAccount];
  479. _metadataNet.errorRetry++;
  480. NSInteger errorCode = response.statusCode;
  481. if (errorCode == 0)
  482. errorCode = error.code;
  483. if([self.delegate respondsToSelector:@selector(readFileFailure:message:errorCode:)] && [recordAccount.account isEqualToString:_metadataNet.account])
  484. [self.delegate readFileFailure:_metadataNet message:[CCError manageErrorOC:response.statusCode error:error] errorCode:errorCode];
  485. // Request trusted certificated
  486. if ([error code] == NSURLErrorServerCertificateUntrusted)
  487. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  488. [self complete];
  489. }];
  490. }
  491. - (NSError *)readFileSync:(NSString *)filePathName
  492. {
  493. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  494. __block NSError *returnError;
  495. dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
  496. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  497. [communication setUserAgent:[CCUtility getUserAgent:_typeCloud]];
  498. [communication readFile:filePathName onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  499. returnError = nil;
  500. dispatch_semaphore_signal(semaphore);
  501. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  502. // Request trusted certificated
  503. if ([error code] == NSURLErrorServerCertificateUntrusted)
  504. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  505. returnError = error;
  506. dispatch_semaphore_signal(semaphore);
  507. }];
  508. while (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_NOW))
  509. [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:k_timeout_webdav]];
  510. return returnError;
  511. }
  512. #pragma --------------------------------------------------------------------------------------------
  513. #pragma mark ===== Shared =====
  514. #pragma --------------------------------------------------------------------------------------------
  515. - (NSMutableDictionary *)getShareID
  516. {
  517. #ifndef EXTENSION
  518. return app.sharesID;
  519. #endif
  520. return [NSMutableDictionary new];
  521. }
  522. - (void)readShareServer
  523. {
  524. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  525. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  526. [communication setUserAgent:[CCUtility getUserAgent:_typeCloud]];
  527. [communication readSharedByServer:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  528. BOOL openWindow = NO;
  529. [[self getShareID] removeAllObjects];
  530. TableAccount *recordAccount = [CCCoreData getActiveAccount];
  531. if ([recordAccount.account isEqualToString:_metadataNet.account]) {
  532. for (OCSharedDto *item in items)
  533. [[self getShareID] setObject:item forKey:[@(item.idRemoteShared) stringValue]];
  534. if ([_metadataNet.selector isEqual:selectorOpenWindowShare]) openWindow = YES;
  535. if ([_metadataNet.action isEqual:actionUpdateShare]) openWindow = YES;
  536. if ([_metadataNet.action isEqual:actionShare]) openWindow = YES;
  537. if ([_metadataNet.action isEqual:actionShareWith]) openWindow = YES;
  538. }
  539. if([self.delegate respondsToSelector:@selector(readSharedSuccess:items:openWindow:)])
  540. [self.delegate readSharedSuccess:_metadataNet items:[self getShareID] openWindow:openWindow];
  541. [self complete];
  542. } failureRequest :^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  543. NSInteger errorCode = response.statusCode;
  544. if (errorCode == 0)
  545. errorCode = error.code;
  546. if([self.delegate respondsToSelector:@selector(shareFailure:message:errorCode:)])
  547. [self.delegate shareFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  548. // Request trusted certificated
  549. if ([error code] == NSURLErrorServerCertificateUntrusted)
  550. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  551. [self complete];
  552. }];
  553. }
  554. - (void)share
  555. {
  556. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  557. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  558. [communication setUserAgent:[CCUtility getUserAgent:_typeCloud]];
  559. [communication shareFileOrFolderByServer:[_activeUrl stringByAppendingString:@"/"] andFileOrFolderPath:[_metadataNet.fileName encodeString:NSUTF8StringEncoding] andPassword:[_metadataNet.password encodeString:NSUTF8StringEncoding] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *token, NSString *redirectedServer) {
  560. [self readShareServer];
  561. } failureRequest :^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  562. NSInteger errorCode = response.statusCode;
  563. if (errorCode == 0)
  564. errorCode = error.code;
  565. if([self.delegate respondsToSelector:@selector(shareFailure:message:errorCode:)])
  566. [self.delegate shareFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  567. // Request trusted certificated
  568. if ([error code] == NSURLErrorServerCertificateUntrusted)
  569. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  570. [self complete];
  571. }];
  572. }
  573. // * @param shareeType -> NSInteger: to set the type of sharee (user/group/federated)
  574. - (void)shareWith
  575. {
  576. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  577. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  578. [communication setUserAgent:[CCUtility getUserAgent:_typeCloud]];
  579. [communication shareWith:_metadataNet.share shareeType:_metadataNet.shareeType inServer:[_activeUrl stringByAppendingString:@"/"] andFileOrFolderPath:[_metadataNet.fileName encodeString:NSUTF8StringEncoding] andPermissions:_metadataNet.sharePermission onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  580. [self readShareServer];
  581. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  582. NSInteger errorCode = response.statusCode;
  583. if (errorCode == 0)
  584. errorCode = error.code;
  585. if([self.delegate respondsToSelector:@selector(shareFailure:message:errorCode:)])
  586. [self.delegate shareFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  587. // Request trusted certificated
  588. if ([error code] == NSURLErrorServerCertificateUntrusted)
  589. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  590. [self complete];
  591. }];
  592. }
  593. - (void)updateShare
  594. {
  595. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  596. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  597. [communication setUserAgent:[CCUtility getUserAgent:_typeCloud]];
  598. [communication updateShare:[_metadataNet.share intValue] ofServerPath:[_activeUrl stringByAppendingString:@"/"] withPasswordProtect:[_metadataNet.password encodeString:NSUTF8StringEncoding] andExpirationTime:_metadataNet.expirationTime andPermissions:_metadataNet.sharePermission onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  599. [self readShareServer];
  600. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  601. #ifndef EXTENSION
  602. [app messageNotification:@"_error_" description:[CCError manageErrorOC:response.statusCode error:error] visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeError];
  603. #endif
  604. NSInteger errorCode = response.statusCode;
  605. if (errorCode == 0)
  606. errorCode = error.code;
  607. if([self.delegate respondsToSelector:@selector(shareFailure:message:errorCode:)])
  608. [self.delegate shareFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  609. // Request trusted certificated
  610. if ([error code] == NSURLErrorServerCertificateUntrusted)
  611. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  612. [self complete];
  613. }];
  614. }
  615. - (void)unShare
  616. {
  617. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  618. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  619. [communication setUserAgent:[CCUtility getUserAgent:_typeCloud]];
  620. [communication unShareFileOrFolderByServer:[_activeUrl stringByAppendingString:@"/"] andIdRemoteShared:[_metadataNet.share intValue] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  621. if([self.delegate respondsToSelector:@selector(unShareSuccess:)])
  622. [self.delegate unShareSuccess:_metadataNet];
  623. [self complete];
  624. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  625. #ifndef EXTENSION
  626. [app messageNotification:@"_error_" description:[CCError manageErrorOC:response.statusCode error:error] visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeError];
  627. #endif
  628. NSInteger errorCode = response.statusCode;
  629. if (errorCode == 0)
  630. errorCode = error.code;
  631. if([self.delegate respondsToSelector:@selector(shareFailure:message:errorCode:)])
  632. [self.delegate shareFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  633. // Request trusted certificated
  634. if ([error code] == NSURLErrorServerCertificateUntrusted)
  635. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  636. [self complete];
  637. }];
  638. }
  639. - (void)getUserAndGroup
  640. {
  641. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  642. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  643. [communication setUserAgent:[CCUtility getUserAgent:_typeCloud]];
  644. [communication searchUsersAndGroupsWith:_metadataNet.options forPage:1 with:50 ofServer:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *itemList, NSString *redirectedServer) {
  645. if([self.delegate respondsToSelector:@selector(getUserAndGroupSuccess:items:)])
  646. [self.delegate getUserAndGroupSuccess:_metadataNet items:itemList];
  647. [self complete];
  648. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  649. NSInteger errorCode = response.statusCode;
  650. if (errorCode == 0)
  651. errorCode = error.code;
  652. if([self.delegate respondsToSelector:@selector(getUserAndGroupFailure:message:errorCode:)])
  653. [self.delegate getUserAndGroupFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  654. // Request trusted certificated
  655. if ([error code] == NSURLErrorServerCertificateUntrusted)
  656. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  657. [self complete];
  658. }];
  659. }
  660. #pragma --------------------------------------------------------------------------------------------
  661. #pragma mark ===== Notification =====
  662. #pragma --------------------------------------------------------------------------------------------
  663. - (void)getNotificationsOfServer
  664. {
  665. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  666. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  667. [communication setUserAgent:[CCUtility getUserAgent:_typeCloud]];
  668. [communication getNotificationsOfServer:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfNotifications, NSString *redirectedServer) {
  669. if ([self.delegate respondsToSelector:@selector(getNotificationsOfServerSuccess:)])
  670. [self.delegate getNotificationsOfServerSuccess:listOfNotifications];
  671. [self complete];
  672. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  673. NSInteger errorCode = response.statusCode;
  674. if (errorCode == 0)
  675. errorCode = error.code;
  676. if([self.delegate respondsToSelector:@selector(getNotificationsOfServerFailure:message:errorCode:)])
  677. [self.delegate getNotificationsOfServerFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  678. // Request trusted certificated
  679. if ([error code] == NSURLErrorServerCertificateUntrusted)
  680. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  681. [self complete];
  682. }];
  683. }
  684. - (void)setNotificationServer
  685. {
  686. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  687. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  688. [communication setUserAgent:[CCUtility getUserAgent:_typeCloud]];
  689. NSString *type = _metadataNet.options;
  690. [communication setNotificationServer:_metadataNet.serverUrl type:type onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  691. if ([self.delegate respondsToSelector:@selector(setNotificationServerSuccess:)])
  692. [self.delegate setNotificationServerSuccess:_metadataNet];
  693. [self complete];
  694. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  695. NSInteger errorCode = response.statusCode;
  696. if (errorCode == 0)
  697. errorCode = error.code;
  698. if([self.delegate respondsToSelector:@selector(setNotificationServerFailure:message:errorCode:)])
  699. [self.delegate setNotificationServerFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  700. // Request trusted certificated
  701. if ([error code] == NSURLErrorServerCertificateUntrusted)
  702. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  703. [self complete];
  704. }];
  705. }
  706. #pragma --------------------------------------------------------------------------------------------
  707. #pragma mark ===== Server =====
  708. #pragma --------------------------------------------------------------------------------------------
  709. - (NSError *)checkServerSync:(NSString *)serverUrl
  710. {
  711. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  712. __block NSError *returnError;
  713. dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
  714. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  715. [communication setUserAgent:[CCUtility getUserAgent:_typeCloud]];
  716. [communication checkServer:serverUrl onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  717. returnError = nil;
  718. dispatch_semaphore_signal(semaphore);
  719. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  720. // Request trusted certificated
  721. if ([error code] == NSURLErrorServerCertificateUntrusted)
  722. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  723. returnError = error;
  724. dispatch_semaphore_signal(semaphore);
  725. }];
  726. while (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_NOW))
  727. [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:k_timeout_webdav]];
  728. return returnError;
  729. }
  730. - (void)getFeaturesSupportedByServer
  731. {
  732. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  733. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  734. [communication setUserAgent:[CCUtility getUserAgent:_typeCloud]];
  735. [communication getFeaturesSupportedByServer:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, BOOL hasShareSupport, BOOL hasShareeSupport, BOOL hasCookiesSupport, BOOL hasForbiddenCharactersSupport, BOOL hasCapabilitiesSupport, BOOL hasFedSharesOptionShareSupport, NSString *redirectedServer) {
  736. TableAccount *recordAccount = [CCCoreData getActiveAccount];
  737. if ([self.delegate respondsToSelector:@selector(getFeaturesSupportedByServerSuccess:hasForbiddenCharactersSupport:hasShareSupport:hasShareeSupport:)] && [recordAccount.account isEqualToString:_metadataNet.account])
  738. [self.delegate getFeaturesSupportedByServerSuccess:hasCapabilitiesSupport hasForbiddenCharactersSupport:hasForbiddenCharactersSupport hasShareSupport:hasShareSupport hasShareeSupport:hasShareeSupport];
  739. [self complete];
  740. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  741. NSInteger errorCode = response.statusCode;
  742. if (errorCode == 0)
  743. errorCode = error.code;
  744. if([self.delegate respondsToSelector:@selector(getInfoServerFailure:message:errorCode:)])
  745. [self.delegate getInfoServerFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  746. // Request trusted certificated
  747. if ([error code] == NSURLErrorServerCertificateUntrusted)
  748. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  749. [self complete];
  750. }];
  751. }
  752. - (void)getCapabilitiesOfServer
  753. {
  754. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  755. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  756. [communication setUserAgent:[CCUtility getUserAgent:_typeCloud]];
  757. [communication getCapabilitiesOfServer:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, OCCapabilities *capabilities, NSString *redirectedServer) {
  758. TableAccount *recordAccount = [CCCoreData getActiveAccount];
  759. if ([self.delegate respondsToSelector:@selector(getCapabilitiesOfServerSuccess:)] && [recordAccount.account isEqualToString:_metadataNet.account])
  760. [self.delegate getCapabilitiesOfServerSuccess:capabilities];
  761. [self complete];
  762. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  763. NSInteger errorCode = response.statusCode;
  764. if (errorCode == 0)
  765. errorCode = error.code;
  766. if([self.delegate respondsToSelector:@selector(getInfoServerFailure:message:errorCode:)])
  767. [self.delegate getInfoServerFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  768. // Request trusted certificated
  769. if ([error code] == NSURLErrorServerCertificateUntrusted)
  770. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  771. [self complete];
  772. }];
  773. }
  774. @end
  775. #pragma --------------------------------------------------------------------------------------------
  776. #pragma mark ===== OCURLSessionManager =====
  777. #pragma --------------------------------------------------------------------------------------------
  778. @implementation OCURLSessionManager
  779. - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
  780. {
  781. // The pinnning check
  782. if ([[CCCertificate sharedManager] checkTrustedChallenge:challenge]) {
  783. completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  784. } else {
  785. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  786. }
  787. }
  788. @end