OCNetworking.m 158 KB

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