OCNetworking.m 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649
  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. #ifndef EXTENSION
  30. #ifdef CUSTOM_BUILD
  31. #import "CustomSwift.h"
  32. #else
  33. #import "Nextcloud-Swift.h"
  34. #endif
  35. #else
  36. #ifdef EXTENSION_SHARE
  37. #ifdef CUSTOM_BUILD
  38. #import "CustomSwiftShare.h"
  39. #else
  40. #import "Share-Swift.h"
  41. #endif
  42. #endif
  43. #ifdef EXTENSION_PICKER
  44. #ifdef CUSTOM_BUILD
  45. #import "CustomSwiftPick.h"
  46. #else
  47. #import "Picker-Swift.h"
  48. #endif
  49. #endif
  50. #endif
  51. @interface OCnetworking ()
  52. {
  53. NSString *_activeUser;
  54. NSString *_activePassword;
  55. NSString *_activeUrl;
  56. NSURLSessionDownloadTask *_downloadTask;
  57. NSURLSessionUploadTask *_uploadTask;
  58. BOOL _isCryptoCloudMode;
  59. }
  60. @end
  61. @implementation OCnetworking
  62. - (id)initWithDelegate:(id <OCNetworkingDelegate>)delegate metadataNet:(CCMetadataNet *)metadataNet withUser:(NSString *)withUser withPassword:(NSString *)withPassword withUrl:(NSString *)withUrl isCryptoCloudMode:(BOOL)isCryptoCloudMode
  63. {
  64. self = [super init];
  65. if (self) {
  66. _delegate = delegate;
  67. _metadataNet = [CCMetadataNet new];
  68. _metadataNet = [metadataNet copy];
  69. _activeUser = withUser;
  70. _activePassword = withPassword;
  71. _activeUrl = withUrl;
  72. _isCryptoCloudMode = isCryptoCloudMode;
  73. }
  74. return self;
  75. }
  76. - (void)start
  77. {
  78. if (![NSThread isMainThread]) {
  79. [self performSelectorOnMainThread:@selector(start) withObject:nil waitUntilDone:NO];
  80. return;
  81. }
  82. [self willChangeValueForKey:@"isExecuting"];
  83. _isExecuting = YES;
  84. [self didChangeValueForKey:@"isExecuting"];
  85. if (self.isCancelled) {
  86. [self finish];
  87. } else {
  88. [self poolNetworking];
  89. }
  90. }
  91. - (void)finish
  92. {
  93. [self willChangeValueForKey:@"isExecuting"];
  94. [self willChangeValueForKey:@"isFinished"];
  95. _isExecuting = NO;
  96. _isFinished = YES;
  97. [self didChangeValueForKey:@"isExecuting"];
  98. [self didChangeValueForKey:@"isFinished"];
  99. }
  100. - (void)cancel
  101. {
  102. if (_isExecuting) {
  103. if (_downloadTask)
  104. [_downloadTask cancel];
  105. if (_uploadTask)
  106. [_uploadTask cancel];
  107. [self complete];
  108. }
  109. [super cancel];
  110. }
  111. - (void)poolNetworking
  112. {
  113. #ifndef EXTENSION
  114. [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
  115. #endif
  116. if([self respondsToSelector:NSSelectorFromString(_metadataNet.action)])
  117. [self performSelector:NSSelectorFromString(_metadataNet.action)];
  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.assetLocalIdentifier 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. // Error
  231. if ([self.delegate respondsToSelector:@selector(downloadThumbnailFailure:message:errorCode:)] && [_metadataNet.action isEqualToString:actionDownloadThumbnail]) {
  232. if (errorCode == 503)
  233. [self.delegate downloadThumbnailFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  234. else
  235. [self.delegate downloadThumbnailFailure:_metadataNet message:[CCError manageErrorOC:response.statusCode error:error] errorCode:errorCode];
  236. }
  237. [self complete];
  238. }];
  239. }
  240. #pragma --------------------------------------------------------------------------------------------
  241. #pragma mark ===== Read Folder =====
  242. #pragma --------------------------------------------------------------------------------------------
  243. - (void)readFolder
  244. {
  245. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  246. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  247. [communication setUserAgent:[CCUtility getUserAgent]];
  248. [communication readFolder:_metadataNet.serverUrl withUserSessionToken:nil onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer, NSString *token) {
  249. NSMutableArray *metadatas = [NSMutableArray new];
  250. // Check items > 0
  251. if ([items count] == 0) {
  252. #ifndef EXTENSION
  253. [app messageNotification:@"Server error" description:@"Read Folder WebDAV : [items NULL] please fix" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  254. #endif
  255. dispatch_async(dispatch_get_main_queue(), ^{
  256. if ([self.delegate respondsToSelector:@selector(readFolderSuccess:permissions:etag:metadatas:)])
  257. [self.delegate readFolderSuccess:_metadataNet permissions:@"" etag:@"" metadatas:metadatas];
  258. });
  259. [self complete];
  260. return;
  261. }
  262. // directory [0]
  263. OCFileDto *itemDtoDirectory = [items objectAtIndex:0];
  264. NSString *permissions = itemDtoDirectory.permissions;
  265. NSString *etagDirectory = itemDtoDirectory.etag;
  266. //NSDate *date = [NSDate dateWithTimeIntervalSince1970:itemDtoDirectory.date];
  267. NSString *directoryID = [CCCoreData addDirectory:_metadataNet.serverUrl permissions:permissions activeAccount:_metadataNet.account];
  268. NSString *cameraFolderName = [CCCoreData getCameraUploadFolderNameActiveAccount:_metadataNet.account];
  269. NSString *cameraFolderPath = [CCCoreData getCameraUploadFolderPathActiveAccount:_metadataNet.account activeUrl:_activeUrl];
  270. NSString *directoryUser = [CCUtility getDirectoryActiveUser:_activeUser activeUrl:_activeUrl];
  271. // Update metadataNet.directoryID
  272. _metadataNet.directoryID = directoryID;
  273. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  274. NSArray *itemsSortedArray = [items sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
  275. NSString *first = [(OCFileDto*)a fileName];
  276. NSString *second = [(OCFileDto*)b fileName];
  277. return [[first lowercaseString] compare:[second lowercaseString]];
  278. }];
  279. for (NSUInteger i=1; i < [itemsSortedArray count]; i++) {
  280. OCFileDto *itemDto = [itemsSortedArray objectAtIndex:i];
  281. itemDto.fileName = [itemDto.fileName stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  282. // Not in Crypto Cloud Mode skip File Crypto
  283. if (_isCryptoCloudMode == NO) {
  284. NSString *fileName = itemDto.fileName;
  285. if (itemDto.isDirectory) {
  286. fileName = [fileName substringToIndex:[fileName length] - 1];
  287. NSString *serverUrl = [CCUtility stringAppendServerUrl:_metadataNet.serverUrl addFileName:fileName];
  288. dispatch_async(dispatch_get_main_queue(), ^{
  289. [CCCoreData addDirectory:serverUrl permissions:nil activeAccount:_metadataNet.account];
  290. });
  291. }
  292. if ([CCUtility isFileCryptated:fileName])
  293. continue;
  294. }
  295. // ----- BUG #942 ---------
  296. if ([itemDto.etag length] == 0) {
  297. #ifndef EXTENSION
  298. [app messageNotification:@"Server error" description:@"Metadata etag absent, record excluded, please fix" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  299. #endif
  300. continue;
  301. }
  302. // ------------------------
  303. [metadatas addObject:[CCUtility trasformedOCFileToCCMetadata:itemDto fileNamePrint:itemDto.fileName serverUrl:_metadataNet.serverUrl directoryID:directoryID cameraFolderName:cameraFolderName cameraFolderPath:cameraFolderPath activeAccount:_metadataNet.account directoryUser:directoryUser]];
  304. }
  305. dispatch_async(dispatch_get_main_queue(), ^{
  306. if ([self.delegate respondsToSelector:@selector(readFolderSuccess:permissions:etag:metadatas:)])
  307. [self.delegate readFolderSuccess:_metadataNet permissions:permissions etag:etagDirectory metadatas:metadatas];
  308. });
  309. });
  310. [self complete];
  311. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) {
  312. NSInteger errorCode = response.statusCode;
  313. if (errorCode == 0)
  314. errorCode = error.code;
  315. // Error
  316. if ([self.delegate respondsToSelector:@selector(readFolderFailure:message:errorCode:)]) {
  317. if (errorCode == 503)
  318. [self.delegate readFolderFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  319. else
  320. [self.delegate readFolderFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  321. }
  322. // Request trusted certificated
  323. if ([error code] == NSURLErrorServerCertificateUntrusted)
  324. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  325. // Activity
  326. [[NCManageDatabase sharedInstance] addActivityClient:_metadataNet.serverUrl fileID:@"" action:k_activityDebugActionReadFolder selector:@"" note:[error.userInfo valueForKey:@"NSLocalizedDescription"] type:k_activityTypeFailure verbose:k_activityVerboseHigh account:_metadataNet.account activeUrl:_activeUrl];
  327. [self complete];
  328. }];
  329. }
  330. #pragma --------------------------------------------------------------------------------------------
  331. #pragma mark ===== Search =====
  332. #pragma --------------------------------------------------------------------------------------------
  333. - (void)search
  334. {
  335. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  336. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  337. [communication setUserAgent:[CCUtility getUserAgent]];
  338. NSString *path = [_activeUrl stringByAppendingString:dav];
  339. NSString *folder = [_metadataNet.serverUrl stringByReplacingOccurrencesOfString:[CCUtility getHomeServerUrlActiveUrl:_activeUrl] withString:@""];
  340. [communication search:path folder:folder fileName:_metadataNet.fileName depth:_metadataNet.options withUserSessionToken:nil onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer, NSString *token) {
  341. NSMutableArray *metadatas = [NSMutableArray new];
  342. NSString *cameraFolderName = [CCCoreData getCameraUploadFolderNameActiveAccount:_metadataNet.account];
  343. NSString *cameraFolderPath = [CCCoreData getCameraUploadFolderPathActiveAccount:_metadataNet.account activeUrl:_activeUrl];
  344. NSString *directoryUser = [CCUtility getDirectoryActiveUser:_activeUser activeUrl:_activeUrl];
  345. for(OCFileDto *itemDto in items) {
  346. itemDto.fileName = [itemDto.fileName stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  347. // Not in Crypto Cloud file
  348. NSString *fileName = itemDto.fileName;
  349. if (itemDto.isDirectory)
  350. fileName = [fileName substringToIndex:[fileName length] - 1];
  351. if ([CCUtility isFileCryptated:fileName])
  352. continue;
  353. // ----- BUG #942 ---------
  354. if ([itemDto.etag length] == 0) {
  355. #ifndef EXTENSION
  356. [app messageNotification:@"Server error" description:@"Metadata etag absent, record excluded, please fix" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  357. #endif
  358. continue;
  359. }
  360. // ------------------------
  361. NSString *serverUrl = [NSString stringWithFormat:@"%@/files/%@", dav, _activeUser];
  362. serverUrl = [itemDto.filePath stringByReplacingOccurrencesOfString:serverUrl withString:@""];
  363. /* TRIM */
  364. if ([serverUrl hasPrefix:@"/"])
  365. serverUrl = [serverUrl substringFromIndex:1];
  366. if ([serverUrl hasSuffix:@"/"])
  367. serverUrl = [serverUrl substringToIndex:[serverUrl length] - 1];
  368. /* */
  369. serverUrl = [CCUtility stringAppendServerUrl:[_activeUrl stringByAppendingString:webDAV] addFileName:serverUrl];
  370. NSString *directoryID = [CCCoreData addDirectory:serverUrl permissions:itemDto.permissions activeAccount:_metadataNet.account];
  371. [metadatas addObject:[CCUtility trasformedOCFileToCCMetadata:itemDto fileNamePrint:itemDto.fileName serverUrl:serverUrl directoryID:directoryID cameraFolderName:cameraFolderName cameraFolderPath:cameraFolderPath activeAccount:_metadataNet.account directoryUser:directoryUser]];
  372. }
  373. if ([self.delegate respondsToSelector:@selector(searchSuccess:metadatas:)])
  374. [self.delegate searchSuccess:_metadataNet metadatas:metadatas];
  375. [self complete];
  376. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) {
  377. NSInteger errorCode = response.statusCode;
  378. if (errorCode == 0)
  379. errorCode = error.code;
  380. // Error
  381. if ([self.delegate respondsToSelector:@selector(searchFailure:message:errorCode:)]) {
  382. if (errorCode == 503)
  383. [self.delegate searchFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  384. else
  385. [self.delegate searchFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  386. }
  387. // Request trusted certificated
  388. if ([error code] == NSURLErrorServerCertificateUntrusted)
  389. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  390. [self complete];
  391. }];
  392. }
  393. #pragma --------------------------------------------------------------------------------------------
  394. #pragma mark ===== Setting Favorite =====
  395. #pragma --------------------------------------------------------------------------------------------
  396. - (void)settingFavorite
  397. {
  398. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  399. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  400. [communication setUserAgent:[CCUtility getUserAgent]];
  401. NSString *path = [_activeUrl stringByAppendingString:dav];
  402. [communication settingFavoriteServer:path andFileOrFolderPath:_metadataNet.fileName favorite:[_metadataNet.options boolValue] withUserSessionToken:nil onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer, NSString *token) {
  403. if ([self.delegate respondsToSelector:@selector(settingFavoriteSuccess:)])
  404. [self.delegate settingFavoriteSuccess:_metadataNet];
  405. [self complete];
  406. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) {
  407. NSInteger errorCode = response.statusCode;
  408. if (errorCode == 0)
  409. errorCode = error.code;
  410. // Error
  411. if ([self.delegate respondsToSelector:@selector(settingFavoriteFailure:message:errorCode:)]) {
  412. if (errorCode == 503)
  413. [self.delegate settingFavoriteFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  414. else
  415. [self.delegate settingFavoriteFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  416. }
  417. // Request trusted certificated
  418. if ([error code] == NSURLErrorServerCertificateUntrusted)
  419. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  420. [self complete];
  421. }];
  422. }
  423. #pragma --------------------------------------------------------------------------------------------
  424. #pragma mark ===== Listing Favorites =====
  425. #pragma --------------------------------------------------------------------------------------------
  426. - (void)listingFavorites
  427. {
  428. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  429. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  430. [communication setUserAgent:[CCUtility getUserAgent]];
  431. NSString *path = [_activeUrl stringByAppendingString:dav];
  432. NSString *folder = [_metadataNet.serverUrl stringByReplacingOccurrencesOfString:[CCUtility getHomeServerUrlActiveUrl:_activeUrl] withString:@""];
  433. [communication listingFavorites:path folder:folder withUserSessionToken:nil onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer, NSString *token) {
  434. NSMutableArray *metadatas = [NSMutableArray new];
  435. NSString *cameraFolderName = [CCCoreData getCameraUploadFolderNameActiveAccount:_metadataNet.account];
  436. NSString *cameraFolderPath = [CCCoreData getCameraUploadFolderPathActiveAccount:_metadataNet.account activeUrl:_activeUrl];
  437. NSString *directoryUser = [CCUtility getDirectoryActiveUser:_activeUser activeUrl:_activeUrl];
  438. // Order by fileNamePath
  439. items = [items sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
  440. OCFileDto *record1 = obj1, *record2 = obj2;
  441. NSString *path1 = [[record1.filePath stringByAppendingString:record1.fileName] lowercaseString];
  442. NSString *path2 = [[record2.filePath stringByAppendingString:record2.fileName] lowercaseString];
  443. return [path1 compare:path2];
  444. }];
  445. for(OCFileDto *itemDto in items) {
  446. itemDto.fileName = [itemDto.fileName stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  447. itemDto.filePath = [itemDto.filePath stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  448. // Not in Crypto Cloud file
  449. NSString *fileName = itemDto.fileName;
  450. if (itemDto.isDirectory)
  451. fileName = [fileName substringToIndex:[fileName length] - 1];
  452. if ([CCUtility isFileCryptated:fileName])
  453. continue;
  454. // ----- BUG #942 ---------
  455. if ([itemDto.etag length] == 0) {
  456. #ifndef EXTENSION
  457. [app messageNotification:@"Server error" description:@"Metadata etag absent, record excluded, please fix" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  458. #endif
  459. continue;
  460. }
  461. // ------------------------
  462. NSString *serverUrl = [NSString stringWithFormat:@"%@/files/%@", dav, _activeUser];
  463. serverUrl = [itemDto.filePath stringByReplacingOccurrencesOfString:serverUrl withString:@""];
  464. /* TRIM */
  465. if ([serverUrl hasPrefix:@"/"])
  466. serverUrl = [serverUrl substringFromIndex:1];
  467. if ([serverUrl hasSuffix:@"/"])
  468. serverUrl = [serverUrl substringToIndex:[serverUrl length] - 1];
  469. /* */
  470. serverUrl = [CCUtility stringAppendServerUrl:[_activeUrl stringByAppendingString:webDAV] addFileName:serverUrl];
  471. NSString *directoryID = [CCCoreData addDirectory:serverUrl permissions:itemDto.permissions activeAccount:_metadataNet.account];
  472. [metadatas addObject:[CCUtility trasformedOCFileToCCMetadata:itemDto fileNamePrint:itemDto.fileName serverUrl:serverUrl directoryID:directoryID cameraFolderName:cameraFolderName cameraFolderPath:cameraFolderPath activeAccount:_metadataNet.account directoryUser:directoryUser]];
  473. }
  474. if ([self.delegate respondsToSelector:@selector(listingFavoritesSuccess:metadatas:)])
  475. [self.delegate listingFavoritesSuccess:_metadataNet metadatas:metadatas];
  476. [self complete];
  477. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) {
  478. NSInteger errorCode = response.statusCode;
  479. if (errorCode == 0)
  480. errorCode = error.code;
  481. // Error
  482. if ([self.delegate respondsToSelector:@selector(listingFavoritesFailure:message:errorCode:)]) {
  483. if (errorCode == 503)
  484. [self.delegate listingFavoritesFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  485. else
  486. [self.delegate listingFavoritesFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  487. }
  488. // Request trusted certificated
  489. if ([error code] == NSURLErrorServerCertificateUntrusted)
  490. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  491. [self complete];
  492. }];
  493. }
  494. #pragma --------------------------------------------------------------------------------------------
  495. #pragma mark ===== Create Folder =====
  496. #pragma --------------------------------------------------------------------------------------------
  497. - (void)createFolder
  498. {
  499. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  500. NSString *nameFolderURL = [NSString stringWithFormat:@"%@/%@", _metadataNet.serverUrl, _metadataNet.fileName];
  501. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  502. [communication setUserAgent:[CCUtility getUserAgent]];
  503. [communication createFolder:nameFolderURL onCommunication:communication withForbiddenCharactersSupported:YES successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  504. if ([self.delegate respondsToSelector:@selector(createFolderSuccess:)])
  505. [self.delegate createFolderSuccess:_metadataNet];
  506. [self complete];
  507. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  508. NSString *message;
  509. if (([_metadataNet.fileName isEqualToString:[CCCoreData getCameraUploadFolderNameActiveAccount:_metadataNet.account]] == YES && [_metadataNet.serverUrl isEqualToString:[CCCoreData getCameraUploadFolderPathActiveAccount:_metadataNet.account activeUrl:_activeUrl]] == YES))
  510. message = nil;
  511. else
  512. message = [CCError manageErrorOC:response.statusCode error:error];
  513. NSInteger errorCode = response.statusCode;
  514. if (errorCode == 0)
  515. errorCode = error.code;
  516. if ([self.delegate respondsToSelector:@selector(createFolderFailure:message:errorCode:)])
  517. [self.delegate createFolderFailure:_metadataNet message:message errorCode:errorCode];
  518. // Request trusted certificated
  519. if ([error code] == NSURLErrorServerCertificateUntrusted)
  520. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  521. [self complete];
  522. } errorBeforeRequest:^(NSError *error) {
  523. NSString *message;
  524. if (([_metadataNet.fileName isEqualToString:[CCCoreData getCameraUploadFolderNameActiveAccount:_metadataNet.account]] == YES && [_metadataNet.serverUrl isEqualToString:[CCCoreData getCameraUploadFolderPathActiveAccount:_metadataNet.account activeUrl:_activeUrl]] == YES))
  525. message = nil;
  526. else {
  527. if (error.code == OCErrorForbidenCharacters)
  528. message = NSLocalizedStringFromTable(@"_forbidden_characters_from_server_", @"Error", nil);
  529. else
  530. message = NSLocalizedStringFromTable(@"_unknow_response_server_", @"Error", nil);
  531. }
  532. // Error
  533. if ([self.delegate respondsToSelector:@selector(createFolderFailure:message:errorCode:)]) {
  534. if (error.code == 503)
  535. [self.delegate createFolderFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:error.code];
  536. else
  537. [self.delegate createFolderFailure:_metadataNet message:message errorCode:error.code];
  538. }
  539. [self complete];
  540. }];
  541. }
  542. - (BOOL)automaticCreateFolderSync:(NSString *)folderPathName
  543. {
  544. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  545. __block BOOL noError = YES;
  546. dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
  547. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  548. [communication setUserAgent:[CCUtility getUserAgent]];
  549. [communication readFile:folderPathName onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  550. dispatch_semaphore_signal(semaphore);
  551. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  552. TableAccount *recordAccount = [CCCoreData getActiveAccount];
  553. [communication createFolder:folderPathName onCommunication:communication withForbiddenCharactersSupported:YES successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  554. [CCCoreData clearDateReadAccount:recordAccount.account serverUrl:[CCUtility deletingLastPathComponentFromServerUrl:folderPathName] directoryID:nil];
  555. dispatch_semaphore_signal(semaphore);
  556. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  557. noError = NO;
  558. dispatch_semaphore_signal(semaphore);
  559. } errorBeforeRequest:^(NSError *error) {
  560. noError = NO;
  561. dispatch_semaphore_signal(semaphore);
  562. }];
  563. }];
  564. while (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_NOW))
  565. [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:k_timeout_webdav]];
  566. return noError;
  567. }
  568. #pragma --------------------------------------------------------------------------------------------
  569. #pragma mark ===== Delete =====
  570. #pragma --------------------------------------------------------------------------------------------
  571. - (void)deleteFileOrFolder
  572. {
  573. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  574. NSString *serverFileUrl = [NSString stringWithFormat:@"%@/%@", _metadataNet.serverUrl, _metadataNet.fileName];
  575. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  576. [communication setUserAgent:[CCUtility getUserAgent]];
  577. [communication deleteFileOrFolder:serverFileUrl onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  578. if ([_metadataNet.selector rangeOfString:selectorDelete].location != NSNotFound && [self.delegate respondsToSelector:@selector(deleteFileOrFolderSuccess:)])
  579. [self.delegate deleteFileOrFolderSuccess:_metadataNet];
  580. [self complete];
  581. } failureRquest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  582. NSInteger errorCode = response.statusCode;
  583. if (errorCode == 0)
  584. errorCode = error.code;
  585. // Error
  586. if ([self.delegate respondsToSelector:@selector(deleteFileOrFolderFailure:message:errorCode:)]) {
  587. if (errorCode == 503)
  588. [self.delegate deleteFileOrFolderFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  589. else
  590. [self.delegate deleteFileOrFolderFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  591. }
  592. // Request trusted certificated
  593. if ([error code] == NSURLErrorServerCertificateUntrusted)
  594. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  595. [self complete];
  596. }];
  597. }
  598. #pragma --------------------------------------------------------------------------------------------
  599. #pragma mark ===== Move =====
  600. #pragma --------------------------------------------------------------------------------------------
  601. - (void)moveFileOrFolder
  602. {
  603. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  604. NSString *origineURL = [NSString stringWithFormat:@"%@/%@", _metadataNet.serverUrl, _metadataNet.fileName];
  605. NSString *destinazioneURL = [NSString stringWithFormat:@"%@/%@", _metadataNet.serverUrlTo, _metadataNet.fileNameTo];
  606. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  607. [communication setUserAgent:[CCUtility getUserAgent]];
  608. [communication moveFileOrFolder:origineURL toDestiny:destinazioneURL onCommunication:communication withForbiddenCharactersSupported:YES successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  609. if ([_metadataNet.selector isEqualToString:selectorRename] && [self.delegate respondsToSelector:@selector(renameSuccess:)])
  610. [self.delegate renameSuccess:_metadataNet];
  611. if ([_metadataNet.selector rangeOfString:selectorMove].location != NSNotFound && [self.delegate respondsToSelector:@selector(moveSuccess:revTo:)])
  612. [self.delegate moveSuccess:_metadataNet revTo:nil];
  613. [self complete];
  614. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  615. NSInteger errorCode = response.statusCode;
  616. if (errorCode == 0)
  617. errorCode = error.code;
  618. if ([self.delegate respondsToSelector:@selector(renameMoveFileOrFolderFailure:message:errorCode:)])
  619. [self.delegate renameMoveFileOrFolderFailure:_metadataNet message:[CCError manageErrorOC:response.statusCode error:error] errorCode:errorCode];
  620. // Request trusted certificated
  621. if ([error code] == NSURLErrorServerCertificateUntrusted)
  622. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  623. [self complete];
  624. } errorBeforeRequest:^(NSError *error) {
  625. NSString *message;
  626. if (error.code == OCErrorMovingTheDestinyAndOriginAreTheSame) {
  627. message = NSLocalizedStringFromTable(@"_error_folder_destiny_is_the_same_", @"Error", nil);
  628. } else if (error.code == OCErrorMovingFolderInsideHimself) {
  629. message = NSLocalizedStringFromTable(@"_error_folder_destiny_is_the_same_", @"Error", nil);
  630. } else if (error.code == OCErrorMovingDestinyNameHaveForbiddenCharacters) {
  631. message = NSLocalizedStringFromTable(@"_forbidden_characters_from_server_", @"Error", nil);
  632. } else {
  633. message = NSLocalizedStringFromTable(@"_unknow_response_server_", @"Error", nil);
  634. }
  635. // Error
  636. if ([self.delegate respondsToSelector:@selector(renameMoveFileOrFolderFailure:message:errorCode:)]) {
  637. if (error.code == 503)
  638. [self.delegate renameMoveFileOrFolderFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:error.code];
  639. else
  640. [self.delegate renameMoveFileOrFolderFailure:_metadataNet message:message errorCode:error.code];
  641. }
  642. [self complete];
  643. }];
  644. }
  645. #pragma --------------------------------------------------------------------------------------------
  646. #pragma mark ===== ReadFile =====
  647. #pragma --------------------------------------------------------------------------------------------
  648. - (void)readFile
  649. {
  650. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  651. NSString *fileName;
  652. if (_metadataNet.fileName)
  653. fileName = [NSString stringWithFormat:@"%@/%@", _metadataNet.serverUrl, _metadataNet.fileName];
  654. else
  655. fileName = _metadataNet.serverUrl;
  656. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  657. [communication setUserAgent:[CCUtility getUserAgent]];
  658. [communication readFile:fileName onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  659. TableAccount *recordAccount = [CCCoreData getActiveAccount];
  660. if ([recordAccount.account isEqualToString:_metadataNet.account] && [items count] > 0) {
  661. CCMetadata *metadata = [[CCMetadata alloc] init];
  662. OCFileDto *itemDto = [items objectAtIndex:0];
  663. itemDto.fileName = _metadataNet.fileName;
  664. NSString *directoryID = [CCCoreData getDirectoryIDFromServerUrl:_metadataNet.serverUrl activeAccount:_metadataNet.account];
  665. NSString *cameraFolderName = [CCCoreData getCameraUploadFolderNameActiveAccount:_metadataNet.account];
  666. NSString *cameraFolderPath = [CCCoreData getCameraUploadFolderPathActiveAccount:_metadataNet.account activeUrl:_activeUrl];
  667. NSString *directoryUser = [CCUtility getDirectoryActiveUser:_activeUser activeUrl:_activeUrl];
  668. metadata = [CCUtility trasformedOCFileToCCMetadata:itemDto fileNamePrint:_metadataNet.fileNamePrint serverUrl:_metadataNet.serverUrl directoryID:directoryID cameraFolderName:cameraFolderName cameraFolderPath:cameraFolderPath activeAccount:_metadataNet.account directoryUser:directoryUser];
  669. if([self.delegate respondsToSelector:@selector(readFileSuccess:metadata:)])
  670. [self.delegate readFileSuccess:_metadataNet metadata:metadata];
  671. }
  672. // BUG 1038
  673. if ([items count] == 0) {
  674. #ifndef EXTENSION
  675. [app messageNotification:@"Server error" description:@"Read File WebDAV : [items NULL] please fix" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  676. #endif
  677. }
  678. [self complete];
  679. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  680. TableAccount *recordAccount = [CCCoreData getActiveAccount];
  681. _metadataNet.errorRetry++;
  682. NSInteger errorCode = response.statusCode;
  683. if (errorCode == 0)
  684. errorCode = error.code;
  685. // Error
  686. if ([self.delegate respondsToSelector:@selector(readFileFailure:message:errorCode:)] && [recordAccount.account isEqualToString:_metadataNet.account]) {
  687. if (errorCode == 503)
  688. [self.delegate readFileFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  689. else
  690. [self.delegate readFileFailure:_metadataNet message:[CCError manageErrorOC:response.statusCode error:error] errorCode:errorCode];
  691. }
  692. // Request trusted certificated
  693. if ([error code] == NSURLErrorServerCertificateUntrusted)
  694. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  695. [self complete];
  696. }];
  697. }
  698. - (NSError *)readFileSync:(NSString *)filePathName
  699. {
  700. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  701. __block NSError *returnError;
  702. dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
  703. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  704. [communication setUserAgent:[CCUtility getUserAgent]];
  705. [communication readFile:filePathName onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  706. returnError = nil;
  707. dispatch_semaphore_signal(semaphore);
  708. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  709. // Request trusted certificated
  710. if ([error code] == NSURLErrorServerCertificateUntrusted)
  711. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  712. returnError = error;
  713. dispatch_semaphore_signal(semaphore);
  714. }];
  715. while (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_NOW))
  716. [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:k_timeout_webdav]];
  717. return returnError;
  718. }
  719. #pragma --------------------------------------------------------------------------------------------
  720. #pragma mark ===== Shared =====
  721. #pragma --------------------------------------------------------------------------------------------
  722. - (NSMutableDictionary *)getShareID
  723. {
  724. #ifndef EXTENSION
  725. return app.sharesID;
  726. #endif
  727. return [NSMutableDictionary new];
  728. }
  729. - (void)readShareServer
  730. {
  731. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  732. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  733. [communication setUserAgent:[CCUtility getUserAgent]];
  734. [communication readSharedByServer:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  735. BOOL openWindow = NO;
  736. [[self getShareID] removeAllObjects];
  737. TableAccount *recordAccount = [CCCoreData getActiveAccount];
  738. if ([recordAccount.account isEqualToString:_metadataNet.account]) {
  739. for (OCSharedDto *item in items)
  740. [[self getShareID] setObject:item forKey:[@(item.idRemoteShared) stringValue]];
  741. if ([_metadataNet.selector isEqual:selectorOpenWindowShare]) openWindow = YES;
  742. if ([_metadataNet.action isEqual:actionUpdateShare]) openWindow = YES;
  743. if ([_metadataNet.action isEqual:actionShare]) openWindow = YES;
  744. if ([_metadataNet.action isEqual:actionShareWith]) openWindow = YES;
  745. }
  746. if([self.delegate respondsToSelector:@selector(readSharedSuccess:items:openWindow:)])
  747. [self.delegate readSharedSuccess:_metadataNet items:[self getShareID] openWindow:openWindow];
  748. [self complete];
  749. } failureRequest :^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  750. NSInteger errorCode = response.statusCode;
  751. if (errorCode == 0)
  752. errorCode = error.code;
  753. // Error
  754. if ([self.delegate respondsToSelector:@selector(shareFailure:message:errorCode:)]) {
  755. if (errorCode == 503)
  756. [self.delegate shareFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  757. else
  758. [self.delegate shareFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  759. }
  760. // Request trusted certificated
  761. if ([error code] == NSURLErrorServerCertificateUntrusted)
  762. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  763. [self complete];
  764. }];
  765. }
  766. - (void)share
  767. {
  768. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  769. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  770. [communication setUserAgent:[CCUtility getUserAgent]];
  771. [communication shareFileOrFolderByServer:[_activeUrl stringByAppendingString:@"/"] andFileOrFolderPath:[_metadataNet.fileName encodeString:NSUTF8StringEncoding] andPassword:[_metadataNet.password encodeString:NSUTF8StringEncoding] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *token, NSString *redirectedServer) {
  772. [self readShareServer];
  773. } failureRequest :^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  774. NSInteger errorCode = response.statusCode;
  775. if (errorCode == 0)
  776. errorCode = error.code;
  777. // Error
  778. if ([self.delegate respondsToSelector:@selector(shareFailure:message:errorCode:)]) {
  779. if (errorCode == 503)
  780. [self.delegate shareFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  781. else
  782. [self.delegate shareFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  783. }
  784. // Request trusted certificated
  785. if ([error code] == NSURLErrorServerCertificateUntrusted)
  786. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  787. [self complete];
  788. }];
  789. }
  790. // * @param shareeType -> NSInteger: to set the type of sharee (user/group/federated)
  791. - (void)shareWith
  792. {
  793. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  794. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  795. [communication setUserAgent:[CCUtility getUserAgent]];
  796. [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) {
  797. [self readShareServer];
  798. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  799. NSInteger errorCode = response.statusCode;
  800. if (errorCode == 0)
  801. errorCode = error.code;
  802. // Error
  803. if ([self.delegate respondsToSelector:@selector(shareFailure:message:errorCode:)]) {
  804. if (errorCode == 503)
  805. [self.delegate shareFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  806. else
  807. [self.delegate shareFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  808. }
  809. // Request trusted certificated
  810. if ([error code] == NSURLErrorServerCertificateUntrusted)
  811. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  812. [self complete];
  813. }];
  814. }
  815. - (void)updateShare
  816. {
  817. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  818. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  819. [communication setUserAgent:[CCUtility getUserAgent]];
  820. [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) {
  821. [self readShareServer];
  822. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  823. #ifndef EXTENSION
  824. [app messageNotification:@"_error_" description:[CCError manageErrorOC:response.statusCode error:error] visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  825. #endif
  826. NSInteger errorCode = response.statusCode;
  827. if (errorCode == 0)
  828. errorCode = error.code;
  829. // Error
  830. if ([self.delegate respondsToSelector:@selector(shareFailure:message:errorCode:)]) {
  831. if (errorCode == 503)
  832. [self.delegate shareFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  833. else
  834. [self.delegate shareFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  835. }
  836. // Request trusted certificated
  837. if ([error code] == NSURLErrorServerCertificateUntrusted)
  838. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  839. [self complete];
  840. }];
  841. }
  842. - (void)unShare
  843. {
  844. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  845. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  846. [communication setUserAgent:[CCUtility getUserAgent]];
  847. [communication unShareFileOrFolderByServer:[_activeUrl stringByAppendingString:@"/"] andIdRemoteShared:[_metadataNet.share intValue] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  848. if([self.delegate respondsToSelector:@selector(unShareSuccess:)])
  849. [self.delegate unShareSuccess:_metadataNet];
  850. [self complete];
  851. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  852. #ifndef EXTENSION
  853. [app messageNotification:@"_error_" description:[CCError manageErrorOC:response.statusCode error:error] visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  854. #endif
  855. NSInteger errorCode = response.statusCode;
  856. if (errorCode == 0)
  857. errorCode = error.code;
  858. // Error
  859. if ([self.delegate respondsToSelector:@selector(shareFailure:message:errorCode:)]) {
  860. if (errorCode == 503)
  861. [self.delegate shareFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  862. else
  863. [self.delegate shareFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  864. }
  865. // Request trusted certificated
  866. if ([error code] == NSURLErrorServerCertificateUntrusted)
  867. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  868. [self complete];
  869. }];
  870. }
  871. - (void)getUserAndGroup
  872. {
  873. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  874. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  875. [communication setUserAgent:[CCUtility getUserAgent]];
  876. [communication searchUsersAndGroupsWith:_metadataNet.options forPage:1 with:50 ofServer:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *itemList, NSString *redirectedServer) {
  877. if([self.delegate respondsToSelector:@selector(getUserAndGroupSuccess:items:)])
  878. [self.delegate getUserAndGroupSuccess:_metadataNet items:itemList];
  879. [self complete];
  880. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  881. NSInteger errorCode = response.statusCode;
  882. if (errorCode == 0)
  883. errorCode = error.code;
  884. // Error
  885. if ([self.delegate respondsToSelector:@selector(getUserAndGroupFailure:message:errorCode:)]) {
  886. if (errorCode == 503)
  887. [self.delegate getUserAndGroupFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  888. else
  889. [self.delegate getUserAndGroupFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  890. }
  891. // Request trusted certificated
  892. if ([error code] == NSURLErrorServerCertificateUntrusted)
  893. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  894. [self complete];
  895. }];
  896. }
  897. #pragma --------------------------------------------------------------------------------------------
  898. #pragma mark ===== Activity =====
  899. #pragma --------------------------------------------------------------------------------------------
  900. - (void)getActivityServer
  901. {
  902. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  903. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  904. [communication setUserAgent:[CCUtility getUserAgent]];
  905. [communication getActivityServer:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfActivity, NSString *redirectedServer) {
  906. if ([self.delegate respondsToSelector:@selector(getActivityServerSuccess:)])
  907. [self.delegate getActivityServerSuccess:listOfActivity];
  908. [self complete];
  909. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  910. NSInteger errorCode = response.statusCode;
  911. if (errorCode == 0)
  912. errorCode = error.code;
  913. // Error
  914. if ([self.delegate respondsToSelector:@selector(getActivityServerFailure:message:errorCode:)]) {
  915. if (errorCode == 503)
  916. [self.delegate getActivityServerFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  917. else
  918. [self.delegate getActivityServerFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  919. }
  920. // Request trusted certificated
  921. if ([error code] == NSURLErrorServerCertificateUntrusted)
  922. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  923. [self complete];
  924. }];
  925. }
  926. #pragma --------------------------------------------------------------------------------------------
  927. #pragma mark ===== External Sites =====
  928. #pragma --------------------------------------------------------------------------------------------
  929. - (void)getExternalSitesServer
  930. {
  931. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  932. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  933. [communication setUserAgent:[CCUtility getUserAgent]];
  934. [communication getExternalSitesServer:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfExternalSites, NSString *redirectedServer) {
  935. if ([self.delegate respondsToSelector:@selector(getExternalSitesServerSuccess:)])
  936. [self.delegate getExternalSitesServerSuccess:listOfExternalSites];
  937. [self complete];
  938. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  939. NSInteger errorCode = response.statusCode;
  940. if (errorCode == 0)
  941. errorCode = error.code;
  942. // Error
  943. if ([self.delegate respondsToSelector:@selector(getExternalSitesServerFailure:message:errorCode:)]) {
  944. if (errorCode == 503)
  945. [self.delegate getExternalSitesServerFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  946. else
  947. [self.delegate getExternalSitesServerFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  948. }
  949. // Request trusted certificated
  950. if ([error code] == NSURLErrorServerCertificateUntrusted)
  951. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  952. [self complete];
  953. }];
  954. }
  955. #pragma --------------------------------------------------------------------------------------------
  956. #pragma mark ===== Notification =====
  957. #pragma --------------------------------------------------------------------------------------------
  958. - (void)getNotificationServer
  959. {
  960. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  961. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  962. [communication setUserAgent:[CCUtility getUserAgent]];
  963. [communication getNotificationServer:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfNotifications, NSString *redirectedServer) {
  964. if ([self.delegate respondsToSelector:@selector(getNotificationServerSuccess:)])
  965. [self.delegate getNotificationServerSuccess:listOfNotifications];
  966. [self complete];
  967. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  968. NSInteger errorCode = response.statusCode;
  969. if (errorCode == 0)
  970. errorCode = error.code;
  971. // Error
  972. if ([self.delegate respondsToSelector:@selector(getNotificationServerFailure:message:errorCode:)]) {
  973. if (errorCode == 503)
  974. [self.delegate getNotificationServerFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  975. else
  976. [self.delegate getNotificationServerFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  977. }
  978. // Request trusted certificated
  979. if ([error code] == NSURLErrorServerCertificateUntrusted)
  980. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  981. // Activity
  982. [[NCManageDatabase sharedInstance] addActivityClient:_activeUrl fileID:@"" action:k_activityDebugActionGetNotification selector:@"" note:[error.userInfo valueForKey:@"NSLocalizedDescription"] type:k_activityTypeFailure verbose:k_activityVerboseHigh account:_metadataNet.account activeUrl:_activeUrl];
  983. [self complete];
  984. }];
  985. }
  986. - (void)setNotificationServer
  987. {
  988. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  989. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  990. [communication setUserAgent:[CCUtility getUserAgent]];
  991. NSString *type = _metadataNet.options;
  992. [communication setNotificationServer:_metadataNet.serverUrl type:type onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  993. if ([self.delegate respondsToSelector:@selector(setNotificationServerSuccess:)])
  994. [self.delegate setNotificationServerSuccess:_metadataNet];
  995. [self complete];
  996. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  997. NSInteger errorCode = response.statusCode;
  998. if (errorCode == 0)
  999. errorCode = error.code;
  1000. // Error
  1001. if ([self.delegate respondsToSelector:@selector(setNotificationServerFailure:message:errorCode:)]) {
  1002. if (errorCode == 503)
  1003. [self.delegate setNotificationServerFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  1004. else
  1005. [self.delegate setNotificationServerFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1006. }
  1007. // Request trusted certificated
  1008. if ([error code] == NSURLErrorServerCertificateUntrusted)
  1009. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1010. [self complete];
  1011. }];
  1012. }
  1013. - (void)subscribingNextcloudServer
  1014. {
  1015. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1016. communication.kindOfCredential = credentialNotSet;
  1017. [communication setUserAgent:[CCUtility getUserAgent]];
  1018. NSDictionary *parameter = _metadataNet.options;
  1019. NSString *pushToken = [parameter objectForKey:@"pushToken"];
  1020. NSString *pushTokenHash = [parameter objectForKey:@"pushTokenHash"];
  1021. NSString *devicePublicKey = [parameter objectForKey:@"devicePublicKey"];
  1022. // encode URL
  1023. devicePublicKey = [CCUtility URLEncodeStringFromString:devicePublicKey];
  1024. [communication subscribingNextcloudServerPush:_activeUrl pushTokenHash:pushTokenHash devicePublicKey:devicePublicKey proxyServerPath:k_pushNotificationServer onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *publicKey, NSString *deviceIdentifier, NSString *signature, NSString *redirectedServer) {
  1025. // encode URL
  1026. deviceIdentifier = [CCUtility URLEncodeStringFromString:deviceIdentifier];
  1027. signature = [CCUtility URLEncodeStringFromString:signature];
  1028. [communication subscribingPushProxy:k_pushNotificationServer pushToken:pushToken deviceIdentifier:deviceIdentifier deviceIdentifierSignature:signature userPublicKey:[CCUtility URLEncodeStringFromString:publicKey] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1029. // Activity
  1030. [[NCManageDatabase sharedInstance] addActivityClient:k_pushNotificationServer fileID:@"" action:k_activityDebugActionPushProxy selector:@"" note:@"Service registered." type:k_activityTypeSuccess verbose:k_activityVerboseHigh account:_metadataNet.account activeUrl:_activeUrl];
  1031. [self complete];
  1032. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1033. NSInteger errorCode = response.statusCode;
  1034. if (errorCode == 0)
  1035. errorCode = error.code;
  1036. // Error
  1037. if ([self.delegate respondsToSelector:@selector(subscribingNextcloudServerFailure:message:errorCode:)]) {
  1038. if (errorCode == 503)
  1039. [self.delegate subscribingNextcloudServerFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  1040. else
  1041. [self.delegate subscribingNextcloudServerFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1042. }
  1043. // Request trusted certificated
  1044. if ([error code] == NSURLErrorServerCertificateUntrusted)
  1045. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1046. // Activity
  1047. [[NCManageDatabase sharedInstance] addActivityClient:k_pushNotificationServer fileID:@"" action:k_activityDebugActionPushProxy selector:@"" note:[error.userInfo valueForKey:@"NSLocalizedDescription"] type:k_activityTypeFailure verbose:k_activityVerboseHigh account:_metadataNet.account activeUrl:_activeUrl];
  1048. [self complete];
  1049. }];
  1050. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1051. NSInteger errorCode = response.statusCode;
  1052. if (errorCode == 0)
  1053. errorCode = error.code;
  1054. // Error
  1055. if ([self.delegate respondsToSelector:@selector(subscribingNextcloudServerFailure:message:errorCode:)]) {
  1056. if (errorCode == 503)
  1057. [self.delegate subscribingNextcloudServerFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  1058. else
  1059. [self.delegate subscribingNextcloudServerFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1060. }
  1061. // Request trusted certificated
  1062. if ([error code] == NSURLErrorServerCertificateUntrusted)
  1063. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1064. // Activity
  1065. [[NCManageDatabase sharedInstance] addActivityClient:_activeUrl fileID:@"" action:k_activityDebugActionServerPush selector:@"" note:[error.userInfo valueForKey:@"NSLocalizedDescription"] type:k_activityTypeFailure verbose:k_activityVerboseHigh account:_metadataNet.account activeUrl:_activeUrl];
  1066. [self complete];
  1067. }];
  1068. }
  1069. #pragma --------------------------------------------------------------------------------------------
  1070. #pragma mark ===== User Profile =====
  1071. #pragma --------------------------------------------------------------------------------------------
  1072. - (void)getUserProfile
  1073. {
  1074. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1075. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  1076. [communication setUserAgent:[CCUtility getUserAgent]];
  1077. [communication getUserProfileServer:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, OCUserProfile *userProfile, NSString *redirectedServer) {
  1078. if ([self.delegate respondsToSelector:@selector(getUserProfileSuccess:userProfile:)])
  1079. [self.delegate getUserProfileSuccess:_metadataNet userProfile:userProfile];
  1080. [self complete];
  1081. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1082. NSInteger errorCode = response.statusCode;
  1083. if (errorCode == 0)
  1084. errorCode = error.code;
  1085. // Error
  1086. if ([self.delegate respondsToSelector:@selector(getUserProfileFailure:message:errorCode:)]) {
  1087. if (errorCode == 503)
  1088. [self.delegate getUserProfileFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  1089. else
  1090. [self.delegate getUserProfileFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1091. }
  1092. // Request trusted certificated
  1093. if ([error code] == NSURLErrorServerCertificateUntrusted)
  1094. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1095. [self complete];
  1096. }];
  1097. }
  1098. #pragma --------------------------------------------------------------------------------------------
  1099. #pragma mark ===== Server =====
  1100. #pragma --------------------------------------------------------------------------------------------
  1101. - (NSError *)checkServerSync:(NSString *)serverUrl
  1102. {
  1103. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1104. __block NSError *returnError;
  1105. dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
  1106. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  1107. [communication setUserAgent:[CCUtility getUserAgent]];
  1108. [communication checkServer:serverUrl onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1109. returnError = nil;
  1110. dispatch_semaphore_signal(semaphore);
  1111. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1112. // Request trusted certificated
  1113. if ([error code] == NSURLErrorServerCertificateUntrusted)
  1114. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1115. returnError = error;
  1116. dispatch_semaphore_signal(semaphore);
  1117. }];
  1118. while (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_NOW))
  1119. [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:k_timeout_webdav]];
  1120. return returnError;
  1121. }
  1122. #pragma --------------------------------------------------------------------------------------------
  1123. #pragma mark ===== Capabilities =====
  1124. #pragma --------------------------------------------------------------------------------------------
  1125. - (void)getCapabilitiesOfServer
  1126. {
  1127. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1128. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  1129. [communication setUserAgent:[CCUtility getUserAgent]];
  1130. [communication getCapabilitiesOfServer:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, OCCapabilities *capabilities, NSString *redirectedServer) {
  1131. TableAccount *recordAccount = [CCCoreData getActiveAccount];
  1132. if ([self.delegate respondsToSelector:@selector(getCapabilitiesOfServerSuccess:)] && [recordAccount.account isEqualToString:_metadataNet.account])
  1133. [self.delegate getCapabilitiesOfServerSuccess:capabilities];
  1134. [self complete];
  1135. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1136. NSInteger errorCode = response.statusCode;
  1137. if (errorCode == 0)
  1138. errorCode = error.code;
  1139. // Error
  1140. if ([self.delegate respondsToSelector:@selector(getCapabilitiesOfServerFailure:message:errorCode:)]) {
  1141. if (errorCode == 503)
  1142. [self.delegate getCapabilitiesOfServerFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  1143. else
  1144. [self.delegate getCapabilitiesOfServerFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1145. }
  1146. // Request trusted certificated
  1147. if ([error code] == NSURLErrorServerCertificateUntrusted)
  1148. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1149. // Activity
  1150. [[NCManageDatabase sharedInstance] addActivityClient:_activeUrl fileID:@"" action:k_activityDebugActionCapabilities selector:@"" note:[error.userInfo valueForKey:@"NSLocalizedDescription"] type:k_activityTypeFailure verbose:k_activityVerboseHigh account:_metadataNet.account activeUrl:_activeUrl];
  1151. [self complete];
  1152. }];
  1153. }
  1154. @end
  1155. #pragma --------------------------------------------------------------------------------------------
  1156. #pragma mark ===== OCURLSessionManager =====
  1157. #pragma --------------------------------------------------------------------------------------------
  1158. @implementation OCURLSessionManager
  1159. - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
  1160. {
  1161. // The pinnning check
  1162. dispatch_async(dispatch_get_main_queue(), ^{
  1163. if ([[CCCertificate sharedManager] checkTrustedChallenge:challenge]) {
  1164. completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  1165. } else {
  1166. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  1167. }
  1168. });
  1169. }
  1170. @end