OCNetworking.m 111 KB

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