OCNetworking.m 98 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009
  1. //
  2. // OCnetworking.m
  3. // Nextcloud iOS
  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 "CCUtility.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 *_activeUserID;
  34. NSString *_activePassword;
  35. NSString *_activeUrl;
  36. NSURLSessionDownloadTask *_downloadTask;
  37. NSURLSessionUploadTask *_uploadTask;
  38. }
  39. @end
  40. @implementation OCnetworking
  41. - (id)initWithDelegate:(id <OCNetworkingDelegate>)delegate metadataNet:(CCMetadataNet *)metadataNet withUser:(NSString *)withUser withUserID:(NSString *)withUserID withPassword:(NSString *)withPassword withUrl:(NSString *)withUrl
  42. {
  43. self = [super init];
  44. if (self) {
  45. _delegate = delegate;
  46. _metadataNet = [CCMetadataNet new];
  47. _metadataNet = [metadataNet copy];
  48. _activeUser = withUser;
  49. _activeUserID = withUserID;
  50. _activePassword = withPassword;
  51. _activeUrl = withUrl;
  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 ===== downloadThumbnail =====
  110. #pragma --------------------------------------------------------------------------------------------
  111. - (void)downloadThumbnail
  112. {
  113. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  114. __block NSString *ext;
  115. NSInteger width = 0, height = 0;
  116. NSString *directoryUser = [CCUtility getDirectoryActiveUser:_activeUser activeUrl:_activeUrl];
  117. NSString *dimOfThumbnail = (NSString *)_metadataNet.options;
  118. if ([dimOfThumbnail.lowercaseString isEqualToString:@"xs"]) { width = 32; height = 32; ext = @"ico"; }
  119. else if ([dimOfThumbnail.lowercaseString isEqualToString:@"s"]) { width = 64; height = 64; ext = @"ico"; }
  120. else if ([dimOfThumbnail.lowercaseString isEqualToString:@"m"]) { width = 128; height = 128; ext = @"ico"; }
  121. else if ([dimOfThumbnail.lowercaseString isEqualToString:@"l"]) { width = 640; height = 640; ext = @"pvw"; }
  122. else if ([dimOfThumbnail.lowercaseString isEqualToString:@"xl"]) { width = 1024; height = 1024; ext = @"pvw"; }
  123. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.%@", directoryUser, _metadataNet.fileID, ext]]) {
  124. [self.delegate downloadThumbnailSuccess:_metadataNet];
  125. [self complete];
  126. return;
  127. }
  128. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  129. [communication setUserAgent:[CCUtility getUserAgent]];
  130. [communication getRemoteThumbnailByServer:[_activeUrl stringByAppendingString:@"/"] ofFilePath:_metadataNet.fileName withWidth:width andHeight:height onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSData *thumbnail, NSString *redirectedServer) {
  131. tableAccount *recordAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  132. if ([recordAccount.account isEqualToString:_metadataNet.account] && [thumbnail length] > 0) {
  133. UIImage *thumbnailImage = [UIImage imageWithData:thumbnail];
  134. NSString *directoryUser = [CCUtility getDirectoryActiveUser:_activeUser activeUrl:_activeUrl];
  135. [CCGraphics saveIcoWithEtag:_metadataNet.fileID image:thumbnailImage writeToFile:[NSString stringWithFormat:@"%@/%@.%@", directoryUser, _metadataNet.fileID, ext] copy:NO move:NO fromPath:nil toPath:nil];
  136. if ([self.delegate respondsToSelector:@selector(downloadThumbnailSuccess:)] && [_metadataNet.action isEqualToString:actionDownloadThumbnail])
  137. [self.delegate downloadThumbnailSuccess:_metadataNet];
  138. } else {
  139. if ([self.delegate respondsToSelector:@selector(downloadThumbnailFailure:message:errorCode:)] && [_metadataNet.action isEqualToString:actionDownloadThumbnail])
  140. [self.delegate downloadThumbnailFailure:_metadataNet message:@"No data" errorCode:0];
  141. }
  142. [self complete];
  143. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  144. NSInteger errorCode = response.statusCode;
  145. if (errorCode == 0)
  146. errorCode = error.code;
  147. // Error
  148. if ([self.delegate respondsToSelector:@selector(downloadThumbnailFailure:message:errorCode:)] && [_metadataNet.action isEqualToString:actionDownloadThumbnail]) {
  149. if (errorCode == 503)
  150. [self.delegate downloadThumbnailFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  151. else
  152. [self.delegate downloadThumbnailFailure:_metadataNet message:[CCError manageErrorOC:response.statusCode error:error] errorCode:errorCode];
  153. }
  154. [self complete];
  155. }];
  156. }
  157. #pragma --------------------------------------------------------------------------------------------
  158. #pragma mark ===== Read Folder =====
  159. #pragma --------------------------------------------------------------------------------------------
  160. - (void)readFolder
  161. {
  162. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  163. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  164. [communication setUserAgent:[CCUtility getUserAgent]];
  165. [communication readFolder:_metadataNet.serverUrl depth:_metadataNet.depth withUserSessionToken:nil onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer, NSString *token) {
  166. NSMutableArray *metadatas = [NSMutableArray new];
  167. BOOL showHiddenFiles = [CCUtility getShowHiddenFiles];
  168. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:_metadataNet.serverUrl account:_metadataNet.account];
  169. // Check items > 0
  170. if ([items count] == 0) {
  171. #ifndef EXTENSION
  172. [app messageNotification:@"Server error" description:@"Read Folder WebDAV : [items NULL] please fix" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  173. #endif
  174. dispatch_async(dispatch_get_main_queue(), ^{
  175. if ([self.delegate respondsToSelector:@selector(readFolderSuccess:metadataFolder:metadatas:)])
  176. [self.delegate readFolderSuccess:_metadataNet metadataFolder:nil metadatas:metadatas];
  177. });
  178. [self complete];
  179. return;
  180. }
  181. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  182. // directory [0]
  183. OCFileDto *itemDtoFolder = [items objectAtIndex:0];
  184. //NSDate *date = [NSDate dateWithTimeIntervalSince1970:itemDtoDirectory.date];
  185. NSString *directoryID = [[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:_metadataNet.serverUrl permissions:itemDtoFolder.permissions encrypted:itemDtoFolder.isEncrypted];
  186. _metadataNet.directoryID = directoryID;
  187. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  188. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:_activeUrl];
  189. NSString *directoryUser = [CCUtility getDirectoryActiveUser:_activeUser activeUrl:_activeUrl];
  190. tableMetadata *metadataFolder;
  191. NSString *directoryIDFolder;
  192. NSString *serverUrlFolder;
  193. NSString *serverUrl;
  194. // Metadata . (self Folder)
  195. if ([_metadataNet.serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:_activeUrl]]) {
  196. // root folder
  197. serverUrlFolder = @"..";
  198. directoryIDFolder = @"00000000-0000-0000-0000-000000000000";
  199. metadataFolder = [CCUtility trasformedOCFileToCCMetadata:itemDtoFolder fileName:@"." serverUrl:serverUrlFolder directoryID:directoryIDFolder autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:_metadataNet.account directoryUser:directoryUser isFolderEncrypted:isFolderEncrypted];
  200. } else {
  201. serverUrlFolder = [CCUtility deletingLastPathComponentFromServerUrl:_metadataNet.serverUrl];
  202. directoryIDFolder = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrlFolder];
  203. if (!directoryIDFolder) {
  204. dispatch_async(dispatch_get_main_queue(), ^{
  205. if ([self.delegate respondsToSelector:@selector(readFolderSuccess:metadataFolder:metadatas:)])
  206. [self.delegate readFolderSuccess:_metadataNet metadataFolder:metadataFolder metadatas:metadatas];
  207. });
  208. }
  209. metadataFolder = [CCUtility trasformedOCFileToCCMetadata:itemDtoFolder fileName:[_metadataNet.serverUrl lastPathComponent] serverUrl:serverUrlFolder directoryID:directoryIDFolder autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:_metadataNet.account directoryUser:directoryUser isFolderEncrypted:isFolderEncrypted];
  210. }
  211. NSArray *itemsSortedArray = [items sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
  212. NSString *first = [(OCFileDto*)a fileName];
  213. NSString *second = [(OCFileDto*)b fileName];
  214. return [[first lowercaseString] compare:[second lowercaseString]];
  215. }];
  216. for (NSUInteger i=1; i < [itemsSortedArray count]; i++) {
  217. OCFileDto *itemDto = [itemsSortedArray objectAtIndex:i];
  218. itemDto.fileName = [itemDto.fileName stringByRemovingPercentEncoding];
  219. NSString *fileName = itemDto.fileName;
  220. // Skip hidden files
  221. if (!showHiddenFiles && [[fileName substringToIndex:1] isEqualToString:@"."])
  222. continue;
  223. if (itemDto.isDirectory) {
  224. fileName = [fileName substringToIndex:[fileName length] - 1];
  225. serverUrl = [CCUtility stringAppendServerUrl:_metadataNet.serverUrl addFileName:fileName];
  226. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:serverUrl permissions:itemDtoFolder.permissions encrypted:itemDto.isEncrypted];
  227. }
  228. // ----- BUG #942 ---------
  229. if ([itemDto.etag length] == 0) {
  230. #ifndef EXTENSION
  231. [app messageNotification:@"Server error" description:@"Metadata fileID absent, record excluded, please fix" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  232. #endif
  233. continue;
  234. }
  235. // ------------------------
  236. [metadatas addObject:[CCUtility trasformedOCFileToCCMetadata:itemDto fileName:itemDto.fileName serverUrl:_metadataNet.serverUrl directoryID:directoryID autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:_metadataNet.account directoryUser:directoryUser isFolderEncrypted:isFolderEncrypted]];
  237. }
  238. dispatch_async(dispatch_get_main_queue(), ^{
  239. if ([self.delegate respondsToSelector:@selector(readFolderSuccess:metadataFolder:metadatas:)])
  240. [self.delegate readFolderSuccess:_metadataNet metadataFolder:metadataFolder metadatas:metadatas];
  241. });
  242. });
  243. [self complete];
  244. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) {
  245. NSInteger errorCode = response.statusCode;
  246. if (errorCode == 0)
  247. errorCode = error.code;
  248. // Error
  249. if ([self.delegate respondsToSelector:@selector(readFolderFailure:message:errorCode:)]) {
  250. if (errorCode == 503)
  251. [self.delegate readFolderFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  252. else
  253. [self.delegate readFolderFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  254. }
  255. // Request trusted certificated
  256. if ([error code] == NSURLErrorServerCertificateUntrusted)
  257. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  258. // Activity
  259. [[NCManageDatabase sharedInstance] addActivityClient:_metadataNet.serverUrl fileID:@"" action:k_activityDebugActionReadFolder selector:@"" note:[error.userInfo valueForKey:@"NSLocalizedDescription"] type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:_activeUrl];
  260. [self complete];
  261. }];
  262. }
  263. #pragma --------------------------------------------------------------------------------------------
  264. #pragma mark ===== Search =====
  265. #pragma --------------------------------------------------------------------------------------------
  266. - (void)search
  267. {
  268. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  269. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  270. [communication setUserAgent:[CCUtility getUserAgent]];
  271. NSString *path = [_activeUrl stringByAppendingString:dav];
  272. NSString *folder = [_metadataNet.serverUrl stringByReplacingOccurrencesOfString:[CCUtility getHomeServerUrlActiveUrl:_activeUrl] withString:@""];
  273. NSString *dateLastModified;
  274. if (_metadataNet.date) {
  275. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  276. NSLocale *enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
  277. [dateFormatter setLocale:enUSPOSIXLocale];
  278. [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZZ"];
  279. dateLastModified = [dateFormatter stringFromDate:_metadataNet.date];
  280. }
  281. [communication search:path folder:folder fileName: [NSString stringWithFormat:@"%%%@%%", _metadataNet.fileName] depth:_metadataNet.depth dateLastModified:dateLastModified contentType:_metadataNet.contentType withUserSessionToken:nil onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer, NSString *token) {
  282. NSMutableArray *metadatas = [NSMutableArray new];
  283. BOOL showHiddenFiles = [CCUtility getShowHiddenFiles];
  284. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:_metadataNet.serverUrl account:_metadataNet.account];
  285. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  286. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:_activeUrl];
  287. NSString *directoryUser = [CCUtility getDirectoryActiveUser:_activeUser activeUrl:_activeUrl];
  288. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  289. for(OCFileDto *itemDto in items) {
  290. NSString *serverUrl;
  291. itemDto.fileName = [itemDto.fileName stringByRemovingPercentEncoding];
  292. NSString *fileName = itemDto.fileName;
  293. if (itemDto.isDirectory)
  294. fileName = [fileName substringToIndex:[fileName length] - 1];
  295. // Skip hidden files
  296. if (!showHiddenFiles && [[fileName substringToIndex:1] isEqualToString:@"."])
  297. continue;
  298. // ----- BUG #942 ---------
  299. if ([itemDto.etag length] == 0) {
  300. #ifndef EXTENSION
  301. [app messageNotification:@"Server error" description:@"Metadata fileID absent, record excluded, please fix" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  302. #endif
  303. continue;
  304. }
  305. // ------------------------
  306. NSRange firstInstance = [itemDto.filePath rangeOfString:[NSString stringWithFormat:@"%@/files/%@", dav, _activeUser]];
  307. NSRange finalRange = NSMakeRange(firstInstance.location + firstInstance.length, itemDto.filePath.length-(firstInstance.location + firstInstance.length));
  308. if (finalRange.location != NSNotFound && finalRange.location + finalRange.length <= itemDto.filePath.length) {
  309. // It's safe to use range on str
  310. serverUrl = [itemDto.filePath substringWithRange:finalRange];
  311. } else {
  312. continue;
  313. }
  314. /* TRIM */
  315. if ([serverUrl hasPrefix:@"/"])
  316. serverUrl = [serverUrl substringFromIndex:1];
  317. if ([serverUrl hasSuffix:@"/"])
  318. serverUrl = [serverUrl substringToIndex:[serverUrl length] - 1];
  319. /* ---- */
  320. serverUrl = [CCUtility stringAppendServerUrl:[_activeUrl stringByAppendingString:webDAV] addFileName:serverUrl];
  321. serverUrl = [serverUrl stringByRemovingPercentEncoding];
  322. NSString *directoryID = [[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:serverUrl permissions:itemDto.permissions encrypted:itemDto.isEncrypted];
  323. [metadatas addObject:[CCUtility trasformedOCFileToCCMetadata:itemDto fileName:itemDto.fileName serverUrl:serverUrl directoryID:directoryID autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:_metadataNet.account directoryUser:directoryUser isFolderEncrypted:isFolderEncrypted]];
  324. }
  325. dispatch_async(dispatch_get_main_queue(), ^{
  326. if ([self.delegate respondsToSelector:@selector(searchSuccess:metadatas:)])
  327. [self.delegate searchSuccess:_metadataNet metadatas:metadatas];
  328. });
  329. });
  330. [self complete];
  331. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) {
  332. NSInteger errorCode = response.statusCode;
  333. if (errorCode == 0)
  334. errorCode = error.code;
  335. // Error
  336. if ([self.delegate respondsToSelector:@selector(searchFailure:message:errorCode:)]) {
  337. if (errorCode == 503)
  338. [self.delegate searchFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  339. else
  340. [self.delegate searchFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  341. }
  342. // Request trusted certificated
  343. if ([error code] == NSURLErrorServerCertificateUntrusted)
  344. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  345. [self complete];
  346. }];
  347. }
  348. #pragma --------------------------------------------------------------------------------------------
  349. #pragma mark ===== Setting Favorite =====
  350. #pragma --------------------------------------------------------------------------------------------
  351. - (void)settingFavorite
  352. {
  353. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  354. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  355. [communication setUserAgent:[CCUtility getUserAgent]];
  356. NSString *path = [_activeUrl stringByAppendingString:dav];
  357. [communication settingFavoriteServer:path andFileOrFolderPath:_metadataNet.fileName favorite:[_metadataNet.options boolValue] withUserSessionToken:nil onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer, NSString *token) {
  358. if ([self.delegate respondsToSelector:@selector(settingFavoriteSuccess:)])
  359. [self.delegate settingFavoriteSuccess:_metadataNet];
  360. [self complete];
  361. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) {
  362. NSInteger errorCode = response.statusCode;
  363. if (errorCode == 0)
  364. errorCode = error.code;
  365. // Error
  366. if ([self.delegate respondsToSelector:@selector(settingFavoriteFailure:message:errorCode:)]) {
  367. if (errorCode == 503)
  368. [self.delegate settingFavoriteFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  369. else
  370. [self.delegate settingFavoriteFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  371. }
  372. // Request trusted certificated
  373. if ([error code] == NSURLErrorServerCertificateUntrusted)
  374. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  375. [self complete];
  376. }];
  377. }
  378. #pragma --------------------------------------------------------------------------------------------
  379. #pragma mark ===== Listing Favorites =====
  380. #pragma --------------------------------------------------------------------------------------------
  381. - (void)listingFavorites
  382. {
  383. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  384. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  385. [communication setUserAgent:[CCUtility getUserAgent]];
  386. NSString *path = [_activeUrl stringByAppendingString:dav];
  387. NSString *folder = [_metadataNet.serverUrl stringByReplacingOccurrencesOfString:[CCUtility getHomeServerUrlActiveUrl:_activeUrl] withString:@""];
  388. [communication listingFavorites:path folder:folder withUserSessionToken:nil onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer, NSString *token) {
  389. NSMutableArray *metadatas = [NSMutableArray new];
  390. BOOL showHiddenFiles = [CCUtility getShowHiddenFiles];
  391. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:_metadataNet.serverUrl account:_metadataNet.account];
  392. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  393. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:_activeUrl];
  394. NSString *directoryUser = [CCUtility getDirectoryActiveUser:_activeUser activeUrl:_activeUrl];
  395. // Order by fileNamePath
  396. items = [items sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
  397. OCFileDto *record1 = obj1, *record2 = obj2;
  398. NSString *path1 = [[record1.filePath stringByAppendingString:record1.fileName] lowercaseString];
  399. NSString *path2 = [[record2.filePath stringByAppendingString:record2.fileName] lowercaseString];
  400. return [path1 compare:path2];
  401. }];
  402. for(OCFileDto *itemDto in items) {
  403. NSString *serverUrl;
  404. itemDto.fileName = [itemDto.fileName stringByRemovingPercentEncoding];
  405. itemDto.filePath = [itemDto.filePath stringByRemovingPercentEncoding];
  406. NSString *fileName = itemDto.fileName;
  407. if (itemDto.isDirectory)
  408. fileName = [fileName substringToIndex:[fileName length] - 1];
  409. // Skip hidden files
  410. if (!showHiddenFiles && [[fileName substringToIndex:1] isEqualToString:@"."])
  411. continue;
  412. // ----- BUG #942 ---------
  413. if ([itemDto.etag length] == 0) {
  414. #ifndef EXTENSION
  415. [app messageNotification:@"Server error" description:@"Metadata fileID absent, record excluded, please fix" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  416. #endif
  417. continue;
  418. }
  419. // ------------------------
  420. NSRange firstInstance = [itemDto.filePath rangeOfString:[NSString stringWithFormat:@"%@/files/%@", dav, _activeUser]];
  421. NSRange finalRange = NSMakeRange(firstInstance.location + firstInstance.length, itemDto.filePath.length-(firstInstance.location + firstInstance.length));
  422. if (finalRange.location != NSNotFound && finalRange.location + finalRange.length <= itemDto.filePath.length) {
  423. // It's safe to use range on str
  424. serverUrl = [itemDto.filePath substringWithRange:finalRange];
  425. } else {
  426. continue;
  427. }
  428. /* TRIM */
  429. if ([serverUrl hasPrefix:@"/"])
  430. serverUrl = [serverUrl substringFromIndex:1];
  431. if ([serverUrl hasSuffix:@"/"])
  432. serverUrl = [serverUrl substringToIndex:[serverUrl length] - 1];
  433. /* */
  434. serverUrl = [CCUtility stringAppendServerUrl:[_activeUrl stringByAppendingString:webDAV] addFileName:serverUrl];
  435. serverUrl = [serverUrl stringByRemovingPercentEncoding];
  436. NSString *directoryID = [[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:serverUrl permissions:itemDto.permissions encrypted:itemDto.isEncrypted];
  437. [metadatas addObject:[CCUtility trasformedOCFileToCCMetadata:itemDto fileName:itemDto.fileName serverUrl:serverUrl directoryID:directoryID autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:_metadataNet.account directoryUser:directoryUser isFolderEncrypted:isFolderEncrypted]];
  438. }
  439. if ([self.delegate respondsToSelector:@selector(listingFavoritesSuccess:metadatas:)])
  440. [self.delegate listingFavoritesSuccess:_metadataNet metadatas:metadatas];
  441. [self complete];
  442. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) {
  443. NSInteger errorCode = response.statusCode;
  444. if (errorCode == 0)
  445. errorCode = error.code;
  446. // Error
  447. if ([self.delegate respondsToSelector:@selector(listingFavoritesFailure:message:errorCode:)]) {
  448. if (errorCode == 503)
  449. [self.delegate listingFavoritesFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  450. else
  451. [self.delegate listingFavoritesFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  452. }
  453. // Request trusted certificated
  454. if ([error code] == NSURLErrorServerCertificateUntrusted)
  455. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  456. [self complete];
  457. }];
  458. }
  459. #pragma --------------------------------------------------------------------------------------------
  460. #pragma mark ===== Create Folder =====
  461. #pragma --------------------------------------------------------------------------------------------
  462. - (void)createFolder
  463. {
  464. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  465. NSString *nameFolderURL = [NSString stringWithFormat:@"%@/%@", _metadataNet.serverUrl, _metadataNet.fileName];
  466. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  467. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:_activeUrl];
  468. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  469. [communication setUserAgent:[CCUtility getUserAgent]];
  470. [communication createFolder:nameFolderURL onCommunication:communication withForbiddenCharactersSupported:YES successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  471. NSDictionary *fields = [response allHeaderFields];
  472. _metadataNet.fileID = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-FileId"]];
  473. _metadataNet.date = [CCUtility dateEnUsPosixFromCloud:[fields objectForKey:@"Date"]];
  474. if ([self.delegate respondsToSelector:@selector(createFolderSuccess:)])
  475. [self.delegate createFolderSuccess:_metadataNet];
  476. [self complete];
  477. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  478. NSString *message;
  479. if (([_metadataNet.fileName isEqualToString:autoUploadFileName] == YES && [_metadataNet.serverUrl isEqualToString:autoUploadDirectory] == YES))
  480. message = nil;
  481. else
  482. message = [CCError manageErrorOC:response.statusCode error:error];
  483. NSInteger errorCode = response.statusCode;
  484. if (errorCode == 0)
  485. errorCode = error.code;
  486. if ([self.delegate respondsToSelector:@selector(createFolderFailure:message:errorCode:)])
  487. [self.delegate createFolderFailure:_metadataNet message:message errorCode:errorCode];
  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. } errorBeforeRequest:^(NSError *error) {
  493. NSString *message;
  494. if (([_metadataNet.fileName isEqualToString:autoUploadFileName] == YES && [_metadataNet.serverUrl isEqualToString:autoUploadDirectory] == YES))
  495. message = nil;
  496. else {
  497. if (error.code == OCErrorForbidenCharacters)
  498. message = NSLocalizedStringFromTable(@"_forbidden_characters_from_server_", @"Error", nil);
  499. else
  500. message = NSLocalizedStringFromTable(@"_unknow_response_server_", @"Error", nil);
  501. }
  502. // Error
  503. if ([self.delegate respondsToSelector:@selector(createFolderFailure:message:errorCode:)]) {
  504. if (error.code == 503)
  505. [self.delegate createFolderFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:error.code];
  506. else
  507. [self.delegate createFolderFailure:_metadataNet message:message errorCode:error.code];
  508. }
  509. [self complete];
  510. }];
  511. }
  512. - (BOOL)automaticCreateFolderSync:(NSString *)folderPathName
  513. {
  514. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  515. __block BOOL noError = YES;
  516. dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
  517. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  518. [communication setUserAgent:[CCUtility getUserAgent]];
  519. [communication readFile:folderPathName onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  520. dispatch_semaphore_signal(semaphore);
  521. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  522. [communication createFolder:folderPathName onCommunication:communication withForbiddenCharactersSupported:YES successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  523. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:[CCUtility deletingLastPathComponentFromServerUrl:folderPathName] directoryID:nil];
  524. dispatch_semaphore_signal(semaphore);
  525. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  526. noError = NO;
  527. dispatch_semaphore_signal(semaphore);
  528. } errorBeforeRequest:^(NSError *error) {
  529. noError = NO;
  530. dispatch_semaphore_signal(semaphore);
  531. }];
  532. }];
  533. while (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_NOW))
  534. [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:k_timeout_webdav]];
  535. return noError;
  536. }
  537. #pragma --------------------------------------------------------------------------------------------
  538. #pragma mark ===== Delete =====
  539. #pragma --------------------------------------------------------------------------------------------
  540. - (void)deleteFileOrFolder
  541. {
  542. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  543. NSString *serverFileUrl = [NSString stringWithFormat:@"%@/%@", _metadataNet.serverUrl, _metadataNet.fileName];
  544. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  545. [communication setUserAgent:[CCUtility getUserAgent]];
  546. // E2E Delete only directory NOT encrypted
  547. if (_metadataNet.directory && _metadataNet.e2eEncrypted) {
  548. [self.delegate deleteFileOrFolderFailure:_metadataNet message:NSLocalizedString(@"_e2e_delete_folder_not_permitted_", nil) errorCode:0];
  549. [self complete];
  550. return;
  551. }
  552. [communication deleteFileOrFolder:serverFileUrl onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  553. if ([_metadataNet.selector rangeOfString:selectorDelete].location != NSNotFound && [self.delegate respondsToSelector:@selector(deleteFileOrFolderSuccess:)])
  554. [self.delegate deleteFileOrFolderSuccess:_metadataNet];
  555. [self complete];
  556. } failureRquest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  557. NSInteger errorCode = response.statusCode;
  558. if (errorCode == 0)
  559. errorCode = error.code;
  560. // Error
  561. if ([self.delegate respondsToSelector:@selector(deleteFileOrFolderFailure:message:errorCode:)]) {
  562. if (errorCode == 503)
  563. [self.delegate deleteFileOrFolderFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  564. else
  565. [self.delegate deleteFileOrFolderFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  566. }
  567. // Request trusted certificated
  568. if ([error code] == NSURLErrorServerCertificateUntrusted)
  569. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  570. [self complete];
  571. }];
  572. }
  573. #pragma --------------------------------------------------------------------------------------------
  574. #pragma mark ===== Move =====
  575. #pragma --------------------------------------------------------------------------------------------
  576. - (void)moveFileOrFolder
  577. {
  578. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  579. NSString *origineURL = [NSString stringWithFormat:@"%@/%@", _metadataNet.serverUrl, _metadataNet.fileName];
  580. NSString *destinazioneURL = [NSString stringWithFormat:@"%@/%@", _metadataNet.serverUrlTo, _metadataNet.fileNameTo];
  581. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  582. [communication setUserAgent:[CCUtility getUserAgent]];
  583. [communication moveFileOrFolder:origineURL toDestiny:destinazioneURL onCommunication:communication withForbiddenCharactersSupported:YES successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  584. if ([_metadataNet.selector isEqualToString:selectorRename] && [self.delegate respondsToSelector:@selector(renameSuccess:)])
  585. [self.delegate renameSuccess:_metadataNet];
  586. if ([_metadataNet.selector rangeOfString:selectorMove].location != NSNotFound && [self.delegate respondsToSelector:@selector(moveSuccess:)])
  587. [self.delegate moveSuccess:_metadataNet];
  588. [self complete];
  589. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  590. NSInteger errorCode = response.statusCode;
  591. if (errorCode == 0)
  592. errorCode = error.code;
  593. if ([self.delegate respondsToSelector:@selector(renameMoveFileOrFolderFailure:message:errorCode:)])
  594. [self.delegate renameMoveFileOrFolderFailure:_metadataNet message:[CCError manageErrorOC:response.statusCode error:error] errorCode:errorCode];
  595. // Request trusted certificated
  596. if ([error code] == NSURLErrorServerCertificateUntrusted)
  597. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  598. [self complete];
  599. } errorBeforeRequest:^(NSError *error) {
  600. NSString *message;
  601. if (error.code == OCErrorMovingTheDestinyAndOriginAreTheSame) {
  602. message = NSLocalizedStringFromTable(@"_error_folder_destiny_is_the_same_", @"Error", nil);
  603. } else if (error.code == OCErrorMovingFolderInsideHimself) {
  604. message = NSLocalizedStringFromTable(@"_error_folder_destiny_is_the_same_", @"Error", nil);
  605. } else if (error.code == OCErrorMovingDestinyNameHaveForbiddenCharacters) {
  606. message = NSLocalizedStringFromTable(@"_forbidden_characters_from_server_", @"Error", nil);
  607. } else {
  608. message = NSLocalizedStringFromTable(@"_unknow_response_server_", @"Error", nil);
  609. }
  610. // Error
  611. if ([self.delegate respondsToSelector:@selector(renameMoveFileOrFolderFailure:message:errorCode:)]) {
  612. if (error.code == 503)
  613. [self.delegate renameMoveFileOrFolderFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:error.code];
  614. else
  615. [self.delegate renameMoveFileOrFolderFailure:_metadataNet message:message errorCode:error.code];
  616. }
  617. [self complete];
  618. }];
  619. }
  620. #pragma --------------------------------------------------------------------------------------------
  621. #pragma mark ===== ReadFile =====
  622. #pragma --------------------------------------------------------------------------------------------
  623. - (void)readFile
  624. {
  625. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  626. NSString *fileName;
  627. if (_metadataNet.fileName) {
  628. fileName = [NSString stringWithFormat:@"%@/%@", _metadataNet.serverUrl, _metadataNet.fileName];
  629. } else {
  630. _metadataNet.fileName = @".";
  631. fileName = _metadataNet.serverUrl;
  632. }
  633. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  634. [communication setUserAgent:[CCUtility getUserAgent]];
  635. [communication readFile:fileName onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  636. tableAccount *recordAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  637. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:_metadataNet.serverUrl account:_metadataNet.account];
  638. if ([recordAccount.account isEqualToString:_metadataNet.account] && [items count] > 0) {
  639. tableMetadata *metadata = [tableMetadata new];
  640. OCFileDto *itemDto = [items objectAtIndex:0];
  641. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_metadataNet.serverUrl];
  642. if (directoryID) {
  643. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  644. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:_activeUrl];
  645. NSString *directoryUser = [CCUtility getDirectoryActiveUser:_activeUser activeUrl:_activeUrl];
  646. metadata = [CCUtility trasformedOCFileToCCMetadata:itemDto fileName:_metadataNet.fileName serverUrl:_metadataNet.serverUrl directoryID:directoryID autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:_metadataNet.account directoryUser:directoryUser isFolderEncrypted:isFolderEncrypted];
  647. if([self.delegate respondsToSelector:@selector(readFileSuccess:metadata:)])
  648. [self.delegate readFileSuccess:_metadataNet metadata:metadata];
  649. } else {
  650. if([self.delegate respondsToSelector:@selector(readFileFailure:message:errorCode:)])
  651. [self.delegate readFileFailure:_metadataNet message:@"Directory not found" errorCode:0];
  652. }
  653. }
  654. // BUG 1038
  655. if ([items count] == 0) {
  656. #ifndef EXTENSION
  657. [app messageNotification:@"Server error" description:@"Read File WebDAV : [items NULL] please fix" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  658. #endif
  659. if([self.delegate respondsToSelector:@selector(readFileFailure:message:errorCode:)])
  660. [self.delegate readFileFailure:_metadataNet message:@"Read File WebDAV : [items NULL] please fix" errorCode:0];
  661. }
  662. [self complete];
  663. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  664. tableAccount *recordAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  665. _metadataNet.errorRetry++;
  666. NSInteger errorCode = response.statusCode;
  667. if (errorCode == 0)
  668. errorCode = error.code;
  669. // Error
  670. if ([self.delegate respondsToSelector:@selector(readFileFailure:message:errorCode:)] && [recordAccount.account isEqualToString:_metadataNet.account]) {
  671. if (errorCode == 503)
  672. [self.delegate readFileFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  673. else
  674. [self.delegate readFileFailure:_metadataNet message:[CCError manageErrorOC:response.statusCode error:error] errorCode:errorCode];
  675. }
  676. // Request trusted certificated
  677. if ([error code] == NSURLErrorServerCertificateUntrusted)
  678. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  679. [self complete];
  680. }];
  681. }
  682. - (NSError *)readFileSync:(NSString *)filePathName
  683. {
  684. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  685. __block NSError *returnError;
  686. dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
  687. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  688. [communication setUserAgent:[CCUtility getUserAgent]];
  689. [communication readFile:filePathName onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  690. returnError = nil;
  691. dispatch_semaphore_signal(semaphore);
  692. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  693. // Request trusted certificated
  694. if ([error code] == NSURLErrorServerCertificateUntrusted)
  695. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  696. returnError = error;
  697. dispatch_semaphore_signal(semaphore);
  698. }];
  699. while (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_NOW))
  700. [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:k_timeout_webdav]];
  701. return returnError;
  702. }
  703. #pragma --------------------------------------------------------------------------------------------
  704. #pragma mark ===== Shared =====
  705. #pragma --------------------------------------------------------------------------------------------
  706. - (void)readShareServer
  707. {
  708. #ifndef EXTENSION
  709. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  710. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  711. [communication setUserAgent:[CCUtility getUserAgent]];
  712. [communication readSharedByServer:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  713. BOOL openWindow = NO;
  714. [app.sharesID removeAllObjects];
  715. tableAccount *recordAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  716. if ([recordAccount.account isEqualToString:_metadataNet.account]) {
  717. for (OCSharedDto *item in items)
  718. [app.sharesID setObject:item forKey:[@(item.idRemoteShared) stringValue]];
  719. if ([_metadataNet.selector isEqual:selectorOpenWindowShare]) openWindow = YES;
  720. if ([_metadataNet.action isEqual:actionUpdateShare]) openWindow = YES;
  721. if ([_metadataNet.action isEqual:actionShare]) openWindow = YES;
  722. if ([_metadataNet.action isEqual:actionShareWith]) openWindow = YES;
  723. }
  724. if([self.delegate respondsToSelector:@selector(readSharedSuccess:items:openWindow:)])
  725. [self.delegate readSharedSuccess:_metadataNet items:app.sharesID openWindow:openWindow];
  726. [self complete];
  727. } failureRequest :^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  728. NSInteger errorCode = response.statusCode;
  729. if (errorCode == 0)
  730. errorCode = error.code;
  731. // Error
  732. if ([self.delegate respondsToSelector:@selector(shareFailure:message:errorCode:)]) {
  733. if (errorCode == 503)
  734. [self.delegate shareFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  735. else
  736. [self.delegate shareFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  737. }
  738. // Request trusted certificated
  739. if ([error code] == NSURLErrorServerCertificateUntrusted)
  740. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  741. [self complete];
  742. }];
  743. #endif
  744. }
  745. - (void)share
  746. {
  747. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  748. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  749. [communication setUserAgent:[CCUtility getUserAgent]];
  750. [communication shareFileOrFolderByServer:[_activeUrl stringByAppendingString:@"/"] andFileOrFolderPath:[_metadataNet.fileName encodeString:NSUTF8StringEncoding] andPassword:[_metadataNet.password encodeString:NSUTF8StringEncoding] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *token, NSString *redirectedServer) {
  751. [self readShareServer];
  752. } failureRequest :^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  753. NSInteger errorCode = response.statusCode;
  754. if (errorCode == 0)
  755. errorCode = error.code;
  756. // Error
  757. if ([self.delegate respondsToSelector:@selector(shareFailure:message:errorCode:)]) {
  758. if (errorCode == 503)
  759. [self.delegate shareFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  760. else
  761. [self.delegate shareFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  762. }
  763. // Request trusted certificated
  764. if ([error code] == NSURLErrorServerCertificateUntrusted)
  765. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  766. [self complete];
  767. }];
  768. }
  769. // * @param shareeType -> NSInteger: to set the type of sharee (user/group/federated)
  770. - (void)shareWith
  771. {
  772. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  773. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  774. [communication setUserAgent:[CCUtility getUserAgent]];
  775. [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) {
  776. [self readShareServer];
  777. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  778. NSInteger errorCode = response.statusCode;
  779. if (errorCode == 0)
  780. errorCode = error.code;
  781. // Error
  782. if ([self.delegate respondsToSelector:@selector(shareFailure:message:errorCode:)]) {
  783. if (errorCode == 503)
  784. [self.delegate shareFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  785. else
  786. [self.delegate shareFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  787. }
  788. // Request trusted certificated
  789. if ([error code] == NSURLErrorServerCertificateUntrusted)
  790. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  791. [self complete];
  792. }];
  793. }
  794. - (void)updateShare
  795. {
  796. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  797. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  798. [communication setUserAgent:[CCUtility getUserAgent]];
  799. [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) {
  800. [self readShareServer];
  801. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  802. #ifndef EXTENSION
  803. [app messageNotification:@"_error_" description:[CCError manageErrorOC:response.statusCode error:error] visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  804. #endif
  805. NSInteger errorCode = response.statusCode;
  806. if (errorCode == 0)
  807. errorCode = error.code;
  808. // Error
  809. if ([self.delegate respondsToSelector:@selector(shareFailure:message:errorCode:)]) {
  810. if (errorCode == 503)
  811. [self.delegate shareFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  812. else
  813. [self.delegate shareFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  814. }
  815. // Request trusted certificated
  816. if ([error code] == NSURLErrorServerCertificateUntrusted)
  817. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  818. [self complete];
  819. }];
  820. }
  821. - (void)unShare
  822. {
  823. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  824. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  825. [communication setUserAgent:[CCUtility getUserAgent]];
  826. [communication unShareFileOrFolderByServer:[_activeUrl stringByAppendingString:@"/"] andIdRemoteShared:[_metadataNet.share intValue] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  827. if([self.delegate respondsToSelector:@selector(unShareSuccess:)])
  828. [self.delegate unShareSuccess:_metadataNet];
  829. [self complete];
  830. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  831. #ifndef EXTENSION
  832. [app messageNotification:@"_error_" description:[CCError manageErrorOC:response.statusCode error:error] visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  833. #endif
  834. NSInteger errorCode = response.statusCode;
  835. if (errorCode == 0)
  836. errorCode = error.code;
  837. // Error
  838. if ([self.delegate respondsToSelector:@selector(shareFailure:message:errorCode:)]) {
  839. if (errorCode == 503)
  840. [self.delegate shareFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  841. else
  842. [self.delegate shareFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  843. }
  844. // Request trusted certificated
  845. if ([error code] == NSURLErrorServerCertificateUntrusted)
  846. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  847. [self complete];
  848. }];
  849. }
  850. - (void)getUserAndGroup
  851. {
  852. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  853. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  854. [communication setUserAgent:[CCUtility getUserAgent]];
  855. [communication searchUsersAndGroupsWith:_metadataNet.options forPage:1 with:50 ofServer:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *itemList, NSString *redirectedServer) {
  856. if([self.delegate respondsToSelector:@selector(getUserAndGroupSuccess:items:)])
  857. [self.delegate getUserAndGroupSuccess:_metadataNet items:itemList];
  858. [self complete];
  859. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  860. NSInteger errorCode = response.statusCode;
  861. if (errorCode == 0)
  862. errorCode = error.code;
  863. // Error
  864. if ([self.delegate respondsToSelector:@selector(getUserAndGroupFailure:message:errorCode:)]) {
  865. if (errorCode == 503)
  866. [self.delegate getUserAndGroupFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  867. else
  868. [self.delegate getUserAndGroupFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  869. }
  870. // Request trusted certificated
  871. if ([error code] == NSURLErrorServerCertificateUntrusted)
  872. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  873. [self complete];
  874. }];
  875. }
  876. - (void)getSharePermissionsFile
  877. {
  878. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  879. NSString *fileName = [NSString stringWithFormat:@"%@/%@", _metadataNet.serverUrl, _metadataNet.fileName];
  880. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  881. [communication setUserAgent:[CCUtility getUserAgent]];
  882. [communication getSharePermissionsFile:fileName onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *permissions, NSString *redirectedServer) {
  883. if([self.delegate respondsToSelector:@selector(getSharePermissionsFileSuccess:permissions:)])
  884. [self.delegate getSharePermissionsFileSuccess:_metadataNet permissions:permissions];
  885. [self complete];
  886. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  887. NSInteger errorCode = response.statusCode;
  888. if (errorCode == 0)
  889. errorCode = error.code;
  890. // Error
  891. if ([self.delegate respondsToSelector:@selector(getSharePermissionsFileFailure:message:errorCode:)]) {
  892. if (errorCode == 503)
  893. [self.delegate getSharePermissionsFileFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  894. else
  895. [self.delegate getSharePermissionsFileFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  896. }
  897. // Request trusted certificated
  898. if ([error code] == NSURLErrorServerCertificateUntrusted)
  899. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  900. [self complete];
  901. }];
  902. }
  903. #pragma --------------------------------------------------------------------------------------------
  904. #pragma mark ===== Activity =====
  905. #pragma --------------------------------------------------------------------------------------------
  906. - (void)getActivityServer
  907. {
  908. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  909. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  910. [communication setUserAgent:[CCUtility getUserAgent]];
  911. [communication getActivityServer:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfActivity, NSString *redirectedServer) {
  912. if ([self.delegate respondsToSelector:@selector(getActivityServerSuccess:)])
  913. [self.delegate getActivityServerSuccess:listOfActivity];
  914. [self complete];
  915. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  916. NSInteger errorCode = response.statusCode;
  917. if (errorCode == 0)
  918. errorCode = error.code;
  919. // Error
  920. if ([self.delegate respondsToSelector:@selector(getActivityServerFailure:message:errorCode:)]) {
  921. if (errorCode == 503)
  922. [self.delegate getActivityServerFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  923. else
  924. [self.delegate getActivityServerFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  925. }
  926. // Request trusted certificated
  927. if ([error code] == NSURLErrorServerCertificateUntrusted)
  928. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  929. [self complete];
  930. }];
  931. }
  932. #pragma --------------------------------------------------------------------------------------------
  933. #pragma mark ===== External Sites =====
  934. #pragma --------------------------------------------------------------------------------------------
  935. - (void)getExternalSitesServer
  936. {
  937. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  938. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  939. [communication setUserAgent:[CCUtility getUserAgent]];
  940. [communication getExternalSitesServer:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfExternalSites, NSString *redirectedServer) {
  941. if ([self.delegate respondsToSelector:@selector(getExternalSitesServerSuccess:)])
  942. [self.delegate getExternalSitesServerSuccess:listOfExternalSites];
  943. [self complete];
  944. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  945. NSInteger errorCode = response.statusCode;
  946. if (errorCode == 0)
  947. errorCode = error.code;
  948. // Error
  949. if ([self.delegate respondsToSelector:@selector(getExternalSitesServerFailure:message:errorCode:)]) {
  950. if (errorCode == 503)
  951. [self.delegate getExternalSitesServerFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  952. else
  953. [self.delegate getExternalSitesServerFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  954. }
  955. // Request trusted certificated
  956. if ([error code] == NSURLErrorServerCertificateUntrusted)
  957. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  958. [self complete];
  959. }];
  960. }
  961. #pragma --------------------------------------------------------------------------------------------
  962. #pragma mark ===== Middleware Ping =====
  963. #pragma --------------------------------------------------------------------------------------------
  964. /*
  965. - (void)middlewarePing
  966. {
  967. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  968. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  969. [communication setUserAgent:[CCUtility getUserAgent]];
  970. [communication getMiddlewarePing:_metadataNet.serverUrl onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfExternalSites, NSString *redirectedServer) {
  971. [self complete];
  972. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  973. NSInteger errorCode = response.statusCode;
  974. if (errorCode == 0)
  975. errorCode = error.code;
  976. // Error
  977. if ([self.delegate respondsToSelector:@selector(getExternalSitesServerFailure:message:errorCode:)]) {
  978. if (errorCode == 503)
  979. [self.delegate getExternalSitesServerFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  980. else
  981. [self.delegate getExternalSitesServerFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  982. }
  983. // Request trusted certificated
  984. if ([error code] == NSURLErrorServerCertificateUntrusted)
  985. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  986. [self complete];
  987. }];
  988. }
  989. */
  990. #pragma --------------------------------------------------------------------------------------------
  991. #pragma mark ===== Notification =====
  992. #pragma --------------------------------------------------------------------------------------------
  993. - (void)getNotificationServer
  994. {
  995. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  996. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  997. [communication setUserAgent:[CCUtility getUserAgent]];
  998. [communication getNotificationServer:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfNotifications, NSString *redirectedServer) {
  999. if ([self.delegate respondsToSelector:@selector(getNotificationServerSuccess:)])
  1000. [self.delegate getNotificationServerSuccess:listOfNotifications];
  1001. [self complete];
  1002. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1003. NSInteger errorCode = response.statusCode;
  1004. if (errorCode == 0)
  1005. errorCode = error.code;
  1006. // Error
  1007. if ([self.delegate respondsToSelector:@selector(getNotificationServerFailure:message:errorCode:)]) {
  1008. if (errorCode == 503)
  1009. [self.delegate getNotificationServerFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  1010. else
  1011. [self.delegate getNotificationServerFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1012. }
  1013. // Request trusted certificated
  1014. if ([error code] == NSURLErrorServerCertificateUntrusted)
  1015. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1016. // Activity
  1017. [[NCManageDatabase sharedInstance] addActivityClient:_activeUrl fileID:@"" action:k_activityDebugActionGetNotification selector:@"" note:[error.userInfo valueForKey:@"NSLocalizedDescription"] type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:_activeUrl];
  1018. [self complete];
  1019. }];
  1020. }
  1021. - (void)setNotificationServer
  1022. {
  1023. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1024. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  1025. [communication setUserAgent:[CCUtility getUserAgent]];
  1026. NSString *type = _metadataNet.options;
  1027. [communication setNotificationServer:_metadataNet.serverUrl type:type onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1028. if ([self.delegate respondsToSelector:@selector(setNotificationServerSuccess:)])
  1029. [self.delegate setNotificationServerSuccess:_metadataNet];
  1030. [self complete];
  1031. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1032. NSInteger errorCode = response.statusCode;
  1033. if (errorCode == 0)
  1034. errorCode = error.code;
  1035. // Error
  1036. if ([self.delegate respondsToSelector:@selector(setNotificationServerFailure:message:errorCode:)]) {
  1037. if (errorCode == 503)
  1038. [self.delegate setNotificationServerFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  1039. else
  1040. [self.delegate setNotificationServerFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1041. }
  1042. // Request trusted certificated
  1043. if ([error code] == NSURLErrorServerCertificateUntrusted)
  1044. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1045. [self complete];
  1046. }];
  1047. }
  1048. - (void)subscribingNextcloudServer
  1049. {
  1050. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1051. communication.kindOfCredential = credentialNotSet;
  1052. [communication setUserAgent:[CCUtility getUserAgent]];
  1053. NSDictionary *parameter = _metadataNet.options;
  1054. NSString *pushToken = [parameter objectForKey:@"pushToken"];
  1055. NSString *pushTokenHash = [parameter objectForKey:@"pushTokenHash"];
  1056. NSString *devicePublicKey = [parameter objectForKey:@"devicePublicKey"];
  1057. // encode URL
  1058. devicePublicKey = [devicePublicKey stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
  1059. [communication subscribingNextcloudServerPush:_activeUrl pushTokenHash:pushTokenHash devicePublicKey:devicePublicKey proxyServerPath: [NCBrandOptions sharedInstance].pushNotificationServer onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *publicKey, NSString *deviceIdentifier, NSString *signature, NSString *redirectedServer) {
  1060. // encode URL
  1061. deviceIdentifier = [deviceIdentifier stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
  1062. signature = [signature stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
  1063. publicKey = [publicKey stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
  1064. [communication subscribingPushProxy:[NCBrandOptions sharedInstance].pushNotificationServer pushToken:pushToken deviceIdentifier:deviceIdentifier deviceIdentifierSignature:signature userPublicKey: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 andUserID:_activeUserID 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 ===== Capabilities =====
  1136. #pragma --------------------------------------------------------------------------------------------
  1137. - (void)getCapabilitiesOfServer
  1138. {
  1139. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1140. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  1141. [communication setUserAgent:[CCUtility getUserAgent]];
  1142. [communication getCapabilitiesOfServer:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, OCCapabilities *capabilities, NSString *redirectedServer) {
  1143. tableAccount *recordAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  1144. if ([self.delegate respondsToSelector:@selector(getCapabilitiesOfServerSuccess:)] && [recordAccount.account isEqualToString:_metadataNet.account])
  1145. [self.delegate getCapabilitiesOfServerSuccess:capabilities];
  1146. [self complete];
  1147. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1148. NSInteger errorCode = response.statusCode;
  1149. if (errorCode == 0)
  1150. errorCode = error.code;
  1151. // Error
  1152. if ([self.delegate respondsToSelector:@selector(getCapabilitiesOfServerFailure:message:errorCode:)]) {
  1153. if (errorCode == 503)
  1154. [self.delegate getCapabilitiesOfServerFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  1155. else
  1156. [self.delegate getCapabilitiesOfServerFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1157. }
  1158. // Request trusted certificated
  1159. if ([error code] == NSURLErrorServerCertificateUntrusted)
  1160. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1161. // Activity
  1162. [[NCManageDatabase sharedInstance] addActivityClient:_activeUrl fileID:@"" action:k_activityDebugActionCapabilities selector:@"" note:[error.userInfo valueForKey:@"NSLocalizedDescription"] type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:_activeUrl];
  1163. [self complete];
  1164. }];
  1165. }
  1166. #pragma --------------------------------------------------------------------------------------------
  1167. #pragma mark ===== End-to-End Encryption =====
  1168. #pragma --------------------------------------------------------------------------------------------
  1169. - (void)getEndToEndPublicKeys
  1170. {
  1171. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1172. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  1173. [communication setUserAgent:[CCUtility getUserAgent]];
  1174. [communication getEndToEndPublicKeys:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *publicKey, NSString *redirectedServer) {
  1175. _metadataNet.key = publicKey;
  1176. if ([self.delegate respondsToSelector:@selector(getEndToEndPublicKeysSuccess:)])
  1177. [self.delegate getEndToEndPublicKeysSuccess:_metadataNet];
  1178. [self complete];
  1179. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1180. NSInteger errorCode = response.statusCode;
  1181. if (errorCode == 0)
  1182. errorCode = error.code;
  1183. // Error
  1184. if ([self.delegate respondsToSelector:@selector(getEndToEndPublicKeysFailure:message:errorCode:)])
  1185. [self.delegate getEndToEndPublicKeysFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1186. // Request trusted certificated
  1187. if ([error code] == NSURLErrorServerCertificateUntrusted)
  1188. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1189. [self complete];
  1190. }];
  1191. }
  1192. - (void)getEndToEndPrivateKeyCipher
  1193. {
  1194. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1195. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  1196. [communication setUserAgent:[CCUtility getUserAgent]];
  1197. [communication getEndToEndPrivateKeyCipher:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *privateKeyChiper, NSString *redirectedServer) {
  1198. _metadataNet.key = privateKeyChiper;
  1199. if ([self.delegate respondsToSelector:@selector(getEndToEndPrivateKeyCipherSuccess:)])
  1200. [self.delegate getEndToEndPrivateKeyCipherSuccess:_metadataNet];
  1201. [self complete];
  1202. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1203. NSInteger errorCode = response.statusCode;
  1204. if (errorCode == 0)
  1205. errorCode = error.code;
  1206. // Error
  1207. if ([self.delegate respondsToSelector:@selector(getEndToEndPrivateKeyCipherFailure:message:errorCode:)])
  1208. [self.delegate getEndToEndPrivateKeyCipherFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1209. // Request trusted certificated
  1210. if ([error code] == NSURLErrorServerCertificateUntrusted)
  1211. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1212. [self complete];
  1213. }];
  1214. }
  1215. - (void)signEndToEndPublicKey
  1216. {
  1217. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1218. // URL Encode
  1219. NSString *publicKey = [CCUtility URLEncodeStringFromString:_metadataNet.key];
  1220. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  1221. [communication setUserAgent:[CCUtility getUserAgent]];
  1222. [communication signEndToEndPublicKey:[_activeUrl stringByAppendingString:@"/"] publicKey:publicKey onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *publicKey, NSString *redirectedServer) {
  1223. _metadataNet.key = publicKey;
  1224. if ([self.delegate respondsToSelector:@selector(signEndToEndPublicKeySuccess:)])
  1225. [self.delegate signEndToEndPublicKeySuccess:_metadataNet];
  1226. [self complete];
  1227. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1228. NSInteger errorCode = response.statusCode;
  1229. if (errorCode == 0)
  1230. errorCode = error.code;
  1231. // Error
  1232. if ([self.delegate respondsToSelector:@selector(signEndToEndPublicKeyFailure:message:errorCode:)])
  1233. [self.delegate signEndToEndPublicKeyFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1234. // Request trusted certificated
  1235. if ([error code] == NSURLErrorServerCertificateUntrusted)
  1236. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1237. [self complete];
  1238. }];
  1239. }
  1240. - (void)storeEndToEndPrivateKeyCipher
  1241. {
  1242. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1243. // URL Encode
  1244. NSString *privateKeyChiper = [CCUtility URLEncodeStringFromString:_metadataNet.keyCipher];
  1245. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  1246. [communication setUserAgent:[CCUtility getUserAgent]];
  1247. [communication storeEndToEndPrivateKeyCipher:[_activeUrl stringByAppendingString:@"/"] privateKeyChiper:privateKeyChiper onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *privateKey, NSString *redirectedServer) {
  1248. if ([self.delegate respondsToSelector:@selector(storeEndToEndPrivateKeyCipherSuccess:)])
  1249. [self.delegate storeEndToEndPrivateKeyCipherSuccess:_metadataNet];
  1250. [self complete];
  1251. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1252. NSInteger errorCode = response.statusCode;
  1253. if (errorCode == 0)
  1254. errorCode = error.code;
  1255. // Error
  1256. if ([self.delegate respondsToSelector:@selector(storeEndToEndPrivateKeyCipherFailure:message:errorCode:)])
  1257. [self.delegate storeEndToEndPrivateKeyCipherFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1258. // Request trusted certificated
  1259. if ([error code] == NSURLErrorServerCertificateUntrusted)
  1260. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1261. [self complete];
  1262. }];
  1263. }
  1264. - (void)deleteEndToEndPublicKey
  1265. {
  1266. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1267. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  1268. [communication setUserAgent:[CCUtility getUserAgent]];
  1269. [communication deleteEndToEndPublicKey:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1270. if ([self.delegate respondsToSelector:@selector(deleteEndToEndPublicKeySuccess:)])
  1271. [self.delegate deleteEndToEndPublicKeySuccess:_metadataNet];
  1272. [self complete];
  1273. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1274. NSInteger errorCode = response.statusCode;
  1275. if (errorCode == 0)
  1276. errorCode = error.code;
  1277. // Error
  1278. if ([self.delegate respondsToSelector:@selector(deleteEndToEndPublicKeyFailure:message:errorCode:)])
  1279. [self.delegate deleteEndToEndPublicKeyFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1280. // Request trusted certificated
  1281. if ([error code] == NSURLErrorServerCertificateUntrusted)
  1282. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1283. [self complete];
  1284. }];
  1285. }
  1286. - (void)deleteEndToEndPrivateKey
  1287. {
  1288. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1289. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  1290. [communication setUserAgent:[CCUtility getUserAgent]];
  1291. [communication deleteEndToEndPrivateKey:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1292. if ([self.delegate respondsToSelector:@selector(deleteEndToEndPrivateKeySuccess:)])
  1293. [self.delegate deleteEndToEndPrivateKeySuccess:_metadataNet];
  1294. [self complete];
  1295. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1296. NSInteger errorCode = response.statusCode;
  1297. if (errorCode == 0)
  1298. errorCode = error.code;
  1299. // Error
  1300. if ([self.delegate respondsToSelector:@selector(deleteEndToEndPrivateKeyFailure:message:errorCode:)])
  1301. [self.delegate deleteEndToEndPrivateKeyFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1302. // Request trusted certificated
  1303. if ([error code] == NSURLErrorServerCertificateUntrusted)
  1304. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1305. [self complete];
  1306. }];
  1307. }
  1308. - (void)getEndToEndServerPublicKey
  1309. {
  1310. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1311. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  1312. [communication setUserAgent:[CCUtility getUserAgent]];
  1313. [communication getEndToEndServerPublicKey:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *publicKey, NSString *redirectedServer) {
  1314. _metadataNet.key = publicKey;
  1315. if ([self.delegate respondsToSelector:@selector(getEndToEndServerPublicKeySuccess:)])
  1316. [self.delegate getEndToEndServerPublicKeySuccess:_metadataNet];
  1317. [self complete];
  1318. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1319. NSInteger errorCode = response.statusCode;
  1320. if (errorCode == 0)
  1321. errorCode = error.code;
  1322. // Error
  1323. if ([self.delegate respondsToSelector:@selector(getEndToEndServerPublicKeyFailure:message:errorCode:)])
  1324. [self.delegate getEndToEndServerPublicKeyFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1325. // Request trusted certificated
  1326. if ([error code] == NSURLErrorServerCertificateUntrusted)
  1327. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1328. [self complete];
  1329. }];
  1330. }
  1331. - (void)getEndToEndMetadata
  1332. {
  1333. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1334. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  1335. [communication setUserAgent:[CCUtility getUserAgent]];
  1336. [communication getEndToEndMetadata:[_activeUrl stringByAppendingString:@"/"] fileID:_metadataNet.fileID onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *encryptedMetadata, NSString *redirectedServer) {
  1337. _metadataNet.encryptedMetadata = encryptedMetadata;
  1338. if ([self.delegate respondsToSelector:@selector(getEndToEndMetadataSuccess:)])
  1339. [self.delegate getEndToEndMetadataSuccess:_metadataNet];
  1340. [self complete];
  1341. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1342. NSInteger errorCode = response.statusCode;
  1343. if (errorCode == 0)
  1344. errorCode = error.code;
  1345. // Error
  1346. if ([self.delegate respondsToSelector:@selector(getEndToEndMetadataFailure:message:errorCode:)])
  1347. [self.delegate getEndToEndMetadataFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1348. // Request trusted certificated
  1349. if ([error code] == NSURLErrorServerCertificateUntrusted)
  1350. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1351. [self complete];
  1352. }];
  1353. }
  1354. - (void)deleteEndToEndMetadata
  1355. {
  1356. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1357. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  1358. [communication setUserAgent:[CCUtility getUserAgent]];
  1359. [communication deleteEndToEndMetadata:[_activeUrl stringByAppendingString:@"/"] fileID:_metadataNet.fileID onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1360. if ([self.delegate respondsToSelector:@selector(deleteEndToEndMetadataSuccess:)])
  1361. [self.delegate deleteEndToEndMetadataSuccess:_metadataNet];
  1362. [self complete];
  1363. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1364. NSInteger errorCode = response.statusCode;
  1365. if (errorCode == 0)
  1366. errorCode = error.code;
  1367. // Error
  1368. if ([self.delegate respondsToSelector:@selector(deleteEndToEndMetadataFailure:message:errorCode:)])
  1369. [self.delegate deleteEndToEndMetadataFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1370. // Request trusted certificated
  1371. if ([error code] == NSURLErrorServerCertificateUntrusted)
  1372. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1373. [self complete];
  1374. }];
  1375. }
  1376. - (void)unlockEndToEndFolderEncrypted
  1377. {
  1378. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1379. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  1380. [communication setUserAgent:[CCUtility getUserAgent]];
  1381. [communication unlockEndToEndFolderEncrypted:[_activeUrl stringByAppendingString:@"/"] fileID:_metadataNet.fileID token:_metadataNet.token onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1382. // 200 ok: file unlocked successful
  1383. if ([self.delegate respondsToSelector:@selector(unlockEndToEndFolderEncryptedSuccess:)])
  1384. [self.delegate unlockEndToEndFolderEncryptedSuccess:_metadataNet];
  1385. [self complete];
  1386. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1387. NSInteger errorCode = response.statusCode;
  1388. if (errorCode == 0)
  1389. errorCode = error.code;
  1390. // Error
  1391. if ([self.delegate respondsToSelector:@selector(unlockEndToEndFolderEncryptedFailure:message:errorCode:)])
  1392. [self.delegate unlockEndToEndFolderEncryptedFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1393. // Request trusted certificated
  1394. if ([error code] == NSURLErrorServerCertificateUntrusted)
  1395. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1396. [self complete];
  1397. }];
  1398. }
  1399. @end
  1400. #pragma --------------------------------------------------------------------------------------------
  1401. #pragma mark ===== OCURLSessionManager =====
  1402. #pragma --------------------------------------------------------------------------------------------
  1403. @implementation OCURLSessionManager
  1404. - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
  1405. {
  1406. // The pinnning check
  1407. if ([[CCCertificate sharedManager] checkTrustedChallenge:challenge]) {
  1408. completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  1409. } else {
  1410. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  1411. }
  1412. }
  1413. @end