OCNetworking.m 98 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981
  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 delegate:(id)delegate 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:delegate 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, NSLocalizedString(@"_no_nextcloud_found_", nil), k_CCErrorInternalError);
  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. completion(account, nil, nil, message, errorCode);
  395. }];
  396. }
  397. - (void)readFileWithAccount:(NSString *)account serverUrl:(NSString *)serverUrl fileName:(NSString *)fileName completion:(void(^)(NSString *account, tableMetadata *metadata, NSString *message, NSInteger errorCode))completion
  398. {
  399. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  400. if (tableAccount == nil) {
  401. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  402. }
  403. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  404. NSString *fileNamePath;
  405. if (fileName) {
  406. fileNamePath = [NSString stringWithFormat:@"%@/%@", serverUrl, fileName];
  407. } else {
  408. fileName= @".";
  409. fileNamePath = serverUrl;
  410. }
  411. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  412. [communication setUserAgent:[CCUtility getUserAgent]];
  413. [communication readFile:fileNamePath onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  414. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:serverUrl account:account];
  415. if ([items count] > 0) {
  416. tableMetadata *metadata = [tableMetadata new];
  417. OCFileDto *itemDto = [items objectAtIndex:0];
  418. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  419. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:tableAccount.url];
  420. metadata = [CCUtility trasformedOCFileToCCMetadata:itemDto fileName:fileName serverUrl:serverUrl autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:account isFolderEncrypted:isFolderEncrypted];
  421. completion(account, metadata, nil, 0);
  422. // BUG 1038 item == 0
  423. } else {
  424. #ifndef EXTENSION
  425. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  426. [appDelegate messageNotification:@"Server error" description:@"Read File WebDAV : [items NULL] please fix" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  427. #endif
  428. completion(account, nil, NSLocalizedString(@"Read File WebDAV : [items NULL] please fix", nil), k_CCErrorInternalError);
  429. }
  430. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  431. NSString *message;
  432. NSInteger errorCode = response.statusCode;
  433. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  434. errorCode = error.code;
  435. // Error
  436. if (errorCode == 503)
  437. message = NSLocalizedString(@"_server_error_retry_", nil);
  438. else
  439. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  440. completion(account, nil, message, errorCode);
  441. }];
  442. }
  443. - (void)createFolderWithAccount:(NSString *)account serverUrl:(NSString *)serverUrl fileName:(NSString *)fileName completion:(void(^)(NSString *account, NSString *fileID, NSDate *date, NSString *message, NSInteger errorCode))completion
  444. {
  445. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  446. if (tableAccount == nil) {
  447. completion(account, nil, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  448. }
  449. NSString *path = [NSString stringWithFormat:@"%@/%@", serverUrl, fileName];
  450. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  451. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:tableAccount.url];
  452. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  453. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  454. [communication setUserAgent:[CCUtility getUserAgent]];
  455. [communication createFolder:path onCommunication:communication withForbiddenCharactersSupported:YES successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  456. NSDictionary *fields = [response allHeaderFields];
  457. NSString *fileID = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-FileId"]];
  458. NSDate *date = [CCUtility dateEnUsPosixFromCloud:[fields objectForKey:@"Date"]];
  459. completion(account, fileID, date, nil, 0);
  460. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  461. NSString *message;
  462. if (([fileName isEqualToString:autoUploadFileName] && [serverUrl isEqualToString:autoUploadDirectory]))
  463. message = nil;
  464. else
  465. message = [CCError manageErrorOC:response.statusCode error:error];
  466. NSInteger errorCode = response.statusCode;
  467. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  468. errorCode = error.code;
  469. completion(account, nil, nil, message, errorCode);
  470. } errorBeforeRequest:^(NSError *error) {
  471. NSString *message;
  472. if (([fileName isEqualToString:autoUploadFileName] && [serverUrl isEqualToString:autoUploadDirectory]))
  473. message = nil;
  474. else {
  475. if (error.code == OCErrorForbidenCharacters)
  476. message = NSLocalizedString(@"_forbidden_characters_from_server_", nil);
  477. else
  478. message = NSLocalizedString(@"_unknow_response_server_", nil);
  479. }
  480. completion(account, nil, nil, message, error.code);
  481. }];
  482. }
  483. - (void)deleteFileOrFolderWithAccount:(NSString *)account path:(NSString *)path completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  484. {
  485. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  486. if (tableAccount == nil) {
  487. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  488. }
  489. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  490. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  491. [communication setUserAgent:[CCUtility getUserAgent]];
  492. [communication deleteFileOrFolder:path onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  493. completion(account, nil, 0);
  494. } failureRquest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  495. NSString *message;
  496. NSInteger errorCode = response.statusCode;
  497. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  498. errorCode = error.code;
  499. // Error
  500. if (errorCode == 503)
  501. message = NSLocalizedString(@"_server_error_retry_", nil);
  502. else
  503. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  504. completion(account, message, errorCode);
  505. }];
  506. }
  507. - (void)moveFileOrFolderWithAccount:(NSString *)account fileName:(NSString *)fileName fileNameTo:(NSString *)fileNameTo completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  508. {
  509. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  510. if (tableAccount == nil) {
  511. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  512. }
  513. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  514. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  515. [communication setUserAgent:[CCUtility getUserAgent]];
  516. [communication moveFileOrFolder:fileName toDestiny:fileNameTo onCommunication:communication withForbiddenCharactersSupported:YES successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  517. completion(account, nil, 0);
  518. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  519. NSInteger errorCode = response.statusCode;
  520. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  521. errorCode = error.code;
  522. NSString *message = [CCError manageErrorOC:response.statusCode error:error];
  523. completion(account, message, error.code);
  524. } errorBeforeRequest:^(NSError *error) {
  525. NSString *message;
  526. if (error.code == OCErrorMovingTheDestinyAndOriginAreTheSame) {
  527. message = NSLocalizedString(@"_error_folder_destiny_is_the_same_", nil);
  528. } else if (error.code == OCErrorMovingFolderInsideHimself) {
  529. message = NSLocalizedString(@"_error_folder_destiny_is_the_same_", nil);
  530. } else if (error.code == OCErrorMovingDestinyNameHaveForbiddenCharacters) {
  531. message = NSLocalizedString(@"_forbidden_characters_from_server_", nil);
  532. } else {
  533. message = NSLocalizedString(@"_unknow_response_server_", nil);
  534. }
  535. completion(account, message, error.code);
  536. }];
  537. }
  538. - (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
  539. {
  540. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  541. if (tableAccount == nil) {
  542. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  543. }
  544. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  545. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  546. [communication setUserAgent:[CCUtility getUserAgent]];
  547. NSString *path = [tableAccount.url stringByAppendingString:k_dav];
  548. NSString *folder = [serverUrl stringByReplacingOccurrencesOfString:[CCUtility getHomeServerUrlActiveUrl:tableAccount.url] withString:@""];
  549. NSString *dateLastModified;
  550. if (date) {
  551. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  552. NSLocale *enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
  553. [dateFormatter setLocale:enUSPOSIXLocale];
  554. [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZZ"];
  555. dateLastModified = [dateFormatter stringFromDate:date];
  556. }
  557. [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) {
  558. NSMutableArray *metadatas = [NSMutableArray new];
  559. BOOL showHiddenFiles = [CCUtility getShowHiddenFiles];
  560. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  561. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:tableAccount.url];
  562. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  563. for (OCFileDto *itemDto in items) {
  564. NSString *serverUrl;
  565. BOOL isFolderEncrypted;
  566. NSString *fileName = [itemDto.fileName stringByReplacingOccurrencesOfString:@"/" withString:@""];
  567. // Skip hidden files
  568. if (fileName.length > 0) {
  569. if (!showHiddenFiles && [[fileName substringToIndex:1] isEqualToString:@"."])
  570. continue;
  571. } else
  572. continue;
  573. NSRange firstInstance = [itemDto.filePath rangeOfString:[NSString stringWithFormat:@"%@/files/%@", k_dav, tableAccount.userID]];
  574. NSString *serverPath = [itemDto.filePath substringFromIndex:firstInstance.length+firstInstance.location+1];
  575. if ([serverPath hasSuffix:@"/"]) serverPath = [serverPath substringToIndex:[serverPath length] - 1];
  576. serverUrl = [CCUtility stringAppendServerUrl:[tableAccount.url stringByAppendingString:k_webDAV] addFileName:serverPath];
  577. if (itemDto.isDirectory) {
  578. (void)[[NCManageDatabase sharedInstance] addDirectoryWithEncrypted:itemDto.isEncrypted favorite:itemDto.isFavorite fileID:itemDto.ocId permissions:itemDto.permissions serverUrl:[NSString stringWithFormat:@"%@/%@", serverUrl, fileName] account:account];
  579. }
  580. isFolderEncrypted = [CCUtility isFolderEncrypted:serverUrl account:account];
  581. [metadatas addObject:[CCUtility trasformedOCFileToCCMetadata:itemDto fileName:itemDto.fileName serverUrl:serverUrl autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:account isFolderEncrypted:isFolderEncrypted]];
  582. }
  583. dispatch_async(dispatch_get_main_queue(), ^{
  584. completion(account, metadatas, nil, 0);
  585. });
  586. });
  587. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) {
  588. NSString *message = @"";
  589. NSInteger errorCode = response.statusCode;
  590. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  591. errorCode = error.code;
  592. // Error
  593. if (errorCode == 503) {
  594. message = NSLocalizedString(@"_server_error_retry_", nil);
  595. } else {
  596. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  597. }
  598. completion(account, nil, message, errorCode);
  599. }];
  600. }
  601. #pragma --------------------------------------------------------------------------------------------
  602. #pragma mark ===== downloadPreview =====
  603. #pragma --------------------------------------------------------------------------------------------
  604. /*
  605. - (void)downloadThumbnailWithMetadata:(tableMetadata*)metadata withWidth:(CGFloat)width andHeight:(CGFloat)height completion:(void (^)(NSString *message, NSInteger errorCode))completion
  606. {
  607. NSString *file = [NSString stringWithFormat:@"%@/%@.ico", [CCUtility getDirectoryProviderStorageFileID:metadata.fileID], metadata.fileNameView];
  608. if ([[NSFileManager defaultManager] fileExistsAtPath:file]) {
  609. completion(nil, 0);
  610. } else {
  611. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  612. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  613. [communication setUserAgent:[CCUtility getUserAgent]];
  614. [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) {
  615. [thumbnail writeToFile:file atomically:YES];
  616. completion(nil, 0);
  617. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  618. NSString *message;
  619. NSInteger errorCode = response.statusCode;
  620. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  621. errorCode = error.code;
  622. // Error
  623. if (errorCode == 503)
  624. message = NSLocalizedString(@"_server_error_retry_", nil);
  625. else
  626. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  627. completion(message, errorCode);
  628. }];
  629. }
  630. }
  631. */
  632. - (void)downloadPreviewWithAccount:(NSString *)account metadata:(tableMetadata*)metadata withWidth:(CGFloat)width andHeight:(CGFloat)height completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  633. {
  634. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  635. if (tableAccount == nil) {
  636. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  637. }
  638. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  639. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  640. [communication setUserAgent:[CCUtility getUserAgent]];
  641. NSString *file = [NSString stringWithFormat:@"%@/%@.ico", [CCUtility getDirectoryProviderStorageFileID:metadata.fileID], metadata.fileNameView];
  642. [communication getRemotePreviewByServer:tableAccount.url ofFilePath:[CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:metadata.serverUrl activeUrl:tableAccount.url] withWidth:width andHeight:height andA:1 andMode:@"cover" path:@"" onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSData *preview, NSString *redirectedServer) {
  643. [preview writeToFile:file atomically:YES];
  644. completion(account, nil, 0);
  645. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  646. NSString *message;
  647. NSInteger errorCode = response.statusCode;
  648. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  649. errorCode = error.code;
  650. // Error
  651. if (errorCode == 503)
  652. message = NSLocalizedString(@"_server_error_retry_", nil);
  653. else
  654. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  655. completion(account, message, errorCode);
  656. }];
  657. }
  658. - (void)downloadPreviewWithAccount:(NSString *)account serverPath:(NSString *)serverPath fileNamePath:(NSString *)fileNamePath completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  659. {
  660. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  661. if (tableAccount == nil) {
  662. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  663. }
  664. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  665. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  666. [communication setUserAgent:[CCUtility getUserAgent]];
  667. [communication getRemotePreviewByServer:tableAccount.url ofFilePath:@"" withWidth:0 andHeight:0 andA:0 andMode:@"" path:serverPath onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSData *preview, NSString *redirectedServer) {
  668. [preview writeToFile:fileNamePath atomically:YES];
  669. completion(account, nil, 0);
  670. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  671. NSString *message;
  672. NSInteger errorCode = response.statusCode;
  673. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  674. errorCode = error.code;
  675. // Error
  676. if (errorCode == 503)
  677. message = NSLocalizedString(@"_server_error_retry_", nil);
  678. else
  679. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  680. completion(account, message, errorCode);
  681. }];
  682. }
  683. - (void)downloadPreviewTrashWithAccount:(NSString *)account FileID:(NSString *)fileID fileName:(NSString *)fileName completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  684. {
  685. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  686. if (tableAccount == nil) {
  687. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  688. }
  689. NSString *file = [NSString stringWithFormat:@"%@/%@.ico", [CCUtility getDirectoryProviderStorageFileID:fileID], fileName];
  690. if ([[NSFileManager defaultManager] fileExistsAtPath:file]) {
  691. completion(account, nil, 0);
  692. } else {
  693. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  694. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  695. [communication setUserAgent:[CCUtility getUserAgent]];
  696. [communication getRemotePreviewTrashByServer:tableAccount.url ofFileID:fileID onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSData *preview, NSString *redirectedServer) {
  697. [preview writeToFile:file atomically:YES];
  698. completion(account, nil, 0);
  699. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  700. NSString *message;
  701. NSInteger errorCode = response.statusCode;
  702. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  703. errorCode = error.code;
  704. // Error
  705. if (errorCode == 503)
  706. message = NSLocalizedString(@"_server_error_retry_", nil);
  707. else
  708. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  709. completion(account, message, errorCode);
  710. }];
  711. }
  712. }
  713. #pragma --------------------------------------------------------------------------------------------
  714. #pragma mark ===== Favorite =====
  715. #pragma --------------------------------------------------------------------------------------------
  716. - (void)listingFavoritesWithAccount:(NSString *)account completion:(void(^)(NSString *account, NSArray *metadatas, NSString *message, NSInteger errorCode))completion
  717. {
  718. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  719. if (tableAccount == nil) {
  720. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  721. }
  722. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  723. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  724. [communication setUserAgent:[CCUtility getUserAgent]];
  725. NSString *path = [tableAccount.url stringByAppendingString:k_dav];
  726. [communication listingFavorites:path folder:@"" withUserSessionToken:nil onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer, NSString *token) {
  727. NSMutableArray *metadatas = [NSMutableArray new];
  728. BOOL showHiddenFiles = [CCUtility getShowHiddenFiles];
  729. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  730. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:tableAccount.url];
  731. // Order by fileNamePath
  732. items = [items sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
  733. OCFileDto *record1 = obj1, *record2 = obj2;
  734. NSString *path1 = [[record1.filePath stringByAppendingString:record1.fileName] lowercaseString];
  735. NSString *path2 = [[record2.filePath stringByAppendingString:record2.fileName] lowercaseString];
  736. return [path1 compare:path2];
  737. }];
  738. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  739. for(OCFileDto *itemDto in items) {
  740. NSString *serverUrl;
  741. BOOL isFolderEncrypted;
  742. NSString *fileName = [itemDto.fileName stringByReplacingOccurrencesOfString:@"/" withString:@""];
  743. // Skip hidden files
  744. if (fileName.length > 0) {
  745. if (!showHiddenFiles && [[fileName substringToIndex:1] isEqualToString:@"."])
  746. continue;
  747. } else
  748. continue;
  749. NSRange firstInstance = [itemDto.filePath rangeOfString:[NSString stringWithFormat:@"%@/files/%@", k_dav, tableAccount.userID]];
  750. NSString *serverPath = [itemDto.filePath substringFromIndex:firstInstance.length+firstInstance.location+1];
  751. if ([serverPath hasSuffix:@"/"])
  752. serverPath = [serverPath substringToIndex:[serverPath length] - 1];
  753. serverUrl = [CCUtility stringAppendServerUrl:[tableAccount.url stringByAppendingString:k_webDAV] addFileName:serverPath];
  754. if (itemDto.isDirectory) {
  755. (void)[[NCManageDatabase sharedInstance] addDirectoryWithEncrypted:itemDto.isEncrypted favorite:itemDto.isFavorite fileID:itemDto.ocId permissions:itemDto.permissions serverUrl:[NSString stringWithFormat:@"%@/%@", serverUrl, fileName] account:account];
  756. }
  757. isFolderEncrypted = [CCUtility isFolderEncrypted:serverUrl account:account];
  758. [metadatas addObject:[CCUtility trasformedOCFileToCCMetadata:itemDto fileName:itemDto.fileName serverUrl:serverUrl autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:account isFolderEncrypted:isFolderEncrypted]];
  759. }
  760. dispatch_async(dispatch_get_main_queue(), ^{
  761. completion(account, metadatas, nil, 0);
  762. });
  763. });
  764. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) {
  765. NSString *message;
  766. NSInteger errorCode = response.statusCode;
  767. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  768. errorCode = error.code;
  769. // Error
  770. if (errorCode == 503)
  771. message = NSLocalizedString(@"_server_error_retry_", nil);
  772. else
  773. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  774. completion(account, nil, message, errorCode);
  775. }];
  776. }
  777. - (void)settingFavoriteWithAccount:(NSString *)account fileName:(NSString *)fileName favorite:(BOOL)favorite completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  778. {
  779. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  780. if (tableAccount == nil) {
  781. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  782. }
  783. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  784. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  785. [communication setUserAgent:[CCUtility getUserAgent]];
  786. NSString *server = [tableAccount.url stringByAppendingString:k_dav];
  787. [communication settingFavoriteServer:server andFileOrFolderPath:fileName favorite:favorite withUserSessionToken:nil onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer, NSString *token) {
  788. completion(account, nil, 0);
  789. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) {
  790. NSString *message;
  791. NSInteger errorCode = response.statusCode;
  792. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  793. errorCode = error.code;
  794. // Error
  795. if (errorCode == 503)
  796. message = NSLocalizedString(@"_server_error_retry_", nil);
  797. else
  798. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  799. completion(account, message, errorCode);
  800. }];
  801. }
  802. #pragma --------------------------------------------------------------------------------------------
  803. #pragma mark ===== Share =====
  804. #pragma --------------------------------------------------------------------------------------------
  805. - (void)readShareWithAccount:(NSString *)account completion:(void (^)(NSString *account, NSArray *items, NSString *message, NSInteger errorCode))completion
  806. {
  807. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  808. if (tableAccount == nil) {
  809. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  810. }
  811. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  812. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  813. [communication setUserAgent:[CCUtility getUserAgent]];
  814. [communication readSharedByServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  815. completion(account, items, nil, 0);
  816. } failureRequest :^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  817. NSString *message = @"";
  818. NSInteger errorCode = response.statusCode;
  819. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  820. errorCode = error.code;
  821. // Error
  822. if (errorCode == 503) {
  823. message = NSLocalizedString(@"_server_error_retry_", nil);
  824. } else {
  825. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  826. }
  827. completion(account, nil, message, errorCode);
  828. }];
  829. }
  830. - (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
  831. {
  832. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  833. if (tableAccount == nil) {
  834. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  835. }
  836. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  837. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  838. [communication setUserAgent:[CCUtility getUserAgent]];
  839. [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) {
  840. completion(account, nil, 0);
  841. } failureRequest :^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  842. NSString *message = @"";
  843. NSInteger errorCode = response.statusCode;
  844. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  845. errorCode = error.code;
  846. // Error
  847. if (errorCode == 503) {
  848. message = NSLocalizedString(@"_server_error_retry_", nil);
  849. } else {
  850. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  851. }
  852. completion(account, message, errorCode);
  853. }];
  854. }
  855. // * @param shareeType -> NSInteger: to set the type of sharee (user/group/federated)
  856. - (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
  857. {
  858. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  859. if (tableAccount == nil) {
  860. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  861. }
  862. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  863. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  864. [communication setUserAgent:[CCUtility getUserAgent]];
  865. [communication shareWith:userOrGroup shareeType:shareeType inServer:[tableAccount.url stringByAppendingString:@"/"] andFileOrFolderPath:[fileName encodeString:NSUTF8StringEncoding] andPermissions:permission onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  866. completion(account, nil, 0);
  867. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  868. NSString *message = @"";
  869. NSInteger errorCode = response.statusCode;
  870. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  871. errorCode = error.code;
  872. // Error
  873. if (errorCode == 503) {
  874. message = NSLocalizedString(@"_server_error_retry_", nil);
  875. } else {
  876. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  877. }
  878. completion(account, message, errorCode);
  879. }];
  880. }
  881. - (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
  882. {
  883. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  884. if (tableAccount == nil) {
  885. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  886. }
  887. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  888. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  889. [communication setUserAgent:[CCUtility getUserAgent]];
  890. [communication updateShare:shareID ofServerPath:[tableAccount.url stringByAppendingString:@"/"] withPasswordProtect:[password encodeString:NSUTF8StringEncoding] andExpirationTime:expirationTime andPermissions:permission andHideDownload:hideDownload onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  891. completion(account, nil, 0);
  892. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  893. NSString *message = @"";
  894. NSInteger errorCode = response.statusCode;
  895. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  896. errorCode = error.code;
  897. // Error
  898. if (errorCode == 503) {
  899. message = NSLocalizedString(@"_server_error_retry_", nil);
  900. } else {
  901. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  902. }
  903. completion(account, message, errorCode);
  904. }];
  905. }
  906. - (void)unshareAccount:(NSString *)account shareID:(NSInteger)shareID completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  907. {
  908. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  909. if (tableAccount == nil) {
  910. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  911. }
  912. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  913. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  914. [communication setUserAgent:[CCUtility getUserAgent]];
  915. [communication unShareFileOrFolderByServer:[tableAccount.url stringByAppendingString:@"/"] andIdRemoteShared:shareID onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  916. completion(account, nil, 0);
  917. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  918. NSString *message = @"";
  919. NSInteger errorCode = response.statusCode;
  920. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  921. errorCode = error.code;
  922. // Error
  923. if (errorCode == 503) {
  924. message = NSLocalizedString(@"_server_error_retry_", nil);
  925. } else {
  926. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  927. }
  928. completion(account, message, errorCode);
  929. }];
  930. }
  931. - (void)getUserGroupWithAccount:(NSString *)account searchString:(NSString *)searchString completion:(void (^)(NSString *account, NSArray *item, NSString *message, NSInteger errorCode))completion
  932. {
  933. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  934. if (tableAccount == nil) {
  935. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  936. }
  937. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  938. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  939. [communication setUserAgent:[CCUtility getUserAgent]];
  940. [communication searchUsersAndGroupsWith:searchString forPage:1 with:50 ofServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *itemList, NSString *redirectedServer) {
  941. completion(account, itemList, nil, 0);
  942. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  943. NSString *message = @"";
  944. NSInteger errorCode = response.statusCode;
  945. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  946. errorCode = error.code;
  947. // Error
  948. if (errorCode == 503) {
  949. message = NSLocalizedString(@"_server_error_retry_", nil);
  950. } else {
  951. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  952. }
  953. completion(account, nil, message, errorCode);
  954. }];
  955. }
  956. - (void)getSharePermissionsFileWithAccount:(NSString *)account fileNamePath:(NSString *)fileNamePath completion:(void (^)(NSString *account, NSString *permissions, NSString *message, NSInteger errorCode))completion
  957. {
  958. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  959. if (tableAccount == nil) {
  960. completion(account, 0, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  961. }
  962. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  963. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  964. [communication setUserAgent:[CCUtility getUserAgent]];
  965. [communication getSharePermissionsFile:fileNamePath onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *permissions, NSString *redirectedServer) {
  966. completion(account, permissions, nil ,0);
  967. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  968. NSString *message = @"";
  969. NSInteger errorCode = response.statusCode;
  970. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  971. errorCode = error.code;
  972. // Error
  973. if (errorCode == 503) {
  974. message = NSLocalizedString(@"_server_error_retry_", nil);
  975. } else {
  976. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  977. }
  978. completion(account, nil, message, errorCode);
  979. }];
  980. }
  981. #pragma --------------------------------------------------------------------------------------------
  982. #pragma mark ===== API =====
  983. #pragma --------------------------------------------------------------------------------------------
  984. - (void)getActivityWithAccount:(NSString *)account since:(NSInteger)since completion:(void(^)(NSString *account, NSArray *listOfActivity, NSString *message, NSInteger errorCode))completion
  985. {
  986. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  987. if (tableAccount == nil) {
  988. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  989. }
  990. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  991. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  992. [communication setUserAgent:[CCUtility getUserAgent]];
  993. [communication getActivityServer:[tableAccount.url stringByAppendingString:@"/"] since:since onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfActivity, NSString *redirectedServer) {
  994. completion(account, listOfActivity, nil, 0);
  995. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  996. NSString *message;
  997. NSInteger errorCode = response.statusCode;
  998. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  999. errorCode = error.code;
  1000. // Error
  1001. if (errorCode == 503)
  1002. message = NSLocalizedString(@"_server_error_retry_", nil);
  1003. else
  1004. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1005. completion(account, nil, message, errorCode);
  1006. }];
  1007. }
  1008. - (void)getExternalSitesWithAccount:(NSString *)account completion:(void (^)(NSString *account, NSArray *listOfExternalSites, NSString *message, NSInteger errorCode))completion
  1009. {
  1010. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1011. if (tableAccount == nil) {
  1012. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1013. }
  1014. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1015. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1016. [communication setUserAgent:[CCUtility getUserAgent]];
  1017. [communication getExternalSitesServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfExternalSites, NSString *redirectedServer) {
  1018. completion(account, listOfExternalSites, nil, 0);
  1019. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1020. NSString *message = @"";
  1021. NSInteger errorCode = response.statusCode;
  1022. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1023. errorCode = error.code;
  1024. // Error
  1025. if (errorCode == 503) {
  1026. message = NSLocalizedString(@"_server_error_retry_", nil);
  1027. } else {
  1028. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1029. }
  1030. completion(account, nil, message, errorCode);
  1031. }];
  1032. }
  1033. /*
  1034. - (void)middlewarePing
  1035. {
  1036. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1037. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  1038. [communication setUserAgent:[CCUtility getUserAgent]];
  1039. [communication getMiddlewarePing:_metadataNet.serverUrl onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfExternalSites, NSString *redirectedServer) {
  1040. [self complete];
  1041. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1042. NSInteger errorCode = response.statusCode;
  1043. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1044. errorCode = error.code;
  1045. // Error
  1046. if ([self.delegate respondsToSelector:@selector(getExternalSitesServerFailure:message:errorCode:)]) {
  1047. if (errorCode == 503)
  1048. [self.delegate getExternalSitesServerFailure:_metadataNet message:NSLocalizedString(@"_server_error_retry_", nil) errorCode:errorCode];
  1049. else
  1050. [self.delegate getExternalSitesServerFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1051. }
  1052. // Request trusted certificated
  1053. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  1054. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1055. [self complete];
  1056. }];
  1057. }
  1058. */
  1059. - (void)getNotificationWithAccount:(NSString *)account completion:(void (^)(NSString *account, NSArray *listOfNotifications, NSString *message, NSInteger errorCode))completion
  1060. {
  1061. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1062. if (tableAccount == nil) {
  1063. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1064. }
  1065. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1066. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1067. [communication setUserAgent:[CCUtility getUserAgent]];
  1068. [communication getNotificationServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfNotifications, NSString *redirectedServer) {
  1069. completion(account, listOfNotifications, nil, 0);
  1070. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1071. NSString *message = @"";
  1072. NSInteger errorCode = response.statusCode;
  1073. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1074. errorCode = error.code;
  1075. // Error
  1076. if (errorCode == 503) {
  1077. message = NSLocalizedString(@"_server_error_retry_", nil);
  1078. } else {
  1079. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1080. }
  1081. completion(account, nil, message, errorCode);
  1082. }];
  1083. }
  1084. - (void)setNotificationWithAccount:(NSString *)account serverUrl:(NSString *)serverUrl type:(NSString *)type completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  1085. {
  1086. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1087. if (tableAccount == nil) {
  1088. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1089. }
  1090. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1091. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1092. [communication setUserAgent:[CCUtility getUserAgent]];
  1093. [communication setNotificationServer:serverUrl type:type onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1094. completion(account, nil, 0);
  1095. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1096. NSString *message = @"";
  1097. NSInteger errorCode = response.statusCode;
  1098. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1099. errorCode = error.code;
  1100. // Error
  1101. if (errorCode == 503) {
  1102. message = NSLocalizedString(@"_server_error_retry_", nil);
  1103. } else {
  1104. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1105. }
  1106. completion(account, message, errorCode);
  1107. }];
  1108. }
  1109. - (void)getCapabilitiesWithAccount:(NSString *)account completion:(void (^)(NSString *account, OCCapabilities *capabilities, NSString *message, NSInteger errorCode))completion
  1110. {
  1111. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1112. if (tableAccount == nil) {
  1113. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1114. }
  1115. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1116. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1117. [communication setUserAgent:[CCUtility getUserAgent]];
  1118. [communication getCapabilitiesOfServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, OCCapabilities *capabilities, NSString *redirectedServer) {
  1119. completion(account, capabilities, nil, 0);
  1120. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1121. NSString *message = @"";
  1122. NSInteger errorCode = response.statusCode;
  1123. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1124. errorCode = error.code;
  1125. // Error
  1126. if (errorCode == 503) {
  1127. message = NSLocalizedString(@"_server_error_retry_", nil);
  1128. } else {
  1129. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1130. }
  1131. completion(account, nil, message, errorCode);
  1132. }];
  1133. }
  1134. - (void)getUserProfileWithAccount:(NSString *)account completion:(void (^)(NSString *account, OCUserProfile *userProfile, NSString *message, NSInteger errorCode))completion
  1135. {
  1136. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1137. if (tableAccount == nil) {
  1138. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1139. }
  1140. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1141. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1142. [communication setUserAgent:[CCUtility getUserAgent]];
  1143. [communication getUserProfileServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, OCUserProfile *userProfile, NSString *redirectedServer) {
  1144. completion(account, userProfile, nil, 0);
  1145. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1146. NSString *message = @"";
  1147. NSInteger errorCode = response.statusCode;
  1148. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1149. errorCode = error.code;
  1150. // Error
  1151. if (errorCode == 503) {
  1152. message = NSLocalizedString(@"_server_error_retry_", nil);
  1153. } else {
  1154. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1155. }
  1156. completion(account, nil, message, errorCode);
  1157. }];
  1158. }
  1159. #pragma --------------------------------------------------------------------------------------------
  1160. #pragma mark ===== Push Notification =====
  1161. #pragma --------------------------------------------------------------------------------------------
  1162. - (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
  1163. {
  1164. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1165. if (tableAccount == nil) {
  1166. completion(account, nil, nil, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1167. }
  1168. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1169. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1170. [communication setUserAgent:[CCUtility getUserAgent]];
  1171. devicePublicKey = [CCUtility URLEncodeStringFromString:devicePublicKey];
  1172. [communication subscribingNextcloudServerPush:url pushTokenHash:pushTokenHash devicePublicKey:devicePublicKey proxyServerPath: [NCBrandOptions sharedInstance].pushNotificationServerProxy onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *publicKey, NSString *deviceIdentifier, NSString *signature, NSString *redirectedServer) {
  1173. deviceIdentifier = [CCUtility URLEncodeStringFromString:deviceIdentifier];
  1174. signature = [CCUtility URLEncodeStringFromString:signature];
  1175. publicKey = [CCUtility URLEncodeStringFromString:publicKey];
  1176. [communication subscribingPushProxy:[NCBrandOptions sharedInstance].pushNotificationServerProxy pushToken:pushToken deviceIdentifier:deviceIdentifier deviceIdentifierSignature:signature publicKey:publicKey onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1177. completion(account, deviceIdentifier, signature, publicKey, nil, 0);
  1178. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1179. NSString *message;
  1180. NSInteger errorCode = response.statusCode;
  1181. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1182. errorCode = error.code;
  1183. // Error
  1184. if (errorCode == 503)
  1185. message = NSLocalizedString(@"_server_error_retry_", nil);
  1186. else
  1187. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1188. completion(account, nil, nil, nil, message, errorCode);
  1189. }];
  1190. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1191. NSString *message;
  1192. NSInteger errorCode = response.statusCode;
  1193. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1194. errorCode = error.code;
  1195. // Error
  1196. if (errorCode == 503)
  1197. message = NSLocalizedString(@"_server_error_retry_", nil);
  1198. else
  1199. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1200. completion(account, nil, nil, nil, message, errorCode);
  1201. }];
  1202. }
  1203. - (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 {
  1204. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1205. if (tableAccount == nil) {
  1206. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1207. }
  1208. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1209. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1210. [communication setUserAgent:[CCUtility getUserAgent]];
  1211. [communication unsubscribingNextcloudServerPush:url onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1212. [communication unsubscribingPushProxy:[NCBrandOptions sharedInstance].pushNotificationServerProxy deviceIdentifier:deviceIdentifier deviceIdentifierSignature:deviceIdentifierSignature publicKey:publicKey onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1213. completion(account, nil, 0);
  1214. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1215. NSString *message;
  1216. NSInteger errorCode = response.statusCode;
  1217. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1218. errorCode = error.code;
  1219. // Error
  1220. if (errorCode == 503)
  1221. message = NSLocalizedString(@"_server_error_retry_", nil);
  1222. else
  1223. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1224. completion(account, message, errorCode);
  1225. }];
  1226. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1227. NSString *message;
  1228. NSInteger errorCode = response.statusCode;
  1229. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1230. errorCode = error.code;
  1231. // Error
  1232. if (errorCode == 503)
  1233. message = NSLocalizedString(@"_server_error_retry_", nil);
  1234. else
  1235. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1236. completion(account, message, errorCode);
  1237. }];
  1238. }
  1239. #pragma --------------------------------------------------------------------------------------------
  1240. #pragma mark ===== Manage Mobile Editor OCS API =====
  1241. #pragma --------------------------------------------------------------------------------------------
  1242. - (void)createLinkRichdocumentsWithAccount:(NSString *)account fileID:(NSString *)fileID completion:(void(^)(NSString *account, NSString *link, NSString *message, NSInteger errorCode))completion
  1243. {
  1244. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1245. if (tableAccount == nil) {
  1246. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1247. }
  1248. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1249. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1250. [communication setUserAgent:[CCUtility getUserAgent]];
  1251. NSString *fileIDServer = [[NCUtility sharedInstance] convertFileIDClientToFileIDServer:fileID];
  1252. [communication createLinkRichdocuments:[tableAccount.url stringByAppendingString:@"/"] fileID:fileIDServer onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *link, NSString *redirectedServer) {
  1253. completion(account, link, nil, 0);
  1254. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1255. NSString *message;
  1256. NSInteger errorCode = response.statusCode;
  1257. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1258. errorCode = error.code;
  1259. // Error
  1260. if (errorCode == 503)
  1261. message = NSLocalizedString(@"_server_error_retry_", nil);
  1262. else
  1263. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1264. completion(account, nil,message, errorCode);
  1265. }];
  1266. }
  1267. - (void)geTemplatesRichdocumentsWithAccount:(NSString *)account typeTemplate:(NSString *)typeTemplate completion:(void(^)(NSString *account, NSArray *listOfTemplate, NSString *message, NSInteger errorCode))completion
  1268. {
  1269. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1270. if (tableAccount == nil) {
  1271. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1272. }
  1273. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1274. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1275. [communication setUserAgent:[CCUtility getUserAgent]];
  1276. [communication geTemplatesRichdocuments:[tableAccount.url stringByAppendingString:@"/"] typeTemplate:typeTemplate onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfTemplate, NSString *redirectedServer) {
  1277. completion(account, listOfTemplate, nil, 0);
  1278. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1279. NSString *message;
  1280. NSInteger errorCode = response.statusCode;
  1281. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1282. errorCode = error.code;
  1283. // Error
  1284. if (errorCode == 503)
  1285. message = NSLocalizedString(@"_server_error_retry_", nil);
  1286. else
  1287. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1288. completion(account, nil, message, errorCode);
  1289. }];
  1290. }
  1291. - (void)createNewRichdocumentsWithAccount:(NSString *)account fileName:(NSString *)fileName serverUrl:(NSString *)serverUrl templateID:(NSString *)templateID completion:(void(^)(NSString *account, NSString *url, NSString *message, NSInteger errorCode))completion
  1292. {
  1293. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1294. if (tableAccount == nil) {
  1295. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1296. }
  1297. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1298. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1299. [communication setUserAgent:[CCUtility getUserAgent]];
  1300. [communication createNewRichdocuments:[tableAccount.url stringByAppendingString:@"/"] path:fileName templateID:templateID onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *url, NSString *redirectedServer) {
  1301. completion(account, url, nil, 0);
  1302. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1303. NSString *message;
  1304. NSInteger errorCode = response.statusCode;
  1305. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1306. errorCode = error.code;
  1307. // Error
  1308. if (errorCode == 503)
  1309. message = NSLocalizedString(@"_server_error_retry_", nil);
  1310. else
  1311. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1312. completion(account, nil, message, errorCode);
  1313. }];
  1314. }
  1315. - (void)createAssetRichdocumentsWithAccount:(NSString *)account fileName:(NSString *)fileName serverUrl:(NSString *)serverUrl completion:(void(^)(NSString *account, NSString *link, NSString *message, NSInteger errorCode))completion
  1316. {
  1317. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1318. if (tableAccount == nil) {
  1319. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1320. }
  1321. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1322. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1323. [communication setUserAgent:[CCUtility getUserAgent]];
  1324. NSString *fileNamePath = [CCUtility returnFileNamePathFromFileName:fileName serverUrl:serverUrl activeUrl:tableAccount.url];
  1325. [communication createAssetRichdocuments:[tableAccount.url stringByAppendingString:@"/"] path:fileNamePath onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *url, NSString *redirectedServer) {
  1326. completion(account, url, nil, 0);
  1327. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1328. NSString *message;
  1329. NSInteger errorCode = response.statusCode;
  1330. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1331. errorCode = error.code;
  1332. // Error
  1333. if (errorCode == 503)
  1334. message = NSLocalizedString(@"_server_error_retry_", nil);
  1335. else
  1336. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1337. completion(account, nil, message, errorCode);
  1338. }];
  1339. }
  1340. #pragma --------------------------------------------------------------------------------------------
  1341. #pragma mark ===== Trash =====
  1342. #pragma --------------------------------------------------------------------------------------------
  1343. - (void)listingTrashWithAccount:(NSString *)account path:(NSString *)path serverUrl:(NSString *)serverUrl completion:(void (^)(NSString *account, NSArray *items, NSString *message, NSInteger errorCode))completion
  1344. {
  1345. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1346. if (tableAccount == nil) {
  1347. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1348. }
  1349. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1350. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1351. [communication setUserAgent:[CCUtility getUserAgent]];
  1352. [communication listingTrash:[serverUrl stringByAppendingString:path] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  1353. // Check items > 0
  1354. if ([items count] == 0) {
  1355. #ifndef EXTENSION
  1356. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  1357. [appDelegate messageNotification:@"Server error" description:@"Read Folder WebDAV : [items NULL] please fix" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  1358. #endif
  1359. completion(account, nil, NSLocalizedString(@"Read Folder WebDAV : [items NULL] please fix", nil), k_CCErrorInternalError);
  1360. } else {
  1361. NSMutableArray *listTrash = [NSMutableArray new];
  1362. //OCFileDto *itemDtoFolder = [items objectAtIndex:0];
  1363. if ([items count] > 1) {
  1364. for (NSUInteger i=1; i < [items count]; i++) {
  1365. OCFileDto *itemDto = [items objectAtIndex:i];
  1366. tableTrash *trash = [tableTrash new];
  1367. trash.account = account;
  1368. trash.date = [NSDate dateWithTimeIntervalSince1970:itemDto.date];
  1369. trash.directory = itemDto.isDirectory;
  1370. trash.fileID = itemDto.ocId;
  1371. trash.fileName = itemDto.fileName;
  1372. trash.filePath = itemDto.filePath;
  1373. trash.size = itemDto.size;
  1374. trash.trashbinFileName = itemDto.trashbinFileName;
  1375. trash.trashbinOriginalLocation = itemDto.trashbinOriginalLocation;
  1376. trash.trashbinDeletionTime = [NSDate dateWithTimeIntervalSince1970:itemDto.trashbinDeletionTime];
  1377. [CCUtility insertTypeFileIconName:trash.trashbinFileName metadata:(tableMetadata *)trash];
  1378. [listTrash addObject:trash];
  1379. }
  1380. }
  1381. completion(account, listTrash, nil, 0);
  1382. }
  1383. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1384. NSString *message;
  1385. NSInteger errorCode = response.statusCode;
  1386. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1387. errorCode = error.code;
  1388. // Error
  1389. if (errorCode == 503)
  1390. message = NSLocalizedString(@"_server_error_retry_", nil);
  1391. else
  1392. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1393. completion(account, nil,message, errorCode);
  1394. }];
  1395. }
  1396. - (void)emptyTrashWithAccount:(NSString *)account completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  1397. {
  1398. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1399. if (tableAccount == nil) {
  1400. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1401. }
  1402. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1403. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1404. [communication setUserAgent:[CCUtility getUserAgent]];
  1405. NSString *path = [NSString stringWithFormat:@"%@%@/trashbin/%@/trash", tableAccount.url, k_dav, tableAccount.userID];
  1406. [communication emptyTrash:path onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1407. completion(account, nil, 0);
  1408. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1409. NSString *message;
  1410. NSInteger errorCode = response.statusCode;
  1411. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1412. errorCode = error.code;
  1413. // Error
  1414. if (errorCode == 503)
  1415. message = NSLocalizedString(@"_server_error_retry_", nil);
  1416. else
  1417. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1418. completion(account, message, errorCode);
  1419. }];
  1420. }
  1421. @end
  1422. #pragma --------------------------------------------------------------------------------------------
  1423. #pragma mark ===== OCURLSessionManager =====
  1424. #pragma --------------------------------------------------------------------------------------------
  1425. @implementation OCURLSessionManager
  1426. - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
  1427. {
  1428. // The pinnning check
  1429. if ([[CCCertificate sharedManager] checkTrustedChallenge:challenge]) {
  1430. completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  1431. } else {
  1432. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  1433. }
  1434. }
  1435. @end