OCNetworking.m 98 KB

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