OCNetworking.m 100 KB

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