OCNetworking.m 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137
  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:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  172. {
  173. [self complete];
  174. if ([self.delegate respondsToSelector:@selector(uploadFileSuccess:fileID:serverUrl:selector:selectorPost:)])
  175. [self.delegate uploadFileSuccess:_metadataNet fileID:fileID serverUrl:serverUrl selector:selector selectorPost:selectorPost];
  176. }
  177. - (void)uploadFileFailure:(CCMetadataNet *)metadataNet fileID:(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:fileID:serverUrl:selector:message:errorCode:)])
  181. [self.delegate uploadFileFailure:_metadataNet fileID: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:k_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 *root = [CCUtility getHomeServerUrlActiveUrl:_activeUrl typeCloud:_typeCloud];
  258. if ([root 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:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  276. #endif
  277. continue;
  278. }
  279. // ------------------------
  280. if ([_metadataNet.selector isEqualToString:selectorSearch] && [itemDto.fileName.lowercaseString hasPrefix:_metadataNet.fileName.lowercaseString] && ![CCUtility isFileCryptated:itemDto.fileName]) {
  281. [metadatas addObject:[CCUtility trasformedOCFileToCCMetadata:itemDto fileNamePrint:itemDto.fileName serverUrl:_metadataNet.serverUrl directoryID:directoryID cameraFolderName:cameraFolderName cameraFolderPath:cameraFolderPath activeAccount:_metadataNet.account directoryUser:directoryUser typeCloud:_typeCloud]];
  282. }
  283. if ([_metadataNet.selector isEqualToString:selectorReadFolder]) {
  284. [metadatas addObject:[CCUtility trasformedOCFileToCCMetadata:itemDto fileNamePrint:itemDto.fileName serverUrl:_metadataNet.serverUrl directoryID:directoryID cameraFolderName:cameraFolderName cameraFolderPath:cameraFolderPath activeAccount:_metadataNet.account directoryUser:directoryUser typeCloud:_typeCloud]];
  285. }
  286. }
  287. dispatch_async(dispatch_get_main_queue(), ^{
  288. if ([_metadataNet.selector isEqualToString:selectorReadFolder] && [self.delegate respondsToSelector:@selector(readFolderSuccess:permissions:rev:metadatas:)])
  289. [self.delegate readFolderSuccess:_metadataNet permissions:permissions rev:rev metadatas:metadatas];
  290. if ([_metadataNet.selector isEqualToString:selectorSearch] && [self.delegate respondsToSelector:@selector(searchSuccess:metadatas:)])
  291. [self.delegate searchSuccess:_metadataNet metadatas:metadatas];
  292. });
  293. });
  294. [self complete];
  295. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) {
  296. NSInteger errorCode = response.statusCode;
  297. if (errorCode == 0)
  298. errorCode = error.code;
  299. if ([_metadataNet.selector isEqualToString:selectorReadFolder] && [self.delegate respondsToSelector:@selector(readFolderFailure:message:errorCode:)])
  300. [self.delegate readFolderFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  301. if ([_metadataNet.selector isEqualToString:selectorSearch] && [self.delegate respondsToSelector:@selector(searchFailure:message:errorCode:)])
  302. [self.delegate searchFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  303. // Request trusted certificated
  304. if ([error code] == NSURLErrorServerCertificateUntrusted)
  305. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  306. [self complete];
  307. }];
  308. }
  309. #pragma --------------------------------------------------------------------------------------------
  310. #pragma mark ===== Create Folder =====
  311. #pragma --------------------------------------------------------------------------------------------
  312. - (void)createFolder
  313. {
  314. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  315. BOOL hasServerForbiddenCharactersSupport;
  316. NSString *nameFolderURL = [NSString stringWithFormat:@"%@/%@", _metadataNet.serverUrl, _metadataNet.fileName];
  317. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  318. [communication setUserAgent:[CCUtility getUserAgent:_typeCloud]];
  319. [communication createFolder:nameFolderURL onCommunication:communication withForbiddenCharactersSupported:hasServerForbiddenCharactersSupport successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  320. if ([self.delegate respondsToSelector:@selector(createFolderSuccess:)])
  321. [self.delegate createFolderSuccess:_metadataNet];
  322. [self complete];
  323. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  324. NSString *message;
  325. if (([_metadataNet.fileName isEqualToString:[CCCoreData getCameraUploadFolderNameActiveAccount:_metadataNet.account]] == YES && [_metadataNet.serverUrl isEqualToString:[CCCoreData getCameraUploadFolderPathActiveAccount:_metadataNet.account activeUrl:_activeUrl typeCloud:_typeCloud]] == YES))
  326. message = nil;
  327. else
  328. message = [CCError manageErrorOC:response.statusCode error:error];
  329. NSInteger errorCode = response.statusCode;
  330. if (errorCode == 0)
  331. errorCode = error.code;
  332. if ([self.delegate respondsToSelector:@selector(createFolderFailure:message:errorCode:)])
  333. [self.delegate createFolderFailure:_metadataNet message:message errorCode:errorCode];
  334. // Request trusted certificated
  335. if ([error code] == NSURLErrorServerCertificateUntrusted)
  336. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  337. [self complete];
  338. } errorBeforeRequest:^(NSError *error) {
  339. NSString *message;
  340. if (([_metadataNet.fileName isEqualToString:[CCCoreData getCameraUploadFolderNameActiveAccount:_metadataNet.account]] == YES && [_metadataNet.serverUrl isEqualToString:[CCCoreData getCameraUploadFolderPathActiveAccount:_metadataNet.account activeUrl:_activeUrl typeCloud:_typeCloud]] == YES))
  341. message = nil;
  342. else {
  343. if (error.code == OCErrorForbidenCharacters)
  344. message = NSLocalizedStringFromTable(@"_forbidden_characters_from_server_", @"Error", nil);
  345. else
  346. message = NSLocalizedStringFromTable(@"_unknow_response_server_", @"Error", nil);
  347. }
  348. if ([self.delegate respondsToSelector:@selector(createFolderFailure:message:errorCode:)])
  349. [self.delegate createFolderFailure:_metadataNet message:message errorCode:error.code];
  350. [self complete];
  351. }];
  352. }
  353. - (NSError *)createFolderSync:(NSString *)folderPathName
  354. {
  355. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  356. BOOL hasServerForbiddenCharactersSupport;
  357. __block NSError *returnError;
  358. dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
  359. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  360. [communication setUserAgent:[CCUtility getUserAgent:_typeCloud]];
  361. [communication createFolder:folderPathName onCommunication:communication withForbiddenCharactersSupported:hasServerForbiddenCharactersSupport successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  362. dispatch_semaphore_signal(semaphore);
  363. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  364. // Request trusted certificated
  365. if ([error code] == NSURLErrorServerCertificateUntrusted)
  366. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  367. returnError = error;
  368. dispatch_semaphore_signal(semaphore);
  369. } errorBeforeRequest:^(NSError *error) {
  370. returnError = error;
  371. dispatch_semaphore_signal(semaphore);
  372. }];
  373. while (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_NOW))
  374. [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:k_timeout_webdav]];
  375. return returnError;
  376. }
  377. #pragma --------------------------------------------------------------------------------------------
  378. #pragma mark ===== Delete =====
  379. #pragma --------------------------------------------------------------------------------------------
  380. - (void)deleteFileOrFolder
  381. {
  382. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  383. NSString *serverFileUrl = [NSString stringWithFormat:@"%@/%@", _metadataNet.serverUrl, _metadataNet.fileName];
  384. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  385. [communication setUserAgent:[CCUtility getUserAgent:_typeCloud]];
  386. [communication deleteFileOrFolder:serverFileUrl onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  387. if ([_metadataNet.selector rangeOfString:selectorDelete].location != NSNotFound && [self.delegate respondsToSelector:@selector(deleteFileOrFolderSuccess:)])
  388. [self.delegate deleteFileOrFolderSuccess:_metadataNet];
  389. [self complete];
  390. } failureRquest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  391. NSInteger errorCode = response.statusCode;
  392. if (errorCode == 0)
  393. errorCode = error.code;
  394. if ([self.delegate respondsToSelector:@selector(deleteFileOrFolderFailure:message:errorCode:)])
  395. [self.delegate deleteFileOrFolderFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  396. // Request trusted certificated
  397. if ([error code] == NSURLErrorServerCertificateUntrusted)
  398. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  399. [self complete];
  400. }];
  401. }
  402. #pragma --------------------------------------------------------------------------------------------
  403. #pragma mark ===== Move =====
  404. #pragma --------------------------------------------------------------------------------------------
  405. - (void)moveFileOrFolder
  406. {
  407. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  408. BOOL hasServerForbiddenCharactersSupport;
  409. NSString *origineURL = [NSString stringWithFormat:@"%@/%@", _metadataNet.serverUrl, _metadataNet.fileName];
  410. NSString *destinazioneURL = [NSString stringWithFormat:@"%@/%@", _metadataNet.serverUrlTo, _metadataNet.fileNameTo];
  411. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  412. [communication setUserAgent:[CCUtility getUserAgent:_typeCloud]];
  413. [communication moveFileOrFolder:origineURL toDestiny:destinazioneURL onCommunication:communication withForbiddenCharactersSupported:hasServerForbiddenCharactersSupport successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  414. if ([_metadataNet.selector isEqualToString:selectorRename] && [self.delegate respondsToSelector:@selector(renameSuccess:)])
  415. [self.delegate renameSuccess:_metadataNet];
  416. if ([_metadataNet.selector rangeOfString:selectorMove].location != NSNotFound && [self.delegate respondsToSelector:@selector(moveSuccess:revTo:)])
  417. [self.delegate moveSuccess:_metadataNet revTo:nil];
  418. [self complete];
  419. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  420. NSInteger errorCode = response.statusCode;
  421. if (errorCode == 0)
  422. errorCode = error.code;
  423. if ([self.delegate respondsToSelector:@selector(renameMoveFileOrFolderFailure:message:errorCode:)])
  424. [self.delegate renameMoveFileOrFolderFailure:_metadataNet message:[CCError manageErrorOC:response.statusCode error:error] errorCode:errorCode];
  425. // Request trusted certificated
  426. if ([error code] == NSURLErrorServerCertificateUntrusted)
  427. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  428. [self complete];
  429. } errorBeforeRequest:^(NSError *error) {
  430. NSString *message;
  431. if (error.code == OCErrorMovingTheDestinyAndOriginAreTheSame) {
  432. message = NSLocalizedStringFromTable(@"_error_folder_destiny_is_the_same_", @"Error", nil);
  433. } else if (error.code == OCErrorMovingFolderInsideHimself) {
  434. message = NSLocalizedStringFromTable(@"_error_folder_destiny_is_the_same_", @"Error", nil);
  435. } else if (error.code == OCErrorMovingDestinyNameHaveForbiddenCharacters) {
  436. message = NSLocalizedStringFromTable(@"_forbidden_characters_from_server_", @"Error", nil);
  437. } else {
  438. message = NSLocalizedStringFromTable(@"_unknow_response_server_", @"Error", nil);
  439. }
  440. if ([self.delegate respondsToSelector:@selector(renameMoveFileOrFolderFailure:message:errorCode:)])
  441. [self.delegate renameMoveFileOrFolderFailure:_metadataNet message:message errorCode:error.code];
  442. [self complete];
  443. }];
  444. }
  445. #pragma --------------------------------------------------------------------------------------------
  446. #pragma mark ===== ReadFile =====
  447. #pragma --------------------------------------------------------------------------------------------
  448. - (void)readFile
  449. {
  450. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  451. NSString *fileName;
  452. if (_metadataNet.fileName)
  453. fileName = [NSString stringWithFormat:@"%@/%@", _metadataNet.serverUrl, _metadataNet.fileName];
  454. else
  455. fileName = _metadataNet.serverUrl;
  456. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  457. [communication setUserAgent:[CCUtility getUserAgent:_typeCloud]];
  458. [communication readFile:fileName onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  459. TableAccount *recordAccount = [CCCoreData getActiveAccount];
  460. if ([recordAccount.account isEqualToString:_metadataNet.account] && [items count] > 0) {
  461. CCMetadata *metadata = [[CCMetadata alloc] init];
  462. OCFileDto *itemDto = [items objectAtIndex:0];
  463. itemDto.fileName = _metadataNet.fileName;
  464. NSString *directoryID = [CCCoreData getDirectoryIDFromServerUrl:_metadataNet.serverUrl activeAccount:_metadataNet.account];
  465. NSString *cameraFolderName = [CCCoreData getCameraUploadFolderNameActiveAccount:_metadataNet.account];
  466. NSString *cameraFolderPath = [CCCoreData getCameraUploadFolderPathActiveAccount:_metadataNet.account activeUrl:_activeUrl typeCloud:_typeCloud];
  467. NSString *directoryUser = [CCUtility getDirectoryActiveUser:_activeUser activeUrl:_activeUrl];
  468. metadata = [CCUtility trasformedOCFileToCCMetadata:itemDto fileNamePrint:_metadataNet.fileNamePrint serverUrl:_metadataNet.serverUrl directoryID:directoryID cameraFolderName:cameraFolderName cameraFolderPath:cameraFolderPath activeAccount:_metadataNet.account directoryUser:directoryUser typeCloud:_typeCloud];
  469. #ifndef EXTENSION
  470. NSString *root = [CCUtility getHomeServerUrlActiveUrl:_activeUrl typeCloud:_typeCloud];
  471. if ([root isEqualToString:fileName]) {
  472. app.quotaUsed = itemDto.quotaUsed;
  473. app.quotaAvailable = itemDto.quotaAvailable;
  474. }
  475. #endif
  476. if([self.delegate respondsToSelector:@selector(readFileSuccess:metadata:)])
  477. [self.delegate readFileSuccess:_metadataNet metadata:metadata];
  478. }
  479. // BUG 1038
  480. if ([items count] == 0) {
  481. #ifndef EXTENSION
  482. [app messageNotification:@"Server error" description:@"Read File WebDAV : [items NULL] please fix" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  483. #endif
  484. }
  485. [self complete];
  486. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  487. TableAccount *recordAccount = [CCCoreData getActiveAccount];
  488. _metadataNet.errorRetry++;
  489. NSInteger errorCode = response.statusCode;
  490. if (errorCode == 0)
  491. errorCode = error.code;
  492. if([self.delegate respondsToSelector:@selector(readFileFailure:message:errorCode:)] && [recordAccount.account isEqualToString:_metadataNet.account])
  493. [self.delegate readFileFailure:_metadataNet message:[CCError manageErrorOC:response.statusCode error:error] errorCode:errorCode];
  494. // Request trusted certificated
  495. if ([error code] == NSURLErrorServerCertificateUntrusted)
  496. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  497. [self complete];
  498. }];
  499. }
  500. - (NSError *)readFileSync:(NSString *)filePathName
  501. {
  502. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  503. __block NSError *returnError;
  504. dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
  505. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  506. [communication setUserAgent:[CCUtility getUserAgent:_typeCloud]];
  507. [communication readFile:filePathName onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  508. returnError = nil;
  509. dispatch_semaphore_signal(semaphore);
  510. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  511. // Request trusted certificated
  512. if ([error code] == NSURLErrorServerCertificateUntrusted)
  513. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  514. returnError = error;
  515. dispatch_semaphore_signal(semaphore);
  516. }];
  517. while (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_NOW))
  518. [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:k_timeout_webdav]];
  519. return returnError;
  520. }
  521. #pragma --------------------------------------------------------------------------------------------
  522. #pragma mark ===== Shared =====
  523. #pragma --------------------------------------------------------------------------------------------
  524. - (NSMutableDictionary *)getShareID
  525. {
  526. #ifndef EXTENSION
  527. return app.sharesID;
  528. #endif
  529. return [NSMutableDictionary new];
  530. }
  531. - (void)readShareServer
  532. {
  533. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  534. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  535. [communication setUserAgent:[CCUtility getUserAgent:_typeCloud]];
  536. [communication readSharedByServer:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  537. BOOL openWindow = NO;
  538. [[self getShareID] removeAllObjects];
  539. TableAccount *recordAccount = [CCCoreData getActiveAccount];
  540. if ([recordAccount.account isEqualToString:_metadataNet.account]) {
  541. for (OCSharedDto *item in items)
  542. [[self getShareID] setObject:item forKey:[@(item.idRemoteShared) stringValue]];
  543. if ([_metadataNet.selector isEqual:selectorOpenWindowShare]) openWindow = YES;
  544. if ([_metadataNet.action isEqual:actionUpdateShare]) openWindow = YES;
  545. if ([_metadataNet.action isEqual:actionShare]) openWindow = YES;
  546. if ([_metadataNet.action isEqual:actionShareWith]) openWindow = YES;
  547. }
  548. if([self.delegate respondsToSelector:@selector(readSharedSuccess:items:openWindow:)])
  549. [self.delegate readSharedSuccess:_metadataNet items:[self getShareID] openWindow:openWindow];
  550. [self complete];
  551. } failureRequest :^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  552. NSInteger errorCode = response.statusCode;
  553. if (errorCode == 0)
  554. errorCode = error.code;
  555. if([self.delegate respondsToSelector:@selector(shareFailure:message:errorCode:)])
  556. [self.delegate shareFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  557. // Request trusted certificated
  558. if ([error code] == NSURLErrorServerCertificateUntrusted)
  559. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  560. [self complete];
  561. }];
  562. }
  563. - (void)share
  564. {
  565. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  566. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  567. [communication setUserAgent:[CCUtility getUserAgent:_typeCloud]];
  568. [communication shareFileOrFolderByServer:[_activeUrl stringByAppendingString:@"/"] andFileOrFolderPath:[_metadataNet.fileName encodeString:NSUTF8StringEncoding] andPassword:[_metadataNet.password encodeString:NSUTF8StringEncoding] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *token, NSString *redirectedServer) {
  569. [self readShareServer];
  570. } failureRequest :^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  571. NSInteger errorCode = response.statusCode;
  572. if (errorCode == 0)
  573. errorCode = error.code;
  574. if([self.delegate respondsToSelector:@selector(shareFailure:message:errorCode:)])
  575. [self.delegate shareFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  576. // Request trusted certificated
  577. if ([error code] == NSURLErrorServerCertificateUntrusted)
  578. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  579. [self complete];
  580. }];
  581. }
  582. // * @param shareeType -> NSInteger: to set the type of sharee (user/group/federated)
  583. - (void)shareWith
  584. {
  585. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  586. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  587. [communication setUserAgent:[CCUtility getUserAgent:_typeCloud]];
  588. [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) {
  589. [self readShareServer];
  590. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  591. NSInteger errorCode = response.statusCode;
  592. if (errorCode == 0)
  593. errorCode = error.code;
  594. if([self.delegate respondsToSelector:@selector(shareFailure:message:errorCode:)])
  595. [self.delegate shareFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  596. // Request trusted certificated
  597. if ([error code] == NSURLErrorServerCertificateUntrusted)
  598. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  599. [self complete];
  600. }];
  601. }
  602. - (void)updateShare
  603. {
  604. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  605. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  606. [communication setUserAgent:[CCUtility getUserAgent:_typeCloud]];
  607. [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) {
  608. [self readShareServer];
  609. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  610. #ifndef EXTENSION
  611. [app messageNotification:@"_error_" description:[CCError manageErrorOC:response.statusCode error:error] visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  612. #endif
  613. NSInteger errorCode = response.statusCode;
  614. if (errorCode == 0)
  615. errorCode = error.code;
  616. if([self.delegate respondsToSelector:@selector(shareFailure:message:errorCode:)])
  617. [self.delegate shareFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  618. // Request trusted certificated
  619. if ([error code] == NSURLErrorServerCertificateUntrusted)
  620. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  621. [self complete];
  622. }];
  623. }
  624. - (void)unShare
  625. {
  626. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  627. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  628. [communication setUserAgent:[CCUtility getUserAgent:_typeCloud]];
  629. [communication unShareFileOrFolderByServer:[_activeUrl stringByAppendingString:@"/"] andIdRemoteShared:[_metadataNet.share intValue] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  630. if([self.delegate respondsToSelector:@selector(unShareSuccess:)])
  631. [self.delegate unShareSuccess:_metadataNet];
  632. [self complete];
  633. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  634. #ifndef EXTENSION
  635. [app messageNotification:@"_error_" description:[CCError manageErrorOC:response.statusCode error:error] visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  636. #endif
  637. NSInteger errorCode = response.statusCode;
  638. if (errorCode == 0)
  639. errorCode = error.code;
  640. if([self.delegate respondsToSelector:@selector(shareFailure:message:errorCode:)])
  641. [self.delegate shareFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  642. // Request trusted certificated
  643. if ([error code] == NSURLErrorServerCertificateUntrusted)
  644. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  645. [self complete];
  646. }];
  647. }
  648. - (void)getUserAndGroup
  649. {
  650. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  651. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  652. [communication setUserAgent:[CCUtility getUserAgent:_typeCloud]];
  653. [communication searchUsersAndGroupsWith:_metadataNet.options forPage:1 with:50 ofServer:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *itemList, NSString *redirectedServer) {
  654. if([self.delegate respondsToSelector:@selector(getUserAndGroupSuccess:items:)])
  655. [self.delegate getUserAndGroupSuccess:_metadataNet items:itemList];
  656. [self complete];
  657. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  658. NSInteger errorCode = response.statusCode;
  659. if (errorCode == 0)
  660. errorCode = error.code;
  661. if([self.delegate respondsToSelector:@selector(getUserAndGroupFailure:message:errorCode:)])
  662. [self.delegate getUserAndGroupFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  663. // Request trusted certificated
  664. if ([error code] == NSURLErrorServerCertificateUntrusted)
  665. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  666. [self complete];
  667. }];
  668. }
  669. #pragma --------------------------------------------------------------------------------------------
  670. #pragma mark ===== Notification =====
  671. #pragma --------------------------------------------------------------------------------------------
  672. - (void)getNotificationsOfServer
  673. {
  674. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  675. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  676. [communication setUserAgent:[CCUtility getUserAgent:_typeCloud]];
  677. [communication getNotificationsOfServer:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfNotifications, NSString *redirectedServer) {
  678. if ([self.delegate respondsToSelector:@selector(getNotificationsOfServerSuccess:)])
  679. [self.delegate getNotificationsOfServerSuccess:listOfNotifications];
  680. [self complete];
  681. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  682. NSInteger errorCode = response.statusCode;
  683. if (errorCode == 0)
  684. errorCode = error.code;
  685. if([self.delegate respondsToSelector:@selector(getNotificationsOfServerFailure:message:errorCode:)])
  686. [self.delegate getNotificationsOfServerFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  687. // Request trusted certificated
  688. if ([error code] == NSURLErrorServerCertificateUntrusted)
  689. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  690. [self complete];
  691. }];
  692. }
  693. - (void)setNotificationServer
  694. {
  695. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  696. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  697. [communication setUserAgent:[CCUtility getUserAgent:_typeCloud]];
  698. NSString *type = _metadataNet.options;
  699. [communication setNotificationServer:_metadataNet.serverUrl type:type onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  700. if ([self.delegate respondsToSelector:@selector(setNotificationServerSuccess:)])
  701. [self.delegate setNotificationServerSuccess:_metadataNet];
  702. [self complete];
  703. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  704. NSInteger errorCode = response.statusCode;
  705. if (errorCode == 0)
  706. errorCode = error.code;
  707. if([self.delegate respondsToSelector:@selector(setNotificationServerFailure:message:errorCode:)])
  708. [self.delegate setNotificationServerFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  709. // Request trusted certificated
  710. if ([error code] == NSURLErrorServerCertificateUntrusted)
  711. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  712. [self complete];
  713. }];
  714. }
  715. #pragma --------------------------------------------------------------------------------------------
  716. #pragma mark ===== Server =====
  717. #pragma --------------------------------------------------------------------------------------------
  718. - (NSError *)checkServerSync:(NSString *)serverUrl
  719. {
  720. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  721. __block NSError *returnError;
  722. dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
  723. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  724. [communication setUserAgent:[CCUtility getUserAgent:_typeCloud]];
  725. [communication checkServer:serverUrl onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  726. returnError = nil;
  727. dispatch_semaphore_signal(semaphore);
  728. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  729. // Request trusted certificated
  730. if ([error code] == NSURLErrorServerCertificateUntrusted)
  731. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  732. returnError = error;
  733. dispatch_semaphore_signal(semaphore);
  734. }];
  735. while (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_NOW))
  736. [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:k_timeout_webdav]];
  737. return returnError;
  738. }
  739. - (void)getFeaturesSupportedByServer
  740. {
  741. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  742. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  743. [communication setUserAgent:[CCUtility getUserAgent:_typeCloud]];
  744. [communication getFeaturesSupportedByServer:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, BOOL hasShareSupport, BOOL hasShareeSupport, BOOL hasCookiesSupport, BOOL hasForbiddenCharactersSupport, BOOL hasCapabilitiesSupport, BOOL hasFedSharesOptionShareSupport, NSString *redirectedServer) {
  745. TableAccount *recordAccount = [CCCoreData getActiveAccount];
  746. if ([self.delegate respondsToSelector:@selector(getFeaturesSupportedByServerSuccess:hasForbiddenCharactersSupport:hasShareSupport:hasShareeSupport:)] && [recordAccount.account isEqualToString:_metadataNet.account])
  747. [self.delegate getFeaturesSupportedByServerSuccess:hasCapabilitiesSupport hasForbiddenCharactersSupport:hasForbiddenCharactersSupport hasShareSupport:hasShareSupport hasShareeSupport:hasShareeSupport];
  748. [self complete];
  749. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  750. NSInteger errorCode = response.statusCode;
  751. if (errorCode == 0)
  752. errorCode = error.code;
  753. if([self.delegate respondsToSelector:@selector(getInfoServerFailure:message:errorCode:)])
  754. [self.delegate getInfoServerFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  755. // Request trusted certificated
  756. if ([error code] == NSURLErrorServerCertificateUntrusted)
  757. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  758. [self complete];
  759. }];
  760. }
  761. - (void)getCapabilitiesOfServer
  762. {
  763. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  764. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  765. [communication setUserAgent:[CCUtility getUserAgent:_typeCloud]];
  766. [communication getCapabilitiesOfServer:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, OCCapabilities *capabilities, NSString *redirectedServer) {
  767. TableAccount *recordAccount = [CCCoreData getActiveAccount];
  768. if ([self.delegate respondsToSelector:@selector(getCapabilitiesOfServerSuccess:)] && [recordAccount.account isEqualToString:_metadataNet.account])
  769. [self.delegate getCapabilitiesOfServerSuccess:capabilities];
  770. [self complete];
  771. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  772. NSInteger errorCode = response.statusCode;
  773. if (errorCode == 0)
  774. errorCode = error.code;
  775. if([self.delegate respondsToSelector:@selector(getInfoServerFailure:message:errorCode:)])
  776. [self.delegate getInfoServerFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  777. // Request trusted certificated
  778. if ([error code] == NSURLErrorServerCertificateUntrusted)
  779. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  780. [self complete];
  781. }];
  782. }
  783. @end
  784. #pragma --------------------------------------------------------------------------------------------
  785. #pragma mark ===== OCURLSessionManager =====
  786. #pragma --------------------------------------------------------------------------------------------
  787. @implementation OCURLSessionManager
  788. - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
  789. {
  790. // The pinnning check
  791. if ([[CCCertificate sharedManager] checkTrustedChallenge:challenge]) {
  792. completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  793. } else {
  794. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  795. }
  796. }
  797. @end