OCNetworking.m 83 KB

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