OCNetworking.m 142 KB

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