OCNetworking.m 124 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375
  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. /*
  400. - (void)readFileWithAccount:(NSString *)account serverUrl:(NSString *)serverUrl fileName:(NSString *)fileName completion:(void(^)(NSString *account, tableMetadata *metadata, NSString *message, NSInteger errorCode))completion
  401. {
  402. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  403. if (tableAccount == nil) {
  404. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  405. } else if ([CCUtility getPassword:account].length == 0) {
  406. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  407. } else if ([CCUtility getCertificateError:account]) {
  408. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  409. }
  410. NSString *fileNamePath;
  411. if (fileName) {
  412. fileNamePath = [NSString stringWithFormat:@"%@/%@", serverUrl, fileName];
  413. } else {
  414. fileName= @".";
  415. fileNamePath = serverUrl;
  416. }
  417. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  418. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  419. [communication setUserAgent:[CCUtility getUserAgent]];
  420. [communication readFile:fileNamePath onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  421. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:serverUrl account:account];
  422. if ([items count] > 0) {
  423. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  424. tableMetadata *metadata = [tableMetadata new];
  425. OCFileDto *itemDto = [items objectAtIndex:0];
  426. metadata = [CCUtility trasformedOCFileToCCMetadata:itemDto fileName:fileName serverUrl:serverUrl account:account isFolderEncrypted:isFolderEncrypted];
  427. dispatch_async(dispatch_get_main_queue(), ^{
  428. completion(account, metadata, nil, 0);
  429. });
  430. });
  431. // BUG 1038 item == 0
  432. } else {
  433. [[NCContentPresenter shared] messageNotification:@"Server error" description:@"Read File WebDAV : [items NULL] please fix" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  434. completion(account, nil, NSLocalizedString(@"Read File WebDAV : [items NULL] please fix", nil), k_CCErrorInternalError);
  435. }
  436. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  437. NSString *message;
  438. NSInteger errorCode = response.statusCode;
  439. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  440. errorCode = error.code;
  441. // Server Unauthorized
  442. if (errorCode == kOCErrorServerUnauthorized || errorCode == kOCErrorServerForbidden) {
  443. [[OCNetworking sharedManager] checkRemoteUser:account function:@"read file or folder" errorCode:errorCode];
  444. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  445. [CCUtility setCertificateError:account error:YES];
  446. }
  447. // Error
  448. if (errorCode == 503)
  449. message = NSLocalizedString(@"_server_error_retry_", nil);
  450. else
  451. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  452. completion(account, nil, message, errorCode);
  453. }];
  454. }
  455. - (void)readFolderWithAccount:(NSString *)account serverUrl:(NSString *)serverUrl depth:(NSString *)depth completion:(void(^)(NSString *account, NSArray *metadatas, tableMetadata *metadataFolder, NSString *message, NSInteger errorCode))completion
  456. {
  457. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  458. if (tableAccount == nil) {
  459. completion(account, nil, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  460. } else if ([CCUtility getPassword:account].length == 0) {
  461. completion(account, nil, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  462. } else if ([CCUtility getCertificateError:account]) {
  463. completion(account, nil, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  464. }
  465. NSString *url = tableAccount.url;
  466. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  467. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  468. [communication setUserAgent:[CCUtility getUserAgent]];
  469. [communication readFolder:serverUrl depth:depth withUserSessionToken:nil onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer, NSString *token) {
  470. // Check items > 0
  471. if ([items count] == 0) {
  472. [[NCContentPresenter shared] messageNotification:@"Server error" description:@"Read Folder WebDAV : [items NULL] please fix" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  473. completion(account, nil, nil, NSLocalizedString(@"Read Folder WebDAV : [items NULL] please fix", nil), k_CCErrorInternalError);
  474. } else {
  475. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  476. BOOL showHiddenFiles = [CCUtility getShowHiddenFiles];
  477. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:serverUrl account:account];
  478. // directory [0]
  479. OCFileDto *itemDtoFolder = [items objectAtIndex:0];
  480. //NSDate *date = [NSDate dateWithTimeIntervalSince1970:itemDtoDirectory.date];
  481. NSMutableArray *metadatas = [NSMutableArray new];
  482. tableMetadata *metadataFolder = [tableMetadata new];
  483. NSString *serverUrlFolder;
  484. // Metadata . (self Folder)
  485. if ([serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:url]]) {
  486. // root folder
  487. serverUrlFolder = k_serverUrl_root;
  488. metadataFolder = [CCUtility trasformedOCFileToCCMetadata:itemDtoFolder fileName:@"." serverUrl:serverUrlFolder account:account isFolderEncrypted:isFolderEncrypted];
  489. } else {
  490. serverUrlFolder = [CCUtility deletingLastPathComponentFromServerUrl:serverUrl];
  491. metadataFolder = [CCUtility trasformedOCFileToCCMetadata:itemDtoFolder fileName:[serverUrl lastPathComponent] serverUrl:serverUrlFolder account:account isFolderEncrypted:isFolderEncrypted];
  492. }
  493. // Add metadata folder
  494. (void)[[NCManageDatabase sharedInstance] addDirectoryWithEncrypted:itemDtoFolder.isEncrypted favorite:itemDtoFolder.isFavorite ocId:itemDtoFolder.ocId permissions:itemDtoFolder.permissions serverUrl:serverUrl richWorkspace:nil account:account];
  495. NSArray *itemsSortedArray = [items sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
  496. NSString *first = [(OCFileDto*)a fileName];
  497. NSString *second = [(OCFileDto*)b fileName];
  498. return [[first lowercaseString] compare:[second lowercaseString]];
  499. }];
  500. for (NSUInteger i=1; i < [itemsSortedArray count]; i++) {
  501. OCFileDto *itemDto = [itemsSortedArray objectAtIndex:i];
  502. NSString *fileName = [itemDto.fileName stringByReplacingOccurrencesOfString:@"/" withString:@""];
  503. // Skip hidden files
  504. if (fileName.length > 0) {
  505. if (!showHiddenFiles && [[fileName substringToIndex:1] isEqualToString:@"."])
  506. continue;
  507. } else {
  508. continue;
  509. }
  510. if (itemDto.isDirectory) {
  511. (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];
  512. }
  513. [metadatas addObject:[CCUtility trasformedOCFileToCCMetadata:itemDto fileName:itemDto.fileName serverUrl:serverUrl account:account isFolderEncrypted:isFolderEncrypted]];
  514. }
  515. dispatch_async(dispatch_get_main_queue(), ^{
  516. completion(account, metadatas, metadataFolder, nil, 0);
  517. });
  518. });
  519. }
  520. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) {
  521. NSString *message;
  522. NSInteger errorCode = response.statusCode;
  523. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  524. errorCode = error.code;
  525. // Server Unauthorized
  526. if (errorCode == kOCErrorServerUnauthorized || errorCode == kOCErrorServerForbidden) {
  527. [[OCNetworking sharedManager] checkRemoteUser:account function:@"read file or folder" errorCode:errorCode];
  528. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  529. [CCUtility setCertificateError:account error:YES];
  530. }
  531. // Error
  532. if (errorCode == 503)
  533. message = NSLocalizedString(@"_server_error_retry_", nil);
  534. else
  535. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  536. completion(account, nil, nil, message, errorCode);
  537. }];
  538. }
  539. */
  540. #pragma --------------------------------------------------------------------------------------------
  541. #pragma mark ===== Share =====
  542. #pragma --------------------------------------------------------------------------------------------
  543. - (void)readShareWithAccount:(NSString *)account completion:(void (^)(NSString *account, NSArray *items, NSString *message, NSInteger errorCode))completion
  544. {
  545. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  546. if (tableAccount == nil) {
  547. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  548. } else if ([CCUtility getPassword:account].length == 0) {
  549. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  550. } else if ([CCUtility getCertificateError:account]) {
  551. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  552. }
  553. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  554. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  555. [communication setUserAgent:[CCUtility getUserAgent]];
  556. [communication readSharedByServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  557. completion(account, items, nil, 0);
  558. } failureRequest :^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  559. NSString *message;
  560. NSInteger errorCode = response.statusCode;
  561. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  562. errorCode = error.code;
  563. // Error
  564. if (errorCode == 503) {
  565. message = NSLocalizedString(@"_server_error_retry_", nil);
  566. } else {
  567. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  568. }
  569. completion(account, nil, message, errorCode);
  570. }];
  571. }
  572. - (void)readShareWithAccount:(NSString *)account path:(NSString *)path completion:(void (^)(NSString *account, NSArray *items, NSString *message, NSInteger errorCode))completion
  573. {
  574. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  575. if (tableAccount == nil) {
  576. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  577. } else if ([CCUtility getPassword:account].length == 0) {
  578. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  579. } else if ([CCUtility getCertificateError:account]) {
  580. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  581. }
  582. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  583. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  584. [communication setUserAgent:[CCUtility getUserAgent]];
  585. [communication readSharedByServer:[tableAccount.url stringByAppendingString:@"/"] andPath:path onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfShared, NSString *redirectedServer) {
  586. completion(account, listOfShared, nil, 0);
  587. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  588. NSString *message;
  589. NSInteger errorCode = response.statusCode;
  590. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  591. errorCode = error.code;
  592. // Error
  593. if (errorCode == 503) {
  594. message = NSLocalizedString(@"_server_error_retry_", nil);
  595. } else {
  596. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  597. }
  598. completion(account, nil, message, errorCode);
  599. }];
  600. }
  601. - (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
  602. {
  603. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  604. if (tableAccount == nil) {
  605. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  606. } else if ([CCUtility getPassword:account].length == 0) {
  607. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  608. } else if ([CCUtility getCertificateError:account]) {
  609. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  610. }
  611. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  612. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  613. [communication setUserAgent:[CCUtility getUserAgent]];
  614. [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) {
  615. completion(account, nil, 0);
  616. } failureRequest :^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  617. NSString *message;
  618. NSInteger errorCode = response.statusCode;
  619. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  620. errorCode = error.code;
  621. // Error
  622. if (errorCode == 503) {
  623. message = NSLocalizedString(@"_server_error_retry_", nil);
  624. } else {
  625. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  626. }
  627. completion(account, message, errorCode);
  628. }];
  629. }
  630. // * @param shareeType -> NSInteger: to set the type of sharee (user/group/federated)
  631. - (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
  632. {
  633. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  634. if (tableAccount == nil) {
  635. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  636. } else if ([CCUtility getPassword:account].length == 0) {
  637. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  638. } else if ([CCUtility getCertificateError:account]) {
  639. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  640. }
  641. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  642. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  643. [communication setUserAgent:[CCUtility getUserAgent]];
  644. [communication shareWith:userOrGroup shareeType:shareeType inServer:[tableAccount.url stringByAppendingString:@"/"] andFileOrFolderPath:[fileName encodeString:NSUTF8StringEncoding] andPermissions:permission onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  645. completion(account, nil, 0);
  646. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  647. NSString *message;
  648. NSInteger errorCode = response.statusCode;
  649. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  650. errorCode = error.code;
  651. // Error
  652. if (errorCode == 503) {
  653. message = NSLocalizedString(@"_server_error_retry_", nil);
  654. } else {
  655. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  656. }
  657. completion(account, message, errorCode);
  658. }];
  659. }
  660. - (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
  661. {
  662. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  663. if (tableAccount == nil) {
  664. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  665. } else if ([CCUtility getPassword:account].length == 0) {
  666. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  667. } else if ([CCUtility getCertificateError:account]) {
  668. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  669. }
  670. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  671. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  672. [communication setUserAgent:[CCUtility getUserAgent]];
  673. [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) {
  674. completion(account, nil, 0);
  675. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  676. NSString *message;
  677. NSInteger errorCode = response.statusCode;
  678. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  679. errorCode = error.code;
  680. // Error
  681. if (errorCode == 503) {
  682. message = NSLocalizedString(@"_server_error_retry_", nil);
  683. } else {
  684. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  685. }
  686. completion(account, message, errorCode);
  687. }];
  688. }
  689. - (void)unshareAccount:(NSString *)account shareID:(NSInteger)shareID completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  690. {
  691. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  692. if (tableAccount == nil) {
  693. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  694. } else if ([CCUtility getPassword:account].length == 0) {
  695. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  696. } else if ([CCUtility getCertificateError:account]) {
  697. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  698. }
  699. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  700. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  701. [communication setUserAgent:[CCUtility getUserAgent]];
  702. [communication unShareFileOrFolderByServer:[tableAccount.url stringByAppendingString:@"/"] andIdRemoteShared:shareID onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  703. completion(account, nil, 0);
  704. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  705. NSString *message;
  706. NSInteger errorCode = response.statusCode;
  707. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  708. errorCode = error.code;
  709. // Error
  710. if (errorCode == 503) {
  711. message = NSLocalizedString(@"_server_error_retry_", nil);
  712. } else {
  713. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  714. }
  715. completion(account, message, errorCode);
  716. }];
  717. }
  718. - (void)getUserGroupWithAccount:(NSString *)account searchString:(NSString *)searchString completion:(void (^)(NSString *account, NSArray *item, NSString *message, NSInteger errorCode))completion
  719. {
  720. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  721. if (tableAccount == nil) {
  722. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  723. } else if ([CCUtility getPassword:account].length == 0) {
  724. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  725. } else if ([CCUtility getCertificateError:account]) {
  726. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  727. }
  728. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  729. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  730. [communication setUserAgent:[CCUtility getUserAgent]];
  731. [communication searchUsersAndGroupsWith:searchString forPage:1 with:50 ofServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *itemList, NSString *redirectedServer) {
  732. completion(account, itemList, nil, 0);
  733. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  734. NSString *message;
  735. NSInteger errorCode = response.statusCode;
  736. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  737. errorCode = error.code;
  738. // Error
  739. if (errorCode == 503) {
  740. message = NSLocalizedString(@"_server_error_retry_", nil);
  741. } else {
  742. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  743. }
  744. completion(account, nil, message, errorCode);
  745. }];
  746. }
  747. #pragma --------------------------------------------------------------------------------------------
  748. #pragma mark ===== VAR =====
  749. #pragma --------------------------------------------------------------------------------------------
  750. - (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
  751. {
  752. BOOL previews = false;
  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. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilitesWithAccount:account];
  762. if (capabilities != nil && capabilities.versionMajor >= k_nextcloud_version_15_0) {
  763. previews = true;
  764. }
  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 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) {
  769. completion(account, listOfActivity, nil, 0);
  770. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  771. NSString *message;
  772. NSInteger errorCode = response.statusCode;
  773. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  774. errorCode = error.code;
  775. // Server Unauthorized
  776. if (errorCode == kOCErrorServerUnauthorized || errorCode == kOCErrorServerForbidden) {
  777. [[OCNetworking sharedManager] checkRemoteUser:account function:@"get activity" errorCode:errorCode];
  778. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  779. [CCUtility setCertificateError:account error:YES];
  780. }
  781. // Error
  782. if (errorCode == 503)
  783. message = NSLocalizedString(@"_server_error_retry_", nil);
  784. else
  785. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  786. completion(account, nil, message, errorCode);
  787. }];
  788. }
  789. - (void)getExternalSitesWithAccount:(NSString *)account completion:(void (^)(NSString *account, NSArray *listOfExternalSites, NSString *message, NSInteger errorCode))completion
  790. {
  791. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  792. if (tableAccount == nil) {
  793. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  794. } else if ([CCUtility getPassword:account].length == 0) {
  795. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  796. } else if ([CCUtility getCertificateError:account]) {
  797. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  798. }
  799. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  800. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  801. [communication setUserAgent:[CCUtility getUserAgent]];
  802. [communication getExternalSitesServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfExternalSites, NSString *redirectedServer) {
  803. completion(account, listOfExternalSites, nil, 0);
  804. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  805. NSString *message;
  806. NSInteger errorCode = response.statusCode;
  807. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  808. errorCode = error.code;
  809. // Server Unauthorized
  810. if (errorCode == kOCErrorServerUnauthorized || errorCode == kOCErrorServerForbidden) {
  811. [[OCNetworking sharedManager] checkRemoteUser:account function:@"get external sites" errorCode:errorCode];
  812. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  813. [CCUtility setCertificateError:account error:YES];
  814. }
  815. // Error
  816. if (errorCode == 503) {
  817. message = NSLocalizedString(@"_server_error_retry_", nil);
  818. } else {
  819. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  820. }
  821. completion(account, nil, message, errorCode);
  822. }];
  823. }
  824. - (void)getNotificationWithAccount:(NSString *)account completion:(void (^)(NSString *account, NSArray *listOfNotifications, NSString *message, NSInteger errorCode))completion
  825. {
  826. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  827. if (tableAccount == nil) {
  828. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  829. } else if ([CCUtility getPassword:account].length == 0) {
  830. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  831. } else if ([CCUtility getCertificateError:account]) {
  832. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  833. }
  834. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  835. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  836. [communication setUserAgent:[CCUtility getUserAgent]];
  837. [communication getNotificationServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfNotifications, NSString *redirectedServer) {
  838. completion(account, listOfNotifications, nil, 0);
  839. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  840. NSString *message;
  841. NSInteger errorCode = response.statusCode;
  842. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  843. errorCode = error.code;
  844. // Server Unauthorized
  845. if (errorCode == kOCErrorServerUnauthorized || errorCode == kOCErrorServerForbidden) {
  846. [[OCNetworking sharedManager] checkRemoteUser:account function:@"get notification" errorCode:errorCode];
  847. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  848. [CCUtility setCertificateError:account error:YES];
  849. }
  850. // Error
  851. if (errorCode == 503) {
  852. message = NSLocalizedString(@"_server_error_retry_", nil);
  853. } else {
  854. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  855. }
  856. completion(account, nil, message, errorCode);
  857. }];
  858. }
  859. - (void)setNotificationWithAccount:(NSString *)account serverUrl:(NSString *)serverUrl type:(NSString *)type completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  860. {
  861. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  862. if (tableAccount == nil) {
  863. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  864. } else if ([CCUtility getPassword:account].length == 0) {
  865. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  866. } else if ([CCUtility getCertificateError:account]) {
  867. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  868. }
  869. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  870. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  871. [communication setUserAgent:[CCUtility getUserAgent]];
  872. [communication setNotificationServer:serverUrl type:type onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  873. completion(account, nil, 0);
  874. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  875. NSString *message;
  876. NSInteger errorCode = response.statusCode;
  877. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  878. errorCode = error.code;
  879. // Server Unauthorized
  880. if (errorCode == kOCErrorServerUnauthorized || errorCode == kOCErrorServerForbidden) {
  881. [[OCNetworking sharedManager] checkRemoteUser:account function:@"set notification" errorCode:errorCode];
  882. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  883. [CCUtility setCertificateError:account error:YES];
  884. }
  885. // Error
  886. if (errorCode == 503) {
  887. message = NSLocalizedString(@"_server_error_retry_", nil);
  888. } else {
  889. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  890. }
  891. completion(account, message, errorCode);
  892. }];
  893. }
  894. - (void)getCapabilitiesWithAccount:(NSString *)account completion:(void (^)(NSString *account, OCCapabilities *capabilities, NSString *message, NSInteger errorCode))completion
  895. {
  896. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  897. if (tableAccount == nil) {
  898. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  899. } else if ([CCUtility getPassword:account].length == 0) {
  900. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  901. } else if ([CCUtility getCertificateError:account]) {
  902. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  903. }
  904. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  905. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  906. [communication setUserAgent:[CCUtility getUserAgent]];
  907. [communication getCapabilitiesOfServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, OCCapabilities *capabilities, NSString *redirectedServer) {
  908. completion(account, capabilities, nil, 0);
  909. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  910. NSString *message;
  911. NSInteger errorCode = response.statusCode;
  912. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  913. errorCode = error.code;
  914. // Server Unauthorized
  915. if (errorCode == kOCErrorServerUnauthorized || errorCode == kOCErrorServerForbidden) {
  916. [[OCNetworking sharedManager] checkRemoteUser:account function:@"get capabilities" errorCode:errorCode];
  917. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  918. [CCUtility setCertificateError:account error:YES];
  919. }
  920. // Error
  921. if (errorCode == 503) {
  922. message = NSLocalizedString(@"_server_error_retry_", nil);
  923. } else {
  924. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  925. }
  926. completion(account, nil, message, errorCode);
  927. }];
  928. }
  929. - (void)getUserProfileWithAccount:(NSString *)account completion:(void (^)(NSString *account, OCUserProfile *userProfile, NSString *message, NSInteger errorCode))completion
  930. {
  931. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  932. if (tableAccount == nil) {
  933. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  934. } else if ([CCUtility getPassword:account].length == 0) {
  935. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  936. } else if ([CCUtility getCertificateError:account]) {
  937. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  938. }
  939. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  940. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  941. [communication setUserAgent:[CCUtility getUserAgent]];
  942. [communication getUserProfileServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, OCUserProfile *userProfile, NSString *redirectedServer) {
  943. completion(account, userProfile, nil, 0);
  944. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  945. NSString *message;
  946. NSInteger errorCode = response.statusCode;
  947. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  948. errorCode = error.code;
  949. // Server Unauthorized
  950. if (errorCode == kOCErrorServerUnauthorized || errorCode == kOCErrorServerForbidden) {
  951. [[OCNetworking sharedManager] checkRemoteUser:account function:@"get user profile" errorCode:errorCode];
  952. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  953. [CCUtility setCertificateError:account error:YES];
  954. }
  955. // Error
  956. if (errorCode == 503) {
  957. message = NSLocalizedString(@"_server_error_retry_", nil);
  958. } else {
  959. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  960. }
  961. completion(account, nil, message, errorCode);
  962. }];
  963. }
  964. #pragma --------------------------------------------------------------------------------------------
  965. #pragma mark ===== Push Notification =====
  966. #pragma --------------------------------------------------------------------------------------------
  967. - (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
  968. {
  969. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  970. if (tableAccount == nil) {
  971. completion(account, nil, nil, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  972. } else if ([CCUtility getPassword:account].length == 0) {
  973. completion(account, nil, nil, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  974. } else if ([CCUtility getCertificateError:account]) {
  975. completion(account, nil, nil, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  976. }
  977. devicePublicKey = [CCUtility URLEncodeStringFromString:devicePublicKey];
  978. NSString *proxyServerPath = [NCBrandOptions sharedInstance].pushNotificationServerProxy;
  979. NSString *proxyServer = [NCBrandOptions sharedInstance].pushNotificationServerProxy;
  980. #ifdef DEBUG
  981. // proxyServerPath = @"http://127.0.0.1:8088";
  982. // proxyServer = @"https://10.132.0.37:8443/pushnotifications";
  983. #endif
  984. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  985. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  986. [communication setUserAgent:[CCUtility getUserAgent]];
  987. [communication subscribingNextcloudServerPush:url pushTokenHash:pushTokenHash devicePublicKey:devicePublicKey proxyServerPath: proxyServerPath onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *publicKey, NSString *deviceIdentifier, NSString *signature, NSString *redirectedServer) {
  988. deviceIdentifier = [CCUtility URLEncodeStringFromString:deviceIdentifier];
  989. signature = [CCUtility URLEncodeStringFromString:signature];
  990. publicKey = [CCUtility URLEncodeStringFromString:publicKey];
  991. [communication subscribingPushProxy:proxyServer pushToken:pushToken deviceIdentifier:deviceIdentifier deviceIdentifierSignature:signature publicKey:publicKey onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  992. completion(account, deviceIdentifier, signature, publicKey, nil, 0);
  993. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  994. NSString *message;
  995. NSInteger errorCode = response.statusCode;
  996. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  997. errorCode = error.code;
  998. // Error
  999. if (errorCode == 503)
  1000. message = NSLocalizedString(@"_server_error_retry_", nil);
  1001. else
  1002. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1003. completion(account, nil, nil, nil, message, errorCode);
  1004. }];
  1005. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1006. NSString *message;
  1007. NSInteger errorCode = response.statusCode;
  1008. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1009. errorCode = error.code;
  1010. // Error
  1011. if (errorCode == 503)
  1012. message = NSLocalizedString(@"_server_error_retry_", nil);
  1013. else
  1014. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1015. completion(account, nil, nil, nil, message, errorCode);
  1016. }];
  1017. }
  1018. - (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 {
  1019. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1020. if (tableAccount == nil) {
  1021. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1022. } else if ([CCUtility getPassword:account].length == 0) {
  1023. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1024. } else if ([CCUtility getCertificateError:account]) {
  1025. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1026. }
  1027. NSString *proxyServer = [NCBrandOptions sharedInstance].pushNotificationServerProxy;
  1028. #ifdef DEBUG
  1029. // proxyServer = @"https://10.132.0.37:8443/pushnotifications";
  1030. #endif
  1031. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1032. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1033. [communication setUserAgent:[CCUtility getUserAgent]];
  1034. [communication unsubscribingNextcloudServerPush:url onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1035. [communication unsubscribingPushProxy:proxyServer deviceIdentifier:deviceIdentifier deviceIdentifierSignature:deviceIdentifierSignature publicKey:publicKey onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1036. completion(account, nil, 0);
  1037. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1038. NSString *message;
  1039. NSInteger errorCode = response.statusCode;
  1040. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1041. errorCode = error.code;
  1042. // Error
  1043. if (errorCode == 503)
  1044. message = NSLocalizedString(@"_server_error_retry_", nil);
  1045. else
  1046. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1047. completion(account, message, errorCode);
  1048. }];
  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. // Error
  1055. if (errorCode == 503)
  1056. message = NSLocalizedString(@"_server_error_retry_", nil);
  1057. else
  1058. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1059. completion(account, message, errorCode);
  1060. }];
  1061. }
  1062. - (void)getServerNotification:(NSString *)serverUrl notificationId:(NSInteger)notificationId completion:(void(^)(NSDictionary*jsongParsed, NSString *message, NSInteger errorCode))completion
  1063. {
  1064. NSString *URLString = [NSString stringWithFormat:@"%@/ocs/v2.php/apps/notifications/api/v2/notifications/%ld?format=json", serverUrl, (long)notificationId];
  1065. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URLString] cachePolicy:0 timeoutInterval:20.0];
  1066. [request addValue:[CCUtility getUserAgent] forHTTPHeaderField:@"User-Agent"];
  1067. [request addValue:@"true" forHTTPHeaderField:@"OCS-APIRequest"];
  1068. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  1069. NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  1070. NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler: ^(NSData *data, NSURLResponse *response, NSError *error) {
  1071. if (error) {
  1072. NSString *message;
  1073. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
  1074. NSInteger errorCode = httpResponse.statusCode;
  1075. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1076. errorCode = error.code;
  1077. // Error
  1078. if (errorCode == 503)
  1079. message = NSLocalizedString(@"_server_error_retry_", nil);
  1080. else
  1081. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1082. completion(nil, message, errorCode);
  1083. } else {
  1084. NSDictionary *jsongParsed = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
  1085. completion(jsongParsed, nil, 0);
  1086. }
  1087. }];
  1088. [task resume];
  1089. }
  1090. - (void)deletingServerNotification:(NSString *)serverUrl notificationId:(NSInteger)notificationId completion:(void(^)(NSString *message, NSInteger errorCode))completion
  1091. {
  1092. // NSData *authData = [[NSString stringWithFormat:@"%@:%@", tableAccount.user, [CCUtility getPassword:tableAccount.account]] dataUsingEncoding:NSUTF8StringEncoding];
  1093. // NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];
  1094. // Delete
  1095. NSString *URLString = [NSString stringWithFormat:@"%@/ocs/v2.php/apps/notifications/api/v2/notifications/%ld", serverUrl, (long)notificationId];
  1096. // Delete-all
  1097. if (notificationId == 0) {
  1098. URLString = [NSString stringWithFormat:@"%@/ocs/v2.php/apps/notifications/api/v2/notifications", serverUrl];
  1099. }
  1100. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URLString] cachePolicy:0 timeoutInterval:20.0];
  1101. // [request setValue:authValue forHTTPHeaderField:@"Authorization"];
  1102. [request addValue:[CCUtility getUserAgent] forHTTPHeaderField:@"User-Agent"];
  1103. [request addValue:@"true" forHTTPHeaderField:@"OCS-APIRequest"];
  1104. [request setHTTPMethod: @"DELETE"];
  1105. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  1106. NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  1107. NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler: ^(NSData *data, NSURLResponse *response, NSError *error) {
  1108. if (error) {
  1109. NSString *message;
  1110. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
  1111. NSInteger errorCode = httpResponse.statusCode;
  1112. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1113. errorCode = error.code;
  1114. // Error
  1115. if (errorCode == 503)
  1116. message = NSLocalizedString(@"_server_error_retry_", nil);
  1117. else
  1118. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1119. completion(message, errorCode);
  1120. } else {
  1121. completion(nil, 0);
  1122. }
  1123. }];
  1124. [task resume];
  1125. }
  1126. #pragma --------------------------------------------------------------------------------------------
  1127. #pragma mark ===== Manage Mobile Editor OCS API =====
  1128. #pragma --------------------------------------------------------------------------------------------
  1129. - (void)createLinkRichdocumentsWithAccount:(NSString *)account fileId:(NSString *)fileId completion:(void(^)(NSString *account, NSString *link, NSString *message, NSInteger errorCode))completion
  1130. {
  1131. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1132. if (tableAccount == nil) {
  1133. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1134. } else if ([CCUtility getPassword:account].length == 0) {
  1135. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1136. } else if ([CCUtility getCertificateError:account]) {
  1137. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1138. }
  1139. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1140. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1141. [communication setUserAgent:[CCUtility getUserAgent]];
  1142. [communication createLinkRichdocuments:[tableAccount.url stringByAppendingString:@"/"] fileId:fileId onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *link, NSString *redirectedServer) {
  1143. completion(account, link, nil, 0);
  1144. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1145. NSString *message;
  1146. NSInteger errorCode = response.statusCode;
  1147. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1148. errorCode = error.code;
  1149. // Error
  1150. if (errorCode == 503)
  1151. message = NSLocalizedString(@"_server_error_retry_", nil);
  1152. else
  1153. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1154. completion(account, nil,message, errorCode);
  1155. }];
  1156. }
  1157. - (void)getTemplatesRichdocumentsWithAccount:(NSString *)account typeTemplate:(NSString *)typeTemplate completion:(void(^)(NSString *account, NSArray *listOfTemplate, NSString *message, NSInteger errorCode))completion
  1158. {
  1159. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1160. if (tableAccount == nil) {
  1161. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1162. } else if ([CCUtility getPassword:account].length == 0) {
  1163. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1164. } else if ([CCUtility getCertificateError:account]) {
  1165. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1166. }
  1167. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1168. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1169. [communication setUserAgent:[CCUtility getUserAgent]];
  1170. [communication getTemplatesRichdocuments:[tableAccount.url stringByAppendingString:@"/"] typeTemplate:typeTemplate onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfTemplate, NSString *redirectedServer) {
  1171. completion(account, listOfTemplate, nil, 0);
  1172. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1173. NSString *message;
  1174. NSInteger errorCode = response.statusCode;
  1175. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1176. errorCode = error.code;
  1177. // Error
  1178. if (errorCode == 503)
  1179. message = NSLocalizedString(@"_server_error_retry_", nil);
  1180. else
  1181. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1182. completion(account, nil, message, errorCode);
  1183. }];
  1184. }
  1185. - (void)createNewRichdocumentsWithAccount:(NSString *)account fileName:(NSString *)fileName serverUrl:(NSString *)serverUrl templateID:(NSString *)templateID completion:(void(^)(NSString *account, NSString *url, NSString *message, NSInteger errorCode))completion
  1186. {
  1187. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1188. if (tableAccount == nil) {
  1189. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1190. } else if ([CCUtility getPassword:account].length == 0) {
  1191. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1192. } else if ([CCUtility getCertificateError:account]) {
  1193. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1194. }
  1195. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1196. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1197. [communication setUserAgent:[CCUtility getUserAgent]];
  1198. [communication createNewRichdocuments:[tableAccount.url stringByAppendingString:@"/"] path:fileName templateID:templateID onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *url, NSString *redirectedServer) {
  1199. completion(account, url, nil, 0);
  1200. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1201. NSString *message;
  1202. NSInteger errorCode = response.statusCode;
  1203. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1204. errorCode = error.code;
  1205. // Error
  1206. if (errorCode == 503)
  1207. message = NSLocalizedString(@"_server_error_retry_", nil);
  1208. else
  1209. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1210. completion(account, nil, message, errorCode);
  1211. }];
  1212. }
  1213. - (void)createAssetRichdocumentsWithAccount:(NSString *)account fileName:(NSString *)fileName serverUrl:(NSString *)serverUrl completion:(void(^)(NSString *account, NSString *link, NSString *message, NSInteger errorCode))completion
  1214. {
  1215. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1216. if (tableAccount == nil) {
  1217. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1218. } else if ([CCUtility getPassword:account].length == 0) {
  1219. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1220. } else if ([CCUtility getCertificateError:account]) {
  1221. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1222. }
  1223. NSString *fileNamePath = [CCUtility returnFileNamePathFromFileName:fileName serverUrl:serverUrl activeUrl:tableAccount.url];
  1224. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1225. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1226. [communication setUserAgent:[CCUtility getUserAgent]];
  1227. [communication createAssetRichdocuments:[tableAccount.url stringByAppendingString:@"/"] path:fileNamePath onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *url, NSString *redirectedServer) {
  1228. completion(account, url, nil, 0);
  1229. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1230. NSString *message;
  1231. NSInteger errorCode = response.statusCode;
  1232. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1233. errorCode = error.code;
  1234. // Error
  1235. if (errorCode == 503)
  1236. message = NSLocalizedString(@"_server_error_retry_", nil);
  1237. else
  1238. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1239. completion(account, nil, message, errorCode);
  1240. }];
  1241. }
  1242. #pragma --------------------------------------------------------------------------------------------
  1243. #pragma mark ===== Full Text Search =====
  1244. #pragma --------------------------------------------------------------------------------------------
  1245. - (void)fullTextSearchWithAccount:(NSString *)account text:(NSString *)text page:(NSInteger)page completion:(void(^)(NSString *account, NSArray *items, NSString *message, NSInteger errorCode))completion
  1246. {
  1247. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1248. if (tableAccount == nil) {
  1249. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1250. } else if ([CCUtility getPassword:account].length == 0) {
  1251. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1252. } else if ([CCUtility getCertificateError:account]) {
  1253. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1254. }
  1255. // Create JSON
  1256. NSMutableDictionary *dataDic = [NSMutableDictionary new];
  1257. [dataDic setValue:@"files" forKey:@"providers"];
  1258. [dataDic setValue:text forKey:@"search"];
  1259. [dataDic setValue:[NSNumber numberWithInteger:page] forKey:@"page"];
  1260. [dataDic setValue:[NSNumber numberWithInt:20] forKey:@"size"];
  1261. NSMutableDictionary *options = [NSMutableDictionary new];
  1262. [options setValue:@"" forKey:@"files_within_dir"];
  1263. [options setValue:@"" forKey:@"files_local"];
  1264. [options setValue:@"" forKey:@"files_extension"];
  1265. [dataDic setValue:options forKey:@"options"];
  1266. NSString *data = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:dataDic options:0 error:nil] encoding:NSUTF8StringEncoding];
  1267. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1268. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1269. [communication setUserAgent:[CCUtility getUserAgent]];
  1270. [communication fullTextSearch:[tableAccount.url stringByAppendingString:@"/"] data:data onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  1271. completion(account, items, nil, 0);
  1272. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1273. NSString *message;
  1274. NSInteger errorCode = response.statusCode;
  1275. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1276. errorCode = error.code;
  1277. // Error
  1278. if (errorCode == 503)
  1279. message = NSLocalizedString(@"_server_error_retry_", nil);
  1280. else
  1281. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1282. completion(account, nil, message, errorCode);
  1283. }];
  1284. }
  1285. #pragma --------------------------------------------------------------------------------------------
  1286. #pragma mark ===== Check remote user =====
  1287. #pragma --------------------------------------------------------------------------------------------
  1288. - (void)checkRemoteUser:(NSString *)account function:(NSString *)function errorCode:(NSInteger)errorCode
  1289. {
  1290. #ifndef EXTENSION
  1291. @synchronized(self) {
  1292. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  1293. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilitesWithAccount:account];
  1294. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1295. NSString *token = [CCUtility getPassword:account];
  1296. if (self.checkRemoteUserInProgress || tableAccount == nil || token == nil) {
  1297. return;
  1298. } else {
  1299. self.checkRemoteUserInProgress = true;
  1300. }
  1301. if (capabilities != nil && capabilities.versionMajor >= k_nextcloud_version_17_0) {
  1302. [[OCNetworking sharedManager] getRemoteWipeStatusWithAccount:account token:token completion:^(NSString *account, BOOL wipe, NSString *message, NSInteger errorCode) {
  1303. if (wipe) {
  1304. [appDelegate deleteAccount:account wipe:true];
  1305. [[NCContentPresenter shared] messageNotification:tableAccount.user description:@"_wipe_account_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  1306. [[OCNetworking sharedManager] setRemoteWipeCompletitionWithUser:tableAccount.user userID:tableAccount.userID url:tableAccount.url token:token completion:^(NSString *message, NSInteger errorCode) {
  1307. NSLog(@"Wiped");
  1308. }];
  1309. } else {
  1310. if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive && [appDelegate.reachability isReachable]) {
  1311. [[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];
  1312. [CCUtility setPassword:account password:nil];
  1313. }
  1314. }
  1315. self.checkRemoteUserInProgress = false;
  1316. }];
  1317. } else if ([CCUtility getPassword:account] != nil) {
  1318. if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive && [appDelegate.reachability isReachable]) {
  1319. [[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];
  1320. [CCUtility setPassword:account password:nil];
  1321. }
  1322. }
  1323. }
  1324. #endif
  1325. }
  1326. - (void)getRemoteWipeStatusWithAccount:(NSString *)account token:(NSString *)token completion:(void(^)(NSString *account, BOOL wipe, NSString *message, NSInteger errorCode))completion
  1327. {
  1328. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1329. if (tableAccount == nil) {
  1330. completion(account, false, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1331. } else if ([CCUtility getPassword:account].length == 0) {
  1332. completion(account, false, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1333. } else if ([CCUtility getCertificateError:account]) {
  1334. completion(account, false, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1335. }
  1336. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1337. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1338. [communication setUserAgent:[CCUtility getUserAgent]];
  1339. [communication getRemoteWipeStatus:tableAccount.url token:token onCommunication:communication successRequest:^(NSHTTPURLResponse *response, BOOL wipe, NSString *redirectedServer) {
  1340. completion(account, wipe, nil, 0);
  1341. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1342. NSString *message;
  1343. NSInteger errorCode = response.statusCode;
  1344. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1345. errorCode = error.code;
  1346. // Server Unauthorized
  1347. if (errorCode == kOCErrorServerUnauthorized || errorCode == kOCErrorServerForbidden) {
  1348. [[OCNetworking sharedManager] checkRemoteUser:account function:@"get remote wipe status" errorCode:errorCode];
  1349. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  1350. [CCUtility setCertificateError:account error:YES];
  1351. }
  1352. // Error
  1353. if (errorCode == 503)
  1354. message = NSLocalizedString(@"_server_error_retry_", nil);
  1355. else
  1356. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1357. completion(account, false, message, errorCode);
  1358. }];
  1359. }
  1360. - (void)setRemoteWipeCompletitionWithUser:(NSString *)user userID:(NSString *)userID url:(NSString *)url token:(NSString *)token completion:(void(^)(NSString *message, NSInteger errorCode))completion
  1361. {
  1362. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1363. [communication setCredentialsWithUser:user andUserID:userID andPassword:token];
  1364. [communication setUserAgent:[CCUtility getUserAgent]];
  1365. [communication setRemoteWipeCompletition:url token:token onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1366. completion(nil, 0);
  1367. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1368. NSString *message;
  1369. NSInteger errorCode = response.statusCode;
  1370. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1371. errorCode = error.code;
  1372. // Error
  1373. if (errorCode == 503)
  1374. message = NSLocalizedString(@"_server_error_retry_", nil);
  1375. else
  1376. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1377. completion(message, errorCode);
  1378. }];
  1379. }
  1380. #pragma --------------------------------------------------------------------------------------------
  1381. #pragma mark ===== Trash =====
  1382. #pragma --------------------------------------------------------------------------------------------
  1383. - (void)listingTrashWithAccount:(NSString *)account path:(NSString *)path serverUrl:(NSString *)serverUrl depth:(NSString *)depth completion:(void (^)(NSString *account, NSArray *items, NSString *message, NSInteger errorCode))completion
  1384. {
  1385. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1386. if (tableAccount == nil) {
  1387. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1388. } else if ([CCUtility getPassword:account].length == 0) {
  1389. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1390. } else if ([CCUtility getCertificateError:account]) {
  1391. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1392. }
  1393. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1394. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1395. [communication setUserAgent:[CCUtility getUserAgent]];
  1396. [communication listingTrash:[serverUrl stringByAppendingString:path] depth:depth onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  1397. // Check items > 0
  1398. if ([items count] == 0) {
  1399. [[NCContentPresenter shared] messageNotification:@"Server error" description:@"Read Folder WebDAV : [items NULL] please fix" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  1400. completion(account, nil, NSLocalizedString(@"Read Folder WebDAV : [items NULL] please fix", nil), k_CCErrorInternalError);
  1401. } else {
  1402. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1403. NSMutableArray *listTrash = [NSMutableArray new];
  1404. //OCFileDto *itemDtoFolder = [items objectAtIndex:0];
  1405. if ([items count] > 1) {
  1406. for (NSUInteger i=1; i < [items count]; i++) {
  1407. OCFileDto *itemDto = [items objectAtIndex:i];
  1408. tableTrash *trash = [tableTrash new];
  1409. trash.account = account;
  1410. trash.date = [NSDate dateWithTimeIntervalSince1970:itemDto.date];
  1411. trash.directory = itemDto.isDirectory;
  1412. trash.fileId = itemDto.fileId;
  1413. trash.fileName = itemDto.fileName;
  1414. NSArray *array = [itemDto.filePath componentsSeparatedByString:path];
  1415. long len = [[array objectAtIndex:0] length];
  1416. trash.filePath = [itemDto.filePath substringFromIndex:len];
  1417. trash.hasPreview = itemDto.hasPreview;
  1418. trash.size = itemDto.size;
  1419. trash.trashbinFileName = itemDto.trashbinFileName;
  1420. trash.trashbinOriginalLocation = itemDto.trashbinOriginalLocation;
  1421. trash.trashbinDeletionTime = [NSDate dateWithTimeIntervalSince1970:itemDto.trashbinDeletionTime];
  1422. NSDictionary *results = [[NCCommunicationCommon sharedInstance] objcGetInternalContenTypeWithFileName:trash.trashbinFileName contentType:@"" directory:itemDto.isDirectory];
  1423. trash.contentType = results[@"contentType"];
  1424. trash.iconName = results[@"iconName"];
  1425. trash.typeFile = results[@"typeFile"];
  1426. [listTrash addObject:trash];
  1427. }
  1428. }
  1429. dispatch_async(dispatch_get_main_queue(), ^{
  1430. completion(account, listTrash, nil, 0);
  1431. });
  1432. });
  1433. }
  1434. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1435. NSString *message;
  1436. NSInteger errorCode = response.statusCode;
  1437. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1438. errorCode = error.code;
  1439. // Error
  1440. if (errorCode == 503)
  1441. message = NSLocalizedString(@"_server_error_retry_", nil);
  1442. else
  1443. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1444. completion(account, nil,message, errorCode);
  1445. }];
  1446. }
  1447. - (void)emptyTrashWithAccount:(NSString *)account completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  1448. {
  1449. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1450. if (tableAccount == nil) {
  1451. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1452. } else if ([CCUtility getPassword:account].length == 0) {
  1453. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1454. } else if ([CCUtility getCertificateError:account]) {
  1455. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1456. }
  1457. NSString *path = [NSString stringWithFormat:@"%@%@/trashbin/%@/trash", tableAccount.url, k_dav, tableAccount.userID];
  1458. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1459. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1460. [communication setUserAgent:[CCUtility getUserAgent]];
  1461. [communication emptyTrash:path onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1462. completion(account, nil, 0);
  1463. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1464. NSString *message;
  1465. NSInteger errorCode = response.statusCode;
  1466. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1467. errorCode = error.code;
  1468. // Error
  1469. if (errorCode == 503)
  1470. message = NSLocalizedString(@"_server_error_retry_", nil);
  1471. else
  1472. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1473. completion(account, message, errorCode);
  1474. }];
  1475. }
  1476. #pragma --------------------------------------------------------------------------------------------
  1477. #pragma mark ===== Comments =====
  1478. #pragma --------------------------------------------------------------------------------------------
  1479. - (void)getCommentsWithAccount:(NSString *)account fileId:(NSString *)fileId completion:(void (^)(NSString *account, NSArray *items, NSString *message, NSInteger errorCode))completion
  1480. {
  1481. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1482. if (tableAccount == nil) {
  1483. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1484. } else if ([CCUtility getPassword:account].length == 0) {
  1485. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1486. } else if ([CCUtility getCertificateError:account]) {
  1487. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1488. }
  1489. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1490. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1491. [communication setUserAgent:[CCUtility getUserAgent]];
  1492. [communication getComments:[NSString stringWithFormat:@"%@%@", tableAccount.url, k_dav] fileId:fileId onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *list, NSString *redirectedServer) {
  1493. completion(account, list, nil, 0);
  1494. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1495. NSString *message;
  1496. NSInteger errorCode = response.statusCode;
  1497. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1498. errorCode = error.code;
  1499. // Error
  1500. if (errorCode == 503)
  1501. message = NSLocalizedString(@"_server_error_retry_", nil);
  1502. else
  1503. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1504. completion(account, nil,message, errorCode);
  1505. }];
  1506. }
  1507. - (void)putCommentsWithAccount:(NSString *)account fileId:(NSString *)fileId message:(NSString *)message completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  1508. {
  1509. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1510. if (tableAccount == nil) {
  1511. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1512. } else if ([CCUtility getPassword:account].length == 0) {
  1513. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1514. } else if ([CCUtility getCertificateError:account]) {
  1515. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1516. }
  1517. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1518. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1519. [communication setUserAgent:[CCUtility getUserAgent]];
  1520. [communication putComments:[NSString stringWithFormat:@"%@%@", tableAccount.url, k_dav] fileId:fileId message:message onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1521. completion(account, nil, 0);
  1522. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1523. NSString *message;
  1524. NSInteger errorCode = response.statusCode;
  1525. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1526. errorCode = error.code;
  1527. // Error
  1528. if (errorCode == 503)
  1529. message = NSLocalizedString(@"_server_error_retry_", nil);
  1530. else
  1531. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1532. completion(account, message, errorCode);
  1533. }];
  1534. }
  1535. - (void)updateCommentsWithAccount:(NSString *)account fileId:(NSString *)fileId messageID:(NSString *)messageID message:(NSString *)message completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  1536. {
  1537. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1538. if (tableAccount == nil) {
  1539. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1540. } else if ([CCUtility getPassword:account].length == 0) {
  1541. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1542. } else if ([CCUtility getCertificateError:account]) {
  1543. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1544. }
  1545. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1546. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1547. [communication setUserAgent:[CCUtility getUserAgent]];
  1548. [communication updateComments:[NSString stringWithFormat:@"%@%@", tableAccount.url, k_dav] fileId:fileId messageID:messageID message:message onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1549. completion(account, nil, 0);
  1550. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1551. NSString *message;
  1552. NSInteger errorCode = response.statusCode;
  1553. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1554. errorCode = error.code;
  1555. // Error
  1556. if (errorCode == 503)
  1557. message = NSLocalizedString(@"_server_error_retry_", nil);
  1558. else
  1559. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1560. completion(account, message, errorCode);
  1561. }];
  1562. }
  1563. - (void)readMarkCommentsWithAccount:(NSString *)account fileId:(NSString *)fileId completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  1564. {
  1565. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1566. if (tableAccount == nil) {
  1567. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1568. } else if ([CCUtility getPassword:account].length == 0) {
  1569. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1570. } else if ([CCUtility getCertificateError:account]) {
  1571. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1572. }
  1573. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1574. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1575. [communication setUserAgent:[CCUtility getUserAgent]];
  1576. [communication readMarkComments:[NSString stringWithFormat:@"%@%@", tableAccount.url, k_dav] fileId:fileId onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1577. completion(account, nil, 0);
  1578. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1579. NSString *message;
  1580. NSInteger errorCode = response.statusCode;
  1581. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1582. errorCode = error.code;
  1583. // Error
  1584. if (errorCode == 503)
  1585. message = NSLocalizedString(@"_server_error_retry_", nil);
  1586. else
  1587. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1588. completion(account, message, errorCode);
  1589. }];
  1590. }
  1591. - (void)deleteCommentsWithAccount:(NSString *)account fileId:(NSString *)fileId messageID:(NSString *)messageID completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  1592. {
  1593. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1594. if (tableAccount == nil) {
  1595. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1596. } else if ([CCUtility getPassword:account].length == 0) {
  1597. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1598. } else if ([CCUtility getCertificateError:account]) {
  1599. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1600. }
  1601. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1602. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1603. [communication setUserAgent:[CCUtility getUserAgent]];
  1604. [communication deleteComments:[NSString stringWithFormat:@"%@%@", tableAccount.url, k_dav] fileId:fileId messageID:messageID onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1605. completion(account, nil, 0);
  1606. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1607. NSString *message;
  1608. NSInteger errorCode = response.statusCode;
  1609. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1610. errorCode = error.code;
  1611. // Error
  1612. if (errorCode == 503)
  1613. message = NSLocalizedString(@"_server_error_retry_", nil);
  1614. else
  1615. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1616. completion(account, message, errorCode);
  1617. }];
  1618. }
  1619. #pragma --------------------------------------------------------------------------------------------
  1620. #pragma mark ===== Third Parts =====
  1621. #pragma --------------------------------------------------------------------------------------------
  1622. - (void)getHCUserProfileWithAccount:(NSString *)account serverUrl:(NSString *)serverUrl completion:(void (^)(NSString *account, OCUserProfile *userProfile, NSString *message, NSInteger errorCode))completion
  1623. {
  1624. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1625. if (tableAccount == nil) {
  1626. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1627. } else if ([CCUtility getPassword:account].length == 0) {
  1628. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1629. } else if ([CCUtility getCertificateError:account]) {
  1630. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1631. }
  1632. NSString *serverPath = [NSString stringWithFormat:@"%@/ocs/v2.php/apps/handwerkcloud/api/v1/settings/%@", serverUrl, tableAccount.userID];
  1633. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1634. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1635. [communication setUserAgent:[CCUtility getUserAgent]];
  1636. [communication getHCUserProfile:serverPath onCommunication:communication successRequest:^(NSHTTPURLResponse *response, OCUserProfile *userProfile, NSString *redirectedServer) {
  1637. completion(account, userProfile, nil, 0);
  1638. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1639. NSString *message;
  1640. NSInteger errorCode = response.statusCode;
  1641. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1642. errorCode = error.code;
  1643. // Server Unauthorized
  1644. if (errorCode == kOCErrorServerUnauthorized || errorCode == kOCErrorServerForbidden) {
  1645. [[OCNetworking sharedManager] checkRemoteUser:account function:@"get user profile" errorCode:errorCode];
  1646. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  1647. [CCUtility setCertificateError:account error:YES];
  1648. }
  1649. // Error
  1650. if (errorCode == 503)
  1651. message = NSLocalizedString(@"_server_error_retry_", nil);
  1652. else
  1653. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1654. completion(account, nil,message, errorCode);
  1655. }];
  1656. }
  1657. - (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
  1658. {
  1659. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1660. if (tableAccount == nil) {
  1661. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1662. } else if ([CCUtility getPassword:account].length == 0) {
  1663. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1664. } else if ([CCUtility getCertificateError:account]) {
  1665. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1666. }
  1667. // Create JSON
  1668. NSMutableDictionary *dataDic = [NSMutableDictionary new];
  1669. if (address) [dataDic setValue:address forKey:@"address"];
  1670. if (businesssize) {
  1671. if ([businesssize isEqualToString:@"1-4"]) { [dataDic setValue:[NSNumber numberWithInt:1] forKey:@"businesssize"]; }
  1672. else if ([businesssize isEqualToString:@"5-9"]) { [dataDic setValue:[NSNumber numberWithInt:5] forKey:@"businesssize"]; }
  1673. else if ([businesssize isEqualToString:@"10-19"]) { [dataDic setValue:[NSNumber numberWithInt:10] forKey:@"businesssize"]; }
  1674. else if ([businesssize isEqualToString:@"20-49"]) { [dataDic setValue:[NSNumber numberWithInt:20] forKey:@"businesssize"]; }
  1675. else if ([businesssize isEqualToString:@"50-99"]) { [dataDic setValue:[NSNumber numberWithInt:50] forKey:@"businesssize"]; }
  1676. else if ([businesssize isEqualToString:@"100-249"]) { [dataDic setValue:[NSNumber numberWithInt:100] forKey:@"businesssize"]; }
  1677. else if ([businesssize isEqualToString:@"250-499"]) { [dataDic setValue:[NSNumber numberWithInt:250] forKey:@"businesssize"]; }
  1678. else if ([businesssize isEqualToString:@"500-999"]) { [dataDic setValue:[NSNumber numberWithInt:500] forKey:@"businesssize"]; }
  1679. else if ([businesssize isEqualToString:@"1000+"]) { [dataDic setValue:[NSNumber numberWithInt:1000] forKey:@"businesssize"]; }
  1680. }
  1681. if (businesstype) [dataDic setValue:businesstype forKey:@"businesstype"];
  1682. if (city) [dataDic setValue:city forKey:@"city"];
  1683. if (company) [dataDic setValue:company forKey:@"company"];
  1684. if (country) [dataDic setValue:country forKey:@"country"];
  1685. if (displayname) [dataDic setValue:displayname forKey:@"displayname"];
  1686. if (email) [dataDic setValue:email forKey:@"email"];
  1687. if (phone) [dataDic setValue:phone forKey:@"phone"];
  1688. if (role_) [dataDic setValue:role_ forKey:@"role"];
  1689. if (twitter) [dataDic setValue:twitter forKey:@"twitter"];
  1690. if (website) [dataDic setValue:website forKey:@"website"];
  1691. if (zip) [dataDic setValue:zip forKey:@"zip"];
  1692. NSString *data = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:dataDic options:0 error:nil] encoding:NSUTF8StringEncoding];
  1693. NSString *serverPath = [NSString stringWithFormat:@"%@/ocs/v2.php/apps/handwerkcloud/api/v1/settings/%@", serverUrl, tableAccount.userID];
  1694. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1695. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1696. [communication setUserAgent:[CCUtility getUserAgent]];
  1697. [communication putHCUserProfile:serverPath data:data onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1698. completion(account, nil, 0);
  1699. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1700. NSString *message;
  1701. NSInteger errorCode = response.statusCode;
  1702. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1703. errorCode = error.code;
  1704. // Server Unauthorized
  1705. if (errorCode == kOCErrorServerUnauthorized || errorCode == kOCErrorServerForbidden) {
  1706. [[OCNetworking sharedManager] checkRemoteUser:account function:@"put user profile" errorCode:errorCode];
  1707. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  1708. [CCUtility setCertificateError:account error:YES];
  1709. }
  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. - (void)getHCFeaturesWithAccount:(NSString *)account serverUrl:(NSString *)serverUrl completion:(void (^)(NSString *account, HCFeatures *features, NSString *message, NSInteger errorCode))completion
  1719. {
  1720. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1721. if (tableAccount == nil) {
  1722. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1723. } else if ([CCUtility getPassword:account].length == 0) {
  1724. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1725. } else if ([CCUtility getCertificateError:account]) {
  1726. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1727. }
  1728. NSString *serverPath = [NSString stringWithFormat:@"%@/ocs/v2.php/apps/handwerkcloud/api/v1/features/%@", serverUrl, tableAccount.userID];
  1729. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1730. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1731. [communication setUserAgent:[CCUtility getUserAgent]];
  1732. [communication getHCFeatures:serverPath onCommunication:communication successRequest:^(NSHTTPURLResponse *response, HCFeatures *features, NSString *redirectedServer) {
  1733. completion(account, features, nil, 0);
  1734. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1735. NSString *message;
  1736. NSInteger errorCode = response.statusCode;
  1737. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1738. errorCode = error.code;
  1739. // Server Unauthorized
  1740. if (errorCode == kOCErrorServerUnauthorized || errorCode == kOCErrorServerForbidden) {
  1741. [[OCNetworking sharedManager] checkRemoteUser:account function:@"get features" errorCode:errorCode];
  1742. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  1743. [CCUtility setCertificateError:account error:YES];
  1744. }
  1745. // Error
  1746. if (errorCode == 503)
  1747. message = NSLocalizedString(@"_server_error_retry_", nil);
  1748. else
  1749. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1750. completion(account, nil,message, errorCode);
  1751. }];
  1752. }
  1753. /*
  1754. - (void)middlewarePing
  1755. {
  1756. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1757. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  1758. [communication setUserAgent:[CCUtility getUserAgent]];
  1759. [communication getMiddlewarePing:_metadataNet.serverUrl onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfExternalSites, NSString *redirectedServer) {
  1760. [self complete];
  1761. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1762. NSInteger errorCode = response.statusCode;
  1763. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1764. errorCode = error.code;
  1765. // Error
  1766. if ([self.delegate respondsToSelector:@selector(getExternalSitesServerFailure:message:errorCode:)]) {
  1767. if (errorCode == 503)
  1768. [self.delegate getExternalSitesServerFailure:_metadataNet message:NSLocalizedString(@"_server_error_retry_", nil) errorCode:errorCode];
  1769. else
  1770. [self.delegate getExternalSitesServerFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1771. }
  1772. // Request trusted certificated
  1773. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  1774. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1775. [self complete];
  1776. }];
  1777. }
  1778. */
  1779. #pragma --------------------------------------------------------------------------------------------
  1780. #pragma mark ===== didReceiveChallenge =====
  1781. #pragma --------------------------------------------------------------------------------------------
  1782. -(void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler
  1783. {
  1784. // The pinnning check
  1785. if ([[NCNetworking sharedInstance] checkTrustedChallengeWithChallenge:challenge directoryCertificate:[CCUtility getDirectoryCerificates]]) {
  1786. completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  1787. } else {
  1788. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  1789. }
  1790. }
  1791. @end
  1792. #pragma --------------------------------------------------------------------------------------------
  1793. #pragma mark ===== OCURLSessionManager =====
  1794. #pragma --------------------------------------------------------------------------------------------
  1795. @implementation OCURLSessionManager
  1796. - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
  1797. {
  1798. // The pinnning check
  1799. if ([[NCNetworking sharedInstance] checkTrustedChallengeWithChallenge:challenge directoryCertificate:[CCUtility getDirectoryCerificates]]) {
  1800. completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  1801. } else {
  1802. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  1803. }
  1804. }
  1805. @end