OCNetworking.m 97 KB

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