OCNetworking.m 98 KB

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