OCNetworking.m 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445
  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. NSURLSessionDownloadTask *_downloadTask;
  35. NSURLSessionUploadTask *_uploadTask;
  36. BOOL _isCryptoCloudMode;
  37. BOOL _hasServerForbiddenCharactersSupport;
  38. }
  39. @end
  40. @implementation OCnetworking
  41. - (id)initWithDelegate:(id <OCNetworkingDelegate>)delegate metadataNet:(CCMetadataNet *)metadataNet withUser:(NSString *)withUser withPassword:(NSString *)withPassword withUrl:(NSString *)withUrl isCryptoCloudMode:(BOOL)isCryptoCloudMode
  42. {
  43. self = [super init];
  44. if (self) {
  45. _delegate = delegate;
  46. _metadataNet = [CCMetadataNet new];
  47. _metadataNet = [metadataNet copy];
  48. _activeUser = withUser;
  49. _activePassword = withPassword;
  50. _activeUrl = withUrl;
  51. _isCryptoCloudMode = isCryptoCloudMode;
  52. }
  53. return self;
  54. }
  55. - (void)start
  56. {
  57. if (![NSThread isMainThread]) {
  58. [self performSelectorOnMainThread:@selector(start) withObject:nil waitUntilDone:NO];
  59. return;
  60. }
  61. [self willChangeValueForKey:@"isExecuting"];
  62. _isExecuting = YES;
  63. [self didChangeValueForKey:@"isExecuting"];
  64. if (self.isCancelled) {
  65. [self finish];
  66. } else {
  67. [self poolNetworking];
  68. }
  69. }
  70. - (void)finish
  71. {
  72. [self willChangeValueForKey:@"isExecuting"];
  73. [self willChangeValueForKey:@"isFinished"];
  74. _isExecuting = NO;
  75. _isFinished = YES;
  76. [self didChangeValueForKey:@"isExecuting"];
  77. [self didChangeValueForKey:@"isFinished"];
  78. }
  79. - (void)cancel
  80. {
  81. if (_isExecuting) {
  82. if (_downloadTask)
  83. [_downloadTask cancel];
  84. if (_uploadTask)
  85. [_uploadTask cancel];
  86. [self complete];
  87. }
  88. [super cancel];
  89. }
  90. - (void)poolNetworking
  91. {
  92. #ifndef EXTENSION
  93. _hasServerForbiddenCharactersSupport = app.hasServerForbiddenCharactersSupport;
  94. [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
  95. #else
  96. _hasServerForbiddenCharactersSupport = YES;
  97. #endif
  98. if([self respondsToSelector:NSSelectorFromString(_metadataNet.action)])
  99. [self performSelector:NSSelectorFromString(_metadataNet.action)];
  100. // Add Activity LOG
  101. if ([_metadataNet.selector length] > 0) {
  102. OCActivity *activity = [OCActivity new];
  103. NSString *file, *subject;
  104. if ([_metadataNet.fileName length] > 0) {
  105. file = [NSString stringWithFormat:@"%@/%@", _metadataNet.serverUrl, _metadataNet.fileName];
  106. subject = [CCUtility returnFileNamePathFromFileName:_metadataNet.fileName serverUrl:_metadataNet.serverUrl activeUrl:_activeUrl];
  107. } else {
  108. file = _metadataNet.serverUrl;
  109. subject = [CCUtility returnFileNamePathFromFileName:@"" serverUrl:_metadataNet.serverUrl activeUrl:_activeUrl];
  110. }
  111. activity.idActivity = 0;
  112. activity.date = [NSDate date];
  113. activity.file = file;
  114. activity.subject = [NSString stringWithFormat:@"%@ : %@",_metadataNet.selector, subject] ;
  115. activity.type = _metadataNet.action;
  116. [CCCoreData addActivity:activity account:_metadataNet.account];
  117. }
  118. }
  119. #pragma --------------------------------------------------------------------------------------------
  120. #pragma mark ===== Delegate =====
  121. #pragma --------------------------------------------------------------------------------------------
  122. - (void)complete
  123. {
  124. [self finish];
  125. #ifndef EXTENSION
  126. [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
  127. #endif
  128. }
  129. #pragma --------------------------------------------------------------------------------------------
  130. #pragma mark ===== downloadFile =====
  131. #pragma --------------------------------------------------------------------------------------------
  132. - (void)downloadFile
  133. {
  134. [[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];
  135. }
  136. - (void)downloadTaskSave:(NSURLSessionDownloadTask *)downloadTask
  137. {
  138. _downloadTask= downloadTask;
  139. if ([self.delegate respondsToSelector:@selector(downloadTaskSave:)])
  140. [self.delegate downloadTaskSave:downloadTask];
  141. }
  142. - (void)downloadFileSuccess:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  143. {
  144. [self complete];
  145. if ([self.delegate respondsToSelector:@selector(downloadFileSuccess:serverUrl:selector:selectorPost:)])
  146. [self.delegate downloadFileSuccess:fileID serverUrl:serverUrl selector:selector selectorPost:selectorPost];
  147. }
  148. - (void)downloadFileFailure:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  149. {
  150. [self complete];
  151. if ([self.delegate respondsToSelector:@selector(downloadFileFailure:serverUrl:selector:message:errorCode:)])
  152. [self.delegate downloadFileFailure:fileID serverUrl:serverUrl selector:selector message:message errorCode:errorCode];
  153. }
  154. #pragma --------------------------------------------------------------------------------------------
  155. #pragma mark ===== uploadFile =====
  156. #pragma --------------------------------------------------------------------------------------------
  157. - (void)uploadFile
  158. {
  159. [[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 errorCode:_metadataNet.errorCode delegate:self];
  160. }
  161. - (void)uploadOnlyPlist
  162. {
  163. [[CCNetworking sharedNetworking] uploadFile:_metadataNet.fileName serverUrl:_metadataNet.serverUrl cryptated:YES onlyPlist:YES session:_metadataNet.session taskStatus:_metadataNet.taskStatus selector:_metadataNet.selector selectorPost:_metadataNet.selectorPost errorCode:_metadataNet.errorCode delegate:self];
  164. }
  165. - (void)uploadAsset
  166. {
  167. [[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 errorCode:_metadataNet.errorCode delegate:self];
  168. }
  169. - (void)uploadTemplate
  170. {
  171. [[CCNetworking sharedNetworking] uploadTemplate:_metadataNet.fileNamePrint fileNameCrypto:_metadataNet.fileName serverUrl:_metadataNet.serverUrl session:_metadataNet.session taskStatus:_metadataNet.taskStatus selector:_metadataNet.selector selectorPost:_metadataNet.selectorPost errorCode:_metadataNet.errorCode delegate:self];
  172. }
  173. - (void)uploadTaskSave:(NSURLSessionUploadTask *)uploadTask
  174. {
  175. _uploadTask = uploadTask;
  176. if ([self.delegate respondsToSelector:@selector(uploadTaskSave:)])
  177. [self.delegate uploadTaskSave:uploadTask];
  178. }
  179. - (void)uploadFileSuccess:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  180. {
  181. [self complete];
  182. if ([self.delegate respondsToSelector:@selector(uploadFileSuccess:fileID:serverUrl:selector:selectorPost:)])
  183. [self.delegate uploadFileSuccess:_metadataNet fileID:fileID serverUrl:serverUrl selector:selector selectorPost:selectorPost];
  184. }
  185. - (void)uploadFileFailure:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  186. {
  187. [self complete];
  188. if ([self.delegate respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  189. [self.delegate uploadFileFailure:_metadataNet fileID:fileID serverUrl:serverUrl selector:selector message:message errorCode:errorCode];
  190. }
  191. #pragma --------------------------------------------------------------------------------------------
  192. #pragma mark ===== downloadThumbnail =====
  193. #pragma --------------------------------------------------------------------------------------------
  194. - (void)downloadThumbnail
  195. {
  196. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  197. __block NSString *ext;
  198. NSInteger width = 0, height = 0;
  199. NSString *directoryUser = [CCUtility getDirectoryActiveUser:_activeUser activeUrl:_activeUrl];
  200. NSString *dimOfThumbnail = (NSString *)_metadataNet.options;
  201. if ([dimOfThumbnail.lowercaseString isEqualToString:@"xs"]) { width = 32; height = 32; ext = @"ico"; }
  202. else if ([dimOfThumbnail.lowercaseString isEqualToString:@"s"]) { width = 64; height = 64; ext = @"ico"; }
  203. else if ([dimOfThumbnail.lowercaseString isEqualToString:@"m"]) { width = 128; height = 128; ext = @"ico"; }
  204. else if ([dimOfThumbnail.lowercaseString isEqualToString:@"l"]) { width = 640; height = 640; ext = @"pvw"; }
  205. else if ([dimOfThumbnail.lowercaseString isEqualToString:@"xl"]) { width = 1024; height = 1024; ext = @"pvw"; }
  206. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.%@", directoryUser, _metadataNet.fileNameLocal, ext]]) {
  207. [self.delegate downloadThumbnailSuccess:_metadataNet];
  208. [self complete];
  209. return;
  210. }
  211. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  212. [communication setUserAgent:[CCUtility getUserAgent]];
  213. [communication getRemoteThumbnailByServer:[_activeUrl stringByAppendingString:@"/"] ofFilePath:_metadataNet.fileName withWidth:width andHeight:height onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSData *thumbnail, NSString *redirectedServer) {
  214. TableAccount *recordAccount = [CCCoreData getActiveAccount];
  215. if ([recordAccount.account isEqualToString:_metadataNet.account] && [thumbnail length] > 0) {
  216. UIImage *thumbnailImage = [UIImage imageWithData:thumbnail];
  217. NSString *directoryUser = [CCUtility getDirectoryActiveUser:_activeUser activeUrl:_activeUrl];
  218. [CCGraphics saveIcoWithFileID:_metadataNet.fileNameLocal image:thumbnailImage writeToFile:[NSString stringWithFormat:@"%@/%@.%@", directoryUser, _metadataNet.fileNameLocal, ext] copy:NO move:NO fromPath:nil toPath:nil];
  219. if ([self.delegate respondsToSelector:@selector(downloadThumbnailSuccess:)] && [_metadataNet.action isEqualToString:actionDownloadThumbnail])
  220. [self.delegate downloadThumbnailSuccess:_metadataNet];
  221. } else {
  222. if ([self.delegate respondsToSelector:@selector(downloadThumbnailFailure:message:errorCode:)] && [_metadataNet.action isEqualToString:actionDownloadThumbnail])
  223. [self.delegate downloadThumbnailFailure:_metadataNet message:@"No data" errorCode:0];
  224. }
  225. [self complete];
  226. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  227. NSInteger errorCode = response.statusCode;
  228. if (errorCode == 0)
  229. errorCode = error.code;
  230. if ([self.delegate respondsToSelector:@selector(downloadThumbnailFailure:message:errorCode:)] && [_metadataNet.action isEqualToString:actionDownloadThumbnail])
  231. [self.delegate downloadThumbnailFailure:_metadataNet message:[CCError manageErrorOC:response.statusCode error:error] errorCode:errorCode];
  232. [self complete];
  233. }];
  234. }
  235. #pragma --------------------------------------------------------------------------------------------
  236. #pragma mark ===== Read Folder =====
  237. #pragma --------------------------------------------------------------------------------------------
  238. - (void)readFolder
  239. {
  240. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  241. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  242. [communication setUserAgent:[CCUtility getUserAgent]];
  243. [communication readFolder:_metadataNet.serverUrl withUserSessionToken:nil onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer, NSString *token) {
  244. NSMutableArray *metadatas = [NSMutableArray new];
  245. // Check items > 0
  246. if ([items count] == 0) {
  247. #ifndef EXTENSION
  248. [app messageNotification:@"Server error" description:@"Read Folder WebDAV : [items NULL] please fix" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  249. #endif
  250. dispatch_async(dispatch_get_main_queue(), ^{
  251. if ([self.delegate respondsToSelector:@selector(readFolderSuccess:permissions:etag:metadatas:)])
  252. [self.delegate readFolderSuccess:_metadataNet permissions:@"" etag:@"" metadatas:metadatas];
  253. });
  254. [self complete];
  255. return;
  256. }
  257. // directory [0]
  258. OCFileDto *itemDtoDirectory = [items objectAtIndex:0];
  259. NSString *permissions = itemDtoDirectory.permissions;
  260. NSString *etagDirectory = itemDtoDirectory.etag;
  261. //NSDate *date = [NSDate dateWithTimeIntervalSince1970:itemDtoDirectory.date];
  262. NSString *directoryID = [CCCoreData addDirectory:_metadataNet.serverUrl permissions:permissions activeAccount:_metadataNet.account];
  263. NSString *cameraFolderName = [CCCoreData getCameraUploadFolderNameActiveAccount:_metadataNet.account];
  264. NSString *cameraFolderPath = [CCCoreData getCameraUploadFolderPathActiveAccount:_metadataNet.account activeUrl:_activeUrl];
  265. NSString *directoryUser = [CCUtility getDirectoryActiveUser:_activeUser activeUrl:_activeUrl];
  266. // Update metadataNet.directoryID
  267. _metadataNet.directoryID = directoryID;
  268. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  269. NSArray *itemsSortedArray = [items sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
  270. NSString *first = [(OCFileDto*)a fileName];
  271. NSString *second = [(OCFileDto*)b fileName];
  272. return [[first lowercaseString] compare:[second lowercaseString]];
  273. }];
  274. for (NSUInteger i=1; i < [itemsSortedArray count]; i++) {
  275. OCFileDto *itemDto = [itemsSortedArray objectAtIndex:i];
  276. itemDto.fileName = [itemDto.fileName stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  277. // Not in Crypto Cloud Mode skip File Crypto
  278. if (_isCryptoCloudMode == NO) {
  279. NSString *fileName = itemDto.fileName;
  280. if (itemDto.isDirectory) {
  281. fileName = [fileName substringToIndex:[fileName length] - 1];
  282. NSString *serverUrl = [CCUtility stringAppendServerUrl:_metadataNet.serverUrl addFileName:fileName];
  283. [CCCoreData addDirectory:serverUrl permissions:nil activeAccount:_metadataNet.account];
  284. }
  285. if ([CCUtility isFileCryptated:fileName])
  286. continue;
  287. }
  288. // ----- BUG #942 ---------
  289. if ([itemDto.etag length] == 0) {
  290. #ifndef EXTENSION
  291. [app messageNotification:@"Server error" description:@"Metadata etag absent, record excluded, please fix" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  292. #endif
  293. continue;
  294. }
  295. // ------------------------
  296. [metadatas addObject:[CCUtility trasformedOCFileToCCMetadata:itemDto fileNamePrint:itemDto.fileName serverUrl:_metadataNet.serverUrl directoryID:directoryID cameraFolderName:cameraFolderName cameraFolderPath:cameraFolderPath activeAccount:_metadataNet.account directoryUser:directoryUser]];
  297. }
  298. dispatch_async(dispatch_get_main_queue(), ^{
  299. if ([self.delegate respondsToSelector:@selector(readFolderSuccess:permissions:etag:metadatas:)])
  300. [self.delegate readFolderSuccess:_metadataNet permissions:permissions etag:etagDirectory metadatas:metadatas];
  301. });
  302. });
  303. [self complete];
  304. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) {
  305. NSInteger errorCode = response.statusCode;
  306. if (errorCode == 0)
  307. errorCode = error.code;
  308. if ([self.delegate respondsToSelector:@selector(readFolderFailure:message:errorCode:)])
  309. [self.delegate readFolderFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  310. // Request trusted certificated
  311. if ([error code] == NSURLErrorServerCertificateUntrusted)
  312. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  313. [self complete];
  314. }];
  315. }
  316. #pragma --------------------------------------------------------------------------------------------
  317. #pragma mark ===== Search =====
  318. #pragma --------------------------------------------------------------------------------------------
  319. - (void)search
  320. {
  321. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  322. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  323. [communication setUserAgent:[CCUtility getUserAgent]];
  324. NSString *path = [_activeUrl stringByAppendingString:dav];
  325. NSString *folder = [_metadataNet.serverUrl stringByReplacingOccurrencesOfString:[CCUtility getHomeServerUrlActiveUrl:_activeUrl] withString:@""];
  326. [communication search:path folder:folder fileName:_metadataNet.fileName depth:_metadataNet.options withUserSessionToken:nil onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer, NSString *token) {
  327. NSMutableArray *metadatas = [NSMutableArray new];
  328. NSString *cameraFolderName = [CCCoreData getCameraUploadFolderNameActiveAccount:_metadataNet.account];
  329. NSString *cameraFolderPath = [CCCoreData getCameraUploadFolderPathActiveAccount:_metadataNet.account activeUrl:_activeUrl];
  330. NSString *directoryUser = [CCUtility getDirectoryActiveUser:_activeUser activeUrl:_activeUrl];
  331. for(OCFileDto *itemDto in items) {
  332. itemDto.fileName = [itemDto.fileName stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  333. // Not in Crypto Cloud file
  334. NSString *fileName = itemDto.fileName;
  335. if (itemDto.isDirectory)
  336. fileName = [fileName substringToIndex:[fileName length] - 1];
  337. if ([CCUtility isFileCryptated:fileName])
  338. continue;
  339. // ----- BUG #942 ---------
  340. if ([itemDto.etag length] == 0) {
  341. #ifndef EXTENSION
  342. [app messageNotification:@"Server error" description:@"Metadata etag absent, record excluded, please fix" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  343. #endif
  344. continue;
  345. }
  346. // ------------------------
  347. NSString *serverUrl = [NSString stringWithFormat:@"%@/files/%@", dav, _activeUser];
  348. serverUrl = [itemDto.filePath stringByReplacingOccurrencesOfString:serverUrl withString:@""];
  349. /* TRIM */
  350. if ([serverUrl hasPrefix:@"/"])
  351. serverUrl = [serverUrl substringFromIndex:1];
  352. if ([serverUrl hasSuffix:@"/"])
  353. serverUrl = [serverUrl substringToIndex:[serverUrl length] - 1];
  354. /* */
  355. serverUrl = [CCUtility stringAppendServerUrl:[_activeUrl stringByAppendingString:webDAV] addFileName:serverUrl];
  356. NSString *directoryID = [CCCoreData addDirectory:serverUrl permissions:itemDto.permissions activeAccount:_metadataNet.account];
  357. [metadatas addObject:[CCUtility trasformedOCFileToCCMetadata:itemDto fileNamePrint:itemDto.fileName serverUrl:serverUrl directoryID:directoryID cameraFolderName:cameraFolderName cameraFolderPath:cameraFolderPath activeAccount:_metadataNet.account directoryUser:directoryUser]];
  358. }
  359. if ([self.delegate respondsToSelector:@selector(searchSuccess:metadatas:)])
  360. [self.delegate searchSuccess:_metadataNet metadatas:metadatas];
  361. [self complete];
  362. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) {
  363. NSInteger errorCode = response.statusCode;
  364. if (errorCode == 0)
  365. errorCode = error.code;
  366. if ([self.delegate respondsToSelector:@selector(searchFailure:message:errorCode:)])
  367. [self.delegate searchFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  368. // Request trusted certificated
  369. if ([error code] == NSURLErrorServerCertificateUntrusted)
  370. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  371. [self complete];
  372. }];
  373. }
  374. #pragma --------------------------------------------------------------------------------------------
  375. #pragma mark ===== Setting Favorite =====
  376. #pragma --------------------------------------------------------------------------------------------
  377. - (void)settingFavorite
  378. {
  379. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  380. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  381. [communication setUserAgent:[CCUtility getUserAgent]];
  382. NSString *path = [_activeUrl stringByAppendingString:dav];
  383. [communication settingFavoriteServer:path andFileOrFolderPath:_metadataNet.fileName favorite:[_metadataNet.options boolValue] withUserSessionToken:nil onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer, NSString *token) {
  384. if ([self.delegate respondsToSelector:@selector(settingFavoriteSuccess:)])
  385. [self.delegate settingFavoriteSuccess:_metadataNet];
  386. [self complete];
  387. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) {
  388. NSInteger errorCode = response.statusCode;
  389. if (errorCode == 0)
  390. errorCode = error.code;
  391. if ([self.delegate respondsToSelector:@selector(settingFavoriteFailure:message:errorCode:)])
  392. [self.delegate settingFavoriteFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  393. // Request trusted certificated
  394. if ([error code] == NSURLErrorServerCertificateUntrusted)
  395. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  396. [self complete];
  397. }];
  398. }
  399. #pragma --------------------------------------------------------------------------------------------
  400. #pragma mark ===== Listing Favorites =====
  401. #pragma --------------------------------------------------------------------------------------------
  402. - (void)listingFavorites
  403. {
  404. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  405. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  406. [communication setUserAgent:[CCUtility getUserAgent]];
  407. NSString *path = [_activeUrl stringByAppendingString:dav];
  408. NSString *folder = [_metadataNet.serverUrl stringByReplacingOccurrencesOfString:[CCUtility getHomeServerUrlActiveUrl:_activeUrl] withString:@""];
  409. [communication listingFavorites:path folder:folder withUserSessionToken:nil onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer, NSString *token) {
  410. NSMutableArray *metadatas = [NSMutableArray new];
  411. NSString *cameraFolderName = [CCCoreData getCameraUploadFolderNameActiveAccount:_metadataNet.account];
  412. NSString *cameraFolderPath = [CCCoreData getCameraUploadFolderPathActiveAccount:_metadataNet.account activeUrl:_activeUrl];
  413. NSString *directoryUser = [CCUtility getDirectoryActiveUser:_activeUser activeUrl:_activeUrl];
  414. // Order by fileNamePath
  415. items = [items sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
  416. OCFileDto *record1 = obj1, *record2 = obj2;
  417. NSString *path1 = [[record1.filePath stringByAppendingString:record1.fileName] lowercaseString];
  418. NSString *path2 = [[record2.filePath stringByAppendingString:record2.fileName] lowercaseString];
  419. return [path1 compare:path2];
  420. }];
  421. for(OCFileDto *itemDto in items) {
  422. itemDto.fileName = [itemDto.fileName stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  423. itemDto.filePath = [itemDto.filePath stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  424. // Not in Crypto Cloud file
  425. NSString *fileName = itemDto.fileName;
  426. if (itemDto.isDirectory)
  427. fileName = [fileName substringToIndex:[fileName length] - 1];
  428. if ([CCUtility isFileCryptated:fileName])
  429. continue;
  430. // ----- BUG #942 ---------
  431. if ([itemDto.etag length] == 0) {
  432. #ifndef EXTENSION
  433. [app messageNotification:@"Server error" description:@"Metadata etag absent, record excluded, please fix" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  434. #endif
  435. continue;
  436. }
  437. // ------------------------
  438. NSString *serverUrl = [NSString stringWithFormat:@"%@/files/%@", dav, _activeUser];
  439. serverUrl = [itemDto.filePath stringByReplacingOccurrencesOfString:serverUrl withString:@""];
  440. /* TRIM */
  441. if ([serverUrl hasPrefix:@"/"])
  442. serverUrl = [serverUrl substringFromIndex:1];
  443. if ([serverUrl hasSuffix:@"/"])
  444. serverUrl = [serverUrl substringToIndex:[serverUrl length] - 1];
  445. /* */
  446. serverUrl = [CCUtility stringAppendServerUrl:[_activeUrl stringByAppendingString:webDAV] addFileName:serverUrl];
  447. NSString *directoryID = [CCCoreData addDirectory:serverUrl permissions:itemDto.permissions activeAccount:_metadataNet.account];
  448. [metadatas addObject:[CCUtility trasformedOCFileToCCMetadata:itemDto fileNamePrint:itemDto.fileName serverUrl:serverUrl directoryID:directoryID cameraFolderName:cameraFolderName cameraFolderPath:cameraFolderPath activeAccount:_metadataNet.account directoryUser:directoryUser]];
  449. }
  450. if ([self.delegate respondsToSelector:@selector(listingFavoritesSuccess:metadatas:)])
  451. [self.delegate listingFavoritesSuccess:_metadataNet metadatas:metadatas];
  452. [self complete];
  453. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) {
  454. NSInteger errorCode = response.statusCode;
  455. if (errorCode == 0)
  456. errorCode = error.code;
  457. if ([self.delegate respondsToSelector:@selector(listingFavoritesFailure:message:errorCode:)])
  458. [self.delegate listingFavoritesFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  459. // Request trusted certificated
  460. if ([error code] == NSURLErrorServerCertificateUntrusted)
  461. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  462. [self complete];
  463. }];
  464. }
  465. #pragma --------------------------------------------------------------------------------------------
  466. #pragma mark ===== Create Folder =====
  467. #pragma --------------------------------------------------------------------------------------------
  468. - (void)createFolder
  469. {
  470. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  471. NSString *nameFolderURL = [NSString stringWithFormat:@"%@/%@", _metadataNet.serverUrl, _metadataNet.fileName];
  472. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  473. [communication setUserAgent:[CCUtility getUserAgent]];
  474. [communication createFolder:nameFolderURL onCommunication:communication withForbiddenCharactersSupported:_hasServerForbiddenCharactersSupport successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  475. if ([self.delegate respondsToSelector:@selector(createFolderSuccess:)])
  476. [self.delegate createFolderSuccess:_metadataNet];
  477. [self complete];
  478. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  479. NSString *message;
  480. if (([_metadataNet.fileName isEqualToString:[CCCoreData getCameraUploadFolderNameActiveAccount:_metadataNet.account]] == YES && [_metadataNet.serverUrl isEqualToString:[CCCoreData getCameraUploadFolderPathActiveAccount:_metadataNet.account activeUrl:_activeUrl]] == YES))
  481. message = nil;
  482. else
  483. message = [CCError manageErrorOC:response.statusCode error:error];
  484. NSInteger errorCode = response.statusCode;
  485. if (errorCode == 0)
  486. errorCode = error.code;
  487. if ([self.delegate respondsToSelector:@selector(createFolderFailure:message:errorCode:)])
  488. [self.delegate createFolderFailure:_metadataNet message:message errorCode:errorCode];
  489. // Request trusted certificated
  490. if ([error code] == NSURLErrorServerCertificateUntrusted)
  491. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  492. [self complete];
  493. } errorBeforeRequest:^(NSError *error) {
  494. NSString *message;
  495. if (([_metadataNet.fileName isEqualToString:[CCCoreData getCameraUploadFolderNameActiveAccount:_metadataNet.account]] == YES && [_metadataNet.serverUrl isEqualToString:[CCCoreData getCameraUploadFolderPathActiveAccount:_metadataNet.account activeUrl:_activeUrl]] == YES))
  496. message = nil;
  497. else {
  498. if (error.code == OCErrorForbidenCharacters)
  499. message = NSLocalizedStringFromTable(@"_forbidden_characters_from_server_", @"Error", nil);
  500. else
  501. message = NSLocalizedStringFromTable(@"_unknow_response_server_", @"Error", nil);
  502. }
  503. if ([self.delegate respondsToSelector:@selector(createFolderFailure:message:errorCode:)])
  504. [self.delegate createFolderFailure:_metadataNet message:message errorCode:error.code];
  505. [self complete];
  506. }];
  507. }
  508. #pragma --------------------------------------------------------------------------------------------
  509. #pragma mark ===== Delete =====
  510. #pragma --------------------------------------------------------------------------------------------
  511. - (void)deleteFileOrFolder
  512. {
  513. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  514. NSString *serverFileUrl = [NSString stringWithFormat:@"%@/%@", _metadataNet.serverUrl, _metadataNet.fileName];
  515. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  516. [communication setUserAgent:[CCUtility getUserAgent]];
  517. [communication deleteFileOrFolder:serverFileUrl onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  518. if ([_metadataNet.selector rangeOfString:selectorDelete].location != NSNotFound && [self.delegate respondsToSelector:@selector(deleteFileOrFolderSuccess:)])
  519. [self.delegate deleteFileOrFolderSuccess:_metadataNet];
  520. [self complete];
  521. } failureRquest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  522. NSInteger errorCode = response.statusCode;
  523. if (errorCode == 0)
  524. errorCode = error.code;
  525. if ([self.delegate respondsToSelector:@selector(deleteFileOrFolderFailure:message:errorCode:)])
  526. [self.delegate deleteFileOrFolderFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  527. // Request trusted certificated
  528. if ([error code] == NSURLErrorServerCertificateUntrusted)
  529. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  530. [self complete];
  531. }];
  532. }
  533. #pragma --------------------------------------------------------------------------------------------
  534. #pragma mark ===== Move =====
  535. #pragma --------------------------------------------------------------------------------------------
  536. - (void)moveFileOrFolder
  537. {
  538. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  539. NSString *origineURL = [NSString stringWithFormat:@"%@/%@", _metadataNet.serverUrl, _metadataNet.fileName];
  540. NSString *destinazioneURL = [NSString stringWithFormat:@"%@/%@", _metadataNet.serverUrlTo, _metadataNet.fileNameTo];
  541. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  542. [communication setUserAgent:[CCUtility getUserAgent]];
  543. [communication moveFileOrFolder:origineURL toDestiny:destinazioneURL onCommunication:communication withForbiddenCharactersSupported:_hasServerForbiddenCharactersSupport successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  544. if ([_metadataNet.selector isEqualToString:selectorRename] && [self.delegate respondsToSelector:@selector(renameSuccess:)])
  545. [self.delegate renameSuccess:_metadataNet];
  546. if ([_metadataNet.selector rangeOfString:selectorMove].location != NSNotFound && [self.delegate respondsToSelector:@selector(moveSuccess:revTo:)])
  547. [self.delegate moveSuccess:_metadataNet revTo:nil];
  548. [self complete];
  549. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  550. NSInteger errorCode = response.statusCode;
  551. if (errorCode == 0)
  552. errorCode = error.code;
  553. if ([self.delegate respondsToSelector:@selector(renameMoveFileOrFolderFailure:message:errorCode:)])
  554. [self.delegate renameMoveFileOrFolderFailure:_metadataNet message:[CCError manageErrorOC:response.statusCode error:error] errorCode:errorCode];
  555. // Request trusted certificated
  556. if ([error code] == NSURLErrorServerCertificateUntrusted)
  557. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  558. [self complete];
  559. } errorBeforeRequest:^(NSError *error) {
  560. NSString *message;
  561. if (error.code == OCErrorMovingTheDestinyAndOriginAreTheSame) {
  562. message = NSLocalizedStringFromTable(@"_error_folder_destiny_is_the_same_", @"Error", nil);
  563. } else if (error.code == OCErrorMovingFolderInsideHimself) {
  564. message = NSLocalizedStringFromTable(@"_error_folder_destiny_is_the_same_", @"Error", nil);
  565. } else if (error.code == OCErrorMovingDestinyNameHaveForbiddenCharacters) {
  566. message = NSLocalizedStringFromTable(@"_forbidden_characters_from_server_", @"Error", nil);
  567. } else {
  568. message = NSLocalizedStringFromTable(@"_unknow_response_server_", @"Error", nil);
  569. }
  570. if ([self.delegate respondsToSelector:@selector(renameMoveFileOrFolderFailure:message:errorCode:)])
  571. [self.delegate renameMoveFileOrFolderFailure:_metadataNet message:message errorCode:error.code];
  572. [self complete];
  573. }];
  574. }
  575. #pragma --------------------------------------------------------------------------------------------
  576. #pragma mark ===== ReadFile =====
  577. #pragma --------------------------------------------------------------------------------------------
  578. - (void)readFile
  579. {
  580. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  581. NSString *fileName;
  582. if (_metadataNet.fileName)
  583. fileName = [NSString stringWithFormat:@"%@/%@", _metadataNet.serverUrl, _metadataNet.fileName];
  584. else
  585. fileName = _metadataNet.serverUrl;
  586. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  587. [communication setUserAgent:[CCUtility getUserAgent]];
  588. [communication readFile:fileName onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  589. TableAccount *recordAccount = [CCCoreData getActiveAccount];
  590. if ([recordAccount.account isEqualToString:_metadataNet.account] && [items count] > 0) {
  591. CCMetadata *metadata = [[CCMetadata alloc] init];
  592. OCFileDto *itemDto = [items objectAtIndex:0];
  593. itemDto.fileName = _metadataNet.fileName;
  594. NSString *directoryID = [CCCoreData getDirectoryIDFromServerUrl:_metadataNet.serverUrl activeAccount:_metadataNet.account];
  595. NSString *cameraFolderName = [CCCoreData getCameraUploadFolderNameActiveAccount:_metadataNet.account];
  596. NSString *cameraFolderPath = [CCCoreData getCameraUploadFolderPathActiveAccount:_metadataNet.account activeUrl:_activeUrl];
  597. NSString *directoryUser = [CCUtility getDirectoryActiveUser:_activeUser activeUrl:_activeUrl];
  598. metadata = [CCUtility trasformedOCFileToCCMetadata:itemDto fileNamePrint:_metadataNet.fileNamePrint serverUrl:_metadataNet.serverUrl directoryID:directoryID cameraFolderName:cameraFolderName cameraFolderPath:cameraFolderPath activeAccount:_metadataNet.account directoryUser:directoryUser];
  599. if([self.delegate respondsToSelector:@selector(readFileSuccess:metadata:)])
  600. [self.delegate readFileSuccess:_metadataNet metadata:metadata];
  601. }
  602. // BUG 1038
  603. if ([items count] == 0) {
  604. #ifndef EXTENSION
  605. [app messageNotification:@"Server error" description:@"Read File WebDAV : [items NULL] please fix" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  606. #endif
  607. }
  608. [self complete];
  609. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  610. TableAccount *recordAccount = [CCCoreData getActiveAccount];
  611. _metadataNet.errorRetry++;
  612. NSInteger errorCode = response.statusCode;
  613. if (errorCode == 0)
  614. errorCode = error.code;
  615. if([self.delegate respondsToSelector:@selector(readFileFailure:message:errorCode:)] && [recordAccount.account isEqualToString:_metadataNet.account])
  616. [self.delegate readFileFailure:_metadataNet message:[CCError manageErrorOC:response.statusCode error:error] errorCode:errorCode];
  617. // Request trusted certificated
  618. if ([error code] == NSURLErrorServerCertificateUntrusted)
  619. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  620. [self complete];
  621. }];
  622. }
  623. - (NSError *)readFileSync:(NSString *)filePathName
  624. {
  625. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  626. __block NSError *returnError;
  627. dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
  628. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  629. [communication setUserAgent:[CCUtility getUserAgent]];
  630. [communication readFile:filePathName onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  631. returnError = nil;
  632. dispatch_semaphore_signal(semaphore);
  633. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  634. // Request trusted certificated
  635. if ([error code] == NSURLErrorServerCertificateUntrusted)
  636. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  637. returnError = error;
  638. dispatch_semaphore_signal(semaphore);
  639. }];
  640. while (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_NOW))
  641. [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:k_timeout_webdav]];
  642. return returnError;
  643. }
  644. #pragma --------------------------------------------------------------------------------------------
  645. #pragma mark ===== Shared =====
  646. #pragma --------------------------------------------------------------------------------------------
  647. - (NSMutableDictionary *)getShareID
  648. {
  649. #ifndef EXTENSION
  650. return app.sharesID;
  651. #endif
  652. return [NSMutableDictionary new];
  653. }
  654. - (void)readShareServer
  655. {
  656. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  657. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  658. [communication setUserAgent:[CCUtility getUserAgent]];
  659. [communication readSharedByServer:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  660. BOOL openWindow = NO;
  661. [[self getShareID] removeAllObjects];
  662. TableAccount *recordAccount = [CCCoreData getActiveAccount];
  663. if ([recordAccount.account isEqualToString:_metadataNet.account]) {
  664. for (OCSharedDto *item in items)
  665. [[self getShareID] setObject:item forKey:[@(item.idRemoteShared) stringValue]];
  666. if ([_metadataNet.selector isEqual:selectorOpenWindowShare]) openWindow = YES;
  667. if ([_metadataNet.action isEqual:actionUpdateShare]) openWindow = YES;
  668. if ([_metadataNet.action isEqual:actionShare]) openWindow = YES;
  669. if ([_metadataNet.action isEqual:actionShareWith]) openWindow = YES;
  670. }
  671. if([self.delegate respondsToSelector:@selector(readSharedSuccess:items:openWindow:)])
  672. [self.delegate readSharedSuccess:_metadataNet items:[self getShareID] openWindow:openWindow];
  673. [self complete];
  674. } failureRequest :^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  675. NSInteger errorCode = response.statusCode;
  676. if (errorCode == 0)
  677. errorCode = error.code;
  678. if([self.delegate respondsToSelector:@selector(shareFailure:message:errorCode:)])
  679. [self.delegate shareFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  680. // Request trusted certificated
  681. if ([error code] == NSURLErrorServerCertificateUntrusted)
  682. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  683. [self complete];
  684. }];
  685. }
  686. - (void)share
  687. {
  688. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  689. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  690. [communication setUserAgent:[CCUtility getUserAgent]];
  691. [communication shareFileOrFolderByServer:[_activeUrl stringByAppendingString:@"/"] andFileOrFolderPath:[_metadataNet.fileName encodeString:NSUTF8StringEncoding] andPassword:[_metadataNet.password encodeString:NSUTF8StringEncoding] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *token, NSString *redirectedServer) {
  692. [self readShareServer];
  693. } failureRequest :^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  694. NSInteger errorCode = response.statusCode;
  695. if (errorCode == 0)
  696. errorCode = error.code;
  697. if([self.delegate respondsToSelector:@selector(shareFailure:message:errorCode:)])
  698. [self.delegate shareFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  699. // Request trusted certificated
  700. if ([error code] == NSURLErrorServerCertificateUntrusted)
  701. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  702. [self complete];
  703. }];
  704. }
  705. // * @param shareeType -> NSInteger: to set the type of sharee (user/group/federated)
  706. - (void)shareWith
  707. {
  708. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  709. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  710. [communication setUserAgent:[CCUtility getUserAgent]];
  711. [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) {
  712. [self readShareServer];
  713. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  714. NSInteger errorCode = response.statusCode;
  715. if (errorCode == 0)
  716. errorCode = error.code;
  717. if([self.delegate respondsToSelector:@selector(shareFailure:message:errorCode:)])
  718. [self.delegate shareFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  719. // Request trusted certificated
  720. if ([error code] == NSURLErrorServerCertificateUntrusted)
  721. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  722. [self complete];
  723. }];
  724. }
  725. - (void)updateShare
  726. {
  727. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  728. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  729. [communication setUserAgent:[CCUtility getUserAgent]];
  730. [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) {
  731. [self readShareServer];
  732. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  733. #ifndef EXTENSION
  734. [app messageNotification:@"_error_" description:[CCError manageErrorOC:response.statusCode error:error] visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  735. #endif
  736. NSInteger errorCode = response.statusCode;
  737. if (errorCode == 0)
  738. errorCode = error.code;
  739. if([self.delegate respondsToSelector:@selector(shareFailure:message:errorCode:)])
  740. [self.delegate shareFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  741. // Request trusted certificated
  742. if ([error code] == NSURLErrorServerCertificateUntrusted)
  743. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  744. [self complete];
  745. }];
  746. }
  747. - (void)unShare
  748. {
  749. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  750. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  751. [communication setUserAgent:[CCUtility getUserAgent]];
  752. [communication unShareFileOrFolderByServer:[_activeUrl stringByAppendingString:@"/"] andIdRemoteShared:[_metadataNet.share intValue] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  753. if([self.delegate respondsToSelector:@selector(unShareSuccess:)])
  754. [self.delegate unShareSuccess:_metadataNet];
  755. [self complete];
  756. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  757. #ifndef EXTENSION
  758. [app messageNotification:@"_error_" description:[CCError manageErrorOC:response.statusCode error:error] visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  759. #endif
  760. NSInteger errorCode = response.statusCode;
  761. if (errorCode == 0)
  762. errorCode = error.code;
  763. if([self.delegate respondsToSelector:@selector(shareFailure:message:errorCode:)])
  764. [self.delegate shareFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  765. // Request trusted certificated
  766. if ([error code] == NSURLErrorServerCertificateUntrusted)
  767. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  768. [self complete];
  769. }];
  770. }
  771. - (void)getUserAndGroup
  772. {
  773. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  774. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  775. [communication setUserAgent:[CCUtility getUserAgent]];
  776. [communication searchUsersAndGroupsWith:_metadataNet.options forPage:1 with:50 ofServer:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *itemList, NSString *redirectedServer) {
  777. if([self.delegate respondsToSelector:@selector(getUserAndGroupSuccess:items:)])
  778. [self.delegate getUserAndGroupSuccess:_metadataNet items:itemList];
  779. [self complete];
  780. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  781. NSInteger errorCode = response.statusCode;
  782. if (errorCode == 0)
  783. errorCode = error.code;
  784. if([self.delegate respondsToSelector:@selector(getUserAndGroupFailure:message:errorCode:)])
  785. [self.delegate getUserAndGroupFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  786. // Request trusted certificated
  787. if ([error code] == NSURLErrorServerCertificateUntrusted)
  788. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  789. [self complete];
  790. }];
  791. }
  792. #pragma --------------------------------------------------------------------------------------------
  793. #pragma mark ===== Activity =====
  794. #pragma --------------------------------------------------------------------------------------------
  795. - (void)getActivityServer
  796. {
  797. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  798. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  799. [communication setUserAgent:[CCUtility getUserAgent]];
  800. [communication getActivityServer:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfActivity, NSString *redirectedServer) {
  801. if ([self.delegate respondsToSelector:@selector(getActivityServerSuccess:)])
  802. [self.delegate getActivityServerSuccess:listOfActivity];
  803. [self complete];
  804. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  805. NSInteger errorCode = response.statusCode;
  806. if (errorCode == 0)
  807. errorCode = error.code;
  808. if([self.delegate respondsToSelector:@selector(getActivityServerFailure:message:errorCode:)])
  809. [self.delegate getActivityServerFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  810. // Request trusted certificated
  811. if ([error code] == NSURLErrorServerCertificateUntrusted)
  812. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  813. [self complete];
  814. }];
  815. }
  816. #pragma --------------------------------------------------------------------------------------------
  817. #pragma mark ===== Notification =====
  818. #pragma --------------------------------------------------------------------------------------------
  819. - (void)getNotificationServer
  820. {
  821. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  822. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  823. [communication setUserAgent:[CCUtility getUserAgent]];
  824. [communication getNotificationServer:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfNotifications, NSString *redirectedServer) {
  825. if ([self.delegate respondsToSelector:@selector(getNotificationServerSuccess:)])
  826. [self.delegate getNotificationServerSuccess:listOfNotifications];
  827. [self complete];
  828. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  829. NSInteger errorCode = response.statusCode;
  830. if (errorCode == 0)
  831. errorCode = error.code;
  832. if([self.delegate respondsToSelector:@selector(getNotificationServerFailure:message:errorCode:)])
  833. [self.delegate getNotificationServerFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  834. // Request trusted certificated
  835. if ([error code] == NSURLErrorServerCertificateUntrusted)
  836. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  837. [self complete];
  838. }];
  839. }
  840. - (void)setNotificationServer
  841. {
  842. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  843. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  844. [communication setUserAgent:[CCUtility getUserAgent]];
  845. NSString *type = _metadataNet.options;
  846. [communication setNotificationServer:_metadataNet.serverUrl type:type onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  847. if ([self.delegate respondsToSelector:@selector(setNotificationServerSuccess:)])
  848. [self.delegate setNotificationServerSuccess:_metadataNet];
  849. [self complete];
  850. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  851. NSInteger errorCode = response.statusCode;
  852. if (errorCode == 0)
  853. errorCode = error.code;
  854. if([self.delegate respondsToSelector:@selector(setNotificationServerFailure:message:errorCode:)])
  855. [self.delegate setNotificationServerFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  856. // Request trusted certificated
  857. if ([error code] == NSURLErrorServerCertificateUntrusted)
  858. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  859. [self complete];
  860. }];
  861. }
  862. - (void)subscribingNextcloudServer
  863. {
  864. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  865. communication.kindOfCredential = credentialNotSet;
  866. [communication setUserAgent:[CCUtility getUserAgent]];
  867. NSDictionary *parameter = _metadataNet.options;
  868. NSString *pushToken = [parameter objectForKey:@"pushToken"];
  869. NSString *pushTokenHash = [parameter objectForKey:@"pushTokenHash"];
  870. NSString *devicePublicKey = [parameter objectForKey:@"devicePublicKey"];
  871. [communication subscribingNextcloudServerPush:_activeUrl pushTokenHash:pushTokenHash devicePublicKey:devicePublicKey onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *publicKey, NSString *deviceIdentifier, NSString *signature, NSString *redirectedServer) {
  872. deviceIdentifier = [self URLEncodeStringFromString:deviceIdentifier];
  873. signature = [self URLEncodeStringFromString:signature];
  874. [communication subscribingPushProxy:_push_notification_server_ pushToken:pushToken deviceIdentifier:deviceIdentifier deviceIdentifierSignature:signature userPublicKey:devicePublicKey onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *publicKey, NSString *deviceIdentifier, NSString *signature, NSString *redirectedServer) {
  875. NSLog(@"OK");
  876. [self complete];
  877. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  878. NSLog(@"error");
  879. [self complete];
  880. }];
  881. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  882. NSInteger errorCode = response.statusCode;
  883. if (errorCode == 0)
  884. errorCode = error.code;
  885. // Request trusted certificated
  886. if ([error code] == NSURLErrorServerCertificateUntrusted)
  887. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  888. [self complete];
  889. }];
  890. }
  891. #pragma --------------------------------------------------------------------------------------------
  892. #pragma mark ===== User Profile =====
  893. #pragma --------------------------------------------------------------------------------------------
  894. - (void)getUserProfile
  895. {
  896. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  897. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  898. [communication setUserAgent:[CCUtility getUserAgent]];
  899. [communication getUserProfileServer:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, OCUserProfile *userProfile, NSString *redirectedServer) {
  900. if ([self.delegate respondsToSelector:@selector(getUserProfileSuccess:userProfile:)])
  901. [self.delegate getUserProfileSuccess:_metadataNet userProfile:userProfile];
  902. [self complete];
  903. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  904. NSInteger errorCode = response.statusCode;
  905. if (errorCode == 0)
  906. errorCode = error.code;
  907. if([self.delegate respondsToSelector:@selector(getUserProfileFailure:message:errorCode:)])
  908. [self.delegate getUserProfileFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  909. // Request trusted certificated
  910. if ([error code] == NSURLErrorServerCertificateUntrusted)
  911. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  912. [self complete];
  913. }];
  914. }
  915. #pragma --------------------------------------------------------------------------------------------
  916. #pragma mark ===== Server =====
  917. #pragma --------------------------------------------------------------------------------------------
  918. - (NSError *)checkServerSync:(NSString *)serverUrl
  919. {
  920. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  921. __block NSError *returnError;
  922. dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
  923. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  924. [communication setUserAgent:[CCUtility getUserAgent]];
  925. [communication checkServer:serverUrl onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  926. returnError = nil;
  927. dispatch_semaphore_signal(semaphore);
  928. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  929. // Request trusted certificated
  930. if ([error code] == NSURLErrorServerCertificateUntrusted)
  931. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  932. returnError = error;
  933. dispatch_semaphore_signal(semaphore);
  934. }];
  935. while (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_NOW))
  936. [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:k_timeout_webdav]];
  937. return returnError;
  938. }
  939. - (void)getFeaturesSupportedByServer
  940. {
  941. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  942. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  943. [communication setUserAgent:[CCUtility getUserAgent]];
  944. [communication getFeaturesSupportedByServer:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, BOOL hasShareSupport, BOOL hasShareeSupport, BOOL hasCookiesSupport, BOOL hasForbiddenCharactersSupport, BOOL hasCapabilitiesSupport, BOOL hasFedSharesOptionShareSupport, NSString *redirectedServer) {
  945. TableAccount *recordAccount = [CCCoreData getActiveAccount];
  946. if ([self.delegate respondsToSelector:@selector(getFeaturesSupportedByServerSuccess:hasForbiddenCharactersSupport:hasShareSupport:hasShareeSupport:)] && [recordAccount.account isEqualToString:_metadataNet.account])
  947. [self.delegate getFeaturesSupportedByServerSuccess:hasCapabilitiesSupport hasForbiddenCharactersSupport:hasForbiddenCharactersSupport hasShareSupport:hasShareSupport hasShareeSupport:hasShareeSupport];
  948. [self complete];
  949. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  950. NSInteger errorCode = response.statusCode;
  951. if (errorCode == 0)
  952. errorCode = error.code;
  953. if([self.delegate respondsToSelector:@selector(getInfoServerFailure:message:errorCode:)])
  954. [self.delegate getInfoServerFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  955. // Request trusted certificated
  956. if ([error code] == NSURLErrorServerCertificateUntrusted)
  957. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  958. [self complete];
  959. }];
  960. }
  961. - (void)getCapabilitiesOfServer
  962. {
  963. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  964. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  965. [communication setUserAgent:[CCUtility getUserAgent]];
  966. [communication getCapabilitiesOfServer:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, OCCapabilities *capabilities, NSString *redirectedServer) {
  967. TableAccount *recordAccount = [CCCoreData getActiveAccount];
  968. if ([self.delegate respondsToSelector:@selector(getCapabilitiesOfServerSuccess:)] && [recordAccount.account isEqualToString:_metadataNet.account])
  969. [self.delegate getCapabilitiesOfServerSuccess:capabilities];
  970. [self complete];
  971. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  972. NSInteger errorCode = response.statusCode;
  973. if (errorCode == 0)
  974. errorCode = error.code;
  975. if([self.delegate respondsToSelector:@selector(getInfoServerFailure:message:errorCode:)])
  976. [self.delegate getInfoServerFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  977. // Request trusted certificated
  978. if ([error code] == NSURLErrorServerCertificateUntrusted)
  979. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  980. [self complete];
  981. }];
  982. }
  983. #pragma --------------------------------------------------------------------------------------------
  984. #pragma mark ===== Utility =====
  985. #pragma --------------------------------------------------------------------------------------------
  986. - (NSString *)URLEncodeStringFromString:(NSString *)string
  987. {
  988. static CFStringRef charset = CFSTR("!@#$%&*()+'\";:=,/?[] ");
  989. CFStringRef str = (__bridge CFStringRef)string;
  990. CFStringEncoding encoding = kCFStringEncodingUTF8;
  991. return (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL, str, NULL, charset, encoding));
  992. }
  993. @end
  994. #pragma --------------------------------------------------------------------------------------------
  995. #pragma mark ===== OCURLSessionManager =====
  996. #pragma --------------------------------------------------------------------------------------------
  997. @implementation OCURLSessionManager
  998. - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
  999. {
  1000. // The pinnning check
  1001. if ([[CCCertificate sharedManager] checkTrustedChallenge:challenge]) {
  1002. completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  1003. } else {
  1004. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  1005. }
  1006. }
  1007. @end