OCNetworking.m 153 KB

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