OCNetworking.m 136 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666
  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. } else if ([CCUtility getPassword:account].length == 0) {
  241. completion(account, 0, nil, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  242. } else if ([CCUtility getCertificateError:account]) {
  243. completion(account, 0, nil, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  244. }
  245. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  246. [communication setUserAgent:[CCUtility getUserAgent]];
  247. NSURLSessionTask *sessionTask = [communication downloadFileSession:fileNameServerUrl toDestiny:fileNameLocalPath defaultPriority:YES onCommunication:communication progress:^(NSProgress *progress) {
  248. //float percent = roundf (progress.fractionCompleted * 100);
  249. } successRequest:^(NSURLResponse *response, NSURL *filePath) {
  250. int64_t totalUnitCount = 0;
  251. NSDate *date = [NSDate date];
  252. NSDateFormatter *dateFormatter = [NSDateFormatter new];
  253. NSLocale *enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
  254. [dateFormatter setLocale:enUSPOSIXLocale];
  255. [dateFormatter setDateFormat:@"EEE, dd MMM y HH:mm:ss zzz"];
  256. NSError *error;
  257. NSDictionary *fields = [(NSHTTPURLResponse*)response allHeaderFields];
  258. NSString *contentLength = [fields objectForKey:@"Content-Length"];
  259. if(contentLength) {
  260. totalUnitCount = (int64_t) [contentLength longLongValue];
  261. }
  262. NSString *dateString = [fields objectForKey:@"Date"];
  263. if (dateString) {
  264. if (![dateFormatter getObjectValue:&date forString:dateString range:nil error:&error]) {
  265. date = [NSDate date];
  266. }
  267. } else {
  268. date = [NSDate date];
  269. }
  270. NSString *etag = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-ETag"]];
  271. if (etag == nil) {
  272. completion(account, 0, nil, nil, NSLocalizedString(@"Internal error", nil), k_CCErrorInternalError);
  273. } else {
  274. completion(account, totalUnitCount, etag, date, nil, 0);
  275. }
  276. } failureRequest:^(NSURLResponse *response, NSError *error) {
  277. NSString *message;
  278. NSInteger errorCode = ((NSHTTPURLResponse*)response).statusCode;
  279. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  280. errorCode = error.code;
  281. // Server Unauthorized
  282. if (errorCode == kOCErrorServerUnauthorized) {
  283. [CCUtility setPassword:account password:nil];
  284. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  285. [CCUtility setCertificateError:account error:YES];
  286. }
  287. // Error
  288. if (errorCode == 503)
  289. message = NSLocalizedString(@"_server_error_retry_", nil);
  290. else
  291. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  292. completion(account, 0, nil, nil, message, errorCode);
  293. }];
  294. return sessionTask;
  295. }
  296. - (NSURLSessionTask *)downloadWithAccount:(NSString *)account url:(NSString *)url fileNameLocalPath:(NSString *)fileNameLocalPath completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  297. {
  298. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  299. if (tableAccount == nil) {
  300. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  301. } else if ([CCUtility getPassword:account].length == 0) {
  302. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  303. } else if ([CCUtility getCertificateError:account]) {
  304. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  305. }
  306. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  307. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  308. [communication setUserAgent:[CCUtility getUserAgent]];
  309. NSURLSessionTask *sessionTask = [communication downloadFileSession:url toDestiny:fileNameLocalPath defaultPriority:YES onCommunication:communication progress:^(NSProgress *progress) {
  310. //float percent = roundf (progress.fractionCompleted * 100);
  311. } successRequest:^(NSURLResponse *response, NSURL *filePath) {
  312. completion(account, nil, 0);
  313. } failureRequest:^(NSURLResponse *response, NSError *error) {
  314. NSString *message;
  315. NSInteger errorCode = ((NSHTTPURLResponse*)response).statusCode;
  316. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  317. errorCode = error.code;
  318. // Server Unauthorized
  319. if (errorCode == kOCErrorServerUnauthorized) {
  320. [CCUtility setPassword:account password:nil];
  321. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  322. [CCUtility setCertificateError:account error:YES];
  323. }
  324. // Error
  325. if (errorCode == 503)
  326. message = NSLocalizedString(@"_server_error_retry_", nil);
  327. else
  328. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  329. completion(account, message, errorCode);
  330. }];
  331. return sessionTask;
  332. }
  333. - (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
  334. {
  335. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  336. if (tableAccount == nil) {
  337. completion(account, nil, nil, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  338. } else if ([CCUtility getPassword:account].length == 0) {
  339. completion(account, nil, nil, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  340. } else if ([CCUtility getCertificateError:account]) {
  341. completion(account, nil, nil, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  342. }
  343. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  344. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  345. [communication setUserAgent:[CCUtility getUserAgent]];
  346. NSURLSessionTask *sessionTask = [communication uploadFileSession:fileNameLocalPath toDestiny:fileNameServerUrl onCommunication:communication progress:^(NSProgress *progress) {
  347. uploadProgress(progress);
  348. //float percent = roundf (progress.fractionCompleted * 100);
  349. } successRequest:^(NSURLResponse *response, NSString *redirectedServer) {
  350. NSDictionary *fields = [(NSHTTPURLResponse*)response allHeaderFields];
  351. NSString *fileID = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-FileId"]];
  352. NSString *etag = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-ETag"]];
  353. NSDate *date = [CCUtility dateEnUsPosixFromCloud:[fields objectForKey:@"Date"]];
  354. completion(account, fileID, etag, date, nil, 0);
  355. } failureRequest:^(NSURLResponse *response, NSString *redirectedServer, NSError *error) {
  356. NSString *message;
  357. NSInteger errorCode = ((NSHTTPURLResponse*)response).statusCode;
  358. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  359. errorCode = error.code;
  360. // Server Unauthorized
  361. if (errorCode == kOCErrorServerUnauthorized) {
  362. [CCUtility setPassword:account password:nil];
  363. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  364. [CCUtility setCertificateError:account error:YES];
  365. }
  366. // Error
  367. if (errorCode == 503)
  368. message = NSLocalizedString(@"_server_error_retry_", nil);
  369. else
  370. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  371. completion(account, nil, nil, nil, message, errorCode);
  372. } failureBeforeRequest:^(NSError *error) {
  373. completion(account, nil, nil, nil, error.description, error.code);
  374. }];
  375. return sessionTask;
  376. }
  377. #pragma --------------------------------------------------------------------------------------------
  378. #pragma mark ===== WebDav =====
  379. #pragma --------------------------------------------------------------------------------------------
  380. - (void)readFolderWithAccount:(NSString *)account serverUrl:(NSString *)serverUrl depth:(NSString *)depth completion:(void(^)(NSString *account, NSArray *metadatas, tableMetadata *metadataFolder, NSString *message, NSInteger errorCode))completion
  381. {
  382. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  383. if (tableAccount == nil) {
  384. completion(account, nil, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  385. } else if ([CCUtility getPassword:account].length == 0) {
  386. completion(account, nil, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  387. } else if ([CCUtility getCertificateError:account]) {
  388. completion(account, nil, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  389. }
  390. NSString *url = tableAccount.url;
  391. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  392. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:url];
  393. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  394. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  395. [communication setUserAgent:[CCUtility getUserAgent]];
  396. [communication readFolder:serverUrl depth:depth withUserSessionToken:nil onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer, NSString *token) {
  397. // Check items > 0
  398. if ([items count] == 0) {
  399. #ifndef EXTENSION
  400. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  401. [appDelegate messageNotification:@"Server error" description:@"Read Folder WebDAV : [items NULL] please fix" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  402. #endif
  403. completion(account, nil, nil, NSLocalizedString(@"Read Folder WebDAV : [items NULL] please fix", nil), k_CCErrorInternalError);
  404. } else {
  405. BOOL showHiddenFiles = [CCUtility getShowHiddenFiles];
  406. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:serverUrl account:account];
  407. // directory [0]
  408. OCFileDto *itemDtoFolder = [items objectAtIndex:0];
  409. //NSDate *date = [NSDate dateWithTimeIntervalSince1970:itemDtoDirectory.date];
  410. NSMutableArray *metadatas = [NSMutableArray new];
  411. tableMetadata *metadataFolder = [tableMetadata new];
  412. NSString *serverUrlFolder;
  413. // Metadata . (self Folder)
  414. if ([serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:url]]) {
  415. // root folder
  416. serverUrlFolder = k_serverUrl_root;
  417. metadataFolder = [CCUtility trasformedOCFileToCCMetadata:itemDtoFolder fileName:@"." serverUrl:serverUrlFolder autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:account isFolderEncrypted:isFolderEncrypted];
  418. } else {
  419. serverUrlFolder = [CCUtility deletingLastPathComponentFromServerUrl:serverUrl];
  420. metadataFolder = [CCUtility trasformedOCFileToCCMetadata:itemDtoFolder fileName:[serverUrl lastPathComponent] serverUrl:serverUrlFolder autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:account isFolderEncrypted:isFolderEncrypted];
  421. }
  422. // Add metadata folder
  423. (void)[[NCManageDatabase sharedInstance] addDirectoryWithEncrypted:itemDtoFolder.isEncrypted favorite:itemDtoFolder.isFavorite fileID:itemDtoFolder.ocId permissions:itemDtoFolder.permissions serverUrl:serverUrl account:account];
  424. NSArray *itemsSortedArray = [items sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
  425. NSString *first = [(OCFileDto*)a fileName];
  426. NSString *second = [(OCFileDto*)b fileName];
  427. return [[first lowercaseString] compare:[second lowercaseString]];
  428. }];
  429. for (NSUInteger i=1; i < [itemsSortedArray count]; i++) {
  430. OCFileDto *itemDto = [itemsSortedArray objectAtIndex:i];
  431. NSString *fileName = [itemDto.fileName stringByReplacingOccurrencesOfString:@"/" withString:@""];
  432. // Skip hidden files
  433. if (fileName.length > 0) {
  434. if (!showHiddenFiles && [[fileName substringToIndex:1] isEqualToString:@"."])
  435. continue;
  436. } else {
  437. continue;
  438. }
  439. if (itemDto.isDirectory) {
  440. (void)[[NCManageDatabase sharedInstance] addDirectoryWithEncrypted:itemDto.isEncrypted favorite:itemDto.isFavorite fileID:itemDto.ocId permissions:itemDto.permissions serverUrl:[CCUtility stringAppendServerUrl:serverUrl addFileName:fileName] account:account];
  441. }
  442. [metadatas addObject:[CCUtility trasformedOCFileToCCMetadata:itemDto fileName:itemDto.fileName serverUrl:serverUrl autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:account isFolderEncrypted:isFolderEncrypted]];
  443. }
  444. completion(account, metadatas, metadataFolder, nil, 0);
  445. }
  446. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) {
  447. NSString *message;
  448. NSInteger errorCode = response.statusCode;
  449. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  450. errorCode = error.code;
  451. // Server Unauthorized
  452. if (errorCode == kOCErrorServerUnauthorized) {
  453. [CCUtility setPassword:account password:nil];
  454. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  455. [CCUtility setCertificateError:account error:YES];
  456. }
  457. // Error
  458. if (errorCode == 503)
  459. message = NSLocalizedString(@"_server_error_retry_", nil);
  460. else
  461. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  462. completion(account, nil, nil, message, errorCode);
  463. }];
  464. }
  465. - (void)readFileWithAccount:(NSString *)account serverUrl:(NSString *)serverUrl fileName:(NSString *)fileName completion:(void(^)(NSString *account, tableMetadata *metadata, NSString *message, NSInteger errorCode))completion
  466. {
  467. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  468. if (tableAccount == nil) {
  469. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  470. } else if ([CCUtility getPassword:account].length == 0) {
  471. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  472. } else if ([CCUtility getCertificateError:account]) {
  473. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  474. }
  475. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  476. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:tableAccount.url];
  477. NSString *fileNamePath;
  478. if (fileName) {
  479. fileNamePath = [NSString stringWithFormat:@"%@/%@", serverUrl, fileName];
  480. } else {
  481. fileName= @".";
  482. fileNamePath = serverUrl;
  483. }
  484. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  485. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  486. [communication setUserAgent:[CCUtility getUserAgent]];
  487. [communication readFile:fileNamePath onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  488. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:serverUrl account:account];
  489. if ([items count] > 0) {
  490. tableMetadata *metadata = [tableMetadata new];
  491. OCFileDto *itemDto = [items objectAtIndex:0];
  492. metadata = [CCUtility trasformedOCFileToCCMetadata:itemDto fileName:fileName serverUrl:serverUrl autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:account isFolderEncrypted:isFolderEncrypted];
  493. completion(account, metadata, nil, 0);
  494. // BUG 1038 item == 0
  495. } else {
  496. #ifndef EXTENSION
  497. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  498. [appDelegate messageNotification:@"Server error" description:@"Read File WebDAV : [items NULL] please fix" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  499. #endif
  500. completion(account, nil, NSLocalizedString(@"Read File WebDAV : [items NULL] please fix", nil), k_CCErrorInternalError);
  501. }
  502. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  503. NSString *message;
  504. NSInteger errorCode = response.statusCode;
  505. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  506. errorCode = error.code;
  507. // Server Unauthorized
  508. if (errorCode == kOCErrorServerUnauthorized) {
  509. [CCUtility setPassword:account password:nil];
  510. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  511. [CCUtility setCertificateError:account error:YES];
  512. }
  513. // Error
  514. if (errorCode == 503)
  515. message = NSLocalizedString(@"_server_error_retry_", nil);
  516. else
  517. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  518. completion(account, nil, message, errorCode);
  519. }];
  520. }
  521. - (void)createFolderWithAccount:(NSString *)account serverUrl:(NSString *)serverUrl fileName:(NSString *)fileName completion:(void(^)(NSString *account, NSString *fileID, NSDate *date, NSString *message, NSInteger errorCode))completion
  522. {
  523. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  524. if (tableAccount == nil) {
  525. completion(account, nil, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  526. } else if ([CCUtility getPassword:account].length == 0) {
  527. completion(account, nil, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  528. } else if ([CCUtility getCertificateError:account]) {
  529. completion(account, nil, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  530. }
  531. NSString *path = [NSString stringWithFormat:@"%@/%@", serverUrl, fileName];
  532. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  533. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:tableAccount.url];
  534. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  535. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  536. [communication setUserAgent:[CCUtility getUserAgent]];
  537. [communication createFolder:path onCommunication:communication withForbiddenCharactersSupported:YES successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  538. NSDictionary *fields = [response allHeaderFields];
  539. NSString *fileID = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-FileId"]];
  540. NSDate *date = [CCUtility dateEnUsPosixFromCloud:[fields objectForKey:@"Date"]];
  541. completion(account, fileID, date, nil, 0);
  542. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  543. NSString *message;
  544. if (([fileName isEqualToString:autoUploadFileName] && [serverUrl isEqualToString:autoUploadDirectory]))
  545. message = nil;
  546. else
  547. message = [CCError manageErrorOC:response.statusCode error:error];
  548. NSInteger errorCode = response.statusCode;
  549. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  550. errorCode = error.code;
  551. // Server Unauthorized
  552. if (errorCode == kOCErrorServerUnauthorized) {
  553. [CCUtility setPassword:account password:nil];
  554. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  555. [CCUtility setCertificateError:account error:YES];
  556. }
  557. completion(account, nil, nil, message, errorCode);
  558. } errorBeforeRequest:^(NSError *error) {
  559. NSString *message;
  560. if (([fileName isEqualToString:autoUploadFileName] && [serverUrl isEqualToString:autoUploadDirectory]))
  561. message = nil;
  562. else {
  563. if (error.code == OCErrorForbidenCharacters)
  564. message = NSLocalizedString(@"_forbidden_characters_from_server_", nil);
  565. else
  566. message = NSLocalizedString(@"_unknow_response_server_", nil);
  567. }
  568. completion(account, nil, nil, message, error.code);
  569. }];
  570. }
  571. - (void)deleteFileOrFolderWithAccount:(NSString *)account path:(NSString *)path completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  572. {
  573. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  574. if (tableAccount == nil) {
  575. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  576. } else if ([CCUtility getPassword:account].length == 0) {
  577. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  578. } else if ([CCUtility getCertificateError:account]) {
  579. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  580. }
  581. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  582. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  583. [communication setUserAgent:[CCUtility getUserAgent]];
  584. [communication deleteFileOrFolder:path onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  585. completion(account, nil, 0);
  586. } failureRquest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  587. NSString *message;
  588. NSInteger errorCode = response.statusCode;
  589. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  590. errorCode = error.code;
  591. // Server Unauthorized
  592. if (errorCode == kOCErrorServerUnauthorized) {
  593. [CCUtility setPassword:account password:nil];
  594. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  595. [CCUtility setCertificateError:account error:YES];
  596. }
  597. // Error
  598. if (errorCode == 503)
  599. message = NSLocalizedString(@"_server_error_retry_", nil);
  600. else
  601. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  602. completion(account, message, errorCode);
  603. }];
  604. }
  605. - (void)moveFileOrFolderWithAccount:(NSString *)account fileName:(NSString *)fileName fileNameTo:(NSString *)fileNameTo completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  606. {
  607. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  608. if (tableAccount == nil) {
  609. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  610. } else if ([CCUtility getPassword:account].length == 0) {
  611. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  612. } else if ([CCUtility getCertificateError:account]) {
  613. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  614. }
  615. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  616. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  617. [communication setUserAgent:[CCUtility getUserAgent]];
  618. [communication moveFileOrFolder:fileName toDestiny:fileNameTo onCommunication:communication withForbiddenCharactersSupported:YES successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  619. completion(account, nil, 0);
  620. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  621. NSString *message;
  622. NSInteger errorCode = response.statusCode;
  623. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  624. errorCode = error.code;
  625. // Server Unauthorized
  626. if (errorCode == kOCErrorServerUnauthorized) {
  627. [CCUtility setPassword:account password:nil];
  628. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  629. [CCUtility setCertificateError:account error:YES];
  630. }
  631. // Error
  632. if (errorCode == 503) {
  633. message = NSLocalizedString(@"_server_error_retry_", nil);
  634. } else {
  635. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  636. }
  637. completion(account, message, errorCode);
  638. } errorBeforeRequest:^(NSError *error) {
  639. NSString *message;
  640. if (error.code == OCErrorMovingTheDestinyAndOriginAreTheSame) {
  641. message = NSLocalizedString(@"_error_folder_destiny_is_the_same_", nil);
  642. } else if (error.code == OCErrorMovingFolderInsideHimself) {
  643. message = NSLocalizedString(@"_error_folder_destiny_is_the_same_", nil);
  644. } else if (error.code == OCErrorMovingDestinyNameHaveForbiddenCharacters) {
  645. message = NSLocalizedString(@"_forbidden_characters_from_server_", nil);
  646. } else {
  647. message = NSLocalizedString(@"_unknow_response_server_", nil);
  648. }
  649. completion(account, message, error.code);
  650. }];
  651. }
  652. - (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
  653. {
  654. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  655. if (tableAccount == nil) {
  656. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  657. } else if ([CCUtility getPassword:account].length == 0) {
  658. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  659. } else if ([CCUtility getCertificateError:account]) {
  660. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  661. }
  662. NSString *path = [tableAccount.url stringByAppendingString:k_dav];
  663. NSString *folder = [serverUrl stringByReplacingOccurrencesOfString:[CCUtility getHomeServerUrlActiveUrl:tableAccount.url] withString:@""];
  664. NSString *lteDateLastModifiedString;
  665. NSString *gteDateLastModifiedString;
  666. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  667. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:tableAccount.url];
  668. NSString *url = tableAccount.url;
  669. NSString *userID = tableAccount.userID;
  670. if (lteDateLastModified) {
  671. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  672. NSLocale *enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
  673. [dateFormatter setLocale:enUSPOSIXLocale];
  674. [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZZ"];
  675. lteDateLastModifiedString = [dateFormatter stringFromDate:lteDateLastModified];
  676. }
  677. if (gteDateLastModified) {
  678. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  679. NSLocale *enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
  680. [dateFormatter setLocale:enUSPOSIXLocale];
  681. [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZZ"];
  682. gteDateLastModifiedString = [dateFormatter stringFromDate:gteDateLastModified];
  683. }
  684. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  685. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  686. [communication setUserAgent:[CCUtility getUserAgent]];
  687. [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) {
  688. NSMutableArray *metadatas = [NSMutableArray new];
  689. BOOL showHiddenFiles = [CCUtility getShowHiddenFiles];
  690. for (OCFileDto *itemDto in items) {
  691. NSString *serverUrl;
  692. BOOL isFolderEncrypted;
  693. NSString *fileName = [itemDto.fileName stringByReplacingOccurrencesOfString:@"/" withString:@""];
  694. // Skip hidden files
  695. if (fileName.length > 0) {
  696. if (!showHiddenFiles && [[fileName substringToIndex:1] isEqualToString:@"."])
  697. continue;
  698. } else
  699. continue;
  700. NSRange firstInstance = [itemDto.filePath rangeOfString:[NSString stringWithFormat:@"%@/files/%@", k_dav, userID]];
  701. NSString *serverPath = [itemDto.filePath substringFromIndex:firstInstance.length+firstInstance.location+1];
  702. if ([serverPath hasSuffix:@"/"]) serverPath = [serverPath substringToIndex:[serverPath length] - 1];
  703. serverUrl = [CCUtility stringAppendServerUrl:[url stringByAppendingString:k_webDAV] addFileName:serverPath];
  704. if (itemDto.isDirectory) {
  705. (void)[[NCManageDatabase sharedInstance] addDirectoryWithEncrypted:itemDto.isEncrypted favorite:itemDto.isFavorite fileID:itemDto.ocId permissions:itemDto.permissions serverUrl:[NSString stringWithFormat:@"%@/%@", serverUrl, fileName] account:account];
  706. }
  707. isFolderEncrypted = [CCUtility isFolderEncrypted:serverUrl account:account];
  708. [metadatas addObject:[CCUtility trasformedOCFileToCCMetadata:itemDto fileName:itemDto.fileName serverUrl:serverUrl autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:account isFolderEncrypted:isFolderEncrypted]];
  709. }
  710. completion(account, metadatas, nil, 0);
  711. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) {
  712. NSString *message;
  713. NSInteger errorCode = response.statusCode;
  714. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  715. errorCode = error.code;
  716. // Server Unauthorized
  717. if (errorCode == kOCErrorServerUnauthorized) {
  718. [CCUtility setPassword:account password:nil];
  719. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  720. [CCUtility setCertificateError:account error:YES];
  721. }
  722. // Error
  723. if (errorCode == 503) {
  724. message = NSLocalizedString(@"_server_error_retry_", nil);
  725. } else {
  726. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  727. }
  728. completion(account, nil, message, errorCode);
  729. }];
  730. }
  731. #pragma --------------------------------------------------------------------------------------------
  732. #pragma mark ===== downloadPreview =====
  733. #pragma --------------------------------------------------------------------------------------------
  734. /*
  735. - (void)downloadThumbnailWithMetadata:(tableMetadata*)metadata withWidth:(CGFloat)width andHeight:(CGFloat)height completion:(void (^)(NSString *message, NSInteger errorCode))completion
  736. {
  737. NSString *file = [NSString stringWithFormat:@"%@/%@.ico", [CCUtility getDirectoryProviderStorageFileID:metadata.fileID], metadata.fileNameView];
  738. if ([[NSFileManager defaultManager] fileExistsAtPath:file]) {
  739. completion(nil, 0);
  740. } else {
  741. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  742. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  743. [communication setUserAgent:[CCUtility getUserAgent]];
  744. [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) {
  745. [thumbnail writeToFile:file atomically:YES];
  746. completion(nil, 0);
  747. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  748. NSString *message;
  749. NSInteger errorCode = response.statusCode;
  750. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  751. errorCode = error.code;
  752. // Error
  753. if (errorCode == 503)
  754. message = NSLocalizedString(@"_server_error_retry_", nil);
  755. else
  756. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  757. completion(message, errorCode);
  758. }];
  759. }
  760. }
  761. */
  762. - (void)downloadPreviewWithAccount:(NSString *)account metadata:(tableMetadata*)metadata withWidth:(CGFloat)width andHeight:(CGFloat)height completion:(void (^)(NSString *account, UIImage *image, NSString *message, NSInteger errorCode))completion
  763. {
  764. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  765. if (tableAccount == nil) {
  766. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  767. } else if ([CCUtility getPassword:account].length == 0) {
  768. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  769. } else if ([CCUtility getCertificateError:account]) {
  770. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  771. }
  772. NSString *file = [NSString stringWithFormat:@"%@/%@.ico", [CCUtility getDirectoryProviderStorageFileID:metadata.fileID], metadata.fileNameView];
  773. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  774. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  775. [communication setUserAgent:[CCUtility getUserAgent]];
  776. [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) {
  777. [preview writeToFile:file atomically:YES];
  778. completion(account, [UIImage imageWithData:preview], nil, 0);
  779. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  780. NSString *message;
  781. NSInteger errorCode = response.statusCode;
  782. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  783. errorCode = error.code;
  784. // Server Unauthorized
  785. if (errorCode == kOCErrorServerUnauthorized) {
  786. [CCUtility setPassword:account password:nil];
  787. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  788. [CCUtility setCertificateError:account error:YES];
  789. }
  790. // Error
  791. if (errorCode == 503)
  792. message = NSLocalizedString(@"_server_error_retry_", nil);
  793. else
  794. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  795. completion(account, nil, message, errorCode);
  796. }];
  797. }
  798. - (void)downloadPreviewWithAccount:(NSString *)account serverPath:(NSString *)serverPath fileNamePath:(NSString *)fileNamePath completion:(void (^)(NSString *account, UIImage *image, NSString *message, NSInteger errorCode))completion
  799. {
  800. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  801. if (tableAccount == nil) {
  802. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  803. } else if ([CCUtility getPassword:account].length == 0) {
  804. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  805. } else if ([CCUtility getCertificateError:account]) {
  806. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  807. }
  808. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  809. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  810. [communication setUserAgent:[CCUtility getUserAgent]];
  811. [communication getRemotePreviewByServer:tableAccount.url ofFilePath:@"" withWidth:0 andHeight:0 andA:0 andMode:@"" path:serverPath onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSData *preview, NSString *redirectedServer) {
  812. [preview writeToFile:fileNamePath atomically:YES];
  813. completion(account, [UIImage imageWithData:preview], nil, 0);
  814. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  815. NSString *message;
  816. NSInteger errorCode = response.statusCode;
  817. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  818. errorCode = error.code;
  819. // Server Unauthorized
  820. if (errorCode == kOCErrorServerUnauthorized) {
  821. [CCUtility setPassword:account password:nil];
  822. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  823. [CCUtility setCertificateError:account error:YES];
  824. }
  825. // Error
  826. if (errorCode == 503)
  827. message = NSLocalizedString(@"_server_error_retry_", nil);
  828. else
  829. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  830. completion(account, nil, message, errorCode);
  831. }];
  832. }
  833. - (void)downloadPreviewTrashWithAccount:(NSString *)account FileID:(NSString *)fileID fileName:(NSString *)fileName completion:(void (^)(NSString *account, UIImage *image, NSString *message, NSInteger errorCode))completion
  834. {
  835. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  836. if (tableAccount == nil) {
  837. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  838. } else if ([CCUtility getPassword:account].length == 0) {
  839. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  840. } else if ([CCUtility getCertificateError:account]) {
  841. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  842. }
  843. NSString *file = [NSString stringWithFormat:@"%@/%@.ico", [CCUtility getDirectoryProviderStorageFileID:fileID], fileName];
  844. if ([[NSFileManager defaultManager] fileExistsAtPath:file]) {
  845. completion(account, [UIImage imageWithContentsOfFile:file], nil, 0);
  846. } else {
  847. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  848. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  849. [communication setUserAgent:[CCUtility getUserAgent]];
  850. [communication getRemotePreviewTrashByServer:tableAccount.url ofFileID:fileID onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSData *preview, NSString *redirectedServer) {
  851. [preview writeToFile:file atomically:YES];
  852. completion(account, [UIImage imageWithData:preview], nil, 0);
  853. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  854. NSString *message;
  855. NSInteger errorCode = response.statusCode;
  856. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  857. errorCode = error.code;
  858. // Server Unauthorized
  859. if (errorCode == kOCErrorServerUnauthorized) {
  860. [CCUtility setPassword:account password:nil];
  861. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  862. [CCUtility setCertificateError:account error:YES];
  863. }
  864. // Error
  865. if (errorCode == 503)
  866. message = NSLocalizedString(@"_server_error_retry_", nil);
  867. else
  868. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  869. completion(account, nil, message, errorCode);
  870. }];
  871. }
  872. }
  873. #pragma --------------------------------------------------------------------------------------------
  874. #pragma mark ===== Favorite =====
  875. #pragma --------------------------------------------------------------------------------------------
  876. - (void)listingFavoritesWithAccount:(NSString *)account completion:(void(^)(NSString *account, NSArray *metadatas, NSString *message, NSInteger errorCode))completion
  877. {
  878. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  879. if (tableAccount == nil) {
  880. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  881. } else if ([CCUtility getPassword:account].length == 0) {
  882. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  883. } else if ([CCUtility getCertificateError:account]) {
  884. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  885. }
  886. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  887. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:tableAccount.url];
  888. NSString *url = tableAccount.url;
  889. NSString *userID = tableAccount.userID;
  890. NSString *path = [url stringByAppendingString:k_dav];
  891. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  892. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  893. [communication setUserAgent:[CCUtility getUserAgent]];
  894. [communication listingFavorites:path folder:@"" withUserSessionToken:nil onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer, NSString *token) {
  895. NSMutableArray *metadatas = [NSMutableArray new];
  896. BOOL showHiddenFiles = [CCUtility getShowHiddenFiles];
  897. // Order by fileNamePath
  898. items = [items sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
  899. OCFileDto *record1 = obj1, *record2 = obj2;
  900. NSString *path1 = [[record1.filePath stringByAppendingString:record1.fileName] lowercaseString];
  901. NSString *path2 = [[record2.filePath stringByAppendingString:record2.fileName] lowercaseString];
  902. return [path1 compare:path2];
  903. }];
  904. for(OCFileDto *itemDto in items) {
  905. NSString *serverUrl;
  906. BOOL isFolderEncrypted;
  907. NSString *fileName = [itemDto.fileName stringByReplacingOccurrencesOfString:@"/" withString:@""];
  908. // Skip hidden files
  909. if (fileName.length > 0) {
  910. if (!showHiddenFiles && [[fileName substringToIndex:1] isEqualToString:@"."])
  911. continue;
  912. } else
  913. continue;
  914. NSRange firstInstance = [itemDto.filePath rangeOfString:[NSString stringWithFormat:@"%@/files/%@", k_dav, userID]];
  915. NSString *serverPath = [itemDto.filePath substringFromIndex:firstInstance.length+firstInstance.location+1];
  916. if ([serverPath hasSuffix:@"/"])
  917. serverPath = [serverPath substringToIndex:[serverPath length] - 1];
  918. serverUrl = [CCUtility stringAppendServerUrl:[url stringByAppendingString:k_webDAV] addFileName:serverPath];
  919. if (itemDto.isDirectory) {
  920. (void)[[NCManageDatabase sharedInstance] addDirectoryWithEncrypted:itemDto.isEncrypted favorite:itemDto.isFavorite fileID:itemDto.ocId permissions:itemDto.permissions serverUrl:[NSString stringWithFormat:@"%@/%@", serverUrl, fileName] account:account];
  921. }
  922. isFolderEncrypted = [CCUtility isFolderEncrypted:serverUrl account:account];
  923. [metadatas addObject:[CCUtility trasformedOCFileToCCMetadata:itemDto fileName:itemDto.fileName serverUrl:serverUrl autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:account isFolderEncrypted:isFolderEncrypted]];
  924. }
  925. completion(account, metadatas, nil, 0);
  926. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) {
  927. NSString *message;
  928. NSInteger errorCode = response.statusCode;
  929. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  930. errorCode = error.code;
  931. // Server Unauthorized
  932. if (errorCode == kOCErrorServerUnauthorized) {
  933. [CCUtility setPassword:account password:nil];
  934. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  935. [CCUtility setCertificateError:account error:YES];
  936. }
  937. // Error
  938. if (errorCode == 503)
  939. message = NSLocalizedString(@"_server_error_retry_", nil);
  940. else
  941. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  942. completion(account, nil, message, errorCode);
  943. }];
  944. }
  945. - (void)settingFavoriteWithAccount:(NSString *)account fileName:(NSString *)fileName favorite:(BOOL)favorite completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  946. {
  947. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  948. if (tableAccount == nil) {
  949. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  950. } else if ([CCUtility getPassword:account].length == 0) {
  951. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  952. } else if ([CCUtility getCertificateError:account]) {
  953. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  954. }
  955. NSString *server = [tableAccount.url stringByAppendingString:k_dav];
  956. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  957. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  958. [communication setUserAgent:[CCUtility getUserAgent]];
  959. [communication settingFavoriteServer:server andFileOrFolderPath:fileName favorite:favorite withUserSessionToken:nil onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer, NSString *token) {
  960. completion(account, nil, 0);
  961. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) {
  962. NSString *message;
  963. NSInteger errorCode = response.statusCode;
  964. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  965. errorCode = error.code;
  966. // Server Unauthorized
  967. if (errorCode == kOCErrorServerUnauthorized) {
  968. [CCUtility setPassword:account password:nil];
  969. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  970. [CCUtility setCertificateError:account error:YES];
  971. }
  972. // Error
  973. if (errorCode == 503)
  974. message = NSLocalizedString(@"_server_error_retry_", nil);
  975. else
  976. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  977. completion(account, message, errorCode);
  978. }];
  979. }
  980. #pragma --------------------------------------------------------------------------------------------
  981. #pragma mark ===== Share =====
  982. #pragma --------------------------------------------------------------------------------------------
  983. - (void)readShareWithAccount:(NSString *)account completion:(void (^)(NSString *account, NSArray *items, NSString *message, NSInteger errorCode))completion
  984. {
  985. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  986. if (tableAccount == nil) {
  987. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  988. } else if ([CCUtility getPassword:account].length == 0) {
  989. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  990. } else if ([CCUtility getCertificateError:account]) {
  991. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  992. }
  993. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  994. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  995. [communication setUserAgent:[CCUtility getUserAgent]];
  996. [communication readSharedByServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  997. completion(account, items, nil, 0);
  998. } failureRequest :^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  999. NSString *message;
  1000. NSInteger errorCode = response.statusCode;
  1001. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1002. errorCode = error.code;
  1003. // Server Unauthorized
  1004. if (errorCode == kOCErrorServerUnauthorized) {
  1005. [CCUtility setPassword:account password:nil];
  1006. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  1007. [CCUtility setCertificateError:account error:YES];
  1008. }
  1009. // Error
  1010. if (errorCode == 503) {
  1011. message = NSLocalizedString(@"_server_error_retry_", nil);
  1012. } else {
  1013. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1014. }
  1015. completion(account, nil, message, errorCode);
  1016. }];
  1017. }
  1018. - (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
  1019. {
  1020. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1021. if (tableAccount == nil) {
  1022. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1023. } else if ([CCUtility getPassword:account].length == 0) {
  1024. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1025. } else if ([CCUtility getCertificateError:account]) {
  1026. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1027. }
  1028. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1029. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1030. [communication setUserAgent:[CCUtility getUserAgent]];
  1031. [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) {
  1032. completion(account, nil, 0);
  1033. } failureRequest :^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1034. NSString *message;
  1035. NSInteger errorCode = response.statusCode;
  1036. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1037. errorCode = error.code;
  1038. // Server Unauthorized
  1039. if (errorCode == kOCErrorServerUnauthorized) {
  1040. [CCUtility setPassword:account password:nil];
  1041. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  1042. [CCUtility setCertificateError:account error:YES];
  1043. }
  1044. // Error
  1045. if (errorCode == 503) {
  1046. message = NSLocalizedString(@"_server_error_retry_", nil);
  1047. } else {
  1048. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1049. }
  1050. completion(account, message, errorCode);
  1051. }];
  1052. }
  1053. // * @param shareeType -> NSInteger: to set the type of sharee (user/group/federated)
  1054. - (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
  1055. {
  1056. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1057. if (tableAccount == nil) {
  1058. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1059. } else if ([CCUtility getPassword:account].length == 0) {
  1060. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1061. } else if ([CCUtility getCertificateError:account]) {
  1062. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1063. }
  1064. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1065. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1066. [communication setUserAgent:[CCUtility getUserAgent]];
  1067. [communication shareWith:userOrGroup shareeType:shareeType inServer:[tableAccount.url stringByAppendingString:@"/"] andFileOrFolderPath:[fileName encodeString:NSUTF8StringEncoding] andPermissions:permission onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1068. completion(account, nil, 0);
  1069. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1070. NSString *message;
  1071. NSInteger errorCode = response.statusCode;
  1072. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1073. errorCode = error.code;
  1074. // Server Unauthorized
  1075. if (errorCode == kOCErrorServerUnauthorized) {
  1076. [CCUtility setPassword:account password:nil];
  1077. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  1078. [CCUtility setCertificateError:account error:YES];
  1079. }
  1080. // Error
  1081. if (errorCode == 503) {
  1082. message = NSLocalizedString(@"_server_error_retry_", nil);
  1083. } else {
  1084. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1085. }
  1086. completion(account, message, errorCode);
  1087. }];
  1088. }
  1089. - (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
  1090. {
  1091. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1092. if (tableAccount == nil) {
  1093. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1094. } else if ([CCUtility getPassword:account].length == 0) {
  1095. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1096. } else if ([CCUtility getCertificateError:account]) {
  1097. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1098. }
  1099. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1100. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1101. [communication setUserAgent:[CCUtility getUserAgent]];
  1102. [communication updateShare:shareID ofServerPath:[tableAccount.url stringByAppendingString:@"/"] withPasswordProtect:[password encodeString:NSUTF8StringEncoding] andExpirationTime:expirationTime andPermissions:permission andHideDownload:hideDownload onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1103. completion(account, nil, 0);
  1104. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1105. NSString *message;
  1106. NSInteger errorCode = response.statusCode;
  1107. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1108. errorCode = error.code;
  1109. // Server Unauthorized
  1110. if (errorCode == kOCErrorServerUnauthorized) {
  1111. [CCUtility setPassword:account password:nil];
  1112. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  1113. [CCUtility setCertificateError:account error:YES];
  1114. }
  1115. // Error
  1116. if (errorCode == 503) {
  1117. message = NSLocalizedString(@"_server_error_retry_", nil);
  1118. } else {
  1119. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1120. }
  1121. completion(account, message, errorCode);
  1122. }];
  1123. }
  1124. - (void)unshareAccount:(NSString *)account shareID:(NSInteger)shareID completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  1125. {
  1126. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1127. if (tableAccount == nil) {
  1128. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1129. } else if ([CCUtility getPassword:account].length == 0) {
  1130. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1131. } else if ([CCUtility getCertificateError:account]) {
  1132. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1133. }
  1134. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1135. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1136. [communication setUserAgent:[CCUtility getUserAgent]];
  1137. [communication unShareFileOrFolderByServer:[tableAccount.url stringByAppendingString:@"/"] andIdRemoteShared:shareID onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1138. completion(account, nil, 0);
  1139. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1140. NSString *message;
  1141. NSInteger errorCode = response.statusCode;
  1142. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1143. errorCode = error.code;
  1144. // Server Unauthorized
  1145. if (errorCode == kOCErrorServerUnauthorized) {
  1146. [CCUtility setPassword:account password:nil];
  1147. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  1148. [CCUtility setCertificateError:account error:YES];
  1149. }
  1150. // Error
  1151. if (errorCode == 503) {
  1152. message = NSLocalizedString(@"_server_error_retry_", nil);
  1153. } else {
  1154. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1155. }
  1156. completion(account, message, errorCode);
  1157. }];
  1158. }
  1159. - (void)getUserGroupWithAccount:(NSString *)account searchString:(NSString *)searchString completion:(void (^)(NSString *account, NSArray *item, NSString *message, NSInteger errorCode))completion
  1160. {
  1161. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1162. if (tableAccount == nil) {
  1163. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1164. } else if ([CCUtility getPassword:account].length == 0) {
  1165. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1166. } else if ([CCUtility getCertificateError:account]) {
  1167. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1168. }
  1169. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1170. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1171. [communication setUserAgent:[CCUtility getUserAgent]];
  1172. [communication searchUsersAndGroupsWith:searchString forPage:1 with:50 ofServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *itemList, NSString *redirectedServer) {
  1173. completion(account, itemList, nil, 0);
  1174. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1175. NSString *message;
  1176. NSInteger errorCode = response.statusCode;
  1177. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1178. errorCode = error.code;
  1179. // Server Unauthorized
  1180. if (errorCode == kOCErrorServerUnauthorized) {
  1181. [CCUtility setPassword:account password:nil];
  1182. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  1183. [CCUtility setCertificateError:account error:YES];
  1184. }
  1185. // Error
  1186. if (errorCode == 503) {
  1187. message = NSLocalizedString(@"_server_error_retry_", nil);
  1188. } else {
  1189. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1190. }
  1191. completion(account, nil, message, errorCode);
  1192. }];
  1193. }
  1194. - (void)getSharePermissionsFileWithAccount:(NSString *)account fileNamePath:(NSString *)fileNamePath completion:(void (^)(NSString *account, NSString *permissions, NSString *message, NSInteger errorCode))completion
  1195. {
  1196. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1197. if (tableAccount == nil) {
  1198. completion(account, 0, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1199. } else if ([CCUtility getPassword:account].length == 0) {
  1200. completion(account, 0, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1201. } else if ([CCUtility getCertificateError:account]) {
  1202. completion(account, 0, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1203. }
  1204. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1205. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1206. [communication setUserAgent:[CCUtility getUserAgent]];
  1207. [communication getSharePermissionsFile:fileNamePath onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *permissions, NSString *redirectedServer) {
  1208. completion(account, permissions, nil ,0);
  1209. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1210. NSString *message;
  1211. NSInteger errorCode = response.statusCode;
  1212. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1213. errorCode = error.code;
  1214. // Server Unauthorized
  1215. if (errorCode == kOCErrorServerUnauthorized) {
  1216. [CCUtility setPassword:account password:nil];
  1217. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  1218. [CCUtility setCertificateError:account error:YES];
  1219. }
  1220. // Error
  1221. if (errorCode == 503) {
  1222. message = NSLocalizedString(@"_server_error_retry_", nil);
  1223. } else {
  1224. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1225. }
  1226. completion(account, nil, message, errorCode);
  1227. }];
  1228. }
  1229. #pragma --------------------------------------------------------------------------------------------
  1230. #pragma mark ===== VAR =====
  1231. #pragma --------------------------------------------------------------------------------------------
  1232. - (void)getActivityWithAccount:(NSString *)account since:(NSInteger)since limit:(NSInteger)limit link:(NSString *)link completion:(void(^)(NSString *account, NSArray *listOfActivity, NSString *message, NSInteger errorCode))completion
  1233. {
  1234. BOOL previews = false;
  1235. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1236. if (tableAccount == nil) {
  1237. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1238. } else if ([CCUtility getPassword:account].length == 0) {
  1239. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1240. } else if ([CCUtility getCertificateError:account]) {
  1241. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1242. }
  1243. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilitesWithAccount:account];
  1244. if (capabilities != nil && capabilities.versionMajor >= k_nextcloud_version_15_0) {
  1245. previews = true;
  1246. }
  1247. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1248. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1249. [communication setUserAgent:[CCUtility getUserAgent]];
  1250. [communication getActivityServer:[tableAccount.url stringByAppendingString:@"/"] since:since limit:limit previews:previews link:link onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfActivity, NSString *redirectedServer) {
  1251. completion(account, listOfActivity, nil, 0);
  1252. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1253. NSString *message;
  1254. NSInteger errorCode = response.statusCode;
  1255. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1256. errorCode = error.code;
  1257. // Server Unauthorized
  1258. if (errorCode == kOCErrorServerUnauthorized) {
  1259. [CCUtility setPassword:account password:nil];
  1260. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  1261. [CCUtility setCertificateError:account error:YES];
  1262. }
  1263. // Error
  1264. if (errorCode == 503)
  1265. message = NSLocalizedString(@"_server_error_retry_", nil);
  1266. else
  1267. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1268. completion(account, nil, message, errorCode);
  1269. }];
  1270. }
  1271. - (void)getExternalSitesWithAccount:(NSString *)account completion:(void (^)(NSString *account, NSArray *listOfExternalSites, NSString *message, NSInteger errorCode))completion
  1272. {
  1273. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1274. if (tableAccount == nil) {
  1275. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1276. } else if ([CCUtility getPassword:account].length == 0) {
  1277. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1278. } else if ([CCUtility getCertificateError:account]) {
  1279. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1280. }
  1281. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1282. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1283. [communication setUserAgent:[CCUtility getUserAgent]];
  1284. [communication getExternalSitesServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfExternalSites, NSString *redirectedServer) {
  1285. completion(account, listOfExternalSites, nil, 0);
  1286. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1287. NSString *message;
  1288. NSInteger errorCode = response.statusCode;
  1289. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1290. errorCode = error.code;
  1291. // Server Unauthorized
  1292. if (errorCode == kOCErrorServerUnauthorized) {
  1293. [CCUtility setPassword:account password:nil];
  1294. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  1295. [CCUtility setCertificateError:account error:YES];
  1296. }
  1297. // Error
  1298. if (errorCode == 503) {
  1299. message = NSLocalizedString(@"_server_error_retry_", nil);
  1300. } else {
  1301. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1302. }
  1303. completion(account, nil, message, errorCode);
  1304. }];
  1305. }
  1306. - (void)getNotificationWithAccount:(NSString *)account completion:(void (^)(NSString *account, NSArray *listOfNotifications, NSString *message, NSInteger errorCode))completion
  1307. {
  1308. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1309. if (tableAccount == nil) {
  1310. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1311. } else if ([CCUtility getPassword:account].length == 0) {
  1312. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1313. } else if ([CCUtility getCertificateError:account]) {
  1314. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1315. }
  1316. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1317. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1318. [communication setUserAgent:[CCUtility getUserAgent]];
  1319. [communication getNotificationServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfNotifications, NSString *redirectedServer) {
  1320. completion(account, listOfNotifications, nil, 0);
  1321. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1322. NSString *message;
  1323. NSInteger errorCode = response.statusCode;
  1324. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1325. errorCode = error.code;
  1326. // Server Unauthorized
  1327. if (errorCode == kOCErrorServerUnauthorized) {
  1328. [CCUtility setPassword:account password:nil];
  1329. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  1330. [CCUtility setCertificateError:account error:YES];
  1331. }
  1332. // Error
  1333. if (errorCode == 503) {
  1334. message = NSLocalizedString(@"_server_error_retry_", nil);
  1335. } else {
  1336. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1337. }
  1338. completion(account, nil, message, errorCode);
  1339. }];
  1340. }
  1341. - (void)setNotificationWithAccount:(NSString *)account serverUrl:(NSString *)serverUrl type:(NSString *)type completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  1342. {
  1343. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1344. if (tableAccount == nil) {
  1345. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1346. } else if ([CCUtility getPassword:account].length == 0) {
  1347. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1348. } else if ([CCUtility getCertificateError:account]) {
  1349. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1350. }
  1351. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1352. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1353. [communication setUserAgent:[CCUtility getUserAgent]];
  1354. [communication setNotificationServer:serverUrl type:type onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1355. completion(account, nil, 0);
  1356. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1357. NSString *message;
  1358. NSInteger errorCode = response.statusCode;
  1359. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1360. errorCode = error.code;
  1361. // Server Unauthorized
  1362. if (errorCode == kOCErrorServerUnauthorized) {
  1363. [CCUtility setPassword:account password:nil];
  1364. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  1365. [CCUtility setCertificateError:account error:YES];
  1366. }
  1367. // Error
  1368. if (errorCode == 503) {
  1369. message = NSLocalizedString(@"_server_error_retry_", nil);
  1370. } else {
  1371. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1372. }
  1373. completion(account, message, errorCode);
  1374. }];
  1375. }
  1376. - (void)getCapabilitiesWithAccount:(NSString *)account completion:(void (^)(NSString *account, OCCapabilities *capabilities, NSString *message, NSInteger errorCode))completion
  1377. {
  1378. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1379. if (tableAccount == nil) {
  1380. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1381. } else if ([CCUtility getPassword:account].length == 0) {
  1382. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1383. } else if ([CCUtility getCertificateError:account]) {
  1384. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1385. }
  1386. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1387. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1388. [communication setUserAgent:[CCUtility getUserAgent]];
  1389. [communication getCapabilitiesOfServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, OCCapabilities *capabilities, NSString *redirectedServer) {
  1390. completion(account, capabilities, nil, 0);
  1391. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1392. NSString *message;
  1393. NSInteger errorCode = response.statusCode;
  1394. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1395. errorCode = error.code;
  1396. // Server Unauthorized
  1397. if (errorCode == kOCErrorServerUnauthorized) {
  1398. [CCUtility setPassword:account password:nil];
  1399. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  1400. [CCUtility setCertificateError:account error:YES];
  1401. }
  1402. // Error
  1403. if (errorCode == 503) {
  1404. message = NSLocalizedString(@"_server_error_retry_", nil);
  1405. } else {
  1406. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1407. }
  1408. completion(account, nil, message, errorCode);
  1409. }];
  1410. }
  1411. - (void)getUserProfileWithAccount:(NSString *)account completion:(void (^)(NSString *account, OCUserProfile *userProfile, NSString *message, NSInteger errorCode))completion
  1412. {
  1413. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1414. if (tableAccount == nil) {
  1415. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1416. } else if ([CCUtility getPassword:account].length == 0) {
  1417. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1418. } else if ([CCUtility getCertificateError:account]) {
  1419. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1420. }
  1421. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1422. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1423. [communication setUserAgent:[CCUtility getUserAgent]];
  1424. [communication getUserProfileServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, OCUserProfile *userProfile, NSString *redirectedServer) {
  1425. completion(account, userProfile, nil, 0);
  1426. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1427. NSString *message;
  1428. NSInteger errorCode = response.statusCode;
  1429. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1430. errorCode = error.code;
  1431. // Server Unauthorized
  1432. if (errorCode == kOCErrorServerUnauthorized) {
  1433. [CCUtility setPassword:account password:nil];
  1434. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  1435. [CCUtility setCertificateError:account error:YES];
  1436. }
  1437. // Error
  1438. if (errorCode == 503) {
  1439. message = NSLocalizedString(@"_server_error_retry_", nil);
  1440. } else {
  1441. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1442. }
  1443. completion(account, nil, message, errorCode);
  1444. }];
  1445. }
  1446. #pragma --------------------------------------------------------------------------------------------
  1447. #pragma mark ===== Push Notification =====
  1448. #pragma --------------------------------------------------------------------------------------------
  1449. - (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
  1450. {
  1451. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1452. if (tableAccount == nil) {
  1453. completion(account, nil, nil, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1454. } else if ([CCUtility getPassword:account].length == 0) {
  1455. completion(account, nil, nil, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1456. } else if ([CCUtility getCertificateError:account]) {
  1457. completion(account, nil, nil, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1458. }
  1459. devicePublicKey = [CCUtility URLEncodeStringFromString:devicePublicKey];
  1460. NSString *proxyServerPath = [NCBrandOptions sharedInstance].pushNotificationServerProxy;
  1461. NSString *proxyServer = [NCBrandOptions sharedInstance].pushNotificationServerProxy;
  1462. #ifdef DEBUG
  1463. proxyServerPath = @"http://127.0.0.1:8088";
  1464. proxyServer = @"https://10.132.0.37:8443/pushnotifications";
  1465. #endif
  1466. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1467. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1468. [communication setUserAgent:[CCUtility getUserAgent]];
  1469. [communication subscribingNextcloudServerPush:url pushTokenHash:pushTokenHash devicePublicKey:devicePublicKey proxyServerPath: proxyServerPath onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *publicKey, NSString *deviceIdentifier, NSString *signature, NSString *redirectedServer) {
  1470. deviceIdentifier = [CCUtility URLEncodeStringFromString:deviceIdentifier];
  1471. signature = [CCUtility URLEncodeStringFromString:signature];
  1472. publicKey = [CCUtility URLEncodeStringFromString:publicKey];
  1473. [communication subscribingPushProxy:proxyServer pushToken:pushToken deviceIdentifier:deviceIdentifier deviceIdentifierSignature:signature publicKey:publicKey onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1474. completion(account, deviceIdentifier, signature, publicKey, nil, 0);
  1475. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1476. NSString *message;
  1477. NSInteger errorCode = response.statusCode;
  1478. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1479. errorCode = error.code;
  1480. // Server Unauthorized
  1481. if (errorCode == kOCErrorServerUnauthorized) {
  1482. [CCUtility setPassword:account password:nil];
  1483. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  1484. [CCUtility setCertificateError:account error:YES];
  1485. }
  1486. // Error
  1487. if (errorCode == 503)
  1488. message = NSLocalizedString(@"_server_error_retry_", nil);
  1489. else
  1490. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1491. completion(account, nil, nil, nil, message, errorCode);
  1492. }];
  1493. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1494. NSString *message;
  1495. NSInteger errorCode = response.statusCode;
  1496. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1497. errorCode = error.code;
  1498. // Server Unauthorized
  1499. if (errorCode == kOCErrorServerUnauthorized) {
  1500. [CCUtility setPassword:account password:nil];
  1501. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  1502. [CCUtility setCertificateError:account error:YES];
  1503. }
  1504. // Error
  1505. if (errorCode == 503)
  1506. message = NSLocalizedString(@"_server_error_retry_", nil);
  1507. else
  1508. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1509. completion(account, nil, nil, nil, message, errorCode);
  1510. }];
  1511. }
  1512. - (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 {
  1513. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1514. if (tableAccount == nil) {
  1515. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1516. } else if ([CCUtility getPassword:account].length == 0) {
  1517. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1518. } else if ([CCUtility getCertificateError:account]) {
  1519. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1520. }
  1521. NSString *proxyServer = [NCBrandOptions sharedInstance].pushNotificationServerProxy;
  1522. #ifdef DEBUG
  1523. proxyServer = @"https://10.132.0.37:8443/pushnotifications";
  1524. #endif
  1525. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1526. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1527. [communication setUserAgent:[CCUtility getUserAgent]];
  1528. [communication unsubscribingNextcloudServerPush:url onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1529. [communication unsubscribingPushProxy:proxyServer deviceIdentifier:deviceIdentifier deviceIdentifierSignature:deviceIdentifierSignature publicKey:publicKey onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1530. completion(account, nil, 0);
  1531. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1532. NSString *message;
  1533. NSInteger errorCode = response.statusCode;
  1534. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1535. errorCode = error.code;
  1536. // Server Unauthorized
  1537. if (errorCode == kOCErrorServerUnauthorized) {
  1538. [CCUtility setPassword:account password:nil];
  1539. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  1540. [CCUtility setCertificateError:account error:YES];
  1541. }
  1542. // Error
  1543. if (errorCode == 503)
  1544. message = NSLocalizedString(@"_server_error_retry_", nil);
  1545. else
  1546. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1547. completion(account, message, errorCode);
  1548. }];
  1549. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1550. NSString *message;
  1551. NSInteger errorCode = response.statusCode;
  1552. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1553. errorCode = error.code;
  1554. // Server Unauthorized
  1555. if (errorCode == kOCErrorServerUnauthorized) {
  1556. [CCUtility setPassword:account password:nil];
  1557. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  1558. [CCUtility setCertificateError:account error:YES];
  1559. }
  1560. // Error
  1561. if (errorCode == 503)
  1562. message = NSLocalizedString(@"_server_error_retry_", nil);
  1563. else
  1564. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1565. completion(account, message, errorCode);
  1566. }];
  1567. }
  1568. - (void)getServerNotification:(NSString *)serverUrl notificationId:(NSInteger)notificationId completion:(void(^)(NSDictionary*jsongParsed, NSString *message, NSInteger errorCode))completion
  1569. {
  1570. NSString *URLString = [NSString stringWithFormat:@"%@/ocs/v2.php/apps/notifications/api/v2/notifications/%ld?format=json", serverUrl, (long)notificationId];
  1571. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URLString] cachePolicy:0 timeoutInterval:20.0];
  1572. [request addValue:[CCUtility getUserAgent] forHTTPHeaderField:@"User-Agent"];
  1573. [request addValue:@"true" forHTTPHeaderField:@"OCS-APIRequest"];
  1574. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  1575. NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  1576. NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler: ^(NSData *data, NSURLResponse *response, NSError *error) {
  1577. if (error) {
  1578. NSString *message;
  1579. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
  1580. NSInteger errorCode = httpResponse.statusCode;
  1581. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1582. errorCode = error.code;
  1583. // Error
  1584. if (errorCode == 503)
  1585. message = NSLocalizedString(@"_server_error_retry_", nil);
  1586. else
  1587. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1588. completion(nil, message, errorCode);
  1589. } else {
  1590. NSDictionary *jsongParsed = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
  1591. completion(jsongParsed, nil, 0);
  1592. }
  1593. }];
  1594. [task resume];
  1595. }
  1596. #pragma --------------------------------------------------------------------------------------------
  1597. #pragma mark ===== Manage Mobile Editor OCS API =====
  1598. #pragma --------------------------------------------------------------------------------------------
  1599. - (void)createLinkRichdocumentsWithAccount:(NSString *)account fileID:(NSString *)fileID completion:(void(^)(NSString *account, NSString *link, NSString *message, NSInteger errorCode))completion
  1600. {
  1601. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1602. if (tableAccount == nil) {
  1603. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1604. } else if ([CCUtility getPassword:account].length == 0) {
  1605. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1606. } else if ([CCUtility getCertificateError:account]) {
  1607. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1608. }
  1609. NSString *fileIDServer = [[NCUtility sharedInstance] convertFileIDClientToFileIDServer:fileID];
  1610. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1611. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1612. [communication setUserAgent:[CCUtility getUserAgent]];
  1613. [communication createLinkRichdocuments:[tableAccount.url stringByAppendingString:@"/"] fileID:fileIDServer onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *link, NSString *redirectedServer) {
  1614. completion(account, link, nil, 0);
  1615. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1616. NSString *message;
  1617. NSInteger errorCode = response.statusCode;
  1618. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1619. errorCode = error.code;
  1620. // Server Unauthorized
  1621. if (errorCode == kOCErrorServerUnauthorized) {
  1622. [CCUtility setPassword:account password:nil];
  1623. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  1624. [CCUtility setCertificateError:account error:YES];
  1625. }
  1626. // Error
  1627. if (errorCode == 503)
  1628. message = NSLocalizedString(@"_server_error_retry_", nil);
  1629. else
  1630. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1631. completion(account, nil,message, errorCode);
  1632. }];
  1633. }
  1634. - (void)geTemplatesRichdocumentsWithAccount:(NSString *)account typeTemplate:(NSString *)typeTemplate completion:(void(^)(NSString *account, NSArray *listOfTemplate, NSString *message, NSInteger errorCode))completion
  1635. {
  1636. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1637. if (tableAccount == nil) {
  1638. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1639. } else if ([CCUtility getPassword:account].length == 0) {
  1640. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1641. } else if ([CCUtility getCertificateError:account]) {
  1642. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1643. }
  1644. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1645. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1646. [communication setUserAgent:[CCUtility getUserAgent]];
  1647. [communication geTemplatesRichdocuments:[tableAccount.url stringByAppendingString:@"/"] typeTemplate:typeTemplate onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfTemplate, NSString *redirectedServer) {
  1648. completion(account, listOfTemplate, nil, 0);
  1649. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1650. NSString *message;
  1651. NSInteger errorCode = response.statusCode;
  1652. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1653. errorCode = error.code;
  1654. // Server Unauthorized
  1655. if (errorCode == kOCErrorServerUnauthorized) {
  1656. [CCUtility setPassword:account password:nil];
  1657. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  1658. [CCUtility setCertificateError:account error:YES];
  1659. }
  1660. // Error
  1661. if (errorCode == 503)
  1662. message = NSLocalizedString(@"_server_error_retry_", nil);
  1663. else
  1664. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1665. completion(account, nil, message, errorCode);
  1666. }];
  1667. }
  1668. - (void)createNewRichdocumentsWithAccount:(NSString *)account fileName:(NSString *)fileName serverUrl:(NSString *)serverUrl templateID:(NSString *)templateID completion:(void(^)(NSString *account, NSString *url, NSString *message, NSInteger errorCode))completion
  1669. {
  1670. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1671. if (tableAccount == nil) {
  1672. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1673. } else if ([CCUtility getPassword:account].length == 0) {
  1674. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1675. } else if ([CCUtility getCertificateError:account]) {
  1676. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1677. }
  1678. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1679. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1680. [communication setUserAgent:[CCUtility getUserAgent]];
  1681. [communication createNewRichdocuments:[tableAccount.url stringByAppendingString:@"/"] path:fileName templateID:templateID onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *url, NSString *redirectedServer) {
  1682. completion(account, url, nil, 0);
  1683. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1684. NSString *message;
  1685. NSInteger errorCode = response.statusCode;
  1686. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1687. errorCode = error.code;
  1688. // Server Unauthorized
  1689. if (errorCode == kOCErrorServerUnauthorized) {
  1690. [CCUtility setPassword:account password:nil];
  1691. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  1692. [CCUtility setCertificateError:account error:YES];
  1693. }
  1694. // Error
  1695. if (errorCode == 503)
  1696. message = NSLocalizedString(@"_server_error_retry_", nil);
  1697. else
  1698. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1699. completion(account, nil, message, errorCode);
  1700. }];
  1701. }
  1702. - (void)createAssetRichdocumentsWithAccount:(NSString *)account fileName:(NSString *)fileName serverUrl:(NSString *)serverUrl completion:(void(^)(NSString *account, NSString *link, NSString *message, NSInteger errorCode))completion
  1703. {
  1704. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1705. if (tableAccount == nil) {
  1706. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1707. } else if ([CCUtility getPassword:account].length == 0) {
  1708. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1709. } else if ([CCUtility getCertificateError:account]) {
  1710. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1711. }
  1712. NSString *fileNamePath = [CCUtility returnFileNamePathFromFileName:fileName serverUrl:serverUrl activeUrl:tableAccount.url];
  1713. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1714. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1715. [communication setUserAgent:[CCUtility getUserAgent]];
  1716. [communication createAssetRichdocuments:[tableAccount.url stringByAppendingString:@"/"] path:fileNamePath onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *url, NSString *redirectedServer) {
  1717. completion(account, url, nil, 0);
  1718. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1719. NSString *message;
  1720. NSInteger errorCode = response.statusCode;
  1721. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1722. errorCode = error.code;
  1723. // Server Unauthorized
  1724. if (errorCode == kOCErrorServerUnauthorized) {
  1725. [CCUtility setPassword:account password:nil];
  1726. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  1727. [CCUtility setCertificateError:account error:YES];
  1728. }
  1729. // Error
  1730. if (errorCode == 503)
  1731. message = NSLocalizedString(@"_server_error_retry_", nil);
  1732. else
  1733. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1734. completion(account, nil, message, errorCode);
  1735. }];
  1736. }
  1737. #pragma --------------------------------------------------------------------------------------------
  1738. #pragma mark ===== Trash =====
  1739. #pragma --------------------------------------------------------------------------------------------
  1740. - (void)listingTrashWithAccount:(NSString *)account path:(NSString *)path serverUrl:(NSString *)serverUrl depth:(NSString *)depth completion:(void (^)(NSString *account, NSArray *items, NSString *message, NSInteger errorCode))completion
  1741. {
  1742. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1743. if (tableAccount == nil) {
  1744. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1745. } else if ([CCUtility getPassword:account].length == 0) {
  1746. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1747. } else if ([CCUtility getCertificateError:account]) {
  1748. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1749. }
  1750. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1751. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1752. [communication setUserAgent:[CCUtility getUserAgent]];
  1753. [communication listingTrash:[serverUrl stringByAppendingString:path] depth:depth onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  1754. // Check items > 0
  1755. if ([items count] == 0) {
  1756. #ifndef EXTENSION
  1757. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  1758. [appDelegate messageNotification:@"Server error" description:@"Read Folder WebDAV : [items NULL] please fix" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  1759. #endif
  1760. completion(account, nil, NSLocalizedString(@"Read Folder WebDAV : [items NULL] please fix", nil), k_CCErrorInternalError);
  1761. } else {
  1762. NSMutableArray *listTrash = [NSMutableArray new];
  1763. //OCFileDto *itemDtoFolder = [items objectAtIndex:0];
  1764. if ([items count] > 1) {
  1765. for (NSUInteger i=1; i < [items count]; i++) {
  1766. OCFileDto *itemDto = [items objectAtIndex:i];
  1767. tableTrash *trash = [tableTrash new];
  1768. trash.account = account;
  1769. trash.date = [NSDate dateWithTimeIntervalSince1970:itemDto.date];
  1770. trash.directory = itemDto.isDirectory;
  1771. trash.fileID = itemDto.ocId;
  1772. trash.fileName = itemDto.fileName;
  1773. NSArray *array = [itemDto.filePath componentsSeparatedByString:path];
  1774. long len = [[array objectAtIndex:0] length];
  1775. trash.filePath = [itemDto.filePath substringFromIndex:len];
  1776. trash.size = itemDto.size;
  1777. trash.trashbinFileName = itemDto.trashbinFileName;
  1778. trash.trashbinOriginalLocation = itemDto.trashbinOriginalLocation;
  1779. trash.trashbinDeletionTime = [NSDate dateWithTimeIntervalSince1970:itemDto.trashbinDeletionTime];
  1780. [CCUtility insertTypeFileIconName:trash.trashbinFileName metadata:(tableMetadata *)trash];
  1781. [listTrash addObject:trash];
  1782. }
  1783. }
  1784. completion(account, listTrash, nil, 0);
  1785. }
  1786. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1787. NSString *message;
  1788. NSInteger errorCode = response.statusCode;
  1789. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1790. errorCode = error.code;
  1791. // Server Unauthorized
  1792. if (errorCode == kOCErrorServerUnauthorized) {
  1793. [CCUtility setPassword:account password:nil];
  1794. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  1795. [CCUtility setCertificateError:account error:YES];
  1796. }
  1797. // Error
  1798. if (errorCode == 503)
  1799. message = NSLocalizedString(@"_server_error_retry_", nil);
  1800. else
  1801. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1802. completion(account, nil,message, errorCode);
  1803. }];
  1804. }
  1805. - (void)emptyTrashWithAccount:(NSString *)account completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  1806. {
  1807. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1808. if (tableAccount == nil) {
  1809. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1810. } else if ([CCUtility getPassword:account].length == 0) {
  1811. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1812. } else if ([CCUtility getCertificateError:account]) {
  1813. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1814. }
  1815. NSString *path = [NSString stringWithFormat:@"%@%@/trashbin/%@/trash", tableAccount.url, k_dav, tableAccount.userID];
  1816. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1817. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1818. [communication setUserAgent:[CCUtility getUserAgent]];
  1819. [communication emptyTrash:path onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1820. completion(account, nil, 0);
  1821. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1822. NSString *message;
  1823. NSInteger errorCode = response.statusCode;
  1824. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1825. errorCode = error.code;
  1826. // Server Unauthorized
  1827. if (errorCode == kOCErrorServerUnauthorized) {
  1828. [CCUtility setPassword:account password:nil];
  1829. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  1830. [CCUtility setCertificateError:account error:YES];
  1831. }
  1832. // Error
  1833. if (errorCode == 503)
  1834. message = NSLocalizedString(@"_server_error_retry_", nil);
  1835. else
  1836. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1837. completion(account, message, errorCode);
  1838. }];
  1839. }
  1840. #pragma --------------------------------------------------------------------------------------------
  1841. #pragma mark ===== Third Parts =====
  1842. #pragma --------------------------------------------------------------------------------------------
  1843. - (void)getHCUserProfileWithAccount:(NSString *)account serverUrl:(NSString *)serverUrl completion:(void (^)(NSString *account, OCUserProfile *userProfile, NSString *message, NSInteger errorCode))completion
  1844. {
  1845. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1846. if (tableAccount == nil) {
  1847. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1848. } else if ([CCUtility getPassword:account].length == 0) {
  1849. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1850. } else if ([CCUtility getCertificateError:account]) {
  1851. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1852. }
  1853. NSString *serverPath = [NSString stringWithFormat:@"%@/ocs/v2.php/apps/handwerkcloud/api/v1/settings/%@", serverUrl, tableAccount.userID];
  1854. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1855. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1856. [communication setUserAgent:[CCUtility getUserAgent]];
  1857. [communication getHCUserProfile:serverPath onCommunication:communication successRequest:^(NSHTTPURLResponse *response, OCUserProfile *userProfile, NSString *redirectedServer) {
  1858. completion(account, userProfile, nil, 0);
  1859. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1860. NSString *message;
  1861. NSInteger errorCode = response.statusCode;
  1862. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1863. errorCode = error.code;
  1864. // Server Unauthorized
  1865. if (errorCode == kOCErrorServerUnauthorized) {
  1866. [CCUtility setPassword:account password:nil];
  1867. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  1868. [CCUtility setCertificateError:account error:YES];
  1869. }
  1870. // Error
  1871. if (errorCode == 503)
  1872. message = NSLocalizedString(@"_server_error_retry_", nil);
  1873. else
  1874. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1875. completion(account, nil,message, errorCode);
  1876. }];
  1877. }
  1878. - (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
  1879. {
  1880. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1881. if (tableAccount == nil) {
  1882. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1883. } else if ([CCUtility getPassword:account].length == 0) {
  1884. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1885. } else if ([CCUtility getCertificateError:account]) {
  1886. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1887. }
  1888. // Create JSON
  1889. NSMutableDictionary *dataDic = [NSMutableDictionary new];
  1890. if (address) [dataDic setValue:address forKey:@"address"];
  1891. if (businesssize) {
  1892. if ([businesssize isEqualToString:@"1-4"]) { [dataDic setValue:[NSNumber numberWithInt:1] forKey:@"businesssize"]; }
  1893. else if ([businesssize isEqualToString:@"5-9"]) { [dataDic setValue:[NSNumber numberWithInt:5] forKey:@"businesssize"]; }
  1894. else if ([businesssize isEqualToString:@"10-19"]) { [dataDic setValue:[NSNumber numberWithInt:10] forKey:@"businesssize"]; }
  1895. else if ([businesssize isEqualToString:@"20-49"]) { [dataDic setValue:[NSNumber numberWithInt:20] forKey:@"businesssize"]; }
  1896. else if ([businesssize isEqualToString:@"50-99"]) { [dataDic setValue:[NSNumber numberWithInt:50] forKey:@"businesssize"]; }
  1897. else if ([businesssize isEqualToString:@"100-249"]) { [dataDic setValue:[NSNumber numberWithInt:100] forKey:@"businesssize"]; }
  1898. else if ([businesssize isEqualToString:@"250-499"]) { [dataDic setValue:[NSNumber numberWithInt:250] forKey:@"businesssize"]; }
  1899. else if ([businesssize isEqualToString:@"500-999"]) { [dataDic setValue:[NSNumber numberWithInt:500] forKey:@"businesssize"]; }
  1900. else if ([businesssize isEqualToString:@"1000+"]) { [dataDic setValue:[NSNumber numberWithInt:1000] forKey:@"businesssize"]; }
  1901. }
  1902. if (businesstype) [dataDic setValue:businesstype forKey:@"businesstype"];
  1903. if (city) [dataDic setValue:city forKey:@"city"];
  1904. if (company) [dataDic setValue:company forKey:@"company"];
  1905. if (country) [dataDic setValue:country forKey:@"country"];
  1906. if (displayname) [dataDic setValue:displayname forKey:@"displayname"];
  1907. if (email) [dataDic setValue:email forKey:@"email"];
  1908. if (phone) [dataDic setValue:phone forKey:@"phone"];
  1909. if (role_) [dataDic setValue:role_ forKey:@"role"];
  1910. if (twitter) [dataDic setValue:twitter forKey:@"twitter"];
  1911. if (website) [dataDic setValue:website forKey:@"website"];
  1912. if (zip) [dataDic setValue:zip forKey:@"zip"];
  1913. NSString *data = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:dataDic options:0 error:nil] encoding:NSUTF8StringEncoding];
  1914. NSString *serverPath = [NSString stringWithFormat:@"%@/ocs/v2.php/apps/handwerkcloud/api/v1/settings/%@", serverUrl, tableAccount.userID];
  1915. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1916. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1917. [communication setUserAgent:[CCUtility getUserAgent]];
  1918. [communication putHCUserProfile:serverPath data:data onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1919. completion(account, nil, 0);
  1920. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1921. NSString *message;
  1922. NSInteger errorCode = response.statusCode;
  1923. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1924. errorCode = error.code;
  1925. // Server Unauthorized
  1926. if (errorCode == kOCErrorServerUnauthorized) {
  1927. [CCUtility setPassword:account password:nil];
  1928. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  1929. [CCUtility setCertificateError:account error:YES];
  1930. }
  1931. // Error
  1932. if (errorCode == 503)
  1933. message = NSLocalizedString(@"_server_error_retry_", nil);
  1934. else
  1935. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1936. completion(account, message, errorCode);
  1937. }];
  1938. }
  1939. - (void)getHCFeaturesWithAccount:(NSString *)account serverUrl:(NSString *)serverUrl completion:(void (^)(NSString *account, HCFeatures *features, NSString *message, NSInteger errorCode))completion
  1940. {
  1941. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1942. if (tableAccount == nil) {
  1943. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1944. } else if ([CCUtility getPassword:account].length == 0) {
  1945. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1946. } else if ([CCUtility getCertificateError:account]) {
  1947. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1948. }
  1949. NSString *serverPath = [NSString stringWithFormat:@"%@/ocs/v2.php/apps/handwerkcloud/api/v1/features/%@", serverUrl, tableAccount.userID];
  1950. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1951. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1952. [communication setUserAgent:[CCUtility getUserAgent]];
  1953. [communication getHCFeatures:serverPath onCommunication:communication successRequest:^(NSHTTPURLResponse *response, HCFeatures *features, NSString *redirectedServer) {
  1954. completion(account, features, nil, 0);
  1955. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1956. NSString *message;
  1957. NSInteger errorCode = response.statusCode;
  1958. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1959. errorCode = error.code;
  1960. // Server Unauthorized
  1961. if (errorCode == kOCErrorServerUnauthorized) {
  1962. [CCUtility setPassword:account password:nil];
  1963. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  1964. [CCUtility setCertificateError:account error:YES];
  1965. }
  1966. // Error
  1967. if (errorCode == 503)
  1968. message = NSLocalizedString(@"_server_error_retry_", nil);
  1969. else
  1970. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1971. completion(account, nil,message, errorCode);
  1972. }];
  1973. }
  1974. /*
  1975. - (void)middlewarePing
  1976. {
  1977. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1978. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  1979. [communication setUserAgent:[CCUtility getUserAgent]];
  1980. [communication getMiddlewarePing:_metadataNet.serverUrl onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfExternalSites, NSString *redirectedServer) {
  1981. [self complete];
  1982. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1983. NSInteger errorCode = response.statusCode;
  1984. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1985. errorCode = error.code;
  1986. // Error
  1987. if ([self.delegate respondsToSelector:@selector(getExternalSitesServerFailure:message:errorCode:)]) {
  1988. if (errorCode == 503)
  1989. [self.delegate getExternalSitesServerFailure:_metadataNet message:NSLocalizedString(@"_server_error_retry_", nil) errorCode:errorCode];
  1990. else
  1991. [self.delegate getExternalSitesServerFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1992. }
  1993. // Request trusted certificated
  1994. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  1995. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1996. [self complete];
  1997. }];
  1998. }
  1999. */
  2000. #pragma --------------------------------------------------------------------------------------------
  2001. #pragma mark ===== didReceiveChallenge =====
  2002. #pragma --------------------------------------------------------------------------------------------
  2003. -(void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler
  2004. {
  2005. // The pinnning check
  2006. if ([[CCCertificate sharedManager] checkTrustedChallenge:challenge]) {
  2007. completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  2008. } else {
  2009. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  2010. }
  2011. }
  2012. @end
  2013. #pragma --------------------------------------------------------------------------------------------
  2014. #pragma mark ===== OCURLSessionManager =====
  2015. #pragma --------------------------------------------------------------------------------------------
  2016. @implementation OCURLSessionManager
  2017. - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
  2018. {
  2019. // The pinnning check
  2020. if ([[CCCertificate sharedManager] checkTrustedChallenge:challenge]) {
  2021. completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  2022. } else {
  2023. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  2024. }
  2025. }
  2026. @end