OCNetworking.m 97 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960
  1. //
  2. // OCnetworking.m
  3. // Nextcloud iOS
  4. //
  5. // Created by Marino Faggiana on 10/05/15.
  6. // Copyright (c) 2017 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  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. @implementation OCNetworking
  30. + (OCNetworking *)sharedManager {
  31. static OCNetworking *sharedManager;
  32. @synchronized(self)
  33. {
  34. if (!sharedManager) {
  35. sharedManager = [OCNetworking new];
  36. }
  37. return sharedManager;
  38. }
  39. }
  40. - (id)init
  41. {
  42. self = [super init];
  43. [self sharedOCCommunication];
  44. return self;
  45. }
  46. #pragma --------------------------------------------------------------------------------------------
  47. #pragma mark ===== OCCommunication =====
  48. #pragma --------------------------------------------------------------------------------------------
  49. - (OCCommunication *)sharedOCCommunication
  50. {
  51. static OCCommunication* sharedOCCommunication = nil;
  52. if (sharedOCCommunication == nil)
  53. {
  54. // Network
  55. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  56. configuration.allowsCellularAccess = YES;
  57. configuration.discretionary = NO;
  58. configuration.HTTPMaximumConnectionsPerHost = k_maxConcurrentOperation;
  59. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  60. OCURLSessionManager *networkSessionManager = [[OCURLSessionManager alloc] initWithSessionConfiguration:configuration];
  61. [networkSessionManager.operationQueue setMaxConcurrentOperationCount: k_maxConcurrentOperation];
  62. networkSessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
  63. // Download
  64. NSURLSessionConfiguration *configurationDownload = [NSURLSessionConfiguration defaultSessionConfiguration];
  65. configurationDownload.allowsCellularAccess = YES;
  66. configurationDownload.discretionary = NO;
  67. configurationDownload.HTTPMaximumConnectionsPerHost = k_maxHTTPConnectionsPerHost;
  68. configurationDownload.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  69. configurationDownload.timeoutIntervalForRequest = k_timeout_upload;
  70. OCURLSessionManager *downloadSessionManager = [[OCURLSessionManager alloc] initWithSessionConfiguration:configurationDownload];
  71. [downloadSessionManager.operationQueue setMaxConcurrentOperationCount:k_maxHTTPConnectionsPerHost];
  72. [downloadSessionManager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition (NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential) {
  73. return NSURLSessionAuthChallengePerformDefaultHandling;
  74. }];
  75. // Upload
  76. NSURLSessionConfiguration *configurationUpload = [NSURLSessionConfiguration defaultSessionConfiguration];
  77. configurationUpload.allowsCellularAccess = YES;
  78. configurationUpload.discretionary = NO;
  79. configurationUpload.HTTPMaximumConnectionsPerHost = k_maxHTTPConnectionsPerHost;
  80. configurationUpload.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  81. configurationUpload.timeoutIntervalForRequest = k_timeout_upload;
  82. OCURLSessionManager *uploadSessionManager = [[OCURLSessionManager alloc] initWithSessionConfiguration:configurationUpload];
  83. [uploadSessionManager.operationQueue setMaxConcurrentOperationCount:k_maxHTTPConnectionsPerHost];
  84. [uploadSessionManager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition (NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential) {
  85. return NSURLSessionAuthChallengePerformDefaultHandling;
  86. }];
  87. sharedOCCommunication = [[OCCommunication alloc] initWithUploadSessionManager:uploadSessionManager andDownloadSessionManager:downloadSessionManager andNetworkSessionManager:networkSessionManager];
  88. }
  89. return sharedOCCommunication;
  90. }
  91. - (OCCommunication *)sharedOCCommunicationExtensionDownload
  92. {
  93. static OCCommunication *sharedOCCommunicationExtensionDownload = nil;
  94. if (sharedOCCommunicationExtensionDownload == nil)
  95. {
  96. NSURLSessionConfiguration *config = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_download_session_extension];
  97. config.sharedContainerIdentifier = [NCBrandOptions sharedInstance].capabilitiesGroups;
  98. config.HTTPMaximumConnectionsPerHost = 1;
  99. config.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  100. config.timeoutIntervalForRequest = k_timeout_upload;
  101. config.sessionSendsLaunchEvents = YES;
  102. [config setAllowsCellularAccess:YES];
  103. OCURLSessionManager *sessionManager = [[OCURLSessionManager alloc] initWithSessionConfiguration:config];
  104. [sessionManager.operationQueue setMaxConcurrentOperationCount:1];
  105. [sessionManager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition (NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential) {
  106. return NSURLSessionAuthChallengePerformDefaultHandling;
  107. }];
  108. sharedOCCommunicationExtensionDownload = [[OCCommunication alloc] initWithUploadSessionManager:nil andDownloadSessionManager:sessionManager andNetworkSessionManager:nil];
  109. }
  110. return sharedOCCommunicationExtensionDownload;
  111. }
  112. #pragma --------------------------------------------------------------------------------------------
  113. #pragma mark ===== Server =====
  114. #pragma --------------------------------------------------------------------------------------------
  115. - (void)checkServerUrl:(NSString *)serverUrl user:(NSString *)user userID:(NSString *)userID password:(NSString *)password completion:(void (^)(NSString *message, NSInteger errorCode))completion
  116. {
  117. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  118. [communication setCredentialsWithUser:user andUserID:userID andPassword:password];
  119. [communication setUserAgent:[CCUtility getUserAgent]];
  120. [communication checkServer:serverUrl onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  121. completion(nil, 0);
  122. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  123. NSString *message;
  124. NSInteger errorCode = response.statusCode;
  125. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  126. errorCode = error.code;
  127. // Error
  128. if (errorCode == 503)
  129. message = NSLocalizedString(@"_server_error_retry_", nil);
  130. else
  131. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  132. completion(message, errorCode);
  133. }];
  134. }
  135. - (void)serverStatusUrl:(NSString *)serverUrl completion:(void(^)(NSString *serverProductName, NSInteger versionMajor, NSInteger versionMicro, NSInteger versionMinor, NSString *message, NSInteger errorCode))completion
  136. {
  137. NSString *urlTest = [serverUrl stringByAppendingString:k_serverStatus];
  138. // Remove stored cookies
  139. NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
  140. for (NSHTTPCookie *cookie in [storage cookies])
  141. {
  142. [storage deleteCookie:cookie];
  143. }
  144. NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlTest] cachePolicy:0 timeoutInterval:20.0];
  145. [request addValue:[CCUtility getUserAgent] forHTTPHeaderField:@"User-Agent"];
  146. [request addValue:@"true" forHTTPHeaderField:@"OCS-APIRequest"];
  147. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  148. NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  149. NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler: ^(NSData *data, NSURLResponse *response, NSError *error) {
  150. dispatch_sync(dispatch_get_main_queue(), ^{
  151. if (error) {
  152. NSString *message;
  153. NSInteger errorCode;
  154. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
  155. errorCode = httpResponse.statusCode;
  156. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  157. errorCode = error.code;
  158. // Error
  159. if (errorCode == 503)
  160. message = NSLocalizedString(@"_server_error_retry_", nil);
  161. else
  162. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  163. completion(nil, 0, 0, 0, message, errorCode);
  164. } else {
  165. NSString *serverProductName = @"";
  166. NSString *serverVersion = @"0.0.0";
  167. NSString *serverVersionString = @"0.0.0";
  168. NSInteger versionMajor = 0;
  169. NSInteger versionMicro = 0;
  170. NSInteger versionMinor = 0;
  171. NSError *error;
  172. NSDictionary *jsongParsed = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
  173. if (error) {
  174. completion(nil, 0, 0, 0, error.description, error.code);
  175. return;
  176. }
  177. serverProductName = [[jsongParsed valueForKey:@"productname"] lowercaseString];
  178. serverVersion = [jsongParsed valueForKey:@"version"];
  179. serverVersionString = [jsongParsed valueForKey:@"versionstring"];
  180. NSArray *arrayVersion = [serverVersionString componentsSeparatedByString:@"."];
  181. if (arrayVersion.count == 1) {
  182. versionMajor = [arrayVersion[0] integerValue];
  183. } else if (arrayVersion.count == 2) {
  184. versionMajor = [arrayVersion[0] integerValue];
  185. versionMinor = [arrayVersion[1] integerValue];
  186. } else if (arrayVersion.count >= 3) {
  187. versionMajor = [arrayVersion[0] integerValue];
  188. versionMinor = [arrayVersion[1] integerValue];
  189. versionMicro = [arrayVersion[2] integerValue];
  190. }
  191. completion(serverProductName, versionMajor, versionMicro, versionMinor, nil, 0);
  192. }
  193. });
  194. }];
  195. [task resume];
  196. }
  197. #pragma --------------------------------------------------------------------------------------------
  198. #pragma mark ===== download / upload =====
  199. #pragma --------------------------------------------------------------------------------------------
  200. - (NSURLSessionTask *)downloadWithAccount:(NSString *)account fileNameServerUrl:(NSString *)fileNameServerUrl fileNameLocalPath:(NSString *)fileNameLocalPath communication:(OCCommunication *)communication completion:(void (^)(NSString *account, int64_t length, NSString *etag, NSDate *date, NSString *message, NSInteger errorCode))completion
  201. {
  202. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  203. if (tableAccount == nil) {
  204. completion(account, 0, nil, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  205. }
  206. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  207. [communication setUserAgent:[CCUtility getUserAgent]];
  208. NSURLSessionTask *sessionTask = [communication downloadFileSession:fileNameServerUrl toDestiny:fileNameLocalPath defaultPriority:YES onCommunication:communication progress:^(NSProgress *progress) {
  209. //float percent = roundf (progress.fractionCompleted * 100);
  210. } successRequest:^(NSURLResponse *response, NSURL *filePath) {
  211. int64_t totalUnitCount = 0;
  212. NSDate *date = [NSDate date];
  213. NSDateFormatter *dateFormatter = [NSDateFormatter new];
  214. NSLocale *enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
  215. [dateFormatter setLocale:enUSPOSIXLocale];
  216. [dateFormatter setDateFormat:@"EEE, dd MMM y HH:mm:ss zzz"];
  217. NSError *error;
  218. NSDictionary *fields = [(NSHTTPURLResponse*)response allHeaderFields];
  219. NSString *contentLength = [fields objectForKey:@"Content-Length"];
  220. if(contentLength) {
  221. totalUnitCount = (int64_t) [contentLength longLongValue];
  222. }
  223. NSString *dateString = [fields objectForKey:@"Date"];
  224. if (dateString) {
  225. if (![dateFormatter getObjectValue:&date forString:dateString range:nil error:&error]) {
  226. date = [NSDate date];
  227. }
  228. } else {
  229. date = [NSDate date];
  230. }
  231. NSString *etag = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-ETag"]];
  232. if (etag == nil) {
  233. completion(account, 0, nil, nil, NSLocalizedString(@"Internal error", nil), k_CCErrorInternalError);
  234. } else {
  235. completion(account, totalUnitCount, etag, date, nil, 0);
  236. }
  237. } failureRequest:^(NSURLResponse *response, NSError *error) {
  238. NSString *message;
  239. NSInteger errorCode;
  240. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
  241. errorCode = httpResponse.statusCode;
  242. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  243. errorCode = error.code;
  244. // Error
  245. if (errorCode == 503)
  246. message = NSLocalizedString(@"_server_error_retry_", nil);
  247. else
  248. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  249. completion(account, 0, nil, nil, message, errorCode);
  250. }];
  251. return sessionTask;
  252. }
  253. - (NSURLSessionTask *)downloadWithAccount:(NSString *)account url:(NSString *)url fileNameLocalPath:(NSString *)fileNameLocalPath completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  254. {
  255. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  256. if (tableAccount == nil) {
  257. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  258. }
  259. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  260. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  261. [communication setUserAgent:[CCUtility getUserAgent]];
  262. NSURLSessionTask *sessionTask = [communication downloadFileSession:url toDestiny:fileNameLocalPath defaultPriority:YES onCommunication:communication progress:^(NSProgress *progress) {
  263. //float percent = roundf (progress.fractionCompleted * 100);
  264. } successRequest:^(NSURLResponse *response, NSURL *filePath) {
  265. completion(account, nil, 0);
  266. } failureRequest:^(NSURLResponse *response, NSError *error) {
  267. NSString *message;
  268. NSInteger errorCode;
  269. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
  270. errorCode = httpResponse.statusCode;
  271. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  272. errorCode = error.code;
  273. // Error
  274. if (errorCode == 503)
  275. message = NSLocalizedString(@"_server_error_retry_", nil);
  276. else
  277. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  278. completion(account, message, errorCode);
  279. }];
  280. return sessionTask;
  281. }
  282. - (NSURLSessionTask *)uploadWithAccount:(NSString *)account fileNameServerUrl:(NSString *)fileNameServerUrl fileNameLocalPath:(NSString *)fileNameLocalPath communication:(OCCommunication *)communication completion:(void(^)(NSString *account, NSString *fileID, NSString *etag, NSDate *date, NSString *message, NSInteger errorCode))completion
  283. {
  284. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  285. if (tableAccount == nil) {
  286. completion(account, nil, nil, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  287. }
  288. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  289. [communication setUserAgent:[CCUtility getUserAgent]];
  290. NSURLSessionTask *sessionTask = [communication uploadFileSession:fileNameLocalPath toDestiny:fileNameServerUrl onCommunication:communication progress:^(NSProgress *progress) {
  291. //float percent = roundf (progress.fractionCompleted * 100);
  292. } successRequest:^(NSURLResponse *response, NSString *redirectedServer) {
  293. NSDictionary *fields = [(NSHTTPURLResponse*)response allHeaderFields];
  294. NSString *fileID = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-FileId"]];
  295. NSString *etag = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-ETag"]];
  296. NSDate *date = [CCUtility dateEnUsPosixFromCloud:[fields objectForKey:@"Date"]];
  297. completion(account, fileID, etag, date, nil, 0);
  298. } failureRequest:^(NSURLResponse *response, NSString *redirectedServer, NSError *error) {
  299. NSString *message;
  300. NSInteger errorCode;
  301. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
  302. errorCode = httpResponse.statusCode;
  303. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  304. errorCode = error.code;
  305. // Error
  306. if (errorCode == 503)
  307. message = NSLocalizedString(@"_server_error_retry_", nil);
  308. else
  309. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  310. completion(account, nil, nil, nil, message, errorCode);
  311. } failureBeforeRequest:^(NSError *error) {
  312. completion(account, nil, nil, nil, error.description, error.code);
  313. }];
  314. return sessionTask;
  315. }
  316. #pragma --------------------------------------------------------------------------------------------
  317. #pragma mark ===== WebDav =====
  318. #pragma --------------------------------------------------------------------------------------------
  319. - (void)readFolderWithAccount:(NSString *)account serverUrl:(NSString *)serverUrl depth:(NSString *)depth completion:(void(^)(NSString *account, NSArray *metadatas, tableMetadata *metadataFolder, NSString *message, NSInteger errorCode))completion
  320. {
  321. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  322. if (tableAccount == nil) {
  323. completion(account, nil, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  324. }
  325. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  326. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  327. [communication setUserAgent:[CCUtility getUserAgent]];
  328. [communication readFolder:serverUrl depth:depth withUserSessionToken:nil onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer, NSString *token) {
  329. // Check items > 0
  330. if ([items count] == 0) {
  331. #ifndef EXTENSION
  332. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  333. [appDelegate messageNotification:@"Server error" description:@"Read Folder WebDAV : [items NULL] please fix" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  334. #endif
  335. completion(account, nil, nil, NSLocalizedString(@"Read Folder WebDAV : [items NULL] please fix", nil), k_CCErrorInternalError);
  336. } else {
  337. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  338. BOOL showHiddenFiles = [CCUtility getShowHiddenFiles];
  339. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:serverUrl account:account];
  340. // directory [0]
  341. OCFileDto *itemDtoFolder = [items objectAtIndex:0];
  342. //NSDate *date = [NSDate dateWithTimeIntervalSince1970:itemDtoDirectory.date];
  343. NSMutableArray *metadatas = [NSMutableArray new];
  344. tableMetadata *metadataFolder = [tableMetadata new];
  345. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  346. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:tableAccount.url];
  347. NSString *serverUrlFolder;
  348. // Metadata . (self Folder)
  349. if ([serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:tableAccount.url]]) {
  350. // root folder
  351. serverUrlFolder = k_serverUrl_root;
  352. metadataFolder = [CCUtility trasformedOCFileToCCMetadata:itemDtoFolder fileName:@"." serverUrl:serverUrlFolder autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:account isFolderEncrypted:isFolderEncrypted];
  353. } else {
  354. serverUrlFolder = [CCUtility deletingLastPathComponentFromServerUrl:serverUrl];
  355. metadataFolder = [CCUtility trasformedOCFileToCCMetadata:itemDtoFolder fileName:[serverUrl lastPathComponent] serverUrl:serverUrlFolder autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:account isFolderEncrypted:isFolderEncrypted];
  356. }
  357. // Add metadata folder
  358. (void)[[NCManageDatabase sharedInstance] addDirectoryWithEncrypted:itemDtoFolder.isEncrypted favorite:itemDtoFolder.isFavorite fileID:itemDtoFolder.ocId permissions:itemDtoFolder.permissions serverUrl:serverUrl account:account];
  359. NSArray *itemsSortedArray = [items sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
  360. NSString *first = [(OCFileDto*)a fileName];
  361. NSString *second = [(OCFileDto*)b fileName];
  362. return [[first lowercaseString] compare:[second lowercaseString]];
  363. }];
  364. for (NSUInteger i=1; i < [itemsSortedArray count]; i++) {
  365. OCFileDto *itemDto = [itemsSortedArray objectAtIndex:i];
  366. NSString *fileName = [itemDto.fileName stringByReplacingOccurrencesOfString:@"/" withString:@""];
  367. // Skip hidden files
  368. if (fileName.length > 0) {
  369. if (!showHiddenFiles && [[fileName substringToIndex:1] isEqualToString:@"."])
  370. continue;
  371. } else {
  372. continue;
  373. }
  374. if (itemDto.isDirectory) {
  375. (void)[[NCManageDatabase sharedInstance] addDirectoryWithEncrypted:itemDto.isEncrypted favorite:itemDto.isFavorite fileID:itemDto.ocId permissions:itemDto.permissions serverUrl:[CCUtility stringAppendServerUrl:serverUrl addFileName:fileName] account:account];
  376. }
  377. [metadatas addObject:[CCUtility trasformedOCFileToCCMetadata:itemDto fileName:itemDto.fileName serverUrl:serverUrl autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:account isFolderEncrypted:isFolderEncrypted]];
  378. }
  379. dispatch_async(dispatch_get_main_queue(), ^{
  380. completion(account, metadatas, metadataFolder, nil, 0);
  381. });
  382. });
  383. }
  384. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) {
  385. NSString *message;
  386. NSInteger errorCode = response.statusCode;
  387. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  388. errorCode = error.code;
  389. // Error
  390. if (errorCode == 503)
  391. message = NSLocalizedString(@"_server_error_retry_", nil);
  392. else
  393. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  394. // Activity
  395. [[NCManageDatabase sharedInstance] addActivityClient:serverUrl fileID:@"" action:k_activityDebugActionReadFolder selector:@"" note:[error.userInfo valueForKey:@"NSLocalizedDescription"] type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:tableAccount.url];
  396. completion(account, nil, nil, message, errorCode);
  397. }];
  398. }
  399. - (void)readFileWithAccount:(NSString *)account serverUrl:(NSString *)serverUrl fileName:(NSString *)fileName completion:(void(^)(NSString *account, tableMetadata *metadata, NSString *message, NSInteger errorCode))completion
  400. {
  401. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  402. if (tableAccount == nil) {
  403. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  404. }
  405. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  406. NSString *fileNamePath;
  407. if (fileName) {
  408. fileNamePath = [NSString stringWithFormat:@"%@/%@", serverUrl, fileName];
  409. } else {
  410. fileName= @".";
  411. fileNamePath = serverUrl;
  412. }
  413. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  414. [communication setUserAgent:[CCUtility getUserAgent]];
  415. [communication readFile:fileNamePath onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  416. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:serverUrl account:account];
  417. if ([items count] > 0) {
  418. tableMetadata *metadata = [tableMetadata new];
  419. OCFileDto *itemDto = [items objectAtIndex:0];
  420. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  421. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:tableAccount.url];
  422. metadata = [CCUtility trasformedOCFileToCCMetadata:itemDto fileName:fileName serverUrl:serverUrl autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:account isFolderEncrypted:isFolderEncrypted];
  423. completion(account, metadata, nil, 0);
  424. // BUG 1038 item == 0
  425. } else {
  426. #ifndef EXTENSION
  427. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  428. [appDelegate messageNotification:@"Server error" description:@"Read File WebDAV : [items NULL] please fix" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  429. #endif
  430. completion(account, nil, NSLocalizedString(@"Read File WebDAV : [items NULL] please fix", nil), k_CCErrorInternalError);
  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 = NSLocalizedString(@"_server_error_retry_", nil);
  440. else
  441. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  442. completion(account, nil, message, errorCode);
  443. }];
  444. }
  445. - (void)createFolderWithAccount:(NSString *)account serverUrl:(NSString *)serverUrl fileName:(NSString *)fileName completion:(void(^)(NSString *account, NSString *fileID, NSDate *date, NSString *message, NSInteger errorCode))completion
  446. {
  447. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  448. if (tableAccount == nil) {
  449. completion(account, nil, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  450. }
  451. NSString *path = [NSString stringWithFormat:@"%@/%@", serverUrl, fileName];
  452. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  453. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:tableAccount.url];
  454. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  455. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  456. [communication setUserAgent:[CCUtility getUserAgent]];
  457. [communication createFolder:path onCommunication:communication withForbiddenCharactersSupported:YES successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  458. NSDictionary *fields = [response allHeaderFields];
  459. NSString *fileID = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-FileId"]];
  460. NSDate *date = [CCUtility dateEnUsPosixFromCloud:[fields objectForKey:@"Date"]];
  461. completion(account, fileID, date, nil, 0);
  462. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  463. NSString *message;
  464. if (([fileName isEqualToString:autoUploadFileName] && [serverUrl isEqualToString:autoUploadDirectory]))
  465. message = nil;
  466. else
  467. message = [CCError manageErrorOC:response.statusCode error:error];
  468. NSInteger errorCode = response.statusCode;
  469. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  470. errorCode = error.code;
  471. completion(account, nil, nil, message, errorCode);
  472. } errorBeforeRequest:^(NSError *error) {
  473. NSString *message;
  474. if (([fileName isEqualToString:autoUploadFileName] && [serverUrl isEqualToString:autoUploadDirectory]))
  475. message = nil;
  476. else {
  477. if (error.code == OCErrorForbidenCharacters)
  478. message = NSLocalizedString(@"_forbidden_characters_from_server_", nil);
  479. else
  480. message = NSLocalizedString(@"_unknow_response_server_", nil);
  481. }
  482. completion(account, nil, nil, message, error.code);
  483. }];
  484. }
  485. - (void)deleteFileOrFolderWithAccount:(NSString *)account path:(NSString *)path completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  486. {
  487. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  488. if (tableAccount == nil) {
  489. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  490. }
  491. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  492. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  493. [communication setUserAgent:[CCUtility getUserAgent]];
  494. [communication deleteFileOrFolder:path onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  495. completion(account, nil, 0);
  496. } failureRquest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  497. NSString *message;
  498. NSInteger errorCode = response.statusCode;
  499. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  500. errorCode = error.code;
  501. // Error
  502. if (errorCode == 503)
  503. message = NSLocalizedString(@"_server_error_retry_", nil);
  504. else
  505. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  506. completion(account, message, errorCode);
  507. }];
  508. }
  509. - (void)moveFileOrFolderWithAccount:(NSString *)account fileName:(NSString *)fileName fileNameTo:(NSString *)fileNameTo completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  510. {
  511. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  512. if (tableAccount == nil) {
  513. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  514. }
  515. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  516. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  517. [communication setUserAgent:[CCUtility getUserAgent]];
  518. [communication moveFileOrFolder:fileName toDestiny:fileNameTo onCommunication:communication withForbiddenCharactersSupported:YES successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  519. completion(account, nil, 0);
  520. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  521. NSInteger errorCode = response.statusCode;
  522. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  523. errorCode = error.code;
  524. NSString *message = [CCError manageErrorOC:response.statusCode error:error];
  525. completion(account, message, error.code);
  526. } errorBeforeRequest:^(NSError *error) {
  527. NSString *message;
  528. if (error.code == OCErrorMovingTheDestinyAndOriginAreTheSame) {
  529. message = NSLocalizedString(@"_error_folder_destiny_is_the_same_", nil);
  530. } else if (error.code == OCErrorMovingFolderInsideHimself) {
  531. message = NSLocalizedString(@"_error_folder_destiny_is_the_same_", nil);
  532. } else if (error.code == OCErrorMovingDestinyNameHaveForbiddenCharacters) {
  533. message = NSLocalizedString(@"_forbidden_characters_from_server_", nil);
  534. } else {
  535. message = NSLocalizedString(@"_unknow_response_server_", nil);
  536. }
  537. completion(account, message, error.code);
  538. }];
  539. }
  540. - (void)searchWithAccount:(NSString *)account fileName:(NSString *)fileName serverUrl:(NSString *)serverUrl contentType:(NSArray *)contentType date:(NSDate *)date depth:(NSString *)depth completion:(void(^)(NSString *account, NSArray *metadatas, NSString *message, NSInteger errorCode))completion
  541. {
  542. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  543. if (tableAccount == nil) {
  544. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  545. }
  546. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  547. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  548. [communication setUserAgent:[CCUtility getUserAgent]];
  549. NSString *path = [tableAccount.url stringByAppendingString:k_dav];
  550. NSString *folder = [serverUrl stringByReplacingOccurrencesOfString:[CCUtility getHomeServerUrlActiveUrl:tableAccount.url] withString:@""];
  551. NSString *dateLastModified;
  552. if (date) {
  553. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  554. NSLocale *enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
  555. [dateFormatter setLocale:enUSPOSIXLocale];
  556. [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZZ"];
  557. dateLastModified = [dateFormatter stringFromDate:date];
  558. }
  559. [communication search:path folder:folder fileName: [NSString stringWithFormat:@"%%%@%%", fileName] depth:depth dateLastModified:dateLastModified contentType:contentType withUserSessionToken:nil onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer, NSString *token) {
  560. NSMutableArray *metadatas = [NSMutableArray new];
  561. BOOL showHiddenFiles = [CCUtility getShowHiddenFiles];
  562. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  563. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:tableAccount.url];
  564. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  565. for (OCFileDto *itemDto in items) {
  566. NSString *serverUrl;
  567. BOOL isFolderEncrypted;
  568. NSString *fileName = [itemDto.fileName stringByReplacingOccurrencesOfString:@"/" withString:@""];
  569. // Skip hidden files
  570. if (fileName.length > 0) {
  571. if (!showHiddenFiles && [[fileName substringToIndex:1] isEqualToString:@"."])
  572. continue;
  573. } else
  574. continue;
  575. NSRange firstInstance = [itemDto.filePath rangeOfString:[NSString stringWithFormat:@"%@/files/%@", k_dav, tableAccount.userID]];
  576. NSString *serverPath = [itemDto.filePath substringFromIndex:firstInstance.length+firstInstance.location+1];
  577. if ([serverPath hasSuffix:@"/"]) serverPath = [serverPath substringToIndex:[serverPath length] - 1];
  578. serverUrl = [CCUtility stringAppendServerUrl:[tableAccount.url stringByAppendingString:k_webDAV] addFileName:serverPath];
  579. if (itemDto.isDirectory) {
  580. (void)[[NCManageDatabase sharedInstance] addDirectoryWithEncrypted:itemDto.isEncrypted favorite:itemDto.isFavorite fileID:itemDto.ocId permissions:itemDto.permissions serverUrl:[NSString stringWithFormat:@"%@/%@", serverUrl, fileName] account:account];
  581. }
  582. isFolderEncrypted = [CCUtility isFolderEncrypted:serverUrl account:account];
  583. [metadatas addObject:[CCUtility trasformedOCFileToCCMetadata:itemDto fileName:itemDto.fileName serverUrl:serverUrl autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:account isFolderEncrypted:isFolderEncrypted]];
  584. }
  585. dispatch_async(dispatch_get_main_queue(), ^{
  586. completion(account, metadatas, nil, 0);
  587. });
  588. });
  589. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) {
  590. NSString *message = @"";
  591. NSInteger errorCode = response.statusCode;
  592. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  593. errorCode = error.code;
  594. // Error
  595. if (errorCode == 503) {
  596. message = NSLocalizedString(@"_server_error_retry_", nil);
  597. } else {
  598. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  599. }
  600. completion(account, nil, message, errorCode);
  601. }];
  602. }
  603. #pragma --------------------------------------------------------------------------------------------
  604. #pragma mark ===== downloadPreview =====
  605. #pragma --------------------------------------------------------------------------------------------
  606. /*
  607. - (void)downloadThumbnailWithMetadata:(tableMetadata*)metadata withWidth:(CGFloat)width andHeight:(CGFloat)height completion:(void (^)(NSString *message, NSInteger errorCode))completion
  608. {
  609. NSString *file = [NSString stringWithFormat:@"%@/%@.ico", [CCUtility getDirectoryProviderStorageFileID:metadata.fileID], metadata.fileNameView];
  610. if ([[NSFileManager defaultManager] fileExistsAtPath:file]) {
  611. completion(nil, 0);
  612. } else {
  613. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  614. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  615. [communication setUserAgent:[CCUtility getUserAgent]];
  616. [communication getRemoteThumbnailByServer:_activeUrl ofFilePath:[CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:metadata.serverUrl activeUrl:_activeUrl] withWidth:width andHeight:height onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSData *thumbnail, NSString *redirectedServer) {
  617. [thumbnail writeToFile:file atomically:YES];
  618. completion(nil, 0);
  619. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  620. NSString *message;
  621. NSInteger errorCode = response.statusCode;
  622. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  623. errorCode = error.code;
  624. // Error
  625. if (errorCode == 503)
  626. message = NSLocalizedString(@"_server_error_retry_", nil);
  627. else
  628. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  629. completion(message, errorCode);
  630. }];
  631. }
  632. }
  633. */
  634. - (void)downloadPreviewWithAccount:(NSString *)account metadata:(tableMetadata*)metadata withWidth:(CGFloat)width andHeight:(CGFloat)height completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  635. {
  636. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  637. if (tableAccount == nil) {
  638. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  639. }
  640. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  641. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  642. [communication setUserAgent:[CCUtility getUserAgent]];
  643. NSString *file = [NSString stringWithFormat:@"%@/%@.ico", [CCUtility getDirectoryProviderStorageFileID:metadata.fileID], metadata.fileNameView];
  644. [communication getRemotePreviewByServer:tableAccount.url ofFilePath:[CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:metadata.serverUrl activeUrl:tableAccount.url] withWidth:width andHeight:height andA:1 andMode:@"cover" onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSData *preview, NSString *redirectedServer) {
  645. [preview writeToFile:file atomically:YES];
  646. completion(account, nil, 0);
  647. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  648. NSString *message;
  649. NSInteger errorCode = response.statusCode;
  650. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  651. errorCode = error.code;
  652. // Error
  653. if (errorCode == 503)
  654. message = NSLocalizedString(@"_server_error_retry_", nil);
  655. else
  656. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  657. completion(account, message, errorCode);
  658. }];
  659. }
  660. - (void)downloadPreviewTrashWithAccount:(NSString *)account FileID:(NSString *)fileID fileName:(NSString *)fileName completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  661. {
  662. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  663. if (tableAccount == nil) {
  664. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  665. }
  666. NSString *file = [NSString stringWithFormat:@"%@/%@.ico", [CCUtility getDirectoryProviderStorageFileID:fileID], fileName];
  667. if ([[NSFileManager defaultManager] fileExistsAtPath:file]) {
  668. completion(account, nil, 0);
  669. } else {
  670. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  671. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  672. [communication setUserAgent:[CCUtility getUserAgent]];
  673. [communication getRemotePreviewTrashByServer:tableAccount.url ofFileID:fileID onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSData *preview, NSString *redirectedServer) {
  674. [preview writeToFile:file atomically:YES];
  675. completion(account, nil, 0);
  676. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  677. NSString *message;
  678. NSInteger errorCode = response.statusCode;
  679. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  680. errorCode = error.code;
  681. // Error
  682. if (errorCode == 503)
  683. message = NSLocalizedString(@"_server_error_retry_", nil);
  684. else
  685. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  686. completion(account, message, errorCode);
  687. }];
  688. }
  689. }
  690. #pragma --------------------------------------------------------------------------------------------
  691. #pragma mark ===== Favorite =====
  692. #pragma --------------------------------------------------------------------------------------------
  693. - (void)listingFavoritesWithAccount:(NSString *)account completion:(void(^)(NSString *account, NSArray *metadatas, NSString *message, NSInteger errorCode))completion
  694. {
  695. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  696. if (tableAccount == nil) {
  697. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  698. }
  699. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  700. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  701. [communication setUserAgent:[CCUtility getUserAgent]];
  702. NSString *path = [tableAccount.url stringByAppendingString:k_dav];
  703. [communication listingFavorites:path folder:@"" withUserSessionToken:nil onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer, NSString *token) {
  704. NSMutableArray *metadatas = [NSMutableArray new];
  705. BOOL showHiddenFiles = [CCUtility getShowHiddenFiles];
  706. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  707. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:tableAccount.url];
  708. // Order by fileNamePath
  709. items = [items sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
  710. OCFileDto *record1 = obj1, *record2 = obj2;
  711. NSString *path1 = [[record1.filePath stringByAppendingString:record1.fileName] lowercaseString];
  712. NSString *path2 = [[record2.filePath stringByAppendingString:record2.fileName] lowercaseString];
  713. return [path1 compare:path2];
  714. }];
  715. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  716. for(OCFileDto *itemDto in items) {
  717. NSString *serverUrl;
  718. BOOL isFolderEncrypted;
  719. NSString *fileName = [itemDto.fileName stringByReplacingOccurrencesOfString:@"/" withString:@""];
  720. // Skip hidden files
  721. if (fileName.length > 0) {
  722. if (!showHiddenFiles && [[fileName substringToIndex:1] isEqualToString:@"."])
  723. continue;
  724. } else
  725. continue;
  726. NSRange firstInstance = [itemDto.filePath rangeOfString:[NSString stringWithFormat:@"%@/files/%@", k_dav, tableAccount.userID]];
  727. NSString *serverPath = [itemDto.filePath substringFromIndex:firstInstance.length+firstInstance.location+1];
  728. if ([serverPath hasSuffix:@"/"])
  729. serverPath = [serverPath substringToIndex:[serverPath length] - 1];
  730. serverUrl = [CCUtility stringAppendServerUrl:[tableAccount.url stringByAppendingString:k_webDAV] addFileName:serverPath];
  731. if (itemDto.isDirectory) {
  732. (void)[[NCManageDatabase sharedInstance] addDirectoryWithEncrypted:itemDto.isEncrypted favorite:itemDto.isFavorite fileID:itemDto.ocId permissions:itemDto.permissions serverUrl:[NSString stringWithFormat:@"%@/%@", serverUrl, fileName] account:account];
  733. }
  734. isFolderEncrypted = [CCUtility isFolderEncrypted:serverUrl account:account];
  735. [metadatas addObject:[CCUtility trasformedOCFileToCCMetadata:itemDto fileName:itemDto.fileName serverUrl:serverUrl autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:account isFolderEncrypted:isFolderEncrypted]];
  736. }
  737. dispatch_async(dispatch_get_main_queue(), ^{
  738. completion(account, metadatas, nil, 0);
  739. });
  740. });
  741. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) {
  742. NSString *message;
  743. NSInteger errorCode = response.statusCode;
  744. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  745. errorCode = error.code;
  746. // Error
  747. if (errorCode == 503)
  748. message = NSLocalizedString(@"_server_error_retry_", nil);
  749. else
  750. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  751. completion(account, nil, message, errorCode);
  752. }];
  753. }
  754. - (void)settingFavoriteWithAccount:(NSString *)account fileName:(NSString *)fileName favorite:(BOOL)favorite completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  755. {
  756. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  757. if (tableAccount == nil) {
  758. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  759. }
  760. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  761. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  762. [communication setUserAgent:[CCUtility getUserAgent]];
  763. NSString *server = [tableAccount.url stringByAppendingString:k_dav];
  764. [communication settingFavoriteServer:server andFileOrFolderPath:fileName favorite:favorite withUserSessionToken:nil onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer, NSString *token) {
  765. completion(account, nil, 0);
  766. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) {
  767. NSString *message;
  768. NSInteger errorCode = response.statusCode;
  769. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  770. errorCode = error.code;
  771. // Error
  772. if (errorCode == 503)
  773. message = NSLocalizedString(@"_server_error_retry_", nil);
  774. else
  775. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  776. completion(account, message, errorCode);
  777. }];
  778. }
  779. #pragma --------------------------------------------------------------------------------------------
  780. #pragma mark ===== Share =====
  781. #pragma --------------------------------------------------------------------------------------------
  782. - (void)readShareWithAccount:(NSString *)account completion:(void (^)(NSString *account, NSArray *items, NSString *message, NSInteger errorCode))completion
  783. {
  784. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  785. if (tableAccount == nil) {
  786. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  787. }
  788. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  789. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  790. [communication setUserAgent:[CCUtility getUserAgent]];
  791. [communication readSharedByServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  792. completion(account, items, nil, 0);
  793. } failureRequest :^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  794. NSString *message = @"";
  795. NSInteger errorCode = response.statusCode;
  796. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  797. errorCode = error.code;
  798. // Error
  799. if (errorCode == 503) {
  800. message = NSLocalizedString(@"_server_error_retry_", nil);
  801. } else {
  802. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  803. }
  804. completion(account, nil, message, errorCode);
  805. }];
  806. }
  807. - (void)shareWithAccount:(NSString *)account fileName:(NSString *)fileName password:(NSString *)password permission:(NSInteger)permission hideDownload:(BOOL)hideDownload completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  808. {
  809. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  810. if (tableAccount == nil) {
  811. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  812. }
  813. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  814. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  815. [communication setUserAgent:[CCUtility getUserAgent]];
  816. [communication shareFileOrFolderByServer:[tableAccount.url stringByAppendingString:@"/"] andFileOrFolderPath:[fileName encodeString:NSUTF8StringEncoding] andPassword:[password encodeString:NSUTF8StringEncoding] andPermission:permission andHideDownload:hideDownload onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *token, NSString *redirectedServer) {
  817. completion(account, nil, 0);
  818. //[self readShareServer];
  819. } failureRequest :^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  820. NSString *message = @"";
  821. NSInteger errorCode = response.statusCode;
  822. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  823. errorCode = error.code;
  824. // Error
  825. if (errorCode == 503) {
  826. message = NSLocalizedString(@"_server_error_retry_", nil);
  827. } else {
  828. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  829. }
  830. completion(account, message, errorCode);
  831. }];
  832. }
  833. // * @param shareeType -> NSInteger: to set the type of sharee (user/group/federated)
  834. - (void)shareUserGroupWithAccount:(NSString *)account userOrGroup:(NSString *)userOrGroup fileName:(NSString *)fileName permission:(NSInteger)permission shareeType:(NSInteger)shareeType completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  835. {
  836. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  837. if (tableAccount == nil) {
  838. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  839. }
  840. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  841. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  842. [communication setUserAgent:[CCUtility getUserAgent]];
  843. [communication shareWith:userOrGroup shareeType:shareeType inServer:[tableAccount.url stringByAppendingString:@"/"] andFileOrFolderPath:[fileName encodeString:NSUTF8StringEncoding] andPermissions:permission onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  844. //[self readShareServer];
  845. completion(account, nil, 0);
  846. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  847. NSString *message = @"";
  848. NSInteger errorCode = response.statusCode;
  849. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  850. errorCode = error.code;
  851. // Error
  852. if (errorCode == 503) {
  853. message = NSLocalizedString(@"_server_error_retry_", nil);
  854. } else {
  855. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  856. }
  857. completion(account, message, errorCode);
  858. }];
  859. }
  860. - (void)shareUpdateAccount:(NSString *)account shareID:(NSInteger)shareID password:(NSString *)password permission:(NSInteger)permission expirationTime:(NSString *)expirationTime hideDownload:(BOOL)hideDownload completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  861. {
  862. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  863. if (tableAccount == nil) {
  864. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  865. }
  866. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  867. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  868. [communication setUserAgent:[CCUtility getUserAgent]];
  869. [communication updateShare:shareID ofServerPath:[tableAccount.url stringByAppendingString:@"/"] withPasswordProtect:[password encodeString:NSUTF8StringEncoding] andExpirationTime:expirationTime andPermissions:permission andHideDownload:hideDownload onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  870. completion(account, nil, 0);
  871. //[self readShareServer];
  872. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  873. NSString *message = @"";
  874. NSInteger errorCode = response.statusCode;
  875. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  876. errorCode = error.code;
  877. // Error
  878. if (errorCode == 503) {
  879. message = NSLocalizedString(@"_server_error_retry_", nil);
  880. } else {
  881. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  882. }
  883. completion(account, message, errorCode);
  884. }];
  885. }
  886. - (void)unshareAccount:(NSString *)account shareID:(NSInteger)shareID completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  887. {
  888. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  889. if (tableAccount == nil) {
  890. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  891. }
  892. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  893. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  894. [communication setUserAgent:[CCUtility getUserAgent]];
  895. [communication unShareFileOrFolderByServer:[tableAccount.url stringByAppendingString:@"/"] andIdRemoteShared:shareID onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  896. completion(account, nil, 0);
  897. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  898. NSString *message = @"";
  899. NSInteger errorCode = response.statusCode;
  900. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  901. errorCode = error.code;
  902. // Error
  903. if (errorCode == 503) {
  904. message = NSLocalizedString(@"_server_error_retry_", nil);
  905. } else {
  906. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  907. }
  908. completion(account, message, errorCode);
  909. }];
  910. }
  911. - (void)getUserGroupWithAccount:(NSString *)account searchString:(NSString *)searchString completion:(void (^)(NSString *account, NSArray *item, NSString *message, NSInteger errorCode))completion
  912. {
  913. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  914. if (tableAccount == nil) {
  915. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  916. }
  917. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  918. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  919. [communication setUserAgent:[CCUtility getUserAgent]];
  920. [communication searchUsersAndGroupsWith:searchString forPage:1 with:50 ofServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *itemList, NSString *redirectedServer) {
  921. completion(account, itemList, nil, 0);
  922. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  923. NSString *message = @"";
  924. NSInteger errorCode = response.statusCode;
  925. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  926. errorCode = error.code;
  927. // Error
  928. if (errorCode == 503) {
  929. message = NSLocalizedString(@"_server_error_retry_", nil);
  930. } else {
  931. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  932. }
  933. completion(account, nil, message, errorCode);
  934. }];
  935. }
  936. - (void)getSharePermissionsFileWithAccount:(NSString *)account fileNamePath:(NSString *)fileNamePath completion:(void (^)(NSString *account, NSString *permissions, NSString *message, NSInteger errorCode))completion
  937. {
  938. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  939. if (tableAccount == nil) {
  940. completion(account, 0, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  941. }
  942. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  943. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  944. [communication setUserAgent:[CCUtility getUserAgent]];
  945. [communication getSharePermissionsFile:fileNamePath onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *permissions, NSString *redirectedServer) {
  946. completion(account, permissions, nil ,0);
  947. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  948. NSString *message = @"";
  949. NSInteger errorCode = response.statusCode;
  950. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  951. errorCode = error.code;
  952. // Error
  953. if (errorCode == 503) {
  954. message = NSLocalizedString(@"_server_error_retry_", nil);
  955. } else {
  956. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  957. }
  958. completion(account, nil, message, errorCode);
  959. }];
  960. }
  961. #pragma --------------------------------------------------------------------------------------------
  962. #pragma mark ===== API =====
  963. #pragma --------------------------------------------------------------------------------------------
  964. - (void)getActivityWithAccount:(NSString *)account completion:(void(^)(NSString *account, NSArray *listOfActivity, NSString *message, NSInteger errorCode))completion
  965. {
  966. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  967. if (tableAccount == nil) {
  968. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  969. }
  970. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  971. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  972. [communication setUserAgent:[CCUtility getUserAgent]];
  973. [communication getActivityServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfActivity, NSString *redirectedServer) {
  974. completion(account, listOfActivity, nil, 0);
  975. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  976. NSString *message;
  977. NSInteger errorCode = response.statusCode;
  978. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  979. errorCode = error.code;
  980. // Error
  981. if (errorCode == 503)
  982. message = NSLocalizedString(@"_server_error_retry_", nil);
  983. else
  984. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  985. completion(account, nil, message, errorCode);
  986. }];
  987. }
  988. - (void)getExternalSitesWithAccount:(NSString *)account completion:(void (^)(NSString *account, NSArray *listOfExternalSites, NSString *message, NSInteger errorCode))completion
  989. {
  990. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  991. if (tableAccount == nil) {
  992. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  993. }
  994. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  995. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  996. [communication setUserAgent:[CCUtility getUserAgent]];
  997. [communication getExternalSitesServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfExternalSites, NSString *redirectedServer) {
  998. completion(account, listOfExternalSites, nil, 0);
  999. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1000. NSString *message = @"";
  1001. NSInteger errorCode = response.statusCode;
  1002. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1003. errorCode = error.code;
  1004. // Error
  1005. if (errorCode == 503) {
  1006. message = NSLocalizedString(@"_server_error_retry_", nil);
  1007. } else {
  1008. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1009. }
  1010. completion(account, nil, message, errorCode);
  1011. }];
  1012. }
  1013. /*
  1014. - (void)middlewarePing
  1015. {
  1016. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1017. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  1018. [communication setUserAgent:[CCUtility getUserAgent]];
  1019. [communication getMiddlewarePing:_metadataNet.serverUrl onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfExternalSites, NSString *redirectedServer) {
  1020. [self complete];
  1021. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1022. NSInteger errorCode = response.statusCode;
  1023. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1024. errorCode = error.code;
  1025. // Error
  1026. if ([self.delegate respondsToSelector:@selector(getExternalSitesServerFailure:message:errorCode:)]) {
  1027. if (errorCode == 503)
  1028. [self.delegate getExternalSitesServerFailure:_metadataNet message:NSLocalizedString(@"_server_error_retry_", nil) errorCode:errorCode];
  1029. else
  1030. [self.delegate getExternalSitesServerFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1031. }
  1032. // Request trusted certificated
  1033. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  1034. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1035. [self complete];
  1036. }];
  1037. }
  1038. */
  1039. - (void)getNotificationWithAccount:(NSString *)account completion:(void (^)(NSString *account, NSArray *listOfNotifications, NSString *message, NSInteger errorCode))completion
  1040. {
  1041. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1042. if (tableAccount == nil) {
  1043. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1044. }
  1045. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1046. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1047. [communication setUserAgent:[CCUtility getUserAgent]];
  1048. [communication getNotificationServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfNotifications, NSString *redirectedServer) {
  1049. completion(account, listOfNotifications, nil, 0);
  1050. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1051. NSString *message = @"";
  1052. NSInteger errorCode = response.statusCode;
  1053. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1054. errorCode = error.code;
  1055. // Error
  1056. if (errorCode == 503) {
  1057. message = NSLocalizedString(@"_server_error_retry_", nil);
  1058. } else {
  1059. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1060. }
  1061. completion(account, nil, message, errorCode);
  1062. }];
  1063. }
  1064. - (void)setNotificationWithAccount:(NSString *)account serverUrl:(NSString *)serverUrl type:(NSString *)type completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  1065. {
  1066. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1067. if (tableAccount == nil) {
  1068. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1069. }
  1070. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1071. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1072. [communication setUserAgent:[CCUtility getUserAgent]];
  1073. [communication setNotificationServer:serverUrl type:type onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1074. completion(account, nil, 0);
  1075. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1076. NSString *message = @"";
  1077. NSInteger errorCode = response.statusCode;
  1078. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1079. errorCode = error.code;
  1080. // Error
  1081. if (errorCode == 503) {
  1082. message = NSLocalizedString(@"_server_error_retry_", nil);
  1083. } else {
  1084. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1085. }
  1086. completion(account, message, errorCode);
  1087. }];
  1088. }
  1089. - (void)getCapabilitiesWithAccount:(NSString *)account completion:(void (^)(NSString *account, OCCapabilities *capabilities, NSString *message, NSInteger errorCode))completion
  1090. {
  1091. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1092. if (tableAccount == nil) {
  1093. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1094. }
  1095. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1096. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1097. [communication setUserAgent:[CCUtility getUserAgent]];
  1098. [communication getCapabilitiesOfServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, OCCapabilities *capabilities, NSString *redirectedServer) {
  1099. completion(account, capabilities, nil, 0);
  1100. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1101. NSString *message = @"";
  1102. NSInteger errorCode = response.statusCode;
  1103. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1104. errorCode = error.code;
  1105. // Error
  1106. if (errorCode == 503) {
  1107. message = NSLocalizedString(@"_server_error_retry_", nil);
  1108. } else {
  1109. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1110. }
  1111. completion(account, nil, message, errorCode);
  1112. }];
  1113. }
  1114. - (void)getUserProfileWithAccount:(NSString *)account completion:(void (^)(NSString *account, OCUserProfile *userProfile, NSString *message, NSInteger errorCode))completion
  1115. {
  1116. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1117. if (tableAccount == nil) {
  1118. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1119. }
  1120. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1121. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1122. [communication setUserAgent:[CCUtility getUserAgent]];
  1123. [communication getUserProfileServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, OCUserProfile *userProfile, NSString *redirectedServer) {
  1124. completion(account, userProfile, nil, 0);
  1125. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1126. NSString *message = @"";
  1127. NSInteger errorCode = response.statusCode;
  1128. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1129. errorCode = error.code;
  1130. // Error
  1131. if (errorCode == 503) {
  1132. message = NSLocalizedString(@"_server_error_retry_", nil);
  1133. } else {
  1134. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1135. }
  1136. completion(account, nil, message, errorCode);
  1137. }];
  1138. }
  1139. #pragma --------------------------------------------------------------------------------------------
  1140. #pragma mark ===== Push Notification =====
  1141. #pragma --------------------------------------------------------------------------------------------
  1142. - (void)subscribingPushNotificationWithAccount:(NSString *)account url:(NSString *)url pushToken:(NSString *)pushToken Hash:(NSString *)pushTokenHash devicePublicKey:(NSString *)devicePublicKey completion:(void(^)(NSString *account, NSString *deviceIdentifier, NSString *deviceIdentifierSignature, NSString *publicKey, NSString *message, NSInteger errorCode))completion
  1143. {
  1144. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1145. if (tableAccount == nil) {
  1146. completion(account, nil, nil, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1147. }
  1148. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1149. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1150. [communication setUserAgent:[CCUtility getUserAgent]];
  1151. devicePublicKey = [CCUtility URLEncodeStringFromString:devicePublicKey];
  1152. [communication subscribingNextcloudServerPush:url pushTokenHash:pushTokenHash devicePublicKey:devicePublicKey proxyServerPath: [NCBrandOptions sharedInstance].pushNotificationServerProxy onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *publicKey, NSString *deviceIdentifier, NSString *signature, NSString *redirectedServer) {
  1153. deviceIdentifier = [CCUtility URLEncodeStringFromString:deviceIdentifier];
  1154. signature = [CCUtility URLEncodeStringFromString:signature];
  1155. publicKey = [CCUtility URLEncodeStringFromString:publicKey];
  1156. [communication subscribingPushProxy:[NCBrandOptions sharedInstance].pushNotificationServerProxy pushToken:pushToken deviceIdentifier:deviceIdentifier deviceIdentifierSignature:signature publicKey:publicKey onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1157. // Activity
  1158. [[NCManageDatabase sharedInstance] addActivityClient:[NCBrandOptions sharedInstance].pushNotificationServerProxy fileID:@"" action:k_activityDebugActionSubscribingPushProxy selector:@"" note:@"Service registered." type:k_activityTypeSuccess verbose:k_activityVerboseHigh activeUrl:@""];
  1159. completion(account, deviceIdentifier, signature, publicKey, nil, 0);
  1160. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1161. NSString *message;
  1162. NSInteger errorCode = response.statusCode;
  1163. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1164. errorCode = error.code;
  1165. // Error
  1166. if (errorCode == 503)
  1167. message = NSLocalizedString(@"_server_error_retry_", nil);
  1168. else
  1169. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1170. // Activity
  1171. [[NCManageDatabase sharedInstance] addActivityClient:[NCBrandOptions sharedInstance].pushNotificationServerProxy fileID:@"" action:k_activityDebugActionSubscribingPushProxy selector:@"" note:[error.userInfo valueForKey:@"NSLocalizedDescription"] type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:@""];
  1172. completion(account, nil, nil, nil, message, errorCode);
  1173. }];
  1174. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1175. NSString *message;
  1176. NSInteger errorCode = response.statusCode;
  1177. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1178. errorCode = error.code;
  1179. // Error
  1180. if (errorCode == 503)
  1181. message = NSLocalizedString(@"_server_error_retry_", nil);
  1182. else
  1183. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1184. completion(account, nil, nil, nil, message, errorCode);
  1185. }];
  1186. }
  1187. - (void)unsubscribingPushNotificationWithAccount:(NSString *)account url:(NSString *)url deviceIdentifier:(NSString *)deviceIdentifier deviceIdentifierSignature:(NSString *)deviceIdentifierSignature publicKey:(NSString *)publicKey completion:(void (^)(NSString *account ,NSString *message, NSInteger errorCode))completion {
  1188. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1189. if (tableAccount == nil) {
  1190. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1191. }
  1192. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1193. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1194. [communication setUserAgent:[CCUtility getUserAgent]];
  1195. [communication unsubscribingNextcloudServerPush:url onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1196. [communication unsubscribingPushProxy:[NCBrandOptions sharedInstance].pushNotificationServerProxy deviceIdentifier:deviceIdentifier deviceIdentifierSignature:deviceIdentifierSignature publicKey:publicKey onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1197. completion(account, nil, 0);
  1198. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1199. NSString *message;
  1200. NSInteger errorCode = response.statusCode;
  1201. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1202. errorCode = error.code;
  1203. // Error
  1204. if (errorCode == 503)
  1205. message = NSLocalizedString(@"_server_error_retry_", nil);
  1206. else
  1207. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1208. completion(account, message, errorCode);
  1209. }];
  1210. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1211. NSString *message;
  1212. NSInteger errorCode = response.statusCode;
  1213. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1214. errorCode = error.code;
  1215. // Error
  1216. if (errorCode == 503)
  1217. message = NSLocalizedString(@"_server_error_retry_", nil);
  1218. else
  1219. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1220. completion(account, message, errorCode);
  1221. }];
  1222. }
  1223. #pragma --------------------------------------------------------------------------------------------
  1224. #pragma mark ===== Manage Mobile Editor OCS API =====
  1225. #pragma --------------------------------------------------------------------------------------------
  1226. - (void)createLinkRichdocumentsWithAccount:(NSString *)account fileID:(NSString *)fileID completion:(void(^)(NSString *account, NSString *link, NSString *message, NSInteger errorCode))completion
  1227. {
  1228. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1229. if (tableAccount == nil) {
  1230. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1231. }
  1232. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1233. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1234. [communication setUserAgent:[CCUtility getUserAgent]];
  1235. NSString *fileIDServer = [[NCUtility sharedInstance] convertFileIDClientToFileIDServer:fileID];
  1236. [communication createLinkRichdocuments:[tableAccount.url stringByAppendingString:@"/"] fileID:fileIDServer onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *link, NSString *redirectedServer) {
  1237. completion(account, link, nil, 0);
  1238. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1239. NSString *message;
  1240. NSInteger errorCode = response.statusCode;
  1241. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1242. errorCode = error.code;
  1243. // Error
  1244. if (errorCode == 503)
  1245. message = NSLocalizedString(@"_server_error_retry_", nil);
  1246. else
  1247. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1248. completion(account, nil,message, errorCode);
  1249. }];
  1250. }
  1251. - (void)geTemplatesRichdocumentsWithAccount:(NSString *)account typeTemplate:(NSString *)typeTemplate completion:(void(^)(NSString *account, NSArray *listOfTemplate, NSString *message, NSInteger errorCode))completion
  1252. {
  1253. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1254. if (tableAccount == nil) {
  1255. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1256. }
  1257. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1258. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1259. [communication setUserAgent:[CCUtility getUserAgent]];
  1260. [communication geTemplatesRichdocuments:[tableAccount.url stringByAppendingString:@"/"] typeTemplate:typeTemplate onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfTemplate, NSString *redirectedServer) {
  1261. completion(account, listOfTemplate, nil, 0);
  1262. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1263. NSString *message;
  1264. NSInteger errorCode = response.statusCode;
  1265. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1266. errorCode = error.code;
  1267. // Error
  1268. if (errorCode == 503)
  1269. message = NSLocalizedString(@"_server_error_retry_", nil);
  1270. else
  1271. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1272. completion(account, nil, message, errorCode);
  1273. }];
  1274. }
  1275. - (void)createNewRichdocumentsWithAccount:(NSString *)account fileName:(NSString *)fileName serverUrl:(NSString *)serverUrl templateID:(NSString *)templateID completion:(void(^)(NSString *account, NSString *url, NSString *message, NSInteger errorCode))completion
  1276. {
  1277. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1278. if (tableAccount == nil) {
  1279. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1280. }
  1281. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1282. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1283. [communication setUserAgent:[CCUtility getUserAgent]];
  1284. [communication createNewRichdocuments:[tableAccount.url stringByAppendingString:@"/"] path:fileName templateID:templateID onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *url, NSString *redirectedServer) {
  1285. completion(account, url, nil, 0);
  1286. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1287. NSString *message;
  1288. NSInteger errorCode = response.statusCode;
  1289. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1290. errorCode = error.code;
  1291. // Error
  1292. if (errorCode == 503)
  1293. message = NSLocalizedString(@"_server_error_retry_", nil);
  1294. else
  1295. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1296. completion(account, nil, message, errorCode);
  1297. }];
  1298. }
  1299. - (void)createAssetRichdocumentsWithAccount:(NSString *)account fileName:(NSString *)fileName serverUrl:(NSString *)serverUrl completion:(void(^)(NSString *account, NSString *link, NSString *message, NSInteger errorCode))completion
  1300. {
  1301. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1302. if (tableAccount == nil) {
  1303. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1304. }
  1305. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1306. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1307. [communication setUserAgent:[CCUtility getUserAgent]];
  1308. NSString *fileNamePath = [CCUtility returnFileNamePathFromFileName:fileName serverUrl:serverUrl activeUrl:tableAccount.url];
  1309. [communication createAssetRichdocuments:[tableAccount.url stringByAppendingString:@"/"] path:fileNamePath onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *url, NSString *redirectedServer) {
  1310. completion(account, url, nil, 0);
  1311. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1312. NSString *message;
  1313. NSInteger errorCode = response.statusCode;
  1314. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1315. errorCode = error.code;
  1316. // Error
  1317. if (errorCode == 503)
  1318. message = NSLocalizedString(@"_server_error_retry_", nil);
  1319. else
  1320. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1321. completion(account, nil, message, errorCode);
  1322. }];
  1323. }
  1324. #pragma --------------------------------------------------------------------------------------------
  1325. #pragma mark ===== Trash =====
  1326. #pragma --------------------------------------------------------------------------------------------
  1327. - (void)listingTrashWithAccount:(NSString *)account path:(NSString *)path serverUrl:(NSString *)serverUrl completion:(void (^)(NSString *account, NSArray *items, NSString *message, NSInteger errorCode))completion
  1328. {
  1329. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1330. if (tableAccount == nil) {
  1331. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1332. }
  1333. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1334. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1335. [communication setUserAgent:[CCUtility getUserAgent]];
  1336. [communication listingTrash:[serverUrl stringByAppendingString:path] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  1337. // Check items > 0
  1338. if ([items count] == 0) {
  1339. #ifndef EXTENSION
  1340. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  1341. [appDelegate messageNotification:@"Server error" description:@"Read Folder WebDAV : [items NULL] please fix" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  1342. #endif
  1343. completion(account, nil, NSLocalizedString(@"Read Folder WebDAV : [items NULL] please fix", nil), k_CCErrorInternalError);
  1344. } else {
  1345. NSMutableArray *listTrash = [NSMutableArray new];
  1346. //OCFileDto *itemDtoFolder = [items objectAtIndex:0];
  1347. if ([items count] > 1) {
  1348. for (NSUInteger i=1; i < [items count]; i++) {
  1349. OCFileDto *itemDto = [items objectAtIndex:i];
  1350. tableTrash *trash = [tableTrash new];
  1351. trash.account = account;
  1352. trash.date = [NSDate dateWithTimeIntervalSince1970:itemDto.date];
  1353. trash.directory = itemDto.isDirectory;
  1354. trash.fileID = itemDto.ocId;
  1355. trash.fileName = itemDto.fileName;
  1356. trash.filePath = itemDto.filePath;
  1357. trash.size = itemDto.size;
  1358. trash.trashbinFileName = itemDto.trashbinFileName;
  1359. trash.trashbinOriginalLocation = itemDto.trashbinOriginalLocation;
  1360. trash.trashbinDeletionTime = [NSDate dateWithTimeIntervalSince1970:itemDto.trashbinDeletionTime];
  1361. [CCUtility insertTypeFileIconName:trash.trashbinFileName metadata:(tableMetadata *)trash];
  1362. [listTrash addObject:trash];
  1363. }
  1364. }
  1365. completion(account, listTrash, nil, 0);
  1366. }
  1367. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1368. NSString *message;
  1369. NSInteger errorCode = response.statusCode;
  1370. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1371. errorCode = error.code;
  1372. // Error
  1373. if (errorCode == 503)
  1374. message = NSLocalizedString(@"_server_error_retry_", nil);
  1375. else
  1376. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1377. completion(account, nil,message, errorCode);
  1378. }];
  1379. }
  1380. - (void)emptyTrashWithAccount:(NSString *)account completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  1381. {
  1382. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1383. if (tableAccount == nil) {
  1384. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1385. }
  1386. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1387. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1388. [communication setUserAgent:[CCUtility getUserAgent]];
  1389. NSString *path = [NSString stringWithFormat:@"%@%@/trashbin/%@/trash", tableAccount.url, k_dav, tableAccount.userID];
  1390. [communication emptyTrash:path onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1391. completion(account, nil, 0);
  1392. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1393. NSString *message;
  1394. NSInteger errorCode = response.statusCode;
  1395. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1396. errorCode = error.code;
  1397. // Error
  1398. if (errorCode == 503)
  1399. message = NSLocalizedString(@"_server_error_retry_", nil);
  1400. else
  1401. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1402. completion(account, message, errorCode);
  1403. }];
  1404. }
  1405. @end
  1406. #pragma --------------------------------------------------------------------------------------------
  1407. #pragma mark ===== OCURLSessionManager =====
  1408. #pragma --------------------------------------------------------------------------------------------
  1409. @implementation OCURLSessionManager
  1410. - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
  1411. {
  1412. // The pinnning check
  1413. if ([[CCCertificate sharedManager] checkTrustedChallenge:challenge]) {
  1414. completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  1415. } else {
  1416. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  1417. }
  1418. }
  1419. @end