OCNetworking.m 64 KB

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