OCNetworking.m 156 KB

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