OCNetworking.m 100 KB

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