OCNetworking.m 108 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137
  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. }
  37. @end
  38. @implementation OCnetworking
  39. - (id)initWithDelegate:(id <OCNetworkingDelegate>)delegate metadataNet:(CCMetadataNet *)metadataNet withUser:(NSString *)withUser withUserID:(NSString *)withUserID withPassword:(NSString *)withPassword withUrl:(NSString *)withUrl
  40. {
  41. self = [super init];
  42. if (self) {
  43. _delegate = delegate;
  44. _metadataNet = [CCMetadataNet new];
  45. _metadataNet = [metadataNet copy];
  46. _activeUser = withUser;
  47. _activeUserID = withUserID;
  48. _activePassword = withPassword;
  49. _activeUrl = withUrl;
  50. }
  51. return self;
  52. }
  53. - (void)start
  54. {
  55. if (![NSThread isMainThread]) {
  56. [self performSelectorOnMainThread:@selector(start) withObject:nil waitUntilDone:NO];
  57. return;
  58. }
  59. [self willChangeValueForKey:@"isExecuting"];
  60. _isExecuting = YES;
  61. [self didChangeValueForKey:@"isExecuting"];
  62. if (self.isCancelled) {
  63. [self finish];
  64. } else {
  65. [self poolNetworking];
  66. }
  67. }
  68. - (void)finish
  69. {
  70. [self willChangeValueForKey:@"isExecuting"];
  71. [self willChangeValueForKey:@"isFinished"];
  72. _isExecuting = NO;
  73. _isFinished = YES;
  74. [self didChangeValueForKey:@"isExecuting"];
  75. [self didChangeValueForKey:@"isFinished"];
  76. }
  77. - (void)cancel
  78. {
  79. if (_isExecuting) {
  80. [self complete];
  81. }
  82. [super cancel];
  83. }
  84. - (void)poolNetworking
  85. {
  86. #ifndef EXTENSION
  87. [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
  88. #endif
  89. if([self respondsToSelector:NSSelectorFromString(_metadataNet.action)])
  90. [self performSelector:NSSelectorFromString(_metadataNet.action)];
  91. }
  92. #pragma --------------------------------------------------------------------------------------------
  93. #pragma mark ===== Delegate =====
  94. #pragma --------------------------------------------------------------------------------------------
  95. - (void)complete
  96. {
  97. [self finish];
  98. #ifndef EXTENSION
  99. [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
  100. #endif
  101. }
  102. #pragma --------------------------------------------------------------------------------------------
  103. #pragma mark ===== Check Server =====
  104. #pragma --------------------------------------------------------------------------------------------
  105. - (void)checkServer:(NSString *)serverUrl success:(void (^)(void))success failure:(void (^)(NSString *message, NSInteger errorCode))failure
  106. {
  107. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  108. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  109. [communication setUserAgent:[CCUtility getUserAgent]];
  110. [communication checkServer:serverUrl onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  111. success();
  112. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  113. NSString *message;
  114. NSInteger errorCode = response.statusCode;
  115. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  116. errorCode = error.code;
  117. // Error
  118. if (errorCode == 503)
  119. message = NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil);
  120. else
  121. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  122. failure(message, errorCode);
  123. }];
  124. }
  125. #pragma --------------------------------------------------------------------------------------------
  126. #pragma mark ===== download =====
  127. #pragma --------------------------------------------------------------------------------------------
  128. - (NSURLSessionTask *)downloadFileNameServerUrl:(NSString *)fileNameServerUrl fileNameLocalPath:(NSString *)fileNameLocalPath communication:(OCCommunication *)communication success:(void (^)(int64_t length, NSString *etag, NSDate *date))success failure:(void (^)(NSString *message, NSInteger errorCode))failure
  129. {
  130. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  131. [communication setUserAgent:[CCUtility getUserAgent]];
  132. NSURLSessionTask *sessionTask = [communication downloadFileSession:fileNameServerUrl toDestiny:fileNameLocalPath defaultPriority:YES onCommunication:communication progress:^(NSProgress *progress) {
  133. //float percent = roundf (progress.fractionCompleted * 100);
  134. } successRequest:^(NSURLResponse *response, NSURL *filePath) {
  135. int64_t totalUnitCount = 0;
  136. NSDate *date = [NSDate date];
  137. NSDateFormatter *dateFormatter = [NSDateFormatter new];
  138. NSLocale *enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
  139. [dateFormatter setLocale:enUSPOSIXLocale];
  140. [dateFormatter setDateFormat:@"EEE, dd MMM y HH:mm:ss zzz"];
  141. NSError *error;
  142. NSDictionary *fields = [(NSHTTPURLResponse*)response allHeaderFields];
  143. NSString *contentLength = [fields objectForKey:@"Content-Length"];
  144. if(contentLength) {
  145. totalUnitCount = (int64_t) [contentLength longLongValue];
  146. }
  147. NSString *etag = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-ETag"]];
  148. NSString *dateString = [fields objectForKey:@"Date"];
  149. if (dateString) {
  150. if (![dateFormatter getObjectValue:&date forString:dateString range:nil error:&error]) {
  151. date = [NSDate date];
  152. }
  153. } else {
  154. date = [NSDate date];
  155. }
  156. success(totalUnitCount, etag, date);
  157. } failureRequest:^(NSURLResponse *response, NSError *error) {
  158. NSString *message;
  159. NSInteger errorCode;
  160. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
  161. errorCode = httpResponse.statusCode;
  162. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  163. errorCode = error.code;
  164. // Error
  165. if (errorCode == 503)
  166. message = NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil);
  167. else
  168. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  169. failure(message, errorCode);
  170. }];
  171. return sessionTask;
  172. }
  173. #pragma --------------------------------------------------------------------------------------------
  174. #pragma mark ===== upload =====
  175. #pragma --------------------------------------------------------------------------------------------
  176. - (NSURLSessionTask *)uploadFileNameServerUrl:(NSString *)fileNameServerUrl fileNameLocalPath:(NSString *)fileNameLocalPath communication:(OCCommunication *)communication success:(void(^)(NSString *fileID, NSString *etag, NSDate *date))success failure:(void (^)(NSString *message, NSInteger errorCode))failure
  177. {
  178. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  179. [communication setUserAgent:[CCUtility getUserAgent]];
  180. NSURLSessionTask *sessionTask = [communication uploadFileSession:fileNameLocalPath toDestiny:fileNameServerUrl onCommunication:communication progress:^(NSProgress *progress) {
  181. //float percent = roundf (progress.fractionCompleted * 100);
  182. } successRequest:^(NSURLResponse *response, NSString *redirectedServer) {
  183. NSDictionary *fields = [(NSHTTPURLResponse*)response allHeaderFields];
  184. NSString *fileID = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-FileId"]];
  185. NSString *etag = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-ETag"]];
  186. NSDate *date = [CCUtility dateEnUsPosixFromCloud:[fields objectForKey:@"Date"]];
  187. success(fileID, etag, date);
  188. } failureRequest:^(NSURLResponse *response, NSString *redirectedServer, NSError *error) {
  189. NSString *message;
  190. NSInteger errorCode;
  191. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
  192. errorCode = httpResponse.statusCode;
  193. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  194. errorCode = error.code;
  195. // Error
  196. if (errorCode == 503)
  197. message = NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil);
  198. else
  199. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  200. failure(message, errorCode);
  201. } failureBeforeRequest:^(NSError *error) {
  202. failure(@"", error.code);
  203. }];
  204. return sessionTask;
  205. }
  206. #pragma --------------------------------------------------------------------------------------------
  207. #pragma mark ===== downloadThumbnail =====
  208. #pragma --------------------------------------------------------------------------------------------
  209. - (void)downloadThumbnail
  210. {
  211. [self downloadThumbnailWithDimOfThumbnail:(NSString *)_metadataNet.options fileName:_metadataNet.fileName fileNameLocal:_metadataNet.fileID success:^{
  212. if ([self.delegate respondsToSelector:@selector(downloadThumbnailSuccessFailure:message:errorCode:)])
  213. [self.delegate downloadThumbnailSuccessFailure:_metadataNet message:nil errorCode:0];
  214. [self complete];
  215. } failure:^(NSString *message, NSInteger errorCode) {
  216. if ([self.delegate respondsToSelector:@selector(downloadThumbnailSuccessFailure:message:errorCode:)]) {
  217. [self.delegate downloadThumbnailSuccessFailure:_metadataNet message:message errorCode:errorCode];
  218. }
  219. [self complete];
  220. }];
  221. }
  222. - (void)downloadThumbnailWithDimOfThumbnail:(NSString *)dimOfThumbnail fileName:(NSString *)fileName fileNameLocal:(NSString *)fileNameLocal success:(void (^)(void))success failure:(void (^)(NSString *message, NSInteger errorCode))failure
  223. {
  224. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  225. __block NSString *ext;
  226. NSInteger width = 0, height = 0;
  227. if ([dimOfThumbnail.lowercaseString isEqualToString:@"xs"]) { width = 32; height = 32; ext = @"ico"; }
  228. else if ([dimOfThumbnail.lowercaseString isEqualToString:@"s"]) { width = 64; height = 64; ext = @"ico"; }
  229. else if ([dimOfThumbnail.lowercaseString isEqualToString:@"m"]) { width = 128; height = 128; ext = @"ico"; }
  230. else if ([dimOfThumbnail.lowercaseString isEqualToString:@"l"]) { width = 640; height = 640; ext = @"pvw"; }
  231. else if ([dimOfThumbnail.lowercaseString isEqualToString:@"xl"]) { width = 1024; height = 1024; ext = @"pvw"; }
  232. NSString *directoryUser = [CCUtility getDirectoryActiveUser:_activeUser activeUrl:_activeUrl];
  233. NSString *fileNamePathLocal = [NSString stringWithFormat:@"%@/%@.%@", directoryUser, fileNameLocal, ext];
  234. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNamePathLocal]) {
  235. success();
  236. } else {
  237. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  238. [communication setUserAgent:[CCUtility getUserAgent]];
  239. [communication getRemoteThumbnailByServer:[_activeUrl stringByAppendingString:@"/"] ofFilePath:fileName withWidth:width andHeight:height onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSData *thumbnail, NSString *redirectedServer) {
  240. [CCGraphics saveIcoWithEtag:fileNameLocal image:[UIImage imageWithData:thumbnail] writeToFile:fileNamePathLocal copy:NO move:NO fromPath:nil toPath:nil];
  241. success();
  242. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  243. NSString *message;
  244. NSInteger errorCode = response.statusCode;
  245. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  246. errorCode = error.code;
  247. // Error
  248. if (errorCode == 503)
  249. message = NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil);
  250. else
  251. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  252. failure(message, errorCode);
  253. }];
  254. }
  255. }
  256. #pragma --------------------------------------------------------------------------------------------
  257. #pragma mark ===== Read Folder =====
  258. #pragma --------------------------------------------------------------------------------------------
  259. - (void)readFolder
  260. {
  261. [self readFolder:_metadataNet.serverUrl depth:_metadataNet.depth account:_metadataNet.account success:^(NSArray *metadatas, tableMetadata *metadataFolder, NSString *directoryID) {
  262. _metadataNet.directoryID = directoryID;
  263. if ([self.delegate respondsToSelector:@selector(readFolderSuccessFailure:metadataFolder:metadatas:message:errorCode:)])
  264. [self.delegate readFolderSuccessFailure:_metadataNet metadataFolder:metadataFolder metadatas:metadatas message:nil errorCode:0];
  265. [self complete];
  266. } failure:^(NSString *message, NSInteger errorCode) {
  267. if ([self.delegate respondsToSelector:@selector(readFolderSuccessFailure:metadataFolder:metadatas:message:errorCode:)])
  268. [self.delegate readFolderSuccessFailure:_metadataNet metadataFolder:nil metadatas:nil message:message errorCode:errorCode];
  269. [self complete];
  270. }];
  271. }
  272. - (void)readFolder:(NSString *)serverUrl depth:(NSString *)depth account:(NSString *)account success:(void(^)(NSArray *metadatas, tableMetadata *metadataFolder, NSString *directoryID))success failure:(void (^)(NSString *message, NSInteger errorCode))failure
  273. {
  274. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  275. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  276. [communication setUserAgent:[CCUtility getUserAgent]];
  277. [communication readFolder:serverUrl depth:depth withUserSessionToken:nil onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer, NSString *token) {
  278. // Test active account
  279. tableAccount *recordAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  280. if (![recordAccount.account isEqualToString:account]) {
  281. failure(NSLocalizedStringFromTable(@"_error_user_not_available_", @"Error", nil), k_CCErrorUserNotAvailble);
  282. } else {
  283. // Check items > 0
  284. if ([items count] == 0) {
  285. #ifndef EXTENSION
  286. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  287. [appDelegate messageNotification:@"Server error" description:@"Read Folder WebDAV : [items NULL] please fix" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  288. #endif
  289. failure(NSLocalizedStringFromTable(@"Read Folder WebDAV : [items NULL] please fix", @"Server error", nil), k_CCErrorInternalError);
  290. } else {
  291. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  292. BOOL showHiddenFiles = [CCUtility getShowHiddenFiles];
  293. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:serverUrl account:account];
  294. // directory [0]
  295. OCFileDto *itemDtoFolder = [items objectAtIndex:0];
  296. //NSDate *date = [NSDate dateWithTimeIntervalSince1970:itemDtoDirectory.date];
  297. NSString *directoryID = [[NCManageDatabase sharedInstance] addDirectoryWithEncrypted:itemDtoFolder.isEncrypted favorite:itemDtoFolder.isFavorite fileID:itemDtoFolder.ocId permissions:itemDtoFolder.permissions serverUrl:serverUrl].directoryID;
  298. NSMutableArray *metadatas = [NSMutableArray new];
  299. tableMetadata *metadataFolder = [tableMetadata new];
  300. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  301. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:_activeUrl];
  302. NSString *directoryUser = [CCUtility getDirectoryActiveUser:_activeUser activeUrl:_activeUrl];
  303. NSString *serverUrlFolder;
  304. NSString *directoryIDFolder;
  305. // Metadata . (self Folder)
  306. if ([serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:_activeUrl]]) {
  307. // root folder
  308. serverUrlFolder = @"..";
  309. directoryIDFolder = @"00000000-0000-0000-0000-000000000000";
  310. metadataFolder = [CCUtility trasformedOCFileToCCMetadata:itemDtoFolder fileName:@"." serverUrl:serverUrlFolder directoryID:directoryIDFolder autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:account directoryUser:directoryUser isFolderEncrypted:isFolderEncrypted];
  311. } else {
  312. serverUrlFolder = [CCUtility deletingLastPathComponentFromServerUrl:serverUrl];
  313. directoryIDFolder = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrlFolder];
  314. if (!directoryIDFolder) {
  315. dispatch_async(dispatch_get_main_queue(), ^{
  316. success(metadatas, metadataFolder, directoryID);
  317. });
  318. return;
  319. }
  320. metadataFolder = [CCUtility trasformedOCFileToCCMetadata:itemDtoFolder fileName:[serverUrl lastPathComponent] serverUrl:serverUrlFolder directoryID:directoryIDFolder autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:account directoryUser:directoryUser isFolderEncrypted:isFolderEncrypted];
  321. }
  322. NSArray *itemsSortedArray = [items sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
  323. NSString *first = [(OCFileDto*)a fileName];
  324. NSString *second = [(OCFileDto*)b fileName];
  325. return [[first lowercaseString] compare:[second lowercaseString]];
  326. }];
  327. for (NSUInteger i=1; i < [itemsSortedArray count]; i++) {
  328. OCFileDto *itemDto = [itemsSortedArray objectAtIndex:i];
  329. NSString *fileName = [itemDto.fileName stringByReplacingOccurrencesOfString:@"/" withString:@""];
  330. // Skip hidden files
  331. if (fileName.length > 0) {
  332. if (!showHiddenFiles && [[fileName substringToIndex:1] isEqualToString:@"."])
  333. continue;
  334. } else {
  335. continue;
  336. }
  337. if (itemDto.isDirectory) {
  338. (void)[[NCManageDatabase sharedInstance] addDirectoryWithEncrypted:itemDto.isEncrypted favorite:itemDto.isFavorite fileID:itemDto.ocId permissions:itemDto.permissions serverUrl:[CCUtility stringAppendServerUrl:serverUrl addFileName:fileName]];
  339. }
  340. // ----- BUG #942 ---------
  341. if ([itemDto.etag length] == 0) {
  342. #ifndef EXTENSION
  343. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  344. [appDelegate messageNotification:@"Server error" description:@"Metadata fileID absent, record excluded, please fix" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  345. #endif
  346. continue;
  347. }
  348. // ------------------------
  349. [metadatas addObject:[CCUtility trasformedOCFileToCCMetadata:itemDto fileName:itemDto.fileName serverUrl:serverUrl directoryID:directoryID autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:account directoryUser:directoryUser isFolderEncrypted:isFolderEncrypted]];
  350. }
  351. dispatch_async(dispatch_get_main_queue(), ^{
  352. success(metadatas, metadataFolder, directoryID);
  353. });
  354. });
  355. }
  356. }
  357. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) {
  358. NSString *message;
  359. NSInteger errorCode = response.statusCode;
  360. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  361. errorCode = error.code;
  362. // Error
  363. if (errorCode == 503)
  364. message = NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil);
  365. else
  366. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  367. // Request trusted certificated
  368. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  369. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  370. // Activity
  371. [[NCManageDatabase sharedInstance] addActivityClient:serverUrl fileID:@"" action:k_activityDebugActionReadFolder selector:@"" note:[error.userInfo valueForKey:@"NSLocalizedDescription"] type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:_activeUrl];
  372. failure(message, errorCode);
  373. }];
  374. }
  375. #pragma --------------------------------------------------------------------------------------------
  376. #pragma mark ===== ReadFile =====
  377. #pragma --------------------------------------------------------------------------------------------
  378. - (void)readFile
  379. {
  380. [self readFile:_metadataNet.fileName serverUrl:_metadataNet.serverUrl account:_metadataNet.account success:^(tableMetadata *metadata) {
  381. if([self.delegate respondsToSelector:@selector(readFileSuccessFailure:metadata:message:errorCode:)])
  382. [self.delegate readFileSuccessFailure:_metadataNet metadata:metadata message:nil errorCode:0];
  383. [self complete];
  384. } failure:^(NSString *message, NSInteger errorCode) {
  385. if ([self.delegate respondsToSelector:@selector(readFileSuccessFailure:metadata:message:errorCode:)])
  386. [self.delegate readFileSuccessFailure:_metadataNet metadata:nil message:message errorCode:errorCode];
  387. [self complete];
  388. }];
  389. }
  390. - (void)readFile:(NSString *)fileName serverUrl:(NSString *)serverUrl account:(NSString *)account success:(void(^)(tableMetadata *metadata))success failure:(void (^)(NSString *message, NSInteger errorCode))failure
  391. {
  392. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  393. NSString *fileNamePath;
  394. if (fileName) {
  395. fileNamePath = [NSString stringWithFormat:@"%@/%@", serverUrl, fileName];
  396. } else {
  397. fileName= @".";
  398. fileNamePath = serverUrl;
  399. }
  400. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  401. [communication setUserAgent:[CCUtility getUserAgent]];
  402. [communication readFile:fileNamePath onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  403. // Test active account
  404. tableAccount *recordAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  405. if (![recordAccount.account isEqualToString:account]) {
  406. failure(NSLocalizedStringFromTable(@"_error_user_not_available_", @"Error", nil), k_CCErrorUserNotAvailble);
  407. } else {
  408. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:serverUrl account:account];
  409. if ([items count] > 0) {
  410. tableMetadata *metadata = [tableMetadata new];
  411. OCFileDto *itemDto = [items objectAtIndex:0];
  412. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  413. if (directoryID) {
  414. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  415. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:_activeUrl];
  416. NSString *directoryUser = [CCUtility getDirectoryActiveUser:_activeUser activeUrl:_activeUrl];
  417. metadata = [CCUtility trasformedOCFileToCCMetadata:itemDto fileName:fileName serverUrl:serverUrl directoryID:directoryID autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:account directoryUser:directoryUser isFolderEncrypted:isFolderEncrypted];
  418. success(metadata);
  419. } else {
  420. failure(NSLocalizedStringFromTable(@"Directory not found", @"Error", nil), k_CCErrorInternalError);
  421. }
  422. }
  423. // BUG 1038 item == 0
  424. else {
  425. #ifndef EXTENSION
  426. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  427. [appDelegate messageNotification:@"Server error" description:@"Read File WebDAV : [items NULL] please fix" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  428. #endif
  429. failure(NSLocalizedStringFromTable(@"Read File WebDAV : [items NULL] please fix", @"Server error", nil), k_CCErrorInternalError);
  430. }
  431. }
  432. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  433. NSString *message;
  434. NSInteger errorCode = response.statusCode;
  435. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  436. errorCode = error.code;
  437. // Error
  438. if (errorCode == 503)
  439. message = NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil);
  440. else
  441. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  442. // Request trusted certificated
  443. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  444. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  445. // Activity
  446. [[NCManageDatabase sharedInstance] addActivityClient:serverUrl fileID:@"" action:k_activityDebugActionReadFolder selector:@"" note:[error.userInfo valueForKey:@"NSLocalizedDescription"] type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:_activeUrl];
  447. failure(message, errorCode);
  448. }];
  449. }
  450. #pragma --------------------------------------------------------------------------------------------
  451. #pragma mark ===== Search =====
  452. #pragma --------------------------------------------------------------------------------------------
  453. - (void)search
  454. {
  455. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  456. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  457. [communication setUserAgent:[CCUtility getUserAgent]];
  458. NSString *path = [_activeUrl stringByAppendingString:dav];
  459. NSString *folder = [_metadataNet.serverUrl stringByReplacingOccurrencesOfString:[CCUtility getHomeServerUrlActiveUrl:_activeUrl] withString:@""];
  460. NSString *dateLastModified;
  461. if (_metadataNet.date) {
  462. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  463. NSLocale *enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
  464. [dateFormatter setLocale:enUSPOSIXLocale];
  465. [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZZ"];
  466. dateLastModified = [dateFormatter stringFromDate:_metadataNet.date];
  467. }
  468. [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) {
  469. // Test active account
  470. tableAccount *recordAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  471. if (![recordAccount.account isEqualToString:_metadataNet.account]) {
  472. if ([self.delegate respondsToSelector:@selector(searchSuccessFailure:metadatas:message:errorCode:)])
  473. [self.delegate searchSuccessFailure:_metadataNet metadatas:nil message:NSLocalizedStringFromTable(@"_error_user_not_available_", @"Error", nil) errorCode:k_CCErrorUserNotAvailble];
  474. [self complete];
  475. return;
  476. }
  477. NSMutableArray *metadatas = [NSMutableArray new];
  478. BOOL showHiddenFiles = [CCUtility getShowHiddenFiles];
  479. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  480. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:_activeUrl];
  481. NSString *directoryUser = [CCUtility getDirectoryActiveUser:_activeUser activeUrl:_activeUrl];
  482. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  483. for(OCFileDto *itemDto in items) {
  484. NSString *serverUrl, *directoryID;
  485. BOOL isFolderEncrypted;
  486. NSString *fileName = [itemDto.fileName stringByReplacingOccurrencesOfString:@"/" withString:@""];
  487. // Skip hidden files
  488. if (fileName.length > 0) {
  489. if (!showHiddenFiles && [[fileName substringToIndex:1] isEqualToString:@"."])
  490. continue;
  491. } else
  492. continue;
  493. // ----- BUG #942 ---------
  494. if ([itemDto.etag length] == 0) {
  495. #ifndef EXTENSION
  496. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  497. [appDelegate messageNotification:@"Server error" description:@"Metadata fileID absent, record excluded, please fix" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  498. #endif
  499. continue;
  500. }
  501. // ------------------------
  502. serverUrl = [itemDto.filePath stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@/files/%@", dav, _activeUserID] withString:@""];
  503. if ([serverUrl hasPrefix:@"/"])
  504. serverUrl = [serverUrl substringFromIndex:1];
  505. if ([serverUrl hasSuffix:@"/"])
  506. serverUrl = [serverUrl substringToIndex:[serverUrl length] - 1];
  507. serverUrl = [CCUtility stringAppendServerUrl:[_activeUrl stringByAppendingString:webDAV] addFileName:serverUrl];
  508. if (itemDto.isDirectory) {
  509. (void)[[NCManageDatabase sharedInstance] addDirectoryWithEncrypted:itemDto.isEncrypted favorite:itemDto.isFavorite fileID:itemDto.ocId permissions:itemDto.permissions serverUrl:[NSString stringWithFormat:@"%@/%@", serverUrl, fileName]];
  510. }
  511. directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  512. isFolderEncrypted = [CCUtility isFolderEncrypted:serverUrl account:_metadataNet.account];
  513. [metadatas addObject:[CCUtility trasformedOCFileToCCMetadata:itemDto fileName:itemDto.fileName serverUrl:serverUrl directoryID:directoryID autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:_metadataNet.account directoryUser:directoryUser isFolderEncrypted:isFolderEncrypted]];
  514. }
  515. dispatch_async(dispatch_get_main_queue(), ^{
  516. if ([self.delegate respondsToSelector:@selector(searchSuccessFailure:metadatas:message:errorCode:)])
  517. [self.delegate searchSuccessFailure:_metadataNet metadatas:metadatas message:nil errorCode:0];
  518. });
  519. });
  520. [self complete];
  521. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) {
  522. NSInteger errorCode = response.statusCode;
  523. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  524. errorCode = error.code;
  525. // Error
  526. if ([self.delegate respondsToSelector:@selector(searchSuccessFailure:metadatas:message:errorCode:)]) {
  527. if (errorCode == 503)
  528. [self.delegate searchSuccessFailure:_metadataNet metadatas:nil message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  529. else
  530. [self.delegate searchSuccessFailure:_metadataNet metadatas:nil message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  531. }
  532. // Request trusted certificated
  533. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  534. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  535. [self complete];
  536. }];
  537. }
  538. #pragma --------------------------------------------------------------------------------------------
  539. #pragma mark ===== Setting Favorite =====
  540. #pragma --------------------------------------------------------------------------------------------
  541. - (void)settingFavorite
  542. {
  543. [self settingFavorite:_metadataNet.fileName serverUrl:_metadataNet.serverUrl favorite:[_metadataNet.options boolValue] success:^{
  544. if ([self.delegate respondsToSelector:@selector(settingFavoriteSuccessFailure:message:errorCode:)])
  545. [self.delegate settingFavoriteSuccessFailure:_metadataNet message:nil errorCode:0];
  546. [self complete];
  547. } failure:^(NSString *message, NSInteger errorCode) {
  548. if ([self.delegate respondsToSelector:@selector(settingFavoriteSuccessFailure:message:errorCode:)])
  549. [self.delegate settingFavoriteSuccessFailure:_metadataNet message:message errorCode:errorCode];
  550. [self complete];
  551. }];
  552. }
  553. - (void)settingFavorite:(NSString *)fileName serverUrl:(NSString *)serverUrl favorite:(BOOL)favorite success:(void (^)(void))success failure:(void (^)(NSString *message, NSInteger errorCode))failure
  554. {
  555. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  556. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  557. [communication setUserAgent:[CCUtility getUserAgent]];
  558. NSString *server = [_activeUrl stringByAppendingString:dav];
  559. [communication settingFavoriteServer:server andFileOrFolderPath:fileName favorite:favorite withUserSessionToken:nil onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer, NSString *token) {
  560. success();
  561. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) {
  562. NSString *message;
  563. NSInteger errorCode = response.statusCode;
  564. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  565. errorCode = error.code;
  566. // Error
  567. if (errorCode == 503)
  568. message = NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil);
  569. else
  570. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  571. // Request trusted certificated
  572. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  573. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  574. failure(message, errorCode);
  575. }];
  576. }
  577. #pragma --------------------------------------------------------------------------------------------
  578. #pragma mark ===== Listing Favorites =====
  579. #pragma --------------------------------------------------------------------------------------------
  580. - (void)listingFavorites
  581. {
  582. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  583. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  584. [communication setUserAgent:[CCUtility getUserAgent]];
  585. NSString *path = [_activeUrl stringByAppendingString:dav];
  586. NSString *folder = [_metadataNet.serverUrl stringByReplacingOccurrencesOfString:[CCUtility getHomeServerUrlActiveUrl:_activeUrl] withString:@""];
  587. [communication listingFavorites:path folder:folder withUserSessionToken:nil onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer, NSString *token) {
  588. // Test active account
  589. tableAccount *recordAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  590. if (![recordAccount.account isEqualToString:_metadataNet.account]) {
  591. if ([self.delegate respondsToSelector:@selector(listingFavoritesSuccessFailure:metadatas:message:errorCode:)])
  592. [self.delegate listingFavoritesSuccessFailure:_metadataNet metadatas:nil message:NSLocalizedStringFromTable(@"_error_user_not_available_", @"Error", nil) errorCode:k_CCErrorUserNotAvailble];
  593. [self complete];
  594. return;
  595. }
  596. NSMutableArray *metadatas = [NSMutableArray new];
  597. BOOL showHiddenFiles = [CCUtility getShowHiddenFiles];
  598. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  599. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:_activeUrl];
  600. NSString *directoryUser = [CCUtility getDirectoryActiveUser:_activeUser activeUrl:_activeUrl];
  601. // Order by fileNamePath
  602. items = [items sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
  603. OCFileDto *record1 = obj1, *record2 = obj2;
  604. NSString *path1 = [[record1.filePath stringByAppendingString:record1.fileName] lowercaseString];
  605. NSString *path2 = [[record2.filePath stringByAppendingString:record2.fileName] lowercaseString];
  606. return [path1 compare:path2];
  607. }];
  608. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  609. for(OCFileDto *itemDto in items) {
  610. NSString *serverUrl, *directoryID;
  611. BOOL isFolderEncrypted;
  612. NSString *fileName = [itemDto.fileName stringByReplacingOccurrencesOfString:@"/" withString:@""];
  613. // Skip hidden files
  614. if (fileName.length > 0) {
  615. if (!showHiddenFiles && [[fileName substringToIndex:1] isEqualToString:@"."])
  616. continue;
  617. } else
  618. continue;
  619. // ----- BUG #942 ---------
  620. if ([itemDto.etag length] == 0) {
  621. #ifndef EXTENSION
  622. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  623. [appDelegate messageNotification:@"Server error" description:@"Metadata fileID absent, record excluded, please fix" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  624. #endif
  625. continue;
  626. }
  627. // ------------------------
  628. serverUrl = [itemDto.filePath stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@/files/%@", dav, _activeUserID] withString:@""];
  629. if ([serverUrl hasPrefix:@"/"])
  630. serverUrl = [serverUrl substringFromIndex:1];
  631. if ([serverUrl hasSuffix:@"/"])
  632. serverUrl = [serverUrl substringToIndex:[serverUrl length] - 1];
  633. serverUrl = [CCUtility stringAppendServerUrl:[_activeUrl stringByAppendingString:webDAV] addFileName:serverUrl];
  634. if (itemDto.isDirectory) {
  635. (void)[[NCManageDatabase sharedInstance] addDirectoryWithEncrypted:itemDto.isEncrypted favorite:itemDto.isFavorite fileID:itemDto.ocId permissions:itemDto.permissions serverUrl:[NSString stringWithFormat:@"%@/%@", serverUrl, fileName]];
  636. }
  637. directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  638. isFolderEncrypted = [CCUtility isFolderEncrypted:serverUrl account:_metadataNet.account];
  639. [metadatas addObject:[CCUtility trasformedOCFileToCCMetadata:itemDto fileName:itemDto.fileName serverUrl:serverUrl directoryID:directoryID autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:_metadataNet.account directoryUser:directoryUser isFolderEncrypted:isFolderEncrypted]];
  640. }
  641. dispatch_async(dispatch_get_main_queue(), ^{
  642. if ([self.delegate respondsToSelector:@selector(listingFavoritesSuccessFailure:metadatas:message:errorCode:)])
  643. [self.delegate listingFavoritesSuccessFailure:_metadataNet metadatas:metadatas message:nil errorCode:0];
  644. });
  645. });
  646. [self complete];
  647. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) {
  648. NSInteger errorCode = response.statusCode;
  649. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  650. errorCode = error.code;
  651. // Error
  652. if ([self.delegate respondsToSelector:@selector(listingFavoritesSuccessFailure:metadatas:message:errorCode:)]) {
  653. if (errorCode == 503)
  654. [self.delegate listingFavoritesSuccessFailure:_metadataNet metadatas:nil message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  655. else
  656. [self.delegate listingFavoritesSuccessFailure:_metadataNet metadatas:nil message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  657. }
  658. // Request trusted certificated
  659. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  660. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  661. [self complete];
  662. }];
  663. }
  664. #pragma --------------------------------------------------------------------------------------------
  665. #pragma mark ===== Create Folder =====
  666. #pragma --------------------------------------------------------------------------------------------
  667. - (void)createFolder
  668. {
  669. [self createFolder:_metadataNet.fileName serverUrl:_metadataNet.serverUrl account:_metadataNet.account success:^(NSString *fileID, NSDate *date) {
  670. _metadataNet.fileID = fileID;
  671. _metadataNet.date = date;
  672. if ([self.delegate respondsToSelector:@selector(createFolderSuccessFailure:message:errorCode:)])
  673. [self.delegate createFolderSuccessFailure:_metadataNet message:nil errorCode:0];
  674. [self complete];
  675. } failure:^(NSString *message, NSInteger errorCode) {
  676. if ([self.delegate respondsToSelector:@selector(createFolderSuccessFailure:message:errorCode:)])
  677. [self.delegate createFolderSuccessFailure:_metadataNet message:message errorCode:errorCode];
  678. [self complete];
  679. }];
  680. }
  681. - (void)createFolder:(NSString *)fileName serverUrl:(NSString *)serverUrl account:(NSString *)account success:(void(^)(NSString *fileID, NSDate *date))success failure:(void (^)(NSString *message, NSInteger errorCode))failure
  682. {
  683. NSString *path = [NSString stringWithFormat:@"%@/%@", serverUrl, fileName];
  684. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  685. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:_activeUrl];
  686. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  687. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  688. [communication setUserAgent:[CCUtility getUserAgent]];
  689. [communication createFolder:path onCommunication:communication withForbiddenCharactersSupported:YES successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  690. if (![[[NCManageDatabase sharedInstance] getAccountActive].account isEqualToString:account]) {
  691. failure(NSLocalizedStringFromTable(@"_error_user_not_available_", @"Error", nil), k_CCErrorUserNotAvailble);
  692. } else {
  693. NSDictionary *fields = [response allHeaderFields];
  694. NSString *fileID = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-FileId"]];
  695. NSDate *date = [CCUtility dateEnUsPosixFromCloud:[fields objectForKey:@"Date"]];
  696. success(fileID, date);
  697. }
  698. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  699. NSString *message;
  700. if (([fileName isEqualToString:autoUploadFileName] && [serverUrl isEqualToString:autoUploadDirectory]))
  701. message = nil;
  702. else
  703. message = [CCError manageErrorOC:response.statusCode error:error];
  704. NSInteger errorCode = response.statusCode;
  705. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  706. errorCode = error.code;
  707. // Request trusted certificated
  708. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  709. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  710. // Activity
  711. [[NCManageDatabase sharedInstance] addActivityClient:path fileID:@"" action:k_activityDebugActionCreateFolder selector:@"" note:NSLocalizedStringFromTable(@"_not_possible_create_folder_", @"Error", nil) type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:_activeUrl];
  712. failure(message, errorCode);
  713. } errorBeforeRequest:^(NSError *error) {
  714. NSString *message;
  715. if (([fileName isEqualToString:autoUploadFileName] && [serverUrl isEqualToString:autoUploadDirectory]))
  716. message = nil;
  717. else {
  718. if (error.code == OCErrorForbidenCharacters)
  719. message = NSLocalizedStringFromTable(@"_forbidden_characters_from_server_", @"Error", nil);
  720. else
  721. message = NSLocalizedStringFromTable(@"_unknow_response_server_", @"Error", nil);
  722. }
  723. failure(message, error.code);
  724. }];
  725. }
  726. #pragma --------------------------------------------------------------------------------------------
  727. #pragma mark ===== Delete =====
  728. #pragma --------------------------------------------------------------------------------------------
  729. - (void)deleteFileOrFolder
  730. {
  731. [self deleteFileOrFolder:_metadataNet.fileName serverUrl:_metadataNet.serverUrl success:^{
  732. if ([self.delegate respondsToSelector:@selector(deleteFileOrFolderSuccessFailure:message:errorCode:)])
  733. [self.delegate deleteFileOrFolderSuccessFailure:_metadataNet message:nil errorCode:0];
  734. [self complete];
  735. } failure:^(NSString *message, NSInteger errorCode) {
  736. if ([self.delegate respondsToSelector:@selector(deleteFileOrFolderSuccessFailure:message:errorCode:)])
  737. [self.delegate deleteFileOrFolderSuccessFailure:_metadataNet message:message errorCode:errorCode];
  738. [self complete];
  739. }];
  740. }
  741. - (void)deleteFileOrFolder:(NSString *)fileName serverUrl:(NSString *)serverUrl success:(void (^)(void))success failure:(void (^)(NSString *message, NSInteger errorCode))failure
  742. {
  743. NSString *serverFilePath = [NSString stringWithFormat:@"%@/%@", serverUrl, fileName];
  744. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  745. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  746. [communication setUserAgent:[CCUtility getUserAgent]];
  747. [communication deleteFileOrFolder:serverFilePath onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  748. success();
  749. } failureRquest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  750. NSString *message;
  751. NSInteger errorCode = response.statusCode;
  752. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  753. errorCode = error.code;
  754. // Error
  755. if (errorCode == 503)
  756. message = NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil);
  757. else
  758. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  759. // Request trusted certificated
  760. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  761. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  762. // Activity
  763. [[NCManageDatabase sharedInstance] addActivityClient:serverUrl fileID:@"" action:k_activityDebugActionDeleteFileFolder selector:@"" note:[error.userInfo valueForKey:@"NSLocalizedDescription"] type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:_activeUrl];
  764. failure(message, errorCode);
  765. }];
  766. }
  767. #pragma --------------------------------------------------------------------------------------------
  768. #pragma mark ===== Move =====
  769. #pragma --------------------------------------------------------------------------------------------
  770. - (void)moveFileOrFolder
  771. {
  772. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@", _metadataNet.serverUrl, _metadataNet.fileName];
  773. NSString *fileNameToPath = [NSString stringWithFormat:@"%@/%@", _metadataNet.serverUrlTo, _metadataNet.fileNameTo];
  774. [self moveFileOrFolder:fileNamePath fileNameTo:fileNameToPath success:^{
  775. if ([_metadataNet.selector isEqualToString:selectorRename] && [self.delegate respondsToSelector:@selector(renameSuccess:)])
  776. [self.delegate renameSuccess:_metadataNet];
  777. if ([_metadataNet.selector isEqualToString:selectorMove] && [self.delegate respondsToSelector:@selector(moveSuccess:)])
  778. [self.delegate moveSuccess:_metadataNet];
  779. [self complete];
  780. } failure:^(NSString *message, NSInteger errorCode) {
  781. if ([self.delegate respondsToSelector:@selector(renameMoveFileOrFolderFailure:message:errorCode:)])
  782. [self.delegate renameMoveFileOrFolderFailure:_metadataNet message:message errorCode:errorCode];
  783. [self complete];
  784. }];
  785. }
  786. - (void)moveFileOrFolder:(NSString *)fileName fileNameTo:(NSString *)fileNameTo success:(void (^)(void))success failure:(void (^)(NSString *message, NSInteger errorCode))failure
  787. {
  788. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  789. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  790. [communication setUserAgent:[CCUtility getUserAgent]];
  791. [communication moveFileOrFolder:fileName toDestiny:fileNameTo onCommunication:communication withForbiddenCharactersSupported:YES successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  792. success();
  793. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  794. NSInteger errorCode = response.statusCode;
  795. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  796. errorCode = error.code;
  797. NSString *message = [CCError manageErrorOC:response.statusCode error:error];
  798. failure(message, error.code);
  799. } errorBeforeRequest:^(NSError *error) {
  800. NSString *message;
  801. if (error.code == OCErrorMovingTheDestinyAndOriginAreTheSame) {
  802. message = NSLocalizedStringFromTable(@"_error_folder_destiny_is_the_same_", @"Error", nil);
  803. } else if (error.code == OCErrorMovingFolderInsideHimself) {
  804. message = NSLocalizedStringFromTable(@"_error_folder_destiny_is_the_same_", @"Error", nil);
  805. } else if (error.code == OCErrorMovingDestinyNameHaveForbiddenCharacters) {
  806. message = NSLocalizedStringFromTable(@"_forbidden_characters_from_server_", @"Error", nil);
  807. } else {
  808. message = NSLocalizedStringFromTable(@"_unknow_response_server_", @"Error", nil);
  809. }
  810. failure(message, error.code);
  811. }];
  812. }
  813. #pragma --------------------------------------------------------------------------------------------
  814. #pragma mark ===== Shared =====
  815. #pragma --------------------------------------------------------------------------------------------
  816. - (void)readShareServer
  817. {
  818. #ifndef EXTENSION
  819. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  820. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  821. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  822. [communication setUserAgent:[CCUtility getUserAgent]];
  823. [communication readSharedByServer:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  824. // Test active account
  825. tableAccount *recordAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  826. if (![recordAccount.account isEqualToString:_metadataNet.account]) {
  827. if ([self.delegate respondsToSelector:@selector(shareFailure:message:errorCode:)])
  828. [self.delegate shareFailure:_metadataNet message:NSLocalizedStringFromTable(@"_error_user_not_available_", @"Error", nil) errorCode:k_CCErrorUserNotAvailble];
  829. [self complete];
  830. return;
  831. }
  832. BOOL openWindow = NO;
  833. [appDelegate.sharesID removeAllObjects];
  834. if ([recordAccount.account isEqualToString:_metadataNet.account]) {
  835. for (OCSharedDto *item in items)
  836. [appDelegate.sharesID setObject:item forKey:[@(item.idRemoteShared) stringValue]];
  837. if ([_metadataNet.selector isEqual:selectorOpenWindowShare]) openWindow = YES;
  838. if ([_metadataNet.action isEqual:actionUpdateShare]) openWindow = YES;
  839. if ([_metadataNet.action isEqual:actionShare]) openWindow = YES;
  840. if ([_metadataNet.action isEqual:actionShareWith]) openWindow = YES;
  841. }
  842. if([self.delegate respondsToSelector:@selector(readSharedSuccess:items:openWindow:)])
  843. [self.delegate readSharedSuccess:_metadataNet items:appDelegate.sharesID openWindow:openWindow];
  844. [self complete];
  845. } failureRequest :^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  846. NSInteger errorCode = response.statusCode;
  847. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  848. errorCode = error.code;
  849. // Error
  850. if ([self.delegate respondsToSelector:@selector(shareFailure:message:errorCode:)]) {
  851. if (errorCode == 503)
  852. [self.delegate shareFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  853. else
  854. [self.delegate shareFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  855. }
  856. // Request trusted certificated
  857. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  858. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  859. [self complete];
  860. }];
  861. #endif
  862. }
  863. - (void)share
  864. {
  865. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  866. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  867. [communication setUserAgent:[CCUtility getUserAgent]];
  868. [communication shareFileOrFolderByServer:[_activeUrl stringByAppendingString:@"/"] andFileOrFolderPath:[_metadataNet.fileName encodeString:NSUTF8StringEncoding] andPassword:[_metadataNet.password encodeString:NSUTF8StringEncoding] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *token, NSString *redirectedServer) {
  869. [self readShareServer];
  870. } failureRequest :^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  871. NSInteger errorCode = response.statusCode;
  872. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  873. errorCode = error.code;
  874. // Error
  875. if ([self.delegate respondsToSelector:@selector(shareFailure:message:errorCode:)]) {
  876. if (errorCode == 503)
  877. [self.delegate shareFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  878. else
  879. [self.delegate shareFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  880. }
  881. // Request trusted certificated
  882. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  883. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  884. [self complete];
  885. }];
  886. }
  887. // * @param shareeType -> NSInteger: to set the type of sharee (user/group/federated)
  888. - (void)shareWith
  889. {
  890. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  891. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  892. [communication setUserAgent:[CCUtility getUserAgent]];
  893. [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) {
  894. [self readShareServer];
  895. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  896. NSInteger errorCode = response.statusCode;
  897. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  898. errorCode = error.code;
  899. // Error
  900. if ([self.delegate respondsToSelector:@selector(shareFailure:message:errorCode:)]) {
  901. if (errorCode == 503)
  902. [self.delegate shareFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  903. else
  904. [self.delegate shareFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  905. }
  906. // Request trusted certificated
  907. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  908. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  909. [self complete];
  910. }];
  911. }
  912. - (void)updateShare
  913. {
  914. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  915. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  916. [communication setUserAgent:[CCUtility getUserAgent]];
  917. [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) {
  918. [self readShareServer];
  919. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  920. #ifndef EXTENSION
  921. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  922. [appDelegate messageNotification:@"_error_" description:[CCError manageErrorOC:response.statusCode error:error] visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  923. #endif
  924. NSInteger errorCode = response.statusCode;
  925. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  926. errorCode = error.code;
  927. // Error
  928. if ([self.delegate respondsToSelector:@selector(shareFailure:message:errorCode:)]) {
  929. if (errorCode == 503)
  930. [self.delegate shareFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  931. else
  932. [self.delegate shareFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  933. }
  934. // Request trusted certificated
  935. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  936. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  937. [self complete];
  938. }];
  939. }
  940. - (void)unShare
  941. {
  942. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  943. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  944. [communication setUserAgent:[CCUtility getUserAgent]];
  945. [communication unShareFileOrFolderByServer:[_activeUrl stringByAppendingString:@"/"] andIdRemoteShared:[_metadataNet.share intValue] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  946. if([self.delegate respondsToSelector:@selector(unShareSuccess:)])
  947. [self.delegate unShareSuccess:_metadataNet];
  948. [self complete];
  949. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  950. #ifndef EXTENSION
  951. [(AppDelegate *)[[UIApplication sharedApplication] delegate] messageNotification:@"_error_" description:[CCError manageErrorOC:response.statusCode error:error] visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  952. #endif
  953. NSInteger errorCode = response.statusCode;
  954. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  955. errorCode = error.code;
  956. // Error
  957. if ([self.delegate respondsToSelector:@selector(shareFailure:message:errorCode:)]) {
  958. if (errorCode == 503)
  959. [self.delegate shareFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  960. else
  961. [self.delegate shareFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  962. }
  963. // Request trusted certificated
  964. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  965. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  966. [self complete];
  967. }];
  968. }
  969. - (void)getUserAndGroup
  970. {
  971. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  972. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  973. [communication setUserAgent:[CCUtility getUserAgent]];
  974. [communication searchUsersAndGroupsWith:_metadataNet.options forPage:1 with:50 ofServer:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *itemList, NSString *redirectedServer) {
  975. if([self.delegate respondsToSelector:@selector(getUserAndGroupSuccess:items:)])
  976. [self.delegate getUserAndGroupSuccess:_metadataNet items:itemList];
  977. [self complete];
  978. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  979. NSInteger errorCode = response.statusCode;
  980. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  981. errorCode = error.code;
  982. // Error
  983. if ([self.delegate respondsToSelector:@selector(getUserAndGroupFailure:message:errorCode:)]) {
  984. if (errorCode == 503)
  985. [self.delegate getUserAndGroupFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  986. else
  987. [self.delegate getUserAndGroupFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  988. }
  989. // Request trusted certificated
  990. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  991. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  992. [self complete];
  993. }];
  994. }
  995. - (void)getSharePermissionsFile
  996. {
  997. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  998. NSString *fileName = [NSString stringWithFormat:@"%@/%@", _metadataNet.serverUrl, _metadataNet.fileName];
  999. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  1000. [communication setUserAgent:[CCUtility getUserAgent]];
  1001. [communication getSharePermissionsFile:fileName onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *permissions, NSString *redirectedServer) {
  1002. // Test active account
  1003. tableAccount *recordAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  1004. if (![recordAccount.account isEqualToString:_metadataNet.account]) {
  1005. if ([self.delegate respondsToSelector:@selector(getSharePermissionsFileFailure:message:errorCode:)])
  1006. [self.delegate getSharePermissionsFileFailure:_metadataNet message:NSLocalizedStringFromTable(@"_error_user_not_available_", @"Error", nil) errorCode:k_CCErrorUserNotAvailble];
  1007. [self complete];
  1008. return;
  1009. }
  1010. if([self.delegate respondsToSelector:@selector(getSharePermissionsFileSuccess:permissions:)])
  1011. [self.delegate getSharePermissionsFileSuccess:_metadataNet permissions:permissions];
  1012. [self complete];
  1013. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1014. NSInteger errorCode = response.statusCode;
  1015. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1016. errorCode = error.code;
  1017. // Error
  1018. if ([self.delegate respondsToSelector:@selector(getSharePermissionsFileFailure:message:errorCode:)]) {
  1019. if (errorCode == 503)
  1020. [self.delegate getSharePermissionsFileFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  1021. else
  1022. [self.delegate getSharePermissionsFileFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1023. }
  1024. // Request trusted certificated
  1025. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  1026. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1027. [self complete];
  1028. }];
  1029. }
  1030. #pragma --------------------------------------------------------------------------------------------
  1031. #pragma mark ===== Activity =====
  1032. #pragma --------------------------------------------------------------------------------------------
  1033. - (void)getActivityServer
  1034. {
  1035. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1036. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  1037. [communication setUserAgent:[CCUtility getUserAgent]];
  1038. [communication getActivityServer:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfActivity, NSString *redirectedServer) {
  1039. // Test active account
  1040. tableAccount *recordAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  1041. if (![recordAccount.account isEqualToString:_metadataNet.account]) {
  1042. if ([self.delegate respondsToSelector:@selector(getActivityServerSuccessFailure:listOfActivity:message:errorCode:)])
  1043. [self.delegate getActivityServerSuccessFailure:_metadataNet listOfActivity:nil message:NSLocalizedStringFromTable(@"_error_user_not_available_", @"Error", nil) errorCode:k_CCErrorUserNotAvailble];
  1044. [self complete];
  1045. return;
  1046. }
  1047. if ([self.delegate respondsToSelector:@selector(getActivityServerSuccessFailure:listOfActivity:message:errorCode:)])
  1048. [self.delegate getActivityServerSuccessFailure:_metadataNet listOfActivity:listOfActivity message:nil errorCode:0];
  1049. [self complete];
  1050. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1051. NSInteger errorCode = response.statusCode;
  1052. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1053. errorCode = error.code;
  1054. // Error
  1055. if ([self.delegate respondsToSelector:@selector(getActivityServerSuccessFailure:listOfActivity:message:errorCode:)]) {
  1056. if (errorCode == 503)
  1057. [self.delegate getActivityServerSuccessFailure:_metadataNet listOfActivity:nil message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  1058. else
  1059. [self.delegate getActivityServerSuccessFailure:_metadataNet listOfActivity:nil message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1060. }
  1061. // Request trusted certificated
  1062. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  1063. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1064. [self complete];
  1065. }];
  1066. }
  1067. #pragma --------------------------------------------------------------------------------------------
  1068. #pragma mark ===== External Sites =====
  1069. #pragma --------------------------------------------------------------------------------------------
  1070. - (void)getExternalSitesServer
  1071. {
  1072. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1073. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  1074. [communication setUserAgent:[CCUtility getUserAgent]];
  1075. [communication getExternalSitesServer:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfExternalSites, NSString *redirectedServer) {
  1076. // Test active account
  1077. tableAccount *recordAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  1078. if (![recordAccount.account isEqualToString:_metadataNet.account]) {
  1079. if ([self.delegate respondsToSelector:@selector(getExternalSitesServerSuccessFailure:listOfExternalSites:message:errorCode:)])
  1080. [self.delegate getExternalSitesServerSuccessFailure:_metadataNet listOfExternalSites:nil message:NSLocalizedStringFromTable(@"_error_user_not_available_", @"Error", nil) errorCode:k_CCErrorUserNotAvailble];
  1081. [self complete];
  1082. return;
  1083. }
  1084. if ([self.delegate respondsToSelector:@selector(getExternalSitesServerSuccessFailure:listOfExternalSites:message:errorCode:)])
  1085. [self.delegate getExternalSitesServerSuccessFailure:_metadataNet listOfExternalSites:listOfExternalSites message:nil errorCode:0];
  1086. [self complete];
  1087. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1088. NSInteger errorCode = response.statusCode;
  1089. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1090. errorCode = error.code;
  1091. // Error
  1092. if ([self.delegate respondsToSelector:@selector(getExternalSitesServerSuccessFailure:listOfExternalSites:message:errorCode:)]) {
  1093. if (errorCode == 503)
  1094. [self.delegate getExternalSitesServerSuccessFailure:_metadataNet listOfExternalSites:nil message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  1095. else
  1096. [self.delegate getExternalSitesServerSuccessFailure:_metadataNet listOfExternalSites:nil message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1097. }
  1098. // Request trusted certificated
  1099. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  1100. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1101. [self complete];
  1102. }];
  1103. }
  1104. #pragma --------------------------------------------------------------------------------------------
  1105. #pragma mark ===== Middleware Ping =====
  1106. #pragma --------------------------------------------------------------------------------------------
  1107. /*
  1108. - (void)middlewarePing
  1109. {
  1110. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1111. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  1112. [communication setUserAgent:[CCUtility getUserAgent]];
  1113. [communication getMiddlewarePing:_metadataNet.serverUrl onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfExternalSites, NSString *redirectedServer) {
  1114. [self complete];
  1115. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1116. NSInteger errorCode = response.statusCode;
  1117. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1118. errorCode = error.code;
  1119. // Error
  1120. if ([self.delegate respondsToSelector:@selector(getExternalSitesServerFailure:message:errorCode:)]) {
  1121. if (errorCode == 503)
  1122. [self.delegate getExternalSitesServerFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  1123. else
  1124. [self.delegate getExternalSitesServerFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1125. }
  1126. // Request trusted certificated
  1127. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  1128. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1129. [self complete];
  1130. }];
  1131. }
  1132. */
  1133. #pragma --------------------------------------------------------------------------------------------
  1134. #pragma mark ===== Notification =====
  1135. #pragma --------------------------------------------------------------------------------------------
  1136. - (void)getNotificationServer
  1137. {
  1138. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1139. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  1140. [communication setUserAgent:[CCUtility getUserAgent]];
  1141. [communication getNotificationServer:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfNotifications, NSString *redirectedServer) {
  1142. // Test active account
  1143. tableAccount *recordAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  1144. if (![recordAccount.account isEqualToString:_metadataNet.account]) {
  1145. if ([self.delegate respondsToSelector:@selector(getNotificationServerSuccessFailure:listOfNotifications:message:errorCode:)])
  1146. [self.delegate getNotificationServerSuccessFailure:_metadataNet listOfNotifications:nil message:NSLocalizedStringFromTable(@"_error_user_not_available_", @"Error", nil) errorCode:k_CCErrorUserNotAvailble];
  1147. [self complete];
  1148. return;
  1149. }
  1150. if ([self.delegate respondsToSelector:@selector(getNotificationServerSuccessFailure:listOfNotifications:message:errorCode:)])
  1151. [self.delegate getNotificationServerSuccessFailure:_metadataNet listOfNotifications:listOfNotifications message:nil errorCode:0];
  1152. [self complete];
  1153. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1154. NSInteger errorCode = response.statusCode;
  1155. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1156. errorCode = error.code;
  1157. // Error
  1158. if ([self.delegate respondsToSelector:@selector(getNotificationServerSuccessFailure:listOfNotifications:message:errorCode:)]) {
  1159. if (errorCode == 503)
  1160. [self.delegate getNotificationServerSuccessFailure:_metadataNet listOfNotifications:nil message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  1161. else
  1162. [self.delegate getNotificationServerSuccessFailure:_metadataNet listOfNotifications:nil message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1163. }
  1164. // Request trusted certificated
  1165. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  1166. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1167. // Activity
  1168. [[NCManageDatabase sharedInstance] addActivityClient:_activeUrl fileID:@"" action:k_activityDebugActionGetNotification selector:@"" note:[error.userInfo valueForKey:@"NSLocalizedDescription"] type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:_activeUrl];
  1169. [self complete];
  1170. }];
  1171. }
  1172. - (void)setNotificationServer
  1173. {
  1174. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1175. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  1176. [communication setUserAgent:[CCUtility getUserAgent]];
  1177. NSString *type = _metadataNet.options;
  1178. [communication setNotificationServer:_metadataNet.serverUrl type:type onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1179. // Test active account
  1180. tableAccount *recordAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  1181. if (![recordAccount.account isEqualToString:_metadataNet.account]) {
  1182. if ([self.delegate respondsToSelector:@selector(setNotificationServerSuccessFailure:message:errorCode:)])
  1183. [self.delegate setNotificationServerSuccessFailure:_metadataNet message:NSLocalizedStringFromTable(@"_error_user_not_available_", @"Error", nil) errorCode:k_CCErrorUserNotAvailble];
  1184. [self complete];
  1185. return;
  1186. }
  1187. if ([self.delegate respondsToSelector:@selector(setNotificationServerSuccessFailure:message:errorCode:)])
  1188. [self.delegate setNotificationServerSuccessFailure:_metadataNet message:nil errorCode:0];
  1189. [self complete];
  1190. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1191. NSInteger errorCode = response.statusCode;
  1192. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1193. errorCode = error.code;
  1194. // Error
  1195. if ([self.delegate respondsToSelector:@selector(setNotificationServerSuccessFailure:message:errorCode:)]) {
  1196. if (errorCode == 503)
  1197. [self.delegate setNotificationServerSuccessFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  1198. else
  1199. [self.delegate setNotificationServerSuccessFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1200. }
  1201. // Request trusted certificated
  1202. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  1203. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1204. [self complete];
  1205. }];
  1206. }
  1207. - (void)subscribingNextcloudServer
  1208. {
  1209. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1210. communication.kindOfCredential = credentialNotSet;
  1211. [communication setUserAgent:[CCUtility getUserAgent]];
  1212. NSDictionary *parameter = _metadataNet.options;
  1213. NSString *pushToken = [parameter objectForKey:@"pushToken"];
  1214. NSString *pushTokenHash = [parameter objectForKey:@"pushTokenHash"];
  1215. NSString *devicePublicKey = [parameter objectForKey:@"devicePublicKey"];
  1216. // encode URL
  1217. devicePublicKey = [devicePublicKey stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
  1218. [communication subscribingNextcloudServerPush:_activeUrl pushTokenHash:pushTokenHash devicePublicKey:devicePublicKey proxyServerPath: [NCBrandOptions sharedInstance].pushNotificationServer onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *publicKey, NSString *deviceIdentifier, NSString *signature, NSString *redirectedServer) {
  1219. // encode URL
  1220. deviceIdentifier = [deviceIdentifier stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
  1221. signature = [signature stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
  1222. publicKey = [publicKey stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
  1223. [communication subscribingPushProxy:[NCBrandOptions sharedInstance].pushNotificationServer pushToken:pushToken deviceIdentifier:deviceIdentifier deviceIdentifierSignature:signature userPublicKey:publicKey onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1224. // Activity
  1225. [[NCManageDatabase sharedInstance] addActivityClient:[NCBrandOptions sharedInstance].pushNotificationServer fileID:@"" action:k_activityDebugActionPushProxy selector:@"" note:@"Service registered." type:k_activityTypeSuccess verbose:k_activityVerboseHigh activeUrl:_activeUrl];
  1226. [self complete];
  1227. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1228. NSInteger errorCode = response.statusCode;
  1229. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1230. errorCode = error.code;
  1231. // Error
  1232. if ([self.delegate respondsToSelector:@selector(subscribingNextcloudServerFailure:message:errorCode:)]) {
  1233. if (errorCode == 503)
  1234. [self.delegate subscribingNextcloudServerFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  1235. else
  1236. [self.delegate subscribingNextcloudServerFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1237. }
  1238. // Request trusted certificated
  1239. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  1240. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1241. // Activity
  1242. [[NCManageDatabase sharedInstance] addActivityClient:[NCBrandOptions sharedInstance].pushNotificationServer fileID:@"" action:k_activityDebugActionPushProxy selector:@"" note:[error.userInfo valueForKey:@"NSLocalizedDescription"] type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:_activeUrl];
  1243. [self complete];
  1244. }];
  1245. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1246. NSInteger errorCode = response.statusCode;
  1247. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1248. errorCode = error.code;
  1249. // Error
  1250. if ([self.delegate respondsToSelector:@selector(subscribingNextcloudServerFailure:message:errorCode:)]) {
  1251. if (errorCode == 503)
  1252. [self.delegate subscribingNextcloudServerFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  1253. else
  1254. [self.delegate subscribingNextcloudServerFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1255. }
  1256. // Request trusted certificated
  1257. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  1258. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1259. // Activity
  1260. [[NCManageDatabase sharedInstance] addActivityClient:_activeUrl fileID:@"" action:k_activityDebugActionServerPush selector:@"" note:[error.userInfo valueForKey:@"NSLocalizedDescription"] type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:_activeUrl];
  1261. [self complete];
  1262. }];
  1263. }
  1264. #pragma --------------------------------------------------------------------------------------------
  1265. #pragma mark ===== User Profile =====
  1266. #pragma --------------------------------------------------------------------------------------------
  1267. - (void)getUserProfile
  1268. {
  1269. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1270. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  1271. [communication setUserAgent:[CCUtility getUserAgent]];
  1272. [communication getUserProfileServer:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, OCUserProfile *userProfile, NSString *redirectedServer) {
  1273. // Test active account
  1274. tableAccount *recordAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  1275. if (![recordAccount.account isEqualToString:_metadataNet.account]) {
  1276. if ([self.delegate respondsToSelector:@selector(getUserProfileSuccessFailure:userProfile:message:errorCode:)])
  1277. [self.delegate getUserProfileSuccessFailure:_metadataNet userProfile:nil message:NSLocalizedStringFromTable(@"_error_user_not_available_", @"Error", nil) errorCode:k_CCErrorUserNotAvailble];
  1278. [self complete];
  1279. return;
  1280. }
  1281. if ([self.delegate respondsToSelector:@selector(getUserProfileSuccessFailure:userProfile:message:errorCode:)])
  1282. [self.delegate getUserProfileSuccessFailure:_metadataNet userProfile:userProfile message:nil errorCode:0];
  1283. [self complete];
  1284. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1285. NSInteger errorCode = response.statusCode;
  1286. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1287. errorCode = error.code;
  1288. // Error
  1289. if ([self.delegate respondsToSelector:@selector(getUserProfileSuccessFailure:userProfile:message:errorCode:)]) {
  1290. if (errorCode == 503)
  1291. [self.delegate getUserProfileSuccessFailure:_metadataNet userProfile:nil message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  1292. else
  1293. [self.delegate getUserProfileSuccessFailure:_metadataNet userProfile:nil message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1294. }
  1295. // Request trusted certificated
  1296. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  1297. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1298. [self complete];
  1299. }];
  1300. }
  1301. #pragma --------------------------------------------------------------------------------------------
  1302. #pragma mark ===== Capabilities =====
  1303. #pragma --------------------------------------------------------------------------------------------
  1304. - (void)getCapabilitiesOfServer
  1305. {
  1306. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1307. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  1308. [communication setUserAgent:[CCUtility getUserAgent]];
  1309. [communication getCapabilitiesOfServer:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, OCCapabilities *capabilities, NSString *redirectedServer) {
  1310. // Test active account
  1311. tableAccount *recordAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  1312. if (![recordAccount.account isEqualToString:_metadataNet.account]) {
  1313. if ([self.delegate respondsToSelector:@selector(getCapabilitiesOfServerSuccessFailure:capabilities:message:errorCode:)])
  1314. [self.delegate getCapabilitiesOfServerSuccessFailure:_metadataNet capabilities:nil message:NSLocalizedStringFromTable(@"_error_user_not_available_", @"Error", nil) errorCode:k_CCErrorUserNotAvailble];
  1315. [self complete];
  1316. return;
  1317. }
  1318. if ([self.delegate respondsToSelector:@selector(getCapabilitiesOfServerSuccessFailure:capabilities:message:errorCode:)])
  1319. [self.delegate getCapabilitiesOfServerSuccessFailure:_metadataNet capabilities:capabilities message:nil errorCode:0];
  1320. [self complete];
  1321. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1322. NSInteger errorCode = response.statusCode;
  1323. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1324. errorCode = error.code;
  1325. // Error
  1326. if ([self.delegate respondsToSelector:@selector(getCapabilitiesOfServerSuccessFailure:capabilities:message:errorCode:)]) {
  1327. if (errorCode == 503)
  1328. [self.delegate getCapabilitiesOfServerSuccessFailure:_metadataNet capabilities:nil message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
  1329. else
  1330. [self.delegate getCapabilitiesOfServerSuccessFailure:_metadataNet capabilities:nil message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1331. }
  1332. // Request trusted certificated
  1333. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  1334. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1335. // Activity
  1336. [[NCManageDatabase sharedInstance] addActivityClient:_activeUrl fileID:@"" action:k_activityDebugActionCapabilities selector:@"" note:[error.userInfo valueForKey:@"NSLocalizedDescription"] type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:_activeUrl];
  1337. [self complete];
  1338. }];
  1339. }
  1340. #pragma --------------------------------------------------------------------------------------------
  1341. #pragma mark ===== End-to-End Encryption =====
  1342. #pragma --------------------------------------------------------------------------------------------
  1343. - (void)getEndToEndPublicKeys
  1344. {
  1345. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1346. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  1347. [communication setUserAgent:[CCUtility getUserAgent]];
  1348. [communication getEndToEndPublicKeys:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *publicKey, NSString *redirectedServer) {
  1349. _metadataNet.key = publicKey;
  1350. if ([self.delegate respondsToSelector:@selector(getEndToEndPublicKeysSuccess:)])
  1351. [self.delegate getEndToEndPublicKeysSuccess:_metadataNet];
  1352. [self complete];
  1353. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1354. NSInteger errorCode = response.statusCode;
  1355. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1356. errorCode = error.code;
  1357. // Error
  1358. if ([self.delegate respondsToSelector:@selector(getEndToEndPublicKeysFailure:message:errorCode:)])
  1359. [self.delegate getEndToEndPublicKeysFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1360. // Request trusted certificated
  1361. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  1362. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1363. [self complete];
  1364. }];
  1365. }
  1366. - (void)getEndToEndPrivateKeyCipher
  1367. {
  1368. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1369. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  1370. [communication setUserAgent:[CCUtility getUserAgent]];
  1371. [communication getEndToEndPrivateKeyCipher:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *privateKeyChiper, NSString *redirectedServer) {
  1372. _metadataNet.key = privateKeyChiper;
  1373. if ([self.delegate respondsToSelector:@selector(getEndToEndPrivateKeyCipherSuccess:)])
  1374. [self.delegate getEndToEndPrivateKeyCipherSuccess:_metadataNet];
  1375. [self complete];
  1376. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1377. NSInteger errorCode = response.statusCode;
  1378. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1379. errorCode = error.code;
  1380. // Error
  1381. if ([self.delegate respondsToSelector:@selector(getEndToEndPrivateKeyCipherFailure:message:errorCode:)])
  1382. [self.delegate getEndToEndPrivateKeyCipherFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1383. // Request trusted certificated
  1384. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  1385. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1386. [self complete];
  1387. }];
  1388. }
  1389. - (void)signEndToEndPublicKey
  1390. {
  1391. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1392. // URL Encode
  1393. NSString *publicKey = [CCUtility URLEncodeStringFromString:_metadataNet.key];
  1394. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  1395. [communication setUserAgent:[CCUtility getUserAgent]];
  1396. [communication signEndToEndPublicKey:[_activeUrl stringByAppendingString:@"/"] publicKey:publicKey onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *publicKey, NSString *redirectedServer) {
  1397. _metadataNet.key = publicKey;
  1398. if ([self.delegate respondsToSelector:@selector(signEndToEndPublicKeySuccess:)])
  1399. [self.delegate signEndToEndPublicKeySuccess:_metadataNet];
  1400. [self complete];
  1401. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1402. NSInteger errorCode = response.statusCode;
  1403. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1404. errorCode = error.code;
  1405. // Error
  1406. if ([self.delegate respondsToSelector:@selector(signEndToEndPublicKeyFailure:message:errorCode:)])
  1407. [self.delegate signEndToEndPublicKeyFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1408. // Request trusted certificated
  1409. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  1410. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1411. [self complete];
  1412. }];
  1413. }
  1414. - (void)storeEndToEndPrivateKeyCipher
  1415. {
  1416. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1417. // URL Encode
  1418. NSString *privateKeyChiper = [CCUtility URLEncodeStringFromString:_metadataNet.keyCipher];
  1419. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  1420. [communication setUserAgent:[CCUtility getUserAgent]];
  1421. [communication storeEndToEndPrivateKeyCipher:[_activeUrl stringByAppendingString:@"/"] privateKeyChiper:privateKeyChiper onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *privateKey, NSString *redirectedServer) {
  1422. if ([self.delegate respondsToSelector:@selector(storeEndToEndPrivateKeyCipherSuccess:)])
  1423. [self.delegate storeEndToEndPrivateKeyCipherSuccess:_metadataNet];
  1424. [self complete];
  1425. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1426. NSInteger errorCode = response.statusCode;
  1427. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1428. errorCode = error.code;
  1429. // Error
  1430. if ([self.delegate respondsToSelector:@selector(storeEndToEndPrivateKeyCipherFailure:message:errorCode:)])
  1431. [self.delegate storeEndToEndPrivateKeyCipherFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1432. // Request trusted certificated
  1433. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  1434. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1435. [self complete];
  1436. }];
  1437. }
  1438. - (void)deleteEndToEndPublicKey
  1439. {
  1440. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1441. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  1442. [communication setUserAgent:[CCUtility getUserAgent]];
  1443. [communication deleteEndToEndPublicKey:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1444. if ([self.delegate respondsToSelector:@selector(deleteEndToEndPublicKeySuccess:)])
  1445. [self.delegate deleteEndToEndPublicKeySuccess:_metadataNet];
  1446. [self complete];
  1447. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1448. NSInteger errorCode = response.statusCode;
  1449. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1450. errorCode = error.code;
  1451. // Error
  1452. if ([self.delegate respondsToSelector:@selector(deleteEndToEndPublicKeyFailure:message:errorCode:)])
  1453. [self.delegate deleteEndToEndPublicKeyFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1454. // Request trusted certificated
  1455. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  1456. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1457. [self complete];
  1458. }];
  1459. }
  1460. - (void)deleteEndToEndPrivateKey
  1461. {
  1462. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1463. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  1464. [communication setUserAgent:[CCUtility getUserAgent]];
  1465. [communication deleteEndToEndPrivateKey:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1466. if ([self.delegate respondsToSelector:@selector(deleteEndToEndPrivateKeySuccess:)])
  1467. [self.delegate deleteEndToEndPrivateKeySuccess:_metadataNet];
  1468. [self complete];
  1469. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1470. NSInteger errorCode = response.statusCode;
  1471. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1472. errorCode = error.code;
  1473. // Error
  1474. if ([self.delegate respondsToSelector:@selector(deleteEndToEndPrivateKeyFailure:message:errorCode:)])
  1475. [self.delegate deleteEndToEndPrivateKeyFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1476. // Request trusted certificated
  1477. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  1478. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1479. [self complete];
  1480. }];
  1481. }
  1482. - (void)getEndToEndServerPublicKey
  1483. {
  1484. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1485. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  1486. [communication setUserAgent:[CCUtility getUserAgent]];
  1487. [communication getEndToEndServerPublicKey:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *publicKey, NSString *redirectedServer) {
  1488. _metadataNet.key = publicKey;
  1489. if ([self.delegate respondsToSelector:@selector(getEndToEndServerPublicKeySuccess:)])
  1490. [self.delegate getEndToEndServerPublicKeySuccess:_metadataNet];
  1491. [self complete];
  1492. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1493. NSInteger errorCode = response.statusCode;
  1494. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1495. errorCode = error.code;
  1496. // Error
  1497. if ([self.delegate respondsToSelector:@selector(getEndToEndServerPublicKeyFailure:message:errorCode:)])
  1498. [self.delegate getEndToEndServerPublicKeyFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1499. // Request trusted certificated
  1500. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  1501. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1502. [self complete];
  1503. }];
  1504. }
  1505. @end
  1506. #pragma --------------------------------------------------------------------------------------------
  1507. #pragma mark ===== OCURLSessionManager =====
  1508. #pragma --------------------------------------------------------------------------------------------
  1509. @implementation OCURLSessionManager
  1510. - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
  1511. {
  1512. // The pinnning check
  1513. if ([[CCCertificate sharedManager] checkTrustedChallenge:challenge]) {
  1514. completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  1515. } else {
  1516. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  1517. }
  1518. }
  1519. @end