OCNetworking.m 159 KB

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