OCNetworking.m 120 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430
  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. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  30. @interface OCnetworking ()
  31. {
  32. NSString *_activeUser;
  33. NSString *_activeUserID;
  34. NSString *_activePassword;
  35. NSString *_activeUrl;
  36. }
  37. @end
  38. @implementation OCnetworking
  39. - (id)initWithDelegate:(id)delegate metadataNet:(CCMetadataNet *)metadataNet withUser:(NSString *)withUser withUserID:(NSString *)withUserID withPassword:(NSString *)withPassword withUrl:(NSString *)withUrl
  40. {
  41. self = [super init];
  42. if (self) {
  43. _delegate = delegate;
  44. _metadataNet = [CCMetadataNet new];
  45. _metadataNet = [metadataNet copy];
  46. _activeUser = withUser;
  47. _activeUserID = withUserID;
  48. _activePassword = withPassword;
  49. _activeUrl = withUrl;
  50. }
  51. return self;
  52. }
  53. - (void)start
  54. {
  55. if (![NSThread isMainThread]) {
  56. [self performSelectorOnMainThread:@selector(start) withObject:nil waitUntilDone:NO];
  57. return;
  58. }
  59. [self willChangeValueForKey:@"isExecuting"];
  60. _isExecuting = YES;
  61. [self didChangeValueForKey:@"isExecuting"];
  62. if (self.isCancelled) {
  63. [self finish];
  64. } else {
  65. [self poolNetworking];
  66. }
  67. }
  68. - (void)finish
  69. {
  70. [self willChangeValueForKey:@"isExecuting"];
  71. [self willChangeValueForKey:@"isFinished"];
  72. _isExecuting = NO;
  73. _isFinished = YES;
  74. [self didChangeValueForKey:@"isExecuting"];
  75. [self didChangeValueForKey:@"isFinished"];
  76. }
  77. - (void)cancel
  78. {
  79. if (_isExecuting) {
  80. [self complete];
  81. }
  82. [super cancel];
  83. }
  84. - (void)poolNetworking
  85. {
  86. #ifndef EXTENSION
  87. [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
  88. #endif
  89. if([self respondsToSelector:NSSelectorFromString(_metadataNet.action)])
  90. [self performSelector:NSSelectorFromString(_metadataNet.action)];
  91. }
  92. #pragma --------------------------------------------------------------------------------------------
  93. #pragma mark ===== Delegate =====
  94. #pragma --------------------------------------------------------------------------------------------
  95. - (void)complete
  96. {
  97. [self finish];
  98. #ifndef EXTENSION
  99. [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
  100. #endif
  101. }
  102. #pragma --------------------------------------------------------------------------------------------
  103. #pragma mark ===== Server =====
  104. #pragma --------------------------------------------------------------------------------------------
  105. - (void)checkServer:(NSString *)serverUrl success:(void (^)(void))success failure:(void (^)(NSString *message, NSInteger errorCode))failure
  106. {
  107. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  108. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  109. [communication setUserAgent:[CCUtility getUserAgent]];
  110. [communication checkServer:serverUrl onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  111. success();
  112. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  113. NSString *message;
  114. NSInteger errorCode = response.statusCode;
  115. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  116. errorCode = error.code;
  117. // Error
  118. if (errorCode == 503)
  119. message = NSLocalizedString(@"_server_error_retry_", nil);
  120. else
  121. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  122. failure(message, errorCode);
  123. }];
  124. }
  125. - (void)serverStatus:(NSString *)serverUrl success:(void(^)(NSString *serverProductName, NSInteger versionMajor, NSInteger versionMicro, NSInteger versionMinor))success failure:(void (^)(NSString *message, NSInteger errorCode))failure
  126. {
  127. NSString *urlTest = [serverUrl stringByAppendingString:k_serverStatus];
  128. // Remove stored cookies
  129. NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
  130. for (NSHTTPCookie *cookie in [storage cookies])
  131. {
  132. [storage deleteCookie:cookie];
  133. }
  134. NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlTest] cachePolicy:0 timeoutInterval:20.0];
  135. [request addValue:[CCUtility getUserAgent] forHTTPHeaderField:@"User-Agent"];
  136. [request addValue:@"true" forHTTPHeaderField:@"OCS-APIRequest"];
  137. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  138. NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self.delegate delegateQueue:nil];
  139. NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler: ^(NSData *data, NSURLResponse *response, NSError *error) {
  140. dispatch_sync(dispatch_get_main_queue(), ^{
  141. if (error) {
  142. NSString *message;
  143. NSInteger errorCode;
  144. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
  145. errorCode = httpResponse.statusCode;
  146. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  147. errorCode = error.code;
  148. // Error
  149. if (errorCode == 503)
  150. message = NSLocalizedString(@"_server_error_retry_", nil);
  151. else
  152. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  153. failure(message, errorCode);
  154. } else {
  155. NSString *serverProductName = @"";
  156. NSString *serverVersion = @"0.0.0";
  157. NSString *serverVersionString = @"0.0.0";
  158. NSInteger versionMajor = 0;
  159. NSInteger versionMicro = 0;
  160. NSInteger versionMinor = 0;
  161. NSError *error;
  162. NSDictionary *jsongParsed = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
  163. if (error) {
  164. failure(error.description, error.code);
  165. return;
  166. }
  167. serverProductName = [[jsongParsed valueForKey:@"productname"] lowercaseString];
  168. serverVersion = [jsongParsed valueForKey:@"version"];
  169. serverVersionString = [jsongParsed valueForKey:@"versionstring"];
  170. NSArray *arrayVersion = [serverVersionString componentsSeparatedByString:@"."];
  171. if (arrayVersion.count == 1) {
  172. versionMajor = [arrayVersion[0] integerValue];
  173. } else if (arrayVersion.count == 2) {
  174. versionMajor = [arrayVersion[0] integerValue];
  175. versionMinor = [arrayVersion[1] integerValue];
  176. } else if (arrayVersion.count >= 3) {
  177. versionMajor = [arrayVersion[0] integerValue];
  178. versionMinor = [arrayVersion[1] integerValue];
  179. versionMicro = [arrayVersion[2] integerValue];
  180. }
  181. success(serverProductName, versionMajor, versionMicro, versionMinor);
  182. }
  183. });
  184. }];
  185. [task resume];
  186. }
  187. #pragma --------------------------------------------------------------------------------------------
  188. #pragma mark ===== download =====
  189. #pragma --------------------------------------------------------------------------------------------
  190. - (NSURLSessionTask *)downloadFileNameServerUrl:(NSString *)fileNameServerUrl fileNameLocalPath:(NSString *)fileNameLocalPath communication:(OCCommunication *)communication success:(void (^)(int64_t length, NSString *etag, NSDate *date))success failure:(void (^)(NSString *message, NSInteger errorCode))failure
  191. {
  192. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  193. [communication setUserAgent:[CCUtility getUserAgent]];
  194. NSURLSessionTask *sessionTask = [communication downloadFileSession:fileNameServerUrl toDestiny:fileNameLocalPath defaultPriority:YES onCommunication:communication progress:^(NSProgress *progress) {
  195. //float percent = roundf (progress.fractionCompleted * 100);
  196. } successRequest:^(NSURLResponse *response, NSURL *filePath) {
  197. int64_t totalUnitCount = 0;
  198. NSDate *date = [NSDate date];
  199. NSDateFormatter *dateFormatter = [NSDateFormatter new];
  200. NSLocale *enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
  201. [dateFormatter setLocale:enUSPOSIXLocale];
  202. [dateFormatter setDateFormat:@"EEE, dd MMM y HH:mm:ss zzz"];
  203. NSError *error;
  204. NSDictionary *fields = [(NSHTTPURLResponse*)response allHeaderFields];
  205. NSString *contentLength = [fields objectForKey:@"Content-Length"];
  206. if(contentLength) {
  207. totalUnitCount = (int64_t) [contentLength longLongValue];
  208. }
  209. NSString *dateString = [fields objectForKey:@"Date"];
  210. if (dateString) {
  211. if (![dateFormatter getObjectValue:&date forString:dateString range:nil error:&error]) {
  212. date = [NSDate date];
  213. }
  214. } else {
  215. date = [NSDate date];
  216. }
  217. NSString *etag = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-ETag"]];
  218. if (etag == nil) {
  219. failure(@"Internal error", k_CCErrorInternalError);
  220. } else {
  221. success(totalUnitCount, etag, date);
  222. }
  223. } failureRequest:^(NSURLResponse *response, NSError *error) {
  224. NSString *message;
  225. NSInteger errorCode;
  226. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
  227. errorCode = httpResponse.statusCode;
  228. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  229. errorCode = error.code;
  230. // Error
  231. if (errorCode == 503)
  232. message = NSLocalizedString(@"_server_error_retry_", nil);
  233. else
  234. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  235. failure(message, errorCode);
  236. }];
  237. return sessionTask;
  238. }
  239. - (NSURLSessionTask *)downloadFile:(NSString *)url fileNameLocalPath:(NSString *)fileNameLocalPath success:(void (^)())success failure:(void (^)(NSString *message, NSInteger errorCode))failure
  240. {
  241. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  242. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  243. [communication setUserAgent:[CCUtility getUserAgent]];
  244. NSURLSessionTask *sessionTask = [communication downloadFileSession:url toDestiny:fileNameLocalPath defaultPriority:YES onCommunication:communication progress:^(NSProgress *progress) {
  245. //float percent = roundf (progress.fractionCompleted * 100);
  246. } successRequest:^(NSURLResponse *response, NSURL *filePath) {
  247. success();
  248. } failureRequest:^(NSURLResponse *response, NSError *error) {
  249. NSString *message;
  250. NSInteger errorCode;
  251. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
  252. errorCode = httpResponse.statusCode;
  253. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  254. errorCode = error.code;
  255. // Error
  256. if (errorCode == 503)
  257. message = NSLocalizedString(@"_server_error_retry_", nil);
  258. else
  259. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  260. failure(message, errorCode);
  261. }];
  262. return sessionTask;
  263. }
  264. #pragma --------------------------------------------------------------------------------------------
  265. #pragma mark ===== upload =====
  266. #pragma --------------------------------------------------------------------------------------------
  267. - (NSURLSessionTask *)uploadFileNameServerUrl:(NSString *)fileNameServerUrl fileNameLocalPath:(NSString *)fileNameLocalPath communication:(OCCommunication *)communication success:(void(^)(NSString *fileID, NSString *etag, NSDate *date))success failure:(void (^)(NSString *message, NSInteger errorCode))failure
  268. {
  269. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  270. [communication setUserAgent:[CCUtility getUserAgent]];
  271. NSURLSessionTask *sessionTask = [communication uploadFileSession:fileNameLocalPath toDestiny:fileNameServerUrl onCommunication:communication progress:^(NSProgress *progress) {
  272. //float percent = roundf (progress.fractionCompleted * 100);
  273. } successRequest:^(NSURLResponse *response, NSString *redirectedServer) {
  274. NSDictionary *fields = [(NSHTTPURLResponse*)response allHeaderFields];
  275. NSString *fileID = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-FileId"]];
  276. NSString *etag = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-ETag"]];
  277. NSDate *date = [CCUtility dateEnUsPosixFromCloud:[fields objectForKey:@"Date"]];
  278. success(fileID, etag, date);
  279. } failureRequest:^(NSURLResponse *response, NSString *redirectedServer, NSError *error) {
  280. NSString *message;
  281. NSInteger errorCode;
  282. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
  283. errorCode = httpResponse.statusCode;
  284. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  285. errorCode = error.code;
  286. // Error
  287. if (errorCode == 503)
  288. message = NSLocalizedString(@"_server_error_retry_", nil);
  289. else
  290. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  291. failure(message, errorCode);
  292. } failureBeforeRequest:^(NSError *error) {
  293. failure(@"", error.code);
  294. }];
  295. return sessionTask;
  296. }
  297. #pragma --------------------------------------------------------------------------------------------
  298. #pragma mark ===== downloadThumbnail / downloadPreview =====
  299. #pragma --------------------------------------------------------------------------------------------
  300. /*
  301. - (void)downloadThumbnailWithMetadata:(tableMetadata*)metadata withWidth:(CGFloat)width andHeight:(CGFloat)height completion:(void (^)(NSString *message, NSInteger errorCode))completion
  302. {
  303. NSString *file = [NSString stringWithFormat:@"%@/%@.ico", [CCUtility getDirectoryProviderStorageFileID:metadata.fileID], metadata.fileNameView];
  304. if ([[NSFileManager defaultManager] fileExistsAtPath:file]) {
  305. completion(nil, 0);
  306. } else {
  307. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  308. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  309. [communication setUserAgent:[CCUtility getUserAgent]];
  310. [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) {
  311. [thumbnail writeToFile:file atomically:YES];
  312. completion(nil, 0);
  313. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  314. NSString *message;
  315. NSInteger errorCode = response.statusCode;
  316. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  317. errorCode = error.code;
  318. // Error
  319. if (errorCode == 503)
  320. message = NSLocalizedString(@"_server_error_retry_", nil);
  321. else
  322. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  323. completion(message, errorCode);
  324. }];
  325. }
  326. }
  327. */
  328. - (void)downloadPreviewTrashWithFileID:(NSString *)fileID fileName:(NSString *)fileName account:(NSString *)account completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  329. {
  330. NSString *file = [NSString stringWithFormat:@"%@/%@.ico", [CCUtility getDirectoryProviderStorageFileID:fileID], fileName];
  331. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  332. if (tableAccount == nil) {
  333. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  334. }
  335. if ([[NSFileManager defaultManager] fileExistsAtPath:file]) {
  336. completion(account, nil, 0);
  337. } else {
  338. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  339. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  340. [communication setUserAgent:[CCUtility getUserAgent]];
  341. [communication getRemotePreviewTrashByServer:tableAccount.url ofFileID:fileID onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSData *preview, NSString *redirectedServer) {
  342. [preview writeToFile:file atomically:YES];
  343. completion(account, nil, 0);
  344. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  345. NSString *message;
  346. NSInteger errorCode = response.statusCode;
  347. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  348. errorCode = error.code;
  349. // Error
  350. if (errorCode == 503)
  351. message = NSLocalizedString(@"_server_error_retry_", nil);
  352. else
  353. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  354. completion(account, message, errorCode);
  355. }];
  356. }
  357. }
  358. - (void)downloadPreviewWithMetadata:(tableMetadata*)metadata withWidth:(CGFloat)width andHeight:(CGFloat)height completion:(void (^)(NSString *message, NSInteger errorCode))completion
  359. {
  360. NSString *file = [NSString stringWithFormat:@"%@/%@.ico", [CCUtility getDirectoryProviderStorageFileID:metadata.fileID], metadata.fileNameView];
  361. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", metadata.account]];
  362. if (tableAccount == nil) {
  363. completion(NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  364. }
  365. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  366. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  367. [communication setUserAgent:[CCUtility getUserAgent]];
  368. [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) {
  369. [preview writeToFile:file atomically:YES];
  370. completion(nil, 0);
  371. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  372. NSString *message;
  373. NSInteger errorCode = response.statusCode;
  374. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  375. errorCode = error.code;
  376. // Error
  377. if (errorCode == 503)
  378. message = NSLocalizedString(@"_server_error_retry_", nil);
  379. else
  380. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  381. completion(message, errorCode);
  382. }];
  383. }
  384. #pragma --------------------------------------------------------------------------------------------
  385. #pragma mark ===== Read Folder =====
  386. #pragma --------------------------------------------------------------------------------------------
  387. - (void)readFolder:(NSString *)serverUrl depth:(NSString *)depth account:(NSString *)account success:(void(^)(NSString *account, NSArray *metadatas, tableMetadata *metadataFolder))success failure:(void (^)(NSString *account, NSString *message, NSInteger errorCode))failure
  388. {
  389. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  390. if (tableAccount == nil) {
  391. failure(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  392. }
  393. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  394. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  395. [communication setUserAgent:[CCUtility getUserAgent]];
  396. [communication readFolder:serverUrl depth:depth withUserSessionToken:nil onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer, NSString *token) {
  397. // Check items > 0
  398. if ([items count] == 0) {
  399. #ifndef EXTENSION
  400. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  401. [appDelegate messageNotification:@"Server error" description:@"Read Folder WebDAV : [items NULL] please fix" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  402. #endif
  403. failure(account, NSLocalizedString(@"Read Folder WebDAV : [items NULL] please fix", nil), k_CCErrorInternalError);
  404. } else {
  405. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  406. BOOL showHiddenFiles = [CCUtility getShowHiddenFiles];
  407. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:serverUrl account:account];
  408. // directory [0]
  409. OCFileDto *itemDtoFolder = [items objectAtIndex:0];
  410. //NSDate *date = [NSDate dateWithTimeIntervalSince1970:itemDtoDirectory.date];
  411. NSMutableArray *metadatas = [NSMutableArray new];
  412. tableMetadata *metadataFolder = [tableMetadata new];
  413. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  414. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:tableAccount.url];
  415. NSString *serverUrlFolder;
  416. // Metadata . (self Folder)
  417. if ([serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:tableAccount.url]]) {
  418. // root folder
  419. serverUrlFolder = k_serverUrl_root;
  420. metadataFolder = [CCUtility trasformedOCFileToCCMetadata:itemDtoFolder fileName:@"." serverUrl:serverUrlFolder autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:account isFolderEncrypted:isFolderEncrypted];
  421. } else {
  422. serverUrlFolder = [CCUtility deletingLastPathComponentFromServerUrl:serverUrl];
  423. metadataFolder = [CCUtility trasformedOCFileToCCMetadata:itemDtoFolder fileName:[serverUrl lastPathComponent] serverUrl:serverUrlFolder autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:account isFolderEncrypted:isFolderEncrypted];
  424. }
  425. // Add metadata folder
  426. (void)[[NCManageDatabase sharedInstance] addDirectoryWithEncrypted:itemDtoFolder.isEncrypted favorite:itemDtoFolder.isFavorite fileID:itemDtoFolder.ocId permissions:itemDtoFolder.permissions serverUrl:serverUrl account:account];
  427. NSArray *itemsSortedArray = [items sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
  428. NSString *first = [(OCFileDto*)a fileName];
  429. NSString *second = [(OCFileDto*)b fileName];
  430. return [[first lowercaseString] compare:[second lowercaseString]];
  431. }];
  432. for (NSUInteger i=1; i < [itemsSortedArray count]; i++) {
  433. OCFileDto *itemDto = [itemsSortedArray objectAtIndex:i];
  434. NSString *fileName = [itemDto.fileName stringByReplacingOccurrencesOfString:@"/" withString:@""];
  435. // Skip hidden files
  436. if (fileName.length > 0) {
  437. if (!showHiddenFiles && [[fileName substringToIndex:1] isEqualToString:@"."])
  438. continue;
  439. } else {
  440. continue;
  441. }
  442. if (itemDto.isDirectory) {
  443. (void)[[NCManageDatabase sharedInstance] addDirectoryWithEncrypted:itemDto.isEncrypted favorite:itemDto.isFavorite fileID:itemDto.ocId permissions:itemDto.permissions serverUrl:[CCUtility stringAppendServerUrl:serverUrl addFileName:fileName] account:account];
  444. }
  445. [metadatas addObject:[CCUtility trasformedOCFileToCCMetadata:itemDto fileName:itemDto.fileName serverUrl:serverUrl autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:account isFolderEncrypted:isFolderEncrypted]];
  446. }
  447. dispatch_async(dispatch_get_main_queue(), ^{
  448. success(account, metadatas, metadataFolder);
  449. });
  450. });
  451. }
  452. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) {
  453. NSString *message;
  454. NSInteger errorCode = response.statusCode;
  455. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  456. errorCode = error.code;
  457. // Error
  458. if (errorCode == 503)
  459. message = NSLocalizedString(@"_server_error_retry_", nil);
  460. else
  461. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  462. // Request trusted certificated
  463. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  464. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  465. // Activity
  466. [[NCManageDatabase sharedInstance] addActivityClient:serverUrl fileID:@"" action:k_activityDebugActionReadFolder selector:@"" note:[error.userInfo valueForKey:@"NSLocalizedDescription"] type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:tableAccount.url];
  467. failure(account, message, errorCode);
  468. }];
  469. }
  470. #pragma --------------------------------------------------------------------------------------------
  471. #pragma mark ===== ReadFile =====
  472. #pragma --------------------------------------------------------------------------------------------
  473. - (void)readFile:(NSString *)fileName serverUrl:(NSString *)serverUrl account:(NSString *)account success:(void(^)(NSString *account, tableMetadata *metadata))success failure:(void (^)(NSString *account, NSString *message, NSInteger errorCode))failure
  474. {
  475. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  476. if (tableAccount == nil) {
  477. failure(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  478. }
  479. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  480. NSString *fileNamePath;
  481. if (fileName) {
  482. fileNamePath = [NSString stringWithFormat:@"%@/%@", serverUrl, fileName];
  483. } else {
  484. fileName= @".";
  485. fileNamePath = serverUrl;
  486. }
  487. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  488. [communication setUserAgent:[CCUtility getUserAgent]];
  489. [communication readFile:fileNamePath onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  490. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:serverUrl account:account];
  491. if ([items count] > 0) {
  492. tableMetadata *metadata = [tableMetadata new];
  493. OCFileDto *itemDto = [items objectAtIndex:0];
  494. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  495. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:tableAccount.url];
  496. metadata = [CCUtility trasformedOCFileToCCMetadata:itemDto fileName:fileName serverUrl:serverUrl autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:account isFolderEncrypted:isFolderEncrypted];
  497. success(account, metadata);
  498. // BUG 1038 item == 0
  499. } else {
  500. #ifndef EXTENSION
  501. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  502. [appDelegate messageNotification:@"Server error" description:@"Read File WebDAV : [items NULL] please fix" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  503. #endif
  504. failure(account, NSLocalizedString(@"Read File WebDAV : [items NULL] please fix", nil), k_CCErrorInternalError);
  505. }
  506. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  507. NSString *message;
  508. NSInteger errorCode = response.statusCode;
  509. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  510. errorCode = error.code;
  511. // Error
  512. if (errorCode == 503)
  513. message = NSLocalizedString(@"_server_error_retry_", nil);
  514. else
  515. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  516. // Request trusted certificated
  517. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  518. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  519. // Activity
  520. [[NCManageDatabase sharedInstance] addActivityClient:serverUrl fileID:@"" action:k_activityDebugActionReadFolder selector:@"" note:[error.userInfo valueForKey:@"NSLocalizedDescription"] type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:tableAccount.url];
  521. failure(account, message, errorCode);
  522. }];
  523. }
  524. #pragma --------------------------------------------------------------------------------------------
  525. #pragma mark ===== Search =====
  526. #pragma --------------------------------------------------------------------------------------------
  527. - (void)search
  528. {
  529. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  530. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  531. [communication setUserAgent:[CCUtility getUserAgent]];
  532. NSString *path = [_activeUrl stringByAppendingString:k_dav];
  533. NSString *folder = [_metadataNet.serverUrl stringByReplacingOccurrencesOfString:[CCUtility getHomeServerUrlActiveUrl:_activeUrl] withString:@""];
  534. NSString *dateLastModified;
  535. if (_metadataNet.date) {
  536. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  537. NSLocale *enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
  538. [dateFormatter setLocale:enUSPOSIXLocale];
  539. [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZZ"];
  540. dateLastModified = [dateFormatter stringFromDate:_metadataNet.date];
  541. }
  542. [communication search:path folder:folder fileName: [NSString stringWithFormat:@"%%%@%%", _metadataNet.fileName] depth:_metadataNet.depth dateLastModified:dateLastModified contentType:_metadataNet.contentType withUserSessionToken:nil onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer, NSString *token) {
  543. // Test active account
  544. tableAccount *recordAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  545. if (![recordAccount.account isEqualToString:_metadataNet.account]) {
  546. if ([self.delegate respondsToSelector:@selector(searchSuccessFailure:metadatas:message:errorCode:)])
  547. [self.delegate searchSuccessFailure:_metadataNet metadatas:nil message:NSLocalizedString(@"_error_user_not_available_", nil) errorCode:k_CCErrorUserNotAvailble];
  548. [self complete];
  549. return;
  550. }
  551. NSMutableArray *metadatas = [NSMutableArray new];
  552. BOOL showHiddenFiles = [CCUtility getShowHiddenFiles];
  553. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  554. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:_activeUrl];
  555. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  556. for(OCFileDto *itemDto in items) {
  557. NSString *serverUrl;
  558. BOOL isFolderEncrypted;
  559. NSString *fileName = [itemDto.fileName stringByReplacingOccurrencesOfString:@"/" withString:@""];
  560. // Skip hidden files
  561. if (fileName.length > 0) {
  562. if (!showHiddenFiles && [[fileName substringToIndex:1] isEqualToString:@"."])
  563. continue;
  564. } else
  565. continue;
  566. NSRange firstInstance = [itemDto.filePath rangeOfString:[NSString stringWithFormat:@"%@/files/%@", k_dav, _activeUserID]];
  567. NSString *serverPath = [itemDto.filePath substringFromIndex:firstInstance.length+firstInstance.location+1];
  568. if ([serverPath hasSuffix:@"/"]) serverPath = [serverPath substringToIndex:[serverPath length] - 1];
  569. serverUrl = [CCUtility stringAppendServerUrl:[_activeUrl stringByAppendingString:k_webDAV] addFileName:serverPath];
  570. if (itemDto.isDirectory) {
  571. (void)[[NCManageDatabase sharedInstance] addDirectoryWithEncrypted:itemDto.isEncrypted favorite:itemDto.isFavorite fileID:itemDto.ocId permissions:itemDto.permissions serverUrl:[NSString stringWithFormat:@"%@/%@", serverUrl, fileName] account:_metadataNet.account];
  572. }
  573. isFolderEncrypted = [CCUtility isFolderEncrypted:serverUrl account:_metadataNet.account];
  574. [metadatas addObject:[CCUtility trasformedOCFileToCCMetadata:itemDto fileName:itemDto.fileName serverUrl:serverUrl autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:_metadataNet.account isFolderEncrypted:isFolderEncrypted]];
  575. }
  576. dispatch_async(dispatch_get_main_queue(), ^{
  577. if ([self.delegate respondsToSelector:@selector(searchSuccessFailure:metadatas:message:errorCode:)])
  578. [self.delegate searchSuccessFailure:_metadataNet metadatas:metadatas message:nil errorCode:0];
  579. });
  580. });
  581. [self complete];
  582. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) {
  583. NSInteger errorCode = response.statusCode;
  584. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  585. errorCode = error.code;
  586. // Error
  587. if ([self.delegate respondsToSelector:@selector(searchSuccessFailure:metadatas:message:errorCode:)]) {
  588. if (errorCode == 503)
  589. [self.delegate searchSuccessFailure:_metadataNet metadatas:nil message:NSLocalizedString(@"_server_error_retry_", nil) errorCode:errorCode];
  590. else
  591. [self.delegate searchSuccessFailure:_metadataNet metadatas:nil message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  592. }
  593. // Request trusted certificated
  594. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  595. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  596. [self complete];
  597. }];
  598. }
  599. #pragma --------------------------------------------------------------------------------------------
  600. #pragma mark ===== Setting Favorite =====
  601. #pragma --------------------------------------------------------------------------------------------
  602. - (void)settingFavorite:(NSString *)fileName account:(NSString *)account favorite:(BOOL)favorite completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  603. {
  604. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  605. if (tableAccount == nil) {
  606. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  607. }
  608. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  609. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  610. [communication setUserAgent:[CCUtility getUserAgent]];
  611. NSString *server = [tableAccount.url stringByAppendingString:k_dav];
  612. [communication settingFavoriteServer:server andFileOrFolderPath:fileName favorite:favorite withUserSessionToken:nil onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer, NSString *token) {
  613. completion(account, nil, 0);
  614. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) {
  615. NSString *message;
  616. NSInteger errorCode = response.statusCode;
  617. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  618. errorCode = error.code;
  619. // Error
  620. if (errorCode == 503)
  621. message = NSLocalizedString(@"_server_error_retry_", nil);
  622. else
  623. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  624. // Request trusted certificated
  625. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  626. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  627. completion(account, message, errorCode);
  628. }];
  629. }
  630. #pragma --------------------------------------------------------------------------------------------
  631. #pragma mark ===== Listing Favorites =====
  632. #pragma --------------------------------------------------------------------------------------------
  633. - (void)listingFavorites:(NSString *)serverUrl account:(NSString *)account success:(void(^)(NSString *account, NSArray *metadatas))success failure:(void (^)(NSString* account, NSString *message, NSInteger errorCode))failure
  634. {
  635. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  636. if (tableAccount == nil) {
  637. failure(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  638. }
  639. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  640. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  641. [communication setUserAgent:[CCUtility getUserAgent]];
  642. NSString *path = [tableAccount.url stringByAppendingString:k_dav];
  643. NSString *folder = [serverUrl stringByReplacingOccurrencesOfString:[CCUtility getHomeServerUrlActiveUrl:tableAccount.url] withString:@""];
  644. [communication listingFavorites:path folder:folder withUserSessionToken:nil onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer, NSString *token) {
  645. NSMutableArray *metadatas = [NSMutableArray new];
  646. BOOL showHiddenFiles = [CCUtility getShowHiddenFiles];
  647. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  648. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:tableAccount.url];
  649. // Order by fileNamePath
  650. items = [items sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
  651. OCFileDto *record1 = obj1, *record2 = obj2;
  652. NSString *path1 = [[record1.filePath stringByAppendingString:record1.fileName] lowercaseString];
  653. NSString *path2 = [[record2.filePath stringByAppendingString:record2.fileName] lowercaseString];
  654. return [path1 compare:path2];
  655. }];
  656. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  657. for(OCFileDto *itemDto in items) {
  658. NSString *serverUrl;
  659. BOOL isFolderEncrypted;
  660. NSString *fileName = [itemDto.fileName stringByReplacingOccurrencesOfString:@"/" withString:@""];
  661. // Skip hidden files
  662. if (fileName.length > 0) {
  663. if (!showHiddenFiles && [[fileName substringToIndex:1] isEqualToString:@"."])
  664. continue;
  665. } else
  666. continue;
  667. NSRange firstInstance = [itemDto.filePath rangeOfString:[NSString stringWithFormat:@"%@/files/%@", k_dav, tableAccount.userID]];
  668. NSString *serverPath = [itemDto.filePath substringFromIndex:firstInstance.length+firstInstance.location+1];
  669. if ([serverPath hasSuffix:@"/"])
  670. serverPath = [serverPath substringToIndex:[serverPath length] - 1];
  671. serverUrl = [CCUtility stringAppendServerUrl:[tableAccount.url stringByAppendingString:k_webDAV] addFileName:serverPath];
  672. if (itemDto.isDirectory) {
  673. (void)[[NCManageDatabase sharedInstance] addDirectoryWithEncrypted:itemDto.isEncrypted favorite:itemDto.isFavorite fileID:itemDto.ocId permissions:itemDto.permissions serverUrl:[NSString stringWithFormat:@"%@/%@", serverUrl, fileName] account:account];
  674. }
  675. isFolderEncrypted = [CCUtility isFolderEncrypted:serverUrl account:account];
  676. [metadatas addObject:[CCUtility trasformedOCFileToCCMetadata:itemDto fileName:itemDto.fileName serverUrl:serverUrl autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:account isFolderEncrypted:isFolderEncrypted]];
  677. }
  678. dispatch_async(dispatch_get_main_queue(), ^{
  679. success(account, metadatas);
  680. });
  681. });
  682. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) {
  683. NSString *message;
  684. NSInteger errorCode = response.statusCode;
  685. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  686. errorCode = error.code;
  687. // Error
  688. if (errorCode == 503)
  689. message = NSLocalizedString(@"_server_error_retry_", nil);
  690. else
  691. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  692. // Request trusted certificated
  693. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  694. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  695. // Activity
  696. [[NCManageDatabase sharedInstance] addActivityClient:serverUrl fileID:@"" action:k_activityDebugActionListingFavorites selector:@"" note:[error.userInfo valueForKey:@"NSLocalizedDescription"] type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:tableAccount.url];
  697. failure(account, message, errorCode);
  698. }];
  699. }
  700. #pragma --------------------------------------------------------------------------------------------
  701. #pragma mark ===== Create Folder =====
  702. #pragma --------------------------------------------------------------------------------------------
  703. - (void)createFolder:(NSString *)fileName serverUrl:(NSString *)serverUrl account:(NSString *)account success:(void(^)(NSString *account, NSString *fileID, NSDate *date))success failure:(void (^)(NSString *account, NSString *message, NSInteger errorCode))failure
  704. {
  705. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  706. if (tableAccount == nil) {
  707. failure(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  708. }
  709. NSString *path = [NSString stringWithFormat:@"%@/%@", serverUrl, fileName];
  710. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  711. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:tableAccount.url];
  712. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  713. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  714. [communication setUserAgent:[CCUtility getUserAgent]];
  715. [communication createFolder:path onCommunication:communication withForbiddenCharactersSupported:YES successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  716. NSDictionary *fields = [response allHeaderFields];
  717. NSString *fileID = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-FileId"]];
  718. NSDate *date = [CCUtility dateEnUsPosixFromCloud:[fields objectForKey:@"Date"]];
  719. success(account, fileID, date);
  720. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  721. NSString *message;
  722. if (([fileName isEqualToString:autoUploadFileName] && [serverUrl isEqualToString:autoUploadDirectory]))
  723. message = nil;
  724. else
  725. message = [CCError manageErrorOC:response.statusCode error:error];
  726. NSInteger errorCode = response.statusCode;
  727. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  728. errorCode = error.code;
  729. // Request trusted certificated
  730. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  731. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  732. // Activity
  733. [[NCManageDatabase sharedInstance] addActivityClient:path fileID:@"" action:k_activityDebugActionCreateFolder selector:@"" note:NSLocalizedString(@"_not_possible_create_folder_", nil) type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:tableAccount.url];
  734. failure(account, message, errorCode);
  735. } errorBeforeRequest:^(NSError *error) {
  736. NSString *message;
  737. if (([fileName isEqualToString:autoUploadFileName] && [serverUrl isEqualToString:autoUploadDirectory]))
  738. message = nil;
  739. else {
  740. if (error.code == OCErrorForbidenCharacters)
  741. message = NSLocalizedString(@"_forbidden_characters_from_server_", nil);
  742. else
  743. message = NSLocalizedString(@"_unknow_response_server_", nil);
  744. }
  745. failure(account, message, error.code);
  746. }];
  747. }
  748. #pragma --------------------------------------------------------------------------------------------
  749. #pragma mark ===== Delete =====
  750. #pragma --------------------------------------------------------------------------------------------
  751. - (void)deleteFileOrFolder:(NSString *)path account:(NSString *)account completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  752. {
  753. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  754. if (tableAccount == nil) {
  755. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  756. }
  757. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  758. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  759. [communication setUserAgent:[CCUtility getUserAgent]];
  760. [communication deleteFileOrFolder:path onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  761. completion(account, nil, 0);
  762. } failureRquest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  763. NSString *message;
  764. NSInteger errorCode = response.statusCode;
  765. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  766. errorCode = error.code;
  767. // Error
  768. if (errorCode == 503)
  769. message = NSLocalizedString(@"_server_error_retry_", nil);
  770. else
  771. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  772. // Request trusted certificated
  773. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  774. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  775. // Activity
  776. [[NCManageDatabase sharedInstance] addActivityClient:_activeUrl fileID:@"" action:k_activityDebugActionDeleteFileFolder selector:@"" note:[error.userInfo valueForKey:@"NSLocalizedDescription"] type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:tableAccount.url];
  777. completion(account, message, errorCode);
  778. }];
  779. }
  780. #pragma --------------------------------------------------------------------------------------------
  781. #pragma mark ===== Move =====
  782. #pragma --------------------------------------------------------------------------------------------
  783. - (void)moveFileOrFolder:(NSString *)fileName fileNameTo:(NSString *)fileNameTo account:(NSString *)account success:(void (^)(NSString *account))success failure:(void (^)(NSString *account, NSString *message, NSInteger errorCode))failure
  784. {
  785. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  786. if (tableAccount == nil) {
  787. failure(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  788. }
  789. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  790. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  791. [communication setUserAgent:[CCUtility getUserAgent]];
  792. [communication moveFileOrFolder:fileName toDestiny:fileNameTo onCommunication:communication withForbiddenCharactersSupported:YES successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  793. success(account);
  794. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  795. NSInteger errorCode = response.statusCode;
  796. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  797. errorCode = error.code;
  798. NSString *message = [CCError manageErrorOC:response.statusCode error:error];
  799. failure(account, message, error.code);
  800. } errorBeforeRequest:^(NSError *error) {
  801. NSString *message;
  802. if (error.code == OCErrorMovingTheDestinyAndOriginAreTheSame) {
  803. message = NSLocalizedString(@"_error_folder_destiny_is_the_same_", nil);
  804. } else if (error.code == OCErrorMovingFolderInsideHimself) {
  805. message = NSLocalizedString(@"_error_folder_destiny_is_the_same_", nil);
  806. } else if (error.code == OCErrorMovingDestinyNameHaveForbiddenCharacters) {
  807. message = NSLocalizedString(@"_forbidden_characters_from_server_", nil);
  808. } else {
  809. message = NSLocalizedString(@"_unknow_response_server_", nil);
  810. }
  811. failure(account, message, error.code);
  812. }];
  813. }
  814. #pragma --------------------------------------------------------------------------------------------
  815. #pragma mark ===== Shared =====
  816. #pragma --------------------------------------------------------------------------------------------
  817. - (void)readShareServer:(NSString *)account completion:(void (^)(NSString *account, NSArray *items, NSString *message, NSInteger errorCode))completion
  818. {
  819. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  820. if (tableAccount == nil) {
  821. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  822. }
  823. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  824. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  825. [communication setUserAgent:[CCUtility getUserAgent]];
  826. [communication readSharedByServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  827. completion(account, items, nil, 0);
  828. } failureRequest :^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  829. NSString *message = @"";
  830. NSInteger errorCode = response.statusCode;
  831. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  832. errorCode = error.code;
  833. // Error
  834. if (errorCode == 503) {
  835. message = NSLocalizedString(@"_server_error_retry_", nil);
  836. } else {
  837. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  838. }
  839. // Request trusted certificated
  840. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  841. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  842. completion(account, nil, message, errorCode);
  843. }];
  844. }
  845. /*
  846. - (void)readShareServer
  847. {
  848. #ifndef EXTENSION
  849. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  850. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  851. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  852. [communication setUserAgent:[CCUtility getUserAgent]];
  853. [communication readSharedByServer:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  854. // Test active account
  855. tableAccount *recordAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  856. if (![recordAccount.account isEqualToString:_metadataNet.account]) {
  857. if ([self.delegate respondsToSelector:@selector(shareFailure:message:errorCode:)])
  858. [self.delegate shareFailure:_metadataNet message:NSLocalizedString(@"_error_user_not_available_", nil) errorCode:k_CCErrorUserNotAvailble];
  859. [self complete];
  860. return;
  861. }
  862. BOOL openWindow = NO;
  863. [appDelegate.sharesID removeAllObjects];
  864. if ([recordAccount.account isEqualToString:_metadataNet.account]) {
  865. for (OCSharedDto *item in items)
  866. [appDelegate.sharesID setObject:item forKey:[@(item.idRemoteShared) stringValue]];
  867. if ([_metadataNet.selector isEqual:selectorOpenWindowShare]) openWindow = YES;
  868. if ([_metadataNet.action isEqual:actionUpdateShare]) openWindow = YES;
  869. if ([_metadataNet.action isEqual:actionShare]) openWindow = YES;
  870. if ([_metadataNet.action isEqual:actionShareWith]) openWindow = YES;
  871. }
  872. if([self.delegate respondsToSelector:@selector(readSharedSuccess:items:openWindow:)])
  873. [self.delegate readSharedSuccess:_metadataNet items:appDelegate.sharesID openWindow:openWindow];
  874. [self complete];
  875. } failureRequest :^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  876. NSInteger errorCode = response.statusCode;
  877. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  878. errorCode = error.code;
  879. // Error
  880. if ([self.delegate respondsToSelector:@selector(shareFailure:message:errorCode:)]) {
  881. if (errorCode == 503)
  882. [self.delegate shareFailure:_metadataNet message:NSLocalizedString(@"_server_error_retry_", nil) errorCode:errorCode];
  883. else
  884. [self.delegate shareFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  885. }
  886. // Request trusted certificated
  887. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  888. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  889. [self complete];
  890. }];
  891. #endif
  892. }
  893. */
  894. - (void)share
  895. {
  896. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  897. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  898. [communication setUserAgent:[CCUtility getUserAgent]];
  899. [communication shareFileOrFolderByServer:[_activeUrl stringByAppendingString:@"/"] andFileOrFolderPath:[_metadataNet.fileName encodeString:NSUTF8StringEncoding] andPassword:[_metadataNet.password encodeString:NSUTF8StringEncoding] andPermission:_metadataNet.sharePermission andHideDownload:_metadataNet.hideDownload onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *token, NSString *redirectedServer) {
  900. //[self readShareServer];
  901. } failureRequest :^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  902. NSInteger errorCode = response.statusCode;
  903. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  904. errorCode = error.code;
  905. // Error
  906. if ([self.delegate respondsToSelector:@selector(shareFailure:message:errorCode:)]) {
  907. if (errorCode == 503)
  908. [self.delegate shareFailure:_metadataNet message:NSLocalizedString(@"_server_error_retry_", nil) errorCode:errorCode];
  909. else
  910. [self.delegate shareFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  911. }
  912. // Request trusted certificated
  913. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  914. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  915. [self complete];
  916. }];
  917. }
  918. // * @param shareeType -> NSInteger: to set the type of sharee (user/group/federated)
  919. - (void)shareWith
  920. {
  921. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  922. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  923. [communication setUserAgent:[CCUtility getUserAgent]];
  924. [communication shareWith:_metadataNet.share shareeType:_metadataNet.shareeType inServer:[_activeUrl stringByAppendingString:@"/"] andFileOrFolderPath:[_metadataNet.fileName encodeString:NSUTF8StringEncoding] andPermissions:_metadataNet.sharePermission onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  925. //[self readShareServer];
  926. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  927. NSInteger errorCode = response.statusCode;
  928. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  929. errorCode = error.code;
  930. // Error
  931. if ([self.delegate respondsToSelector:@selector(shareFailure:message:errorCode:)]) {
  932. if (errorCode == 503)
  933. [self.delegate shareFailure:_metadataNet message:NSLocalizedString(@"_server_error_retry_", nil) errorCode:errorCode];
  934. else
  935. [self.delegate shareFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  936. }
  937. // Request trusted certificated
  938. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  939. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  940. [self complete];
  941. }];
  942. }
  943. - (void)updateShare
  944. {
  945. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  946. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  947. [communication setUserAgent:[CCUtility getUserAgent]];
  948. [communication updateShare:[_metadataNet.share intValue] ofServerPath:[_activeUrl stringByAppendingString:@"/"] withPasswordProtect:[_metadataNet.password encodeString:NSUTF8StringEncoding] andExpirationTime:_metadataNet.expirationTime andPermissions:_metadataNet.sharePermission andHideDownload:_metadataNet.hideDownload onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  949. //[self readShareServer];
  950. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  951. #ifndef EXTENSION
  952. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  953. [appDelegate messageNotification:@"_error_" description:[CCError manageErrorOC:response.statusCode error:error] visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  954. #endif
  955. NSInteger errorCode = response.statusCode;
  956. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  957. errorCode = error.code;
  958. // Error
  959. if ([self.delegate respondsToSelector:@selector(shareFailure:message:errorCode:)]) {
  960. if (errorCode == 503)
  961. [self.delegate shareFailure:_metadataNet message:NSLocalizedString(@"_server_error_retry_", nil) errorCode:errorCode];
  962. else
  963. [self.delegate shareFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  964. }
  965. // Request trusted certificated
  966. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  967. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  968. [self complete];
  969. }];
  970. }
  971. - (void)unShare
  972. {
  973. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  974. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  975. [communication setUserAgent:[CCUtility getUserAgent]];
  976. [communication unShareFileOrFolderByServer:[_activeUrl stringByAppendingString:@"/"] andIdRemoteShared:[_metadataNet.share intValue] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  977. if([self.delegate respondsToSelector:@selector(unShareSuccess:)])
  978. [self.delegate unShareSuccess:_metadataNet];
  979. [self complete];
  980. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  981. #ifndef EXTENSION
  982. [(AppDelegate *)[[UIApplication sharedApplication] delegate] messageNotification:@"_error_" description:[CCError manageErrorOC:response.statusCode error:error] visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  983. #endif
  984. NSInteger errorCode = response.statusCode;
  985. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  986. errorCode = error.code;
  987. // Error
  988. if ([self.delegate respondsToSelector:@selector(shareFailure:message:errorCode:)]) {
  989. if (errorCode == 503)
  990. [self.delegate shareFailure:_metadataNet message:NSLocalizedString(@"_server_error_retry_", nil) errorCode:errorCode];
  991. else
  992. [self.delegate shareFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  993. }
  994. // Request trusted certificated
  995. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  996. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  997. [self complete];
  998. }];
  999. }
  1000. - (void)getUserAndGroup
  1001. {
  1002. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1003. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  1004. [communication setUserAgent:[CCUtility getUserAgent]];
  1005. [communication searchUsersAndGroupsWith:_metadataNet.optionAny forPage:1 with:50 ofServer:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *itemList, NSString *redirectedServer) {
  1006. if([self.delegate respondsToSelector:@selector(getUserAndGroupSuccess:items:)])
  1007. [self.delegate getUserAndGroupSuccess:_metadataNet items:itemList];
  1008. [self complete];
  1009. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1010. NSInteger errorCode = response.statusCode;
  1011. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1012. errorCode = error.code;
  1013. // Error
  1014. if ([self.delegate respondsToSelector:@selector(getUserAndGroupFailure:message:errorCode:)]) {
  1015. if (errorCode == 503)
  1016. [self.delegate getUserAndGroupFailure:_metadataNet message:NSLocalizedString(@"_server_error_retry_", nil) errorCode:errorCode];
  1017. else
  1018. [self.delegate getUserAndGroupFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1019. }
  1020. // Request trusted certificated
  1021. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  1022. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1023. [self complete];
  1024. }];
  1025. }
  1026. - (void)getSharePermissionsFile
  1027. {
  1028. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1029. NSString *fileName = [NSString stringWithFormat:@"%@/%@", _metadataNet.serverUrl, _metadataNet.fileName];
  1030. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  1031. [communication setUserAgent:[CCUtility getUserAgent]];
  1032. [communication getSharePermissionsFile:fileName onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *permissions, NSString *redirectedServer) {
  1033. // Test active account
  1034. tableAccount *recordAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  1035. if (![recordAccount.account isEqualToString:_metadataNet.account]) {
  1036. if ([self.delegate respondsToSelector:@selector(getSharePermissionsFileFailure:message:errorCode:)])
  1037. [self.delegate getSharePermissionsFileFailure:_metadataNet message:NSLocalizedString(@"_error_user_not_available_", nil) errorCode:k_CCErrorUserNotAvailble];
  1038. [self complete];
  1039. return;
  1040. }
  1041. if([self.delegate respondsToSelector:@selector(getSharePermissionsFileSuccess:permissions:)])
  1042. [self.delegate getSharePermissionsFileSuccess:_metadataNet permissions:permissions];
  1043. [self complete];
  1044. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1045. NSInteger errorCode = response.statusCode;
  1046. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1047. errorCode = error.code;
  1048. // Error
  1049. if ([self.delegate respondsToSelector:@selector(getSharePermissionsFileFailure:message:errorCode:)]) {
  1050. if (errorCode == 503)
  1051. [self.delegate getSharePermissionsFileFailure:_metadataNet message:NSLocalizedString(@"_server_error_retry_", nil) errorCode:errorCode];
  1052. else
  1053. [self.delegate getSharePermissionsFileFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1054. }
  1055. // Request trusted certificated
  1056. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  1057. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1058. [self complete];
  1059. }];
  1060. }
  1061. #pragma --------------------------------------------------------------------------------------------
  1062. #pragma mark ===== Activity =====
  1063. #pragma --------------------------------------------------------------------------------------------
  1064. - (void)getActivityServer:(NSString *)account success:(void(^)(NSString *account, NSArray *listOfActivity))success failure:(void (^)(NSString *account, NSString *message, NSInteger errorCode))failure
  1065. {
  1066. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1067. if (tableAccount == nil) {
  1068. failure(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1069. }
  1070. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1071. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1072. [communication setUserAgent:[CCUtility getUserAgent]];
  1073. [communication getActivityServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfActivity, NSString *redirectedServer) {
  1074. success(account, listOfActivity);
  1075. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1076. NSString *message;
  1077. NSInteger errorCode = response.statusCode;
  1078. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1079. errorCode = error.code;
  1080. // Error
  1081. if (errorCode == 503)
  1082. message = NSLocalizedString(@"_server_error_retry_", nil);
  1083. else
  1084. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1085. failure(account, message, errorCode);
  1086. }];
  1087. }
  1088. #pragma --------------------------------------------------------------------------------------------
  1089. #pragma mark ===== External Sites =====
  1090. #pragma --------------------------------------------------------------------------------------------
  1091. - (void)getExternalSitesServer:(NSString *)account completion:(void (^)(NSString *account, NSArray *listOfExternalSites, NSString *message, NSInteger errorCode))completion
  1092. {
  1093. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1094. if (tableAccount == nil) {
  1095. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1096. }
  1097. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1098. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1099. [communication setUserAgent:[CCUtility getUserAgent]];
  1100. [communication getExternalSitesServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfExternalSites, NSString *redirectedServer) {
  1101. completion(account, listOfExternalSites, nil, 0);
  1102. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1103. NSString *message = @"";
  1104. NSInteger errorCode = response.statusCode;
  1105. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1106. errorCode = error.code;
  1107. // Error
  1108. if (errorCode == 503) {
  1109. message = NSLocalizedString(@"_server_error_retry_", nil);
  1110. } else {
  1111. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1112. }
  1113. // Request trusted certificated
  1114. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  1115. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1116. completion(account, nil, message, errorCode);
  1117. }];
  1118. }
  1119. #pragma --------------------------------------------------------------------------------------------
  1120. #pragma mark ===== Middleware Ping =====
  1121. #pragma --------------------------------------------------------------------------------------------
  1122. /*
  1123. - (void)middlewarePing
  1124. {
  1125. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1126. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  1127. [communication setUserAgent:[CCUtility getUserAgent]];
  1128. [communication getMiddlewarePing:_metadataNet.serverUrl onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfExternalSites, NSString *redirectedServer) {
  1129. [self complete];
  1130. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1131. NSInteger errorCode = response.statusCode;
  1132. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1133. errorCode = error.code;
  1134. // Error
  1135. if ([self.delegate respondsToSelector:@selector(getExternalSitesServerFailure:message:errorCode:)]) {
  1136. if (errorCode == 503)
  1137. [self.delegate getExternalSitesServerFailure:_metadataNet message:NSLocalizedString(@"_server_error_retry_", nil) errorCode:errorCode];
  1138. else
  1139. [self.delegate getExternalSitesServerFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1140. }
  1141. // Request trusted certificated
  1142. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  1143. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1144. [self complete];
  1145. }];
  1146. }
  1147. */
  1148. #pragma --------------------------------------------------------------------------------------------
  1149. #pragma mark ===== Notification =====
  1150. #pragma --------------------------------------------------------------------------------------------
  1151. - (void)getNotificationServer:(NSString *)account completion:(void (^)(NSString *account, NSArray *listOfNotifications, NSString *message, NSInteger errorCode))completion
  1152. {
  1153. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1154. if (tableAccount == nil) {
  1155. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1156. }
  1157. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1158. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1159. [communication setUserAgent:[CCUtility getUserAgent]];
  1160. [communication getNotificationServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfNotifications, NSString *redirectedServer) {
  1161. completion(account, listOfNotifications, nil, 0);
  1162. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1163. NSString *message = @"";
  1164. NSInteger errorCode = response.statusCode;
  1165. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1166. errorCode = error.code;
  1167. // Error
  1168. if (errorCode == 503) {
  1169. message = NSLocalizedString(@"_server_error_retry_", nil);
  1170. } else {
  1171. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1172. }
  1173. // Request trusted certificated
  1174. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  1175. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1176. // Activity
  1177. [[NCManageDatabase sharedInstance] addActivityClient:_activeUrl fileID:@"" action:k_activityDebugActionGetNotification selector:@"" note:[error.userInfo valueForKey:@"NSLocalizedDescription"] type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:@""];
  1178. completion(account, nil, message, errorCode);
  1179. }];
  1180. }
  1181. - (void)setNotificationServer
  1182. {
  1183. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1184. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  1185. [communication setUserAgent:[CCUtility getUserAgent]];
  1186. NSString *type = _metadataNet.optionAny;
  1187. [communication setNotificationServer:_metadataNet.serverUrl type:type onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1188. // Test active account
  1189. tableAccount *recordAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  1190. if (![recordAccount.account isEqualToString:_metadataNet.account]) {
  1191. if ([self.delegate respondsToSelector:@selector(setNotificationServerSuccessFailure:message:errorCode:)])
  1192. [self.delegate setNotificationServerSuccessFailure:_metadataNet message:NSLocalizedString(@"_error_user_not_available_", nil) errorCode:k_CCErrorUserNotAvailble];
  1193. [self complete];
  1194. return;
  1195. }
  1196. if ([self.delegate respondsToSelector:@selector(setNotificationServerSuccessFailure:message:errorCode:)])
  1197. [self.delegate setNotificationServerSuccessFailure:_metadataNet message:nil errorCode:0];
  1198. [self complete];
  1199. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1200. NSInteger errorCode = response.statusCode;
  1201. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1202. errorCode = error.code;
  1203. // Error
  1204. if ([self.delegate respondsToSelector:@selector(setNotificationServerSuccessFailure:message:errorCode:)]) {
  1205. if (errorCode == 503)
  1206. [self.delegate setNotificationServerSuccessFailure:_metadataNet message:NSLocalizedString(@"_server_error_retry_", nil) errorCode:errorCode];
  1207. else
  1208. [self.delegate setNotificationServerSuccessFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1209. }
  1210. // Request trusted certificated
  1211. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  1212. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1213. [self complete];
  1214. }];
  1215. }
  1216. #pragma --------------------------------------------------------------------------------------------
  1217. #pragma mark ===== Push Notification =====
  1218. #pragma --------------------------------------------------------------------------------------------
  1219. - (void)subscribingPushNotificationServer:(NSString *)url pushToken:(NSString *)pushToken Hash:(NSString *)pushTokenHash devicePublicKey:(NSString *)devicePublicKey success:(void(^)(NSString *deviceIdentifier, NSString *deviceIdentifierSignature, NSString *publicKey))success failure:(void (^)(NSString *message, NSInteger errorCode))failure
  1220. {
  1221. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1222. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  1223. [communication setUserAgent:[CCUtility getUserAgent]];
  1224. devicePublicKey = [CCUtility URLEncodeStringFromString:devicePublicKey];
  1225. [communication subscribingNextcloudServerPush:url pushTokenHash:pushTokenHash devicePublicKey:devicePublicKey proxyServerPath: [NCBrandOptions sharedInstance].pushNotificationServerProxy onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *publicKey, NSString *deviceIdentifier, NSString *signature, NSString *redirectedServer) {
  1226. deviceIdentifier = [CCUtility URLEncodeStringFromString:deviceIdentifier];
  1227. signature = [CCUtility URLEncodeStringFromString:signature];
  1228. publicKey = [CCUtility URLEncodeStringFromString:publicKey];
  1229. [communication subscribingPushProxy:[NCBrandOptions sharedInstance].pushNotificationServerProxy pushToken:pushToken deviceIdentifier:deviceIdentifier deviceIdentifierSignature:signature publicKey:publicKey onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1230. // Activity
  1231. [[NCManageDatabase sharedInstance] addActivityClient:[NCBrandOptions sharedInstance].pushNotificationServerProxy fileID:@"" action:k_activityDebugActionSubscribingPushProxy selector:@"" note:@"Service registered." type:k_activityTypeSuccess verbose:k_activityVerboseHigh activeUrl:_activeUrl];
  1232. success(deviceIdentifier, signature, publicKey);
  1233. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1234. NSString *message;
  1235. NSInteger errorCode = response.statusCode;
  1236. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1237. errorCode = error.code;
  1238. // Error
  1239. if (errorCode == 503)
  1240. message = NSLocalizedString(@"_server_error_retry_", nil);
  1241. else
  1242. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1243. // Activity
  1244. [[NCManageDatabase sharedInstance] addActivityClient:[NCBrandOptions sharedInstance].pushNotificationServerProxy fileID:@"" action:k_activityDebugActionSubscribingPushProxy selector:@"" note:[error.userInfo valueForKey:@"NSLocalizedDescription"] type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:_activeUrl];
  1245. failure(message, errorCode);
  1246. }];
  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. // Activity
  1258. [[NCManageDatabase sharedInstance] addActivityClient:_activeUrl fileID:@"" action:k_activityDebugActionSubscribingServerPush selector:@"" note:[error.userInfo valueForKey:@"NSLocalizedDescription"] type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:_activeUrl];
  1259. failure(message, errorCode);
  1260. }];
  1261. }
  1262. - (void)unsubscribingPushNotificationServer:(NSString *)url deviceIdentifier:(NSString *)deviceIdentifier deviceIdentifierSignature:(NSString *)deviceIdentifierSignature publicKey:(NSString *)publicKey success:(void (^)(void))success failure:(void (^)(NSString *message, NSInteger errorCode))failure {
  1263. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1264. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  1265. [communication setUserAgent:[CCUtility getUserAgent]];
  1266. [communication unsubscribingNextcloudServerPush:url onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1267. [communication unsubscribingPushProxy:[NCBrandOptions sharedInstance].pushNotificationServerProxy deviceIdentifier:deviceIdentifier deviceIdentifierSignature:deviceIdentifierSignature publicKey:publicKey onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1268. success();
  1269. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1270. NSString *message;
  1271. NSInteger errorCode = response.statusCode;
  1272. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1273. errorCode = error.code;
  1274. // Error
  1275. if (errorCode == 503)
  1276. message = NSLocalizedString(@"_server_error_retry_", nil);
  1277. else
  1278. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1279. // Activity
  1280. [[NCManageDatabase sharedInstance] addActivityClient:_activeUrl fileID:@"" action:k_activityDebugActionUnsubscribingPushProxy selector:@"" note:[error.userInfo valueForKey:@"NSLocalizedDescription"] type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:_activeUrl];
  1281. failure(message, errorCode);
  1282. }];
  1283. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1284. NSString *message;
  1285. NSInteger errorCode = response.statusCode;
  1286. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1287. errorCode = error.code;
  1288. // Error
  1289. if (errorCode == 503)
  1290. message = NSLocalizedString(@"_server_error_retry_", nil);
  1291. else
  1292. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1293. // Activity
  1294. [[NCManageDatabase sharedInstance] addActivityClient:_activeUrl fileID:@"" action:k_activityDebugActionUnsubscribingServerPush selector:@"" note:[error.userInfo valueForKey:@"NSLocalizedDescription"] type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:_activeUrl];
  1295. failure(message, errorCode);
  1296. }];
  1297. }
  1298. #pragma --------------------------------------------------------------------------------------------
  1299. #pragma mark ===== User Profile =====
  1300. #pragma --------------------------------------------------------------------------------------------
  1301. - (void)getUserProfile
  1302. {
  1303. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1304. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  1305. [communication setUserAgent:[CCUtility getUserAgent]];
  1306. [communication getUserProfileServer:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, OCUserProfile *userProfile, NSString *redirectedServer) {
  1307. // Test active account
  1308. tableAccount *recordAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  1309. if (![recordAccount.account isEqualToString:_metadataNet.account]) {
  1310. if ([self.delegate respondsToSelector:@selector(getUserProfileSuccessFailure:userProfile:message:errorCode:)])
  1311. [self.delegate getUserProfileSuccessFailure:_metadataNet userProfile:nil message:NSLocalizedString(@"_error_user_not_available_", nil) errorCode:k_CCErrorUserNotAvailble];
  1312. [self complete];
  1313. return;
  1314. }
  1315. if ([self.delegate respondsToSelector:@selector(getUserProfileSuccessFailure:userProfile:message:errorCode:)])
  1316. [self.delegate getUserProfileSuccessFailure:_metadataNet userProfile:userProfile message:nil errorCode:0];
  1317. [self complete];
  1318. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1319. NSInteger errorCode = response.statusCode;
  1320. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1321. errorCode = error.code;
  1322. // Error
  1323. if ([self.delegate respondsToSelector:@selector(getUserProfileSuccessFailure:userProfile:message:errorCode:)]) {
  1324. if (errorCode == 503)
  1325. [self.delegate getUserProfileSuccessFailure:_metadataNet userProfile:nil message:NSLocalizedString(@"_server_error_retry_", nil) errorCode:errorCode];
  1326. else
  1327. [self.delegate getUserProfileSuccessFailure:_metadataNet userProfile:nil message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1328. }
  1329. // Request trusted certificated
  1330. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  1331. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1332. [self complete];
  1333. }];
  1334. }
  1335. #pragma --------------------------------------------------------------------------------------------
  1336. #pragma mark ===== Capabilities =====
  1337. #pragma --------------------------------------------------------------------------------------------
  1338. - (void)getCapabilitiesOfServer:(NSString *)account completion:(void (^)(NSString *account, OCCapabilities *capabilities, NSString *message, NSInteger errorCode))completion
  1339. {
  1340. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1341. if (tableAccount == nil) {
  1342. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1343. }
  1344. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1345. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1346. [communication setUserAgent:[CCUtility getUserAgent]];
  1347. [communication getCapabilitiesOfServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, OCCapabilities *capabilities, NSString *redirectedServer) {
  1348. completion(account, capabilities, nil, 0);
  1349. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1350. NSString *message = @"";
  1351. NSInteger errorCode = response.statusCode;
  1352. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1353. errorCode = error.code;
  1354. // Error
  1355. if (errorCode == 503) {
  1356. message = NSLocalizedString(@"_server_error_retry_", nil);
  1357. } else {
  1358. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1359. }
  1360. // Request trusted certificated
  1361. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  1362. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1363. // Activity
  1364. [[NCManageDatabase sharedInstance] addActivityClient:_activeUrl fileID:@"" action:k_activityDebugActionCapabilities selector:@"" note:[error.userInfo valueForKey:@"NSLocalizedDescription"] type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:_activeUrl];
  1365. completion(account, nil, message, errorCode);
  1366. }];
  1367. }
  1368. #pragma --------------------------------------------------------------------------------------------
  1369. #pragma mark ===== End-to-End Encryption =====
  1370. #pragma --------------------------------------------------------------------------------------------
  1371. - (void)getEndToEndPublicKeys
  1372. {
  1373. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1374. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  1375. [communication setUserAgent:[CCUtility getUserAgent]];
  1376. [communication getEndToEndPublicKeys:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *publicKey, NSString *redirectedServer) {
  1377. _metadataNet.key = publicKey;
  1378. if ([self.delegate respondsToSelector:@selector(getEndToEndPublicKeysSuccess:)])
  1379. [self.delegate getEndToEndPublicKeysSuccess:_metadataNet];
  1380. [self complete];
  1381. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1382. NSInteger errorCode = response.statusCode;
  1383. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1384. errorCode = error.code;
  1385. // Error
  1386. if ([self.delegate respondsToSelector:@selector(getEndToEndPublicKeysFailure:message:errorCode:)])
  1387. [self.delegate getEndToEndPublicKeysFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1388. // Request trusted certificated
  1389. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  1390. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1391. [self complete];
  1392. }];
  1393. }
  1394. - (void)getEndToEndPrivateKeyCipher
  1395. {
  1396. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1397. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  1398. [communication setUserAgent:[CCUtility getUserAgent]];
  1399. [communication getEndToEndPrivateKeyCipher:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *privateKeyChiper, NSString *redirectedServer) {
  1400. _metadataNet.key = privateKeyChiper;
  1401. if ([self.delegate respondsToSelector:@selector(getEndToEndPrivateKeyCipherSuccess:)])
  1402. [self.delegate getEndToEndPrivateKeyCipherSuccess:_metadataNet];
  1403. [self complete];
  1404. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1405. NSInteger errorCode = response.statusCode;
  1406. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1407. errorCode = error.code;
  1408. // Error
  1409. if ([self.delegate respondsToSelector:@selector(getEndToEndPrivateKeyCipherFailure:message:errorCode:)])
  1410. [self.delegate getEndToEndPrivateKeyCipherFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1411. // Request trusted certificated
  1412. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  1413. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1414. [self complete];
  1415. }];
  1416. }
  1417. - (void)signEndToEndPublicKey
  1418. {
  1419. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1420. // URL Encode
  1421. NSString *publicKey = [CCUtility URLEncodeStringFromString:_metadataNet.key];
  1422. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  1423. [communication setUserAgent:[CCUtility getUserAgent]];
  1424. [communication signEndToEndPublicKey:[_activeUrl stringByAppendingString:@"/"] publicKey:publicKey onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *publicKey, NSString *redirectedServer) {
  1425. _metadataNet.key = publicKey;
  1426. if ([self.delegate respondsToSelector:@selector(signEndToEndPublicKeySuccess:)])
  1427. [self.delegate signEndToEndPublicKeySuccess:_metadataNet];
  1428. [self complete];
  1429. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1430. NSInteger errorCode = response.statusCode;
  1431. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1432. errorCode = error.code;
  1433. // Error
  1434. if ([self.delegate respondsToSelector:@selector(signEndToEndPublicKeyFailure:message:errorCode:)])
  1435. [self.delegate signEndToEndPublicKeyFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1436. // Request trusted certificated
  1437. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  1438. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1439. [self complete];
  1440. }];
  1441. }
  1442. - (void)storeEndToEndPrivateKeyCipher
  1443. {
  1444. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1445. // URL Encode
  1446. NSString *privateKeyChiper = [CCUtility URLEncodeStringFromString:_metadataNet.keyCipher];
  1447. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  1448. [communication setUserAgent:[CCUtility getUserAgent]];
  1449. [communication storeEndToEndPrivateKeyCipher:[_activeUrl stringByAppendingString:@"/"] privateKeyChiper:privateKeyChiper onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *privateKey, NSString *redirectedServer) {
  1450. if ([self.delegate respondsToSelector:@selector(storeEndToEndPrivateKeyCipherSuccess:)])
  1451. [self.delegate storeEndToEndPrivateKeyCipherSuccess:_metadataNet];
  1452. [self complete];
  1453. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1454. NSInteger errorCode = response.statusCode;
  1455. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1456. errorCode = error.code;
  1457. // Error
  1458. if ([self.delegate respondsToSelector:@selector(storeEndToEndPrivateKeyCipherFailure:message:errorCode:)])
  1459. [self.delegate storeEndToEndPrivateKeyCipherFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1460. // Request trusted certificated
  1461. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  1462. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1463. [self complete];
  1464. }];
  1465. }
  1466. - (void)deleteEndToEndPublicKey
  1467. {
  1468. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1469. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  1470. [communication setUserAgent:[CCUtility getUserAgent]];
  1471. [communication deleteEndToEndPublicKey:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1472. if ([self.delegate respondsToSelector:@selector(deleteEndToEndPublicKeySuccess:)])
  1473. [self.delegate deleteEndToEndPublicKeySuccess:_metadataNet];
  1474. [self complete];
  1475. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1476. NSInteger errorCode = response.statusCode;
  1477. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1478. errorCode = error.code;
  1479. // Error
  1480. if ([self.delegate respondsToSelector:@selector(deleteEndToEndPublicKeyFailure:message:errorCode:)])
  1481. [self.delegate deleteEndToEndPublicKeyFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1482. // Request trusted certificated
  1483. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  1484. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1485. [self complete];
  1486. }];
  1487. }
  1488. - (void)deleteEndToEndPrivateKey
  1489. {
  1490. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1491. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  1492. [communication setUserAgent:[CCUtility getUserAgent]];
  1493. [communication deleteEndToEndPrivateKey:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1494. if ([self.delegate respondsToSelector:@selector(deleteEndToEndPrivateKeySuccess:)])
  1495. [self.delegate deleteEndToEndPrivateKeySuccess:_metadataNet];
  1496. [self complete];
  1497. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1498. NSInteger errorCode = response.statusCode;
  1499. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1500. errorCode = error.code;
  1501. // Error
  1502. if ([self.delegate respondsToSelector:@selector(deleteEndToEndPrivateKeyFailure:message:errorCode:)])
  1503. [self.delegate deleteEndToEndPrivateKeyFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1504. // Request trusted certificated
  1505. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  1506. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1507. [self complete];
  1508. }];
  1509. }
  1510. - (void)getEndToEndServerPublicKey
  1511. {
  1512. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1513. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  1514. [communication setUserAgent:[CCUtility getUserAgent]];
  1515. [communication getEndToEndServerPublicKey:[_activeUrl stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *publicKey, NSString *redirectedServer) {
  1516. _metadataNet.key = publicKey;
  1517. if ([self.delegate respondsToSelector:@selector(getEndToEndServerPublicKeySuccess:)])
  1518. [self.delegate getEndToEndServerPublicKeySuccess:_metadataNet];
  1519. [self complete];
  1520. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1521. NSInteger errorCode = response.statusCode;
  1522. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1523. errorCode = error.code;
  1524. // Error
  1525. if ([self.delegate respondsToSelector:@selector(getEndToEndServerPublicKeyFailure:message:errorCode:)])
  1526. [self.delegate getEndToEndServerPublicKeyFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1527. // Request trusted certificated
  1528. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  1529. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1530. [self complete];
  1531. }];
  1532. }
  1533. #pragma --------------------------------------------------------------------------------------------
  1534. #pragma mark ===== Manage Mobile Editor OCS API =====
  1535. #pragma --------------------------------------------------------------------------------------------
  1536. - (void)createLinkRichdocumentsWithFileID:(NSString *)fileID success:(void(^)(NSString *link))success failure:(void (^)(NSString *message, NSInteger errorCode))failure
  1537. {
  1538. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1539. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  1540. [communication setUserAgent:[CCUtility getUserAgent]];
  1541. NSString *fileIDServer = [[NCUtility sharedInstance] convertFileIDClientToFileIDServer:fileID];
  1542. [communication createLinkRichdocuments:[_activeUrl stringByAppendingString:@"/"] fileID:fileIDServer onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *link, NSString *redirectedServer) {
  1543. success(link);
  1544. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1545. NSString *message;
  1546. NSInteger errorCode = response.statusCode;
  1547. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1548. errorCode = error.code;
  1549. // Error
  1550. if (errorCode == 503)
  1551. message = NSLocalizedString(@"_server_error_retry_", nil);
  1552. else
  1553. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1554. // Activity
  1555. [[NCManageDatabase sharedInstance] addActivityClient:_activeUrl fileID:@"" action:k_activityDebugActionUnsubscribingServerPush selector:@"" note:[error.userInfo valueForKey:@"NSLocalizedDescription"] type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:_activeUrl];
  1556. failure(message, errorCode);
  1557. }];
  1558. }
  1559. - (void)geTemplatesRichdocumentsWithTypeTemplate:(NSString *)typeTemplate success:(void(^)(NSArray *listOfTemplate))success failure:(void (^)(NSString *message, NSInteger errorCode))failure
  1560. {
  1561. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1562. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  1563. [communication setUserAgent:[CCUtility getUserAgent]];
  1564. [communication geTemplatesRichdocuments:[_activeUrl stringByAppendingString:@"/"] typeTemplate:typeTemplate onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfTemplate, NSString *redirectedServer) {
  1565. success(listOfTemplate);
  1566. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1567. NSString *message;
  1568. NSInteger errorCode = response.statusCode;
  1569. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1570. errorCode = error.code;
  1571. // Error
  1572. if (errorCode == 503)
  1573. message = NSLocalizedString(@"_server_error_retry_", nil);
  1574. else
  1575. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1576. // Activity
  1577. [[NCManageDatabase sharedInstance] addActivityClient:_activeUrl fileID:@"" action:k_activityDebugActionUnsubscribingServerPush selector:@"" note:[error.userInfo valueForKey:@"NSLocalizedDescription"] type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:_activeUrl];
  1578. failure(message, errorCode);
  1579. }];
  1580. }
  1581. - (void)createNewRichdocumentsWithFileName:(NSString *)fileName serverUrl:(NSString *)serverUrl templateID:(NSString *)templateID success:(void(^)(NSString *url))success failure:(void (^)(NSString *message, NSInteger errorCode))failure
  1582. {
  1583. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1584. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  1585. [communication setUserAgent:[CCUtility getUserAgent]];
  1586. [communication createNewRichdocuments:[_activeUrl stringByAppendingString:@"/"] path:fileName templateID:templateID onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *url, NSString *redirectedServer) {
  1587. success(url);
  1588. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1589. NSString *message;
  1590. NSInteger errorCode = response.statusCode;
  1591. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1592. errorCode = error.code;
  1593. // Error
  1594. if (errorCode == 503)
  1595. message = NSLocalizedString(@"_server_error_retry_", nil);
  1596. else
  1597. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1598. // Activity
  1599. [[NCManageDatabase sharedInstance] addActivityClient:_activeUrl fileID:@"" action:k_activityDebugActionUnsubscribingServerPush selector:@"" note:[error.userInfo valueForKey:@"NSLocalizedDescription"] type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:_activeUrl];
  1600. failure(message, errorCode);
  1601. }];
  1602. }
  1603. - (void)createAssetRichdocumentsWithFileName:(NSString *)fileName serverUrl:(NSString *)serverUrl success:(void(^)(NSString *link))success failure:(void (^)(NSString *message, NSInteger errorCode))failure
  1604. {
  1605. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1606. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  1607. [communication setUserAgent:[CCUtility getUserAgent]];
  1608. NSString *fileNamePath = [CCUtility returnFileNamePathFromFileName:fileName serverUrl:serverUrl activeUrl:_activeUrl];
  1609. [communication createAssetRichdocuments:[_activeUrl stringByAppendingString:@"/"] path:fileNamePath onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *url, NSString *redirectedServer) {
  1610. success(url);
  1611. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1612. NSString *message;
  1613. NSInteger errorCode = response.statusCode;
  1614. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1615. errorCode = error.code;
  1616. // Error
  1617. if (errorCode == 503)
  1618. message = NSLocalizedString(@"_server_error_retry_", nil);
  1619. else
  1620. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1621. // Activity
  1622. [[NCManageDatabase sharedInstance] addActivityClient:_activeUrl fileID:@"" action:k_activityDebugActionUnsubscribingServerPush selector:@"" note:[error.userInfo valueForKey:@"NSLocalizedDescription"] type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:_activeUrl];
  1623. failure(message, errorCode);
  1624. }];
  1625. }
  1626. #pragma --------------------------------------------------------------------------------------------
  1627. #pragma mark ===== Trash =====
  1628. #pragma --------------------------------------------------------------------------------------------
  1629. - (void)listingTrash:(NSString *)serverUrl path:(NSString *)path account:(NSString *)account success:(void(^)(NSArray *items))success failure:(void (^)(NSString *message, NSInteger errorCode))failure
  1630. {
  1631. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1632. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  1633. [communication setUserAgent:[CCUtility getUserAgent]];
  1634. [communication listingTrash:[serverUrl stringByAppendingString:path] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  1635. // Test active account
  1636. tableAccount *recordAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  1637. if (![recordAccount.account isEqualToString:account]) {
  1638. failure(NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1639. } else {
  1640. // Check items > 0
  1641. if ([items count] == 0) {
  1642. #ifndef EXTENSION
  1643. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  1644. [appDelegate messageNotification:@"Server error" description:@"Read Folder WebDAV : [items NULL] please fix" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  1645. #endif
  1646. failure(NSLocalizedString(@"Read Folder WebDAV : [items NULL] please fix", nil), k_CCErrorInternalError);
  1647. } else {
  1648. NSMutableArray *listTrash = [NSMutableArray new];
  1649. //OCFileDto *itemDtoFolder = [items objectAtIndex:0];
  1650. if ([items count] > 1) {
  1651. for (NSUInteger i=1; i < [items count]; i++) {
  1652. OCFileDto *itemDto = [items objectAtIndex:i];
  1653. tableTrash *trash = [tableTrash new];
  1654. trash.account = account;
  1655. trash.date = [NSDate dateWithTimeIntervalSince1970:itemDto.date];
  1656. trash.directory = itemDto.isDirectory;
  1657. trash.fileID = itemDto.ocId;
  1658. trash.fileName = itemDto.fileName;
  1659. trash.filePath = itemDto.filePath;
  1660. trash.size = itemDto.size;
  1661. trash.trashbinFileName = itemDto.trashbinFileName;
  1662. trash.trashbinOriginalLocation = itemDto.trashbinOriginalLocation;
  1663. trash.trashbinDeletionTime = [NSDate dateWithTimeIntervalSince1970:itemDto.trashbinDeletionTime];
  1664. [CCUtility insertTypeFileIconName:trash.trashbinFileName metadata:(tableMetadata *)trash];
  1665. [listTrash addObject:trash];
  1666. }
  1667. }
  1668. success(listTrash);
  1669. }
  1670. }
  1671. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1672. NSString *message;
  1673. NSInteger errorCode = response.statusCode;
  1674. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1675. errorCode = error.code;
  1676. // Error
  1677. if (errorCode == 503)
  1678. message = NSLocalizedString(@"_server_error_retry_", nil);
  1679. else
  1680. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1681. // Activity
  1682. [[NCManageDatabase sharedInstance] addActivityClient:_activeUrl fileID:@"" action:k_activityDebugActionUnsubscribingServerPush selector:@"" note:[error.userInfo valueForKey:@"NSLocalizedDescription"] type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:_activeUrl];
  1683. failure(message, errorCode);
  1684. }];
  1685. }
  1686. - (void)emptyTrash:(void (^)(NSString *message, NSInteger errorCode))completion
  1687. {
  1688. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1689. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  1690. [communication setUserAgent:[CCUtility getUserAgent]];
  1691. NSString *path = [NSString stringWithFormat:@"%@%@/trashbin/%@/trash", _activeUrl, k_dav, _activeUserID];
  1692. [communication emptyTrash:path onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1693. completion(nil, 0);
  1694. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1695. NSString *message;
  1696. NSInteger errorCode = response.statusCode;
  1697. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1698. errorCode = error.code;
  1699. // Error
  1700. if (errorCode == 503)
  1701. message = NSLocalizedString(@"_server_error_retry_", nil);
  1702. else
  1703. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1704. // Activity
  1705. [[NCManageDatabase sharedInstance] addActivityClient:_activeUrl fileID:@"" action:k_activityDebugActionUnsubscribingServerPush selector:@"" note:[error.userInfo valueForKey:@"NSLocalizedDescription"] type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:_activeUrl];
  1706. completion(message, errorCode);
  1707. }];
  1708. }
  1709. @end
  1710. #pragma --------------------------------------------------------------------------------------------
  1711. #pragma mark ===== OCURLSessionManager =====
  1712. #pragma --------------------------------------------------------------------------------------------
  1713. @implementation OCURLSessionManager
  1714. - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
  1715. {
  1716. // The pinnning check
  1717. if ([[CCCertificate sharedManager] checkTrustedChallenge:challenge]) {
  1718. completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  1719. } else {
  1720. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  1721. }
  1722. }
  1723. @end