OCNetworking.m 99 KB

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