OCNetworking.m 149 KB

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