OCNetworking.m 159 KB

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