OCNetworking.m 124 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370
  1. //
  2. // OCnetworking.m
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 10/05/15.
  6. // Copyright (c) 2017 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "OCNetworking.h"
  24. #import "CCUtility.h"
  25. #import "CCGraphics.h"
  26. #import "NSString+Encode.h"
  27. #import "NCBridgeSwift.h"
  28. #import "NCXMLGetAppPasswordParser.h"
  29. @implementation OCNetworking
  30. + (OCNetworking *)sharedManager {
  31. static OCNetworking *sharedManager;
  32. @synchronized(self)
  33. {
  34. if (!sharedManager) {
  35. sharedManager = [OCNetworking new];
  36. sharedManager.checkRemoteUserInProgress = false;
  37. }
  38. return sharedManager;
  39. }
  40. }
  41. - (id)init
  42. {
  43. self = [super init];
  44. [self sharedOCCommunication];
  45. return self;
  46. }
  47. #pragma --------------------------------------------------------------------------------------------
  48. #pragma mark ===== OCCommunication =====
  49. #pragma --------------------------------------------------------------------------------------------
  50. - (OCCommunication *)sharedOCCommunication
  51. {
  52. static OCCommunication* sharedOCCommunication = nil;
  53. if (sharedOCCommunication == nil)
  54. {
  55. // Network
  56. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  57. configuration.allowsCellularAccess = YES;
  58. configuration.discretionary = NO;
  59. configuration.HTTPMaximumConnectionsPerHost = k_maxConcurrentOperation;
  60. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  61. OCURLSessionManager *networkSessionManager = [[OCURLSessionManager alloc] initWithSessionConfiguration:configuration];
  62. [networkSessionManager.operationQueue setMaxConcurrentOperationCount: k_maxConcurrentOperation];
  63. networkSessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
  64. // Download
  65. NSURLSessionConfiguration *configurationDownload = [NSURLSessionConfiguration defaultSessionConfiguration];
  66. configurationDownload.allowsCellularAccess = YES;
  67. configurationDownload.discretionary = NO;
  68. configurationDownload.HTTPMaximumConnectionsPerHost = k_maxHTTPConnectionsPerHost;
  69. configurationDownload.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  70. configurationDownload.timeoutIntervalForRequest = k_timeout_upload;
  71. OCURLSessionManager *downloadSessionManager = [[OCURLSessionManager alloc] initWithSessionConfiguration:configurationDownload];
  72. [downloadSessionManager.operationQueue setMaxConcurrentOperationCount:k_maxHTTPConnectionsPerHost];
  73. [downloadSessionManager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition (NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential) {
  74. return NSURLSessionAuthChallengePerformDefaultHandling;
  75. }];
  76. // Upload
  77. NSURLSessionConfiguration *configurationUpload = [NSURLSessionConfiguration defaultSessionConfiguration];
  78. configurationUpload.allowsCellularAccess = YES;
  79. configurationUpload.discretionary = NO;
  80. configurationUpload.HTTPMaximumConnectionsPerHost = k_maxHTTPConnectionsPerHost;
  81. configurationUpload.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  82. configurationUpload.timeoutIntervalForRequest = k_timeout_upload;
  83. OCURLSessionManager *uploadSessionManager = [[OCURLSessionManager alloc] initWithSessionConfiguration:configurationUpload];
  84. [uploadSessionManager.operationQueue setMaxConcurrentOperationCount:k_maxHTTPConnectionsPerHost];
  85. [uploadSessionManager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition (NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential) {
  86. return NSURLSessionAuthChallengePerformDefaultHandling;
  87. }];
  88. sharedOCCommunication = [[OCCommunication alloc] initWithUploadSessionManager:uploadSessionManager andDownloadSessionManager:downloadSessionManager andNetworkSessionManager:networkSessionManager];
  89. }
  90. return sharedOCCommunication;
  91. }
  92. #pragma --------------------------------------------------------------------------------------------
  93. #pragma mark ===== Server =====
  94. #pragma --------------------------------------------------------------------------------------------
  95. - (void)checkServerUrl:(NSString *)serverUrl user:(NSString *)user userID:(NSString *)userID password:(NSString *)password completion:(void (^)(NSString *message, NSInteger errorCode))completion
  96. {
  97. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  98. [communication setCredentialsWithUser:user andUserID:userID andPassword:password];
  99. [communication setUserAgent:[CCUtility getUserAgent]];
  100. [communication checkServer:serverUrl onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  101. completion(nil, 0);
  102. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  103. NSString *message;
  104. NSInteger errorCode = response.statusCode;
  105. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  106. errorCode = error.code;
  107. // Error
  108. if (errorCode == 503)
  109. message = NSLocalizedString(@"_server_error_retry_", nil);
  110. else
  111. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  112. completion(message, errorCode);
  113. }];
  114. }
  115. /*
  116. - (void)serverStatusUrl:(NSString *)serverUrl completion:(void(^)(NSString *serverProductName, NSInteger versionMajor, NSInteger versionMicro, NSInteger versionMinor, BOOL extendedSupport,NSString *message, NSInteger errorCode))completion
  117. {
  118. NSString *urlTest = [serverUrl stringByAppendingString:k_serverStatus];
  119. // Remove stored cookies
  120. NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
  121. for (NSHTTPCookie *cookie in [storage cookies])
  122. {
  123. [storage deleteCookie:cookie];
  124. }
  125. NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlTest] cachePolicy:0 timeoutInterval:20.0];
  126. [request addValue:[CCUtility getUserAgent] forHTTPHeaderField:@"User-Agent"];
  127. [request addValue:@"true" forHTTPHeaderField:@"OCS-APIRequest"];
  128. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  129. NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  130. NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler: ^(NSData *data, NSURLResponse *response, NSError *error) {
  131. if (error) {
  132. NSString *message;
  133. NSInteger errorCode;
  134. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
  135. errorCode = httpResponse.statusCode;
  136. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  137. errorCode = error.code;
  138. // Error
  139. if (errorCode == 503)
  140. message = NSLocalizedString(@"_server_error_retry_", nil);
  141. else
  142. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  143. dispatch_sync(dispatch_get_main_queue(), ^{
  144. completion(nil, 0, 0, 0, false, message, errorCode);
  145. });
  146. } else {
  147. NSString *serverProductName = @"";
  148. NSString *serverVersion = @"0.0.0";
  149. NSString *serverVersionString = @"0.0.0";
  150. NSInteger versionMajor = 0;
  151. NSInteger versionMicro = 0;
  152. NSInteger versionMinor = 0;
  153. BOOL extendedSupport = FALSE;
  154. NSError *error;
  155. NSDictionary *jsongParsed = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
  156. if (error) {
  157. dispatch_sync(dispatch_get_main_queue(), ^{
  158. completion(nil, 0, 0, 0, extendedSupport, NSLocalizedString(@"_no_nextcloud_found_", nil), k_CCErrorInternalError);
  159. });
  160. } else {
  161. serverProductName = [[jsongParsed valueForKey:@"productname"] lowercaseString];
  162. serverVersion = [jsongParsed valueForKey:@"version"];
  163. serverVersionString = [jsongParsed valueForKey:@"versionstring"];
  164. NSArray *arrayVersion = [serverVersionString componentsSeparatedByString:@"."];
  165. if (arrayVersion.count == 1) {
  166. versionMajor = [arrayVersion[0] integerValue];
  167. } else if (arrayVersion.count == 2) {
  168. versionMajor = [arrayVersion[0] integerValue];
  169. versionMinor = [arrayVersion[1] integerValue];
  170. } else if (arrayVersion.count >= 3) {
  171. versionMajor = [arrayVersion[0] integerValue];
  172. versionMinor = [arrayVersion[1] integerValue];
  173. versionMicro = [arrayVersion[2] integerValue];
  174. }
  175. extendedSupport = [[jsongParsed valueForKey:@"extendedSupport"] boolValue];
  176. dispatch_sync(dispatch_get_main_queue(), ^{
  177. completion(serverProductName, versionMajor, versionMicro, versionMinor, extendedSupport, nil, 0);
  178. });
  179. }
  180. }
  181. }];
  182. [task resume];
  183. }
  184. */
  185. /*
  186. - (void)downloadContentsOfUrl:(NSString *)serverUrl completion:(void(^)(NSData *data, NSString *message, NSInteger errorCode))completion
  187. {
  188. // Remove stored cookies
  189. NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
  190. for (NSHTTPCookie *cookie in [storage cookies])
  191. {
  192. [storage deleteCookie:cookie];
  193. }
  194. NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:serverUrl] cachePolicy:0 timeoutInterval:20.0];
  195. [request addValue:[CCUtility getUserAgent] forHTTPHeaderField:@"User-Agent"];
  196. [request addValue:@"true" forHTTPHeaderField:@"OCS-APIRequest"];
  197. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  198. NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  199. NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler: ^(NSData *data, NSURLResponse *response, NSError *error) {
  200. dispatch_sync(dispatch_get_main_queue(), ^{
  201. if (error) {
  202. NSString *message;
  203. NSInteger errorCode;
  204. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
  205. errorCode = httpResponse.statusCode;
  206. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  207. errorCode = error.code;
  208. // Error
  209. if (errorCode == 503)
  210. message = NSLocalizedString(@"_server_error_retry_", nil);
  211. else
  212. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  213. completion(nil, message, errorCode);
  214. } else {
  215. completion(data, nil, 0);
  216. }
  217. });
  218. }];
  219. [task resume];
  220. }
  221. */
  222. - (void)getAppPassword:(NSString *)serverUrl username:(NSString *)username password:(NSString *)password completion:(void(^)(NSString *token, NSString *message, NSInteger errorCode))completion
  223. {
  224. NSData *authData = [[NSString stringWithFormat:@"%@:%@", username, password] dataUsingEncoding:NSUTF8StringEncoding];
  225. NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];
  226. NSString *URLString = [NSString stringWithFormat:@"%@/ocs/v2.php/core/getapppassword", serverUrl];
  227. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URLString] cachePolicy:0 timeoutInterval:20.0];
  228. [request setValue:authValue forHTTPHeaderField:@"Authorization"];
  229. [request addValue:[CCUtility getUserAgent] forHTTPHeaderField:@"User-Agent"];
  230. [request addValue:@"true" forHTTPHeaderField:@"OCS-APIRequest"];
  231. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  232. NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  233. NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler: ^(NSData *data, NSURLResponse *response, NSError *error) {
  234. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
  235. NSInteger errorCode = 0;
  236. NSString *message = @"";
  237. NSString *token = nil;
  238. if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {
  239. NCXMLGetAppPasswordParser *parser = [NCXMLGetAppPasswordParser new];
  240. [parser initParserWithData:data];
  241. token = parser.token;
  242. } else {
  243. errorCode = httpResponse.statusCode;
  244. message = [NSHTTPURLResponse localizedStringForStatusCode:httpResponse.statusCode];
  245. }
  246. dispatch_async(dispatch_get_main_queue(), ^{
  247. completion(token, message, errorCode);
  248. });
  249. }];
  250. [task resume];
  251. }
  252. #pragma --------------------------------------------------------------------------------------------
  253. #pragma mark ===== download / upload =====
  254. #pragma --------------------------------------------------------------------------------------------
  255. - (NSURLSessionTask *)downloadWithAccount:(NSString *)account fileNameServerUrl:(NSString *)fileNameServerUrl fileNameLocalPath:(NSString *)fileNameLocalPath encode:(BOOL)encode communication:(OCCommunication *)communication completion:(void (^)(NSString *account, int64_t length, NSString *etag, NSDate *date, NSString *message, NSInteger errorCode))completion
  256. {
  257. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  258. if (tableAccount == nil) {
  259. completion(account, 0, nil, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  260. } else if ([CCUtility getPassword:account].length == 0) {
  261. completion(account, 0, nil, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  262. } else if ([CCUtility getCertificateError:account]) {
  263. completion(account, 0, nil, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  264. }
  265. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  266. [communication setUserAgent:[CCUtility getUserAgent]];
  267. NSURLSessionTask *sessionTask = [communication downloadFileSession:fileNameServerUrl toDestiny:fileNameLocalPath defaultPriority:YES encode:encode onCommunication:communication progress:^(NSProgress *progress) {
  268. //float percent = roundf (progress.fractionCompleted * 100);
  269. } successRequest:^(NSURLResponse *response, NSURL *filePath) {
  270. int64_t totalUnitCount = 0;
  271. NSDate *date = [NSDate date];
  272. NSDateFormatter *dateFormatter = [NSDateFormatter new];
  273. NSLocale *enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
  274. [dateFormatter setLocale:enUSPOSIXLocale];
  275. [dateFormatter setDateFormat:@"EEE, dd MMM y HH:mm:ss zzz"];
  276. NSError *error;
  277. NSDictionary *fields = [(NSHTTPURLResponse*)response allHeaderFields];
  278. NSString *contentLength = [fields objectForKey:@"Content-Length"];
  279. if(contentLength) {
  280. totalUnitCount = (int64_t) [contentLength longLongValue];
  281. }
  282. NSString *dateString = [fields objectForKey:@"Date"];
  283. if (dateString) {
  284. if (![dateFormatter getObjectValue:&date forString:dateString range:nil error:&error]) {
  285. date = [NSDate date];
  286. }
  287. } else {
  288. date = [NSDate date];
  289. }
  290. NSString *etag = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-ETag"]];
  291. if (etag == nil) {
  292. completion(account, 0, nil, nil, NSLocalizedString(@"Internal error", nil), k_CCErrorInternalError);
  293. } else {
  294. completion(account, totalUnitCount, etag, date, nil, 0);
  295. }
  296. } failureRequest:^(NSURLResponse *response, NSError *error) {
  297. NSString *message;
  298. NSInteger errorCode = ((NSHTTPURLResponse*)response).statusCode;
  299. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  300. errorCode = error.code;
  301. // Server Unauthorized
  302. if (errorCode == kOCErrorServerUnauthorized || errorCode == kOCErrorServerForbidden) {
  303. [[OCNetworking sharedManager] checkRemoteUser:account function:@"download" errorCode:errorCode];
  304. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  305. [CCUtility setCertificateError:account error:YES];
  306. }
  307. // Error
  308. if (errorCode == 503)
  309. message = NSLocalizedString(@"_server_error_retry_", nil);
  310. else
  311. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  312. completion(account, 0, nil, nil, message, errorCode);
  313. }];
  314. return sessionTask;
  315. }
  316. - (NSURLSessionTask *)downloadWithAccount:(NSString *)account url:(NSString *)url fileNameLocalPath:(NSString *)fileNameLocalPath encode:(BOOL)encode completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  317. {
  318. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  319. if (tableAccount == nil) {
  320. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  321. } else if ([CCUtility getPassword:account].length == 0) {
  322. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  323. } else if ([CCUtility getCertificateError:account]) {
  324. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  325. }
  326. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  327. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  328. [communication setUserAgent:[CCUtility getUserAgent]];
  329. NSURLSessionTask *sessionTask = [communication downloadFileSession:url toDestiny:fileNameLocalPath defaultPriority:YES encode:encode onCommunication:communication progress:^(NSProgress *progress) {
  330. //float percent = roundf (progress.fractionCompleted * 100);
  331. } successRequest:^(NSURLResponse *response, NSURL *filePath) {
  332. completion(account, nil, 0);
  333. } failureRequest:^(NSURLResponse *response, NSError *error) {
  334. NSString *message;
  335. NSInteger errorCode = ((NSHTTPURLResponse*)response).statusCode;
  336. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  337. errorCode = error.code;
  338. // Server Unauthorized
  339. if (errorCode == kOCErrorServerUnauthorized || errorCode == kOCErrorServerForbidden) {
  340. [[OCNetworking sharedManager] checkRemoteUser:account function:@"download" errorCode:errorCode];
  341. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  342. [CCUtility setCertificateError:account error:YES];
  343. }
  344. // Error
  345. if (errorCode == 503)
  346. message = NSLocalizedString(@"_server_error_retry_", nil);
  347. else
  348. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  349. completion(account, message, errorCode);
  350. }];
  351. return sessionTask;
  352. }
  353. - (NSURLSessionTask *)uploadWithAccount:(NSString *)account fileNameServerUrl:(NSString *)fileNameServerUrl fileNameLocalPath:(NSString *)fileNameLocalPath encode:(BOOL)encode communication:(OCCommunication *)communication progress:(void(^)(NSProgress *progress))uploadProgress completion:(void(^)(NSString *account, NSString *ocId, NSString *etag, NSDate *date, NSString *message, NSInteger errorCode))completion
  354. {
  355. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  356. if (tableAccount == nil) {
  357. completion(account, nil, nil, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  358. } else if ([CCUtility getPassword:account].length == 0) {
  359. completion(account, nil, nil, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  360. } else if ([CCUtility getCertificateError:account]) {
  361. completion(account, nil, nil, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  362. }
  363. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  364. [communication setUserAgent:[CCUtility getUserAgent]];
  365. NSURLSessionTask *sessionTask = [communication uploadFileSession:fileNameLocalPath toDestiny:fileNameServerUrl encode:encode onCommunication:communication progress:^(NSProgress *progress) {
  366. uploadProgress(progress);
  367. //float percent = roundf (progress.fractionCompleted * 100);
  368. } successRequest:^(NSURLResponse *response, NSString *redirectedServer) {
  369. NSDictionary *fields = [(NSHTTPURLResponse*)response allHeaderFields];
  370. NSString *ocId = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-FileId"]];
  371. NSString *etag = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-ETag"]];
  372. NSDate *date = [CCUtility dateEnUsPosixFromCloud:[fields objectForKey:@"Date"]];
  373. completion(account, ocId, etag, date, nil, 0);
  374. } failureRequest:^(NSURLResponse *response, NSString *redirectedServer, NSError *error) {
  375. NSString *message;
  376. NSInteger errorCode = ((NSHTTPURLResponse*)response).statusCode;
  377. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  378. errorCode = error.code;
  379. // Server Unauthorized
  380. if (errorCode == kOCErrorServerUnauthorized || errorCode == kOCErrorServerForbidden) {
  381. [[OCNetworking sharedManager] checkRemoteUser:account function:@"upload" errorCode:errorCode];
  382. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  383. [CCUtility setCertificateError:account error:YES];
  384. }
  385. // Error
  386. if (errorCode == 503)
  387. message = NSLocalizedString(@"_server_error_retry_", nil);
  388. else
  389. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  390. completion(account, nil, nil, nil, message, errorCode);
  391. } failureBeforeRequest:^(NSError *error) {
  392. completion(account, nil, nil, nil, error.description, error.code);
  393. }];
  394. return sessionTask;
  395. }
  396. #pragma --------------------------------------------------------------------------------------------
  397. #pragma mark ===== WebDav =====
  398. #pragma --------------------------------------------------------------------------------------------
  399. - (void)readFileWithAccount:(NSString *)account serverUrl:(NSString *)serverUrl fileName:(NSString *)fileName completion:(void(^)(NSString *account, tableMetadata *metadata, NSString *message, NSInteger errorCode))completion
  400. {
  401. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  402. if (tableAccount == nil) {
  403. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  404. } else if ([CCUtility getPassword:account].length == 0) {
  405. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  406. } else if ([CCUtility getCertificateError:account]) {
  407. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  408. }
  409. NSString *fileNamePath;
  410. if (fileName) {
  411. fileNamePath = [NSString stringWithFormat:@"%@/%@", serverUrl, fileName];
  412. } else {
  413. fileName= @".";
  414. fileNamePath = serverUrl;
  415. }
  416. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  417. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  418. [communication setUserAgent:[CCUtility getUserAgent]];
  419. [communication readFile:fileNamePath onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  420. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:serverUrl account:account];
  421. if ([items count] > 0) {
  422. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  423. tableMetadata *metadata = [tableMetadata new];
  424. OCFileDto *itemDto = [items objectAtIndex:0];
  425. metadata = [CCUtility trasformedOCFileToCCMetadata:itemDto fileName:fileName serverUrl:serverUrl account:account isFolderEncrypted:isFolderEncrypted];
  426. dispatch_async(dispatch_get_main_queue(), ^{
  427. completion(account, metadata, nil, 0);
  428. });
  429. });
  430. // BUG 1038 item == 0
  431. } else {
  432. [[NCContentPresenter shared] messageNotification:@"Server error" description:@"Read File WebDAV : [items NULL] please fix" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  433. completion(account, nil, NSLocalizedString(@"Read File WebDAV : [items NULL] please fix", nil), k_CCErrorInternalError);
  434. }
  435. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  436. NSString *message;
  437. NSInteger errorCode = response.statusCode;
  438. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  439. errorCode = error.code;
  440. // Server Unauthorized
  441. if (errorCode == kOCErrorServerUnauthorized || errorCode == kOCErrorServerForbidden) {
  442. [[OCNetworking sharedManager] checkRemoteUser:account function:@"read file or folder" errorCode:errorCode];
  443. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  444. [CCUtility setCertificateError:account error:YES];
  445. }
  446. // Error
  447. if (errorCode == 503)
  448. message = NSLocalizedString(@"_server_error_retry_", nil);
  449. else
  450. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  451. completion(account, nil, message, errorCode);
  452. }];
  453. }
  454. - (void)readFolderWithAccount:(NSString *)account serverUrl:(NSString *)serverUrl depth:(NSString *)depth completion:(void(^)(NSString *account, NSArray *metadatas, tableMetadata *metadataFolder, NSString *message, NSInteger errorCode))completion
  455. {
  456. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  457. if (tableAccount == nil) {
  458. completion(account, nil, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  459. } else if ([CCUtility getPassword:account].length == 0) {
  460. completion(account, nil, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  461. } else if ([CCUtility getCertificateError:account]) {
  462. completion(account, nil, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  463. }
  464. NSString *url = tableAccount.url;
  465. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  466. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  467. [communication setUserAgent:[CCUtility getUserAgent]];
  468. [communication readFolder:serverUrl depth:depth withUserSessionToken:nil onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer, NSString *token) {
  469. // Check items > 0
  470. if ([items count] == 0) {
  471. [[NCContentPresenter shared] messageNotification:@"Server error" description:@"Read Folder WebDAV : [items NULL] please fix" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  472. completion(account, nil, nil, NSLocalizedString(@"Read Folder WebDAV : [items NULL] please fix", nil), k_CCErrorInternalError);
  473. } else {
  474. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  475. BOOL showHiddenFiles = [CCUtility getShowHiddenFiles];
  476. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:serverUrl account:account];
  477. // directory [0]
  478. OCFileDto *itemDtoFolder = [items objectAtIndex:0];
  479. //NSDate *date = [NSDate dateWithTimeIntervalSince1970:itemDtoDirectory.date];
  480. NSMutableArray *metadatas = [NSMutableArray new];
  481. tableMetadata *metadataFolder = [tableMetadata new];
  482. NSString *serverUrlFolder;
  483. // Metadata . (self Folder)
  484. if ([serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:url]]) {
  485. // root folder
  486. serverUrlFolder = k_serverUrl_root;
  487. metadataFolder = [CCUtility trasformedOCFileToCCMetadata:itemDtoFolder fileName:@"." serverUrl:serverUrlFolder account:account isFolderEncrypted:isFolderEncrypted];
  488. } else {
  489. serverUrlFolder = [CCUtility deletingLastPathComponentFromServerUrl:serverUrl];
  490. metadataFolder = [CCUtility trasformedOCFileToCCMetadata:itemDtoFolder fileName:[serverUrl lastPathComponent] serverUrl:serverUrlFolder account:account isFolderEncrypted:isFolderEncrypted];
  491. }
  492. // Add metadata folder
  493. (void)[[NCManageDatabase sharedInstance] addDirectoryWithEncrypted:itemDtoFolder.isEncrypted favorite:itemDtoFolder.isFavorite ocId:itemDtoFolder.ocId permissions:itemDtoFolder.permissions serverUrl:serverUrl richWorkspace:nil account:account];
  494. NSArray *itemsSortedArray = [items sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
  495. NSString *first = [(OCFileDto*)a fileName];
  496. NSString *second = [(OCFileDto*)b fileName];
  497. return [[first lowercaseString] compare:[second lowercaseString]];
  498. }];
  499. for (NSUInteger i=1; i < [itemsSortedArray count]; i++) {
  500. OCFileDto *itemDto = [itemsSortedArray objectAtIndex:i];
  501. NSString *fileName = [itemDto.fileName stringByReplacingOccurrencesOfString:@"/" withString:@""];
  502. // Skip hidden files
  503. if (fileName.length > 0) {
  504. if (!showHiddenFiles && [[fileName substringToIndex:1] isEqualToString:@"."])
  505. continue;
  506. } else {
  507. continue;
  508. }
  509. if (itemDto.isDirectory) {
  510. (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];
  511. }
  512. [metadatas addObject:[CCUtility trasformedOCFileToCCMetadata:itemDto fileName:itemDto.fileName serverUrl:serverUrl account:account isFolderEncrypted:isFolderEncrypted]];
  513. }
  514. dispatch_async(dispatch_get_main_queue(), ^{
  515. completion(account, metadatas, metadataFolder, nil, 0);
  516. });
  517. });
  518. }
  519. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) {
  520. NSString *message;
  521. NSInteger errorCode = response.statusCode;
  522. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  523. errorCode = error.code;
  524. // Server Unauthorized
  525. if (errorCode == kOCErrorServerUnauthorized || errorCode == kOCErrorServerForbidden) {
  526. [[OCNetworking sharedManager] checkRemoteUser:account function:@"read file or folder" errorCode:errorCode];
  527. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  528. [CCUtility setCertificateError:account error:YES];
  529. }
  530. // Error
  531. if (errorCode == 503)
  532. message = NSLocalizedString(@"_server_error_retry_", nil);
  533. else
  534. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  535. completion(account, nil, nil, message, errorCode);
  536. }];
  537. }
  538. #pragma --------------------------------------------------------------------------------------------
  539. #pragma mark ===== Share =====
  540. #pragma --------------------------------------------------------------------------------------------
  541. - (void)readShareWithAccount:(NSString *)account completion:(void (^)(NSString *account, NSArray *items, NSString *message, NSInteger errorCode))completion
  542. {
  543. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  544. if (tableAccount == nil) {
  545. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  546. } else if ([CCUtility getPassword:account].length == 0) {
  547. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  548. } else if ([CCUtility getCertificateError:account]) {
  549. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  550. }
  551. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  552. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  553. [communication setUserAgent:[CCUtility getUserAgent]];
  554. [communication readSharedByServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  555. completion(account, items, nil, 0);
  556. } failureRequest :^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  557. NSString *message;
  558. NSInteger errorCode = response.statusCode;
  559. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  560. errorCode = error.code;
  561. // Error
  562. if (errorCode == 503) {
  563. message = NSLocalizedString(@"_server_error_retry_", nil);
  564. } else {
  565. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  566. }
  567. completion(account, nil, message, errorCode);
  568. }];
  569. }
  570. - (void)readShareWithAccount:(NSString *)account path:(NSString *)path completion:(void (^)(NSString *account, NSArray *items, NSString *message, NSInteger errorCode))completion
  571. {
  572. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  573. if (tableAccount == nil) {
  574. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  575. } else if ([CCUtility getPassword:account].length == 0) {
  576. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  577. } else if ([CCUtility getCertificateError:account]) {
  578. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  579. }
  580. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  581. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  582. [communication setUserAgent:[CCUtility getUserAgent]];
  583. [communication readSharedByServer:[tableAccount.url stringByAppendingString:@"/"] andPath:path onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfShared, NSString *redirectedServer) {
  584. completion(account, listOfShared, nil, 0);
  585. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  586. NSString *message;
  587. NSInteger errorCode = response.statusCode;
  588. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  589. errorCode = error.code;
  590. // Error
  591. if (errorCode == 503) {
  592. message = NSLocalizedString(@"_server_error_retry_", nil);
  593. } else {
  594. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  595. }
  596. completion(account, nil, message, errorCode);
  597. }];
  598. }
  599. - (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
  600. {
  601. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  602. if (tableAccount == nil) {
  603. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  604. } else if ([CCUtility getPassword:account].length == 0) {
  605. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  606. } else if ([CCUtility getCertificateError:account]) {
  607. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  608. }
  609. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  610. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  611. [communication setUserAgent:[CCUtility getUserAgent]];
  612. [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) {
  613. completion(account, nil, 0);
  614. } failureRequest :^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  615. NSString *message;
  616. NSInteger errorCode = response.statusCode;
  617. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  618. errorCode = error.code;
  619. // Error
  620. if (errorCode == 503) {
  621. message = NSLocalizedString(@"_server_error_retry_", nil);
  622. } else {
  623. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  624. }
  625. completion(account, message, errorCode);
  626. }];
  627. }
  628. // * @param shareeType -> NSInteger: to set the type of sharee (user/group/federated)
  629. - (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
  630. {
  631. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  632. if (tableAccount == nil) {
  633. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  634. } else if ([CCUtility getPassword:account].length == 0) {
  635. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  636. } else if ([CCUtility getCertificateError:account]) {
  637. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  638. }
  639. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  640. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  641. [communication setUserAgent:[CCUtility getUserAgent]];
  642. [communication shareWith:userOrGroup shareeType:shareeType inServer:[tableAccount.url stringByAppendingString:@"/"] andFileOrFolderPath:[fileName encodeString:NSUTF8StringEncoding] andPermissions:permission onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  643. completion(account, nil, 0);
  644. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  645. NSString *message;
  646. NSInteger errorCode = response.statusCode;
  647. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  648. errorCode = error.code;
  649. // Error
  650. if (errorCode == 503) {
  651. message = NSLocalizedString(@"_server_error_retry_", nil);
  652. } else {
  653. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  654. }
  655. completion(account, message, errorCode);
  656. }];
  657. }
  658. - (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
  659. {
  660. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  661. if (tableAccount == nil) {
  662. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  663. } else if ([CCUtility getPassword:account].length == 0) {
  664. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  665. } else if ([CCUtility getCertificateError:account]) {
  666. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  667. }
  668. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  669. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  670. [communication setUserAgent:[CCUtility getUserAgent]];
  671. [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) {
  672. completion(account, nil, 0);
  673. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  674. NSString *message;
  675. NSInteger errorCode = response.statusCode;
  676. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  677. errorCode = error.code;
  678. // Error
  679. if (errorCode == 503) {
  680. message = NSLocalizedString(@"_server_error_retry_", nil);
  681. } else {
  682. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  683. }
  684. completion(account, message, errorCode);
  685. }];
  686. }
  687. - (void)unshareAccount:(NSString *)account shareID:(NSInteger)shareID completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  688. {
  689. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  690. if (tableAccount == nil) {
  691. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  692. } else if ([CCUtility getPassword:account].length == 0) {
  693. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  694. } else if ([CCUtility getCertificateError:account]) {
  695. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  696. }
  697. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  698. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  699. [communication setUserAgent:[CCUtility getUserAgent]];
  700. [communication unShareFileOrFolderByServer:[tableAccount.url stringByAppendingString:@"/"] andIdRemoteShared:shareID onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  701. completion(account, nil, 0);
  702. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  703. NSString *message;
  704. NSInteger errorCode = response.statusCode;
  705. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  706. errorCode = error.code;
  707. // Error
  708. if (errorCode == 503) {
  709. message = NSLocalizedString(@"_server_error_retry_", nil);
  710. } else {
  711. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  712. }
  713. completion(account, message, errorCode);
  714. }];
  715. }
  716. - (void)getUserGroupWithAccount:(NSString *)account searchString:(NSString *)searchString completion:(void (^)(NSString *account, NSArray *item, NSString *message, NSInteger errorCode))completion
  717. {
  718. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  719. if (tableAccount == nil) {
  720. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  721. } else if ([CCUtility getPassword:account].length == 0) {
  722. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  723. } else if ([CCUtility getCertificateError:account]) {
  724. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  725. }
  726. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  727. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  728. [communication setUserAgent:[CCUtility getUserAgent]];
  729. [communication searchUsersAndGroupsWith:searchString forPage:1 with:50 ofServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *itemList, NSString *redirectedServer) {
  730. completion(account, itemList, nil, 0);
  731. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  732. NSString *message;
  733. NSInteger errorCode = response.statusCode;
  734. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  735. errorCode = error.code;
  736. // Error
  737. if (errorCode == 503) {
  738. message = NSLocalizedString(@"_server_error_retry_", nil);
  739. } else {
  740. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  741. }
  742. completion(account, nil, message, errorCode);
  743. }];
  744. }
  745. #pragma --------------------------------------------------------------------------------------------
  746. #pragma mark ===== VAR =====
  747. #pragma --------------------------------------------------------------------------------------------
  748. - (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
  749. {
  750. BOOL previews = false;
  751. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  752. if (tableAccount == nil) {
  753. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  754. } else if ([CCUtility getPassword:account].length == 0) {
  755. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  756. } else if ([CCUtility getCertificateError:account]) {
  757. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  758. }
  759. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilitesWithAccount:account];
  760. if (capabilities != nil && capabilities.versionMajor >= k_nextcloud_version_15_0) {
  761. previews = true;
  762. }
  763. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  764. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  765. [communication setUserAgent:[CCUtility getUserAgent]];
  766. [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) {
  767. completion(account, listOfActivity, nil, 0);
  768. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  769. NSString *message;
  770. NSInteger errorCode = response.statusCode;
  771. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  772. errorCode = error.code;
  773. // Server Unauthorized
  774. if (errorCode == kOCErrorServerUnauthorized || errorCode == kOCErrorServerForbidden) {
  775. [[OCNetworking sharedManager] checkRemoteUser:account function:@"get activity" errorCode:errorCode];
  776. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  777. [CCUtility setCertificateError:account error:YES];
  778. }
  779. // Error
  780. if (errorCode == 503)
  781. message = NSLocalizedString(@"_server_error_retry_", nil);
  782. else
  783. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  784. completion(account, nil, message, errorCode);
  785. }];
  786. }
  787. - (void)getExternalSitesWithAccount:(NSString *)account completion:(void (^)(NSString *account, NSArray *listOfExternalSites, NSString *message, NSInteger errorCode))completion
  788. {
  789. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  790. if (tableAccount == nil) {
  791. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  792. } else if ([CCUtility getPassword:account].length == 0) {
  793. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  794. } else if ([CCUtility getCertificateError:account]) {
  795. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  796. }
  797. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  798. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  799. [communication setUserAgent:[CCUtility getUserAgent]];
  800. [communication getExternalSitesServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfExternalSites, NSString *redirectedServer) {
  801. completion(account, listOfExternalSites, nil, 0);
  802. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  803. NSString *message;
  804. NSInteger errorCode = response.statusCode;
  805. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  806. errorCode = error.code;
  807. // Server Unauthorized
  808. if (errorCode == kOCErrorServerUnauthorized || errorCode == kOCErrorServerForbidden) {
  809. [[OCNetworking sharedManager] checkRemoteUser:account function:@"get external sites" errorCode:errorCode];
  810. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  811. [CCUtility setCertificateError:account error:YES];
  812. }
  813. // Error
  814. if (errorCode == 503) {
  815. message = NSLocalizedString(@"_server_error_retry_", nil);
  816. } else {
  817. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  818. }
  819. completion(account, nil, message, errorCode);
  820. }];
  821. }
  822. - (void)getNotificationWithAccount:(NSString *)account completion:(void (^)(NSString *account, NSArray *listOfNotifications, NSString *message, NSInteger errorCode))completion
  823. {
  824. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  825. if (tableAccount == nil) {
  826. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  827. } else if ([CCUtility getPassword:account].length == 0) {
  828. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  829. } else if ([CCUtility getCertificateError:account]) {
  830. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  831. }
  832. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  833. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  834. [communication setUserAgent:[CCUtility getUserAgent]];
  835. [communication getNotificationServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfNotifications, NSString *redirectedServer) {
  836. completion(account, listOfNotifications, nil, 0);
  837. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  838. NSString *message;
  839. NSInteger errorCode = response.statusCode;
  840. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  841. errorCode = error.code;
  842. // Server Unauthorized
  843. if (errorCode == kOCErrorServerUnauthorized || errorCode == kOCErrorServerForbidden) {
  844. [[OCNetworking sharedManager] checkRemoteUser:account function:@"get notification" errorCode:errorCode];
  845. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  846. [CCUtility setCertificateError:account error:YES];
  847. }
  848. // Error
  849. if (errorCode == 503) {
  850. message = NSLocalizedString(@"_server_error_retry_", nil);
  851. } else {
  852. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  853. }
  854. completion(account, nil, message, errorCode);
  855. }];
  856. }
  857. - (void)setNotificationWithAccount:(NSString *)account serverUrl:(NSString *)serverUrl type:(NSString *)type completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  858. {
  859. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  860. if (tableAccount == nil) {
  861. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  862. } else if ([CCUtility getPassword:account].length == 0) {
  863. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  864. } else if ([CCUtility getCertificateError:account]) {
  865. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  866. }
  867. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  868. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  869. [communication setUserAgent:[CCUtility getUserAgent]];
  870. [communication setNotificationServer:serverUrl type:type onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  871. completion(account, nil, 0);
  872. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  873. NSString *message;
  874. NSInteger errorCode = response.statusCode;
  875. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  876. errorCode = error.code;
  877. // Server Unauthorized
  878. if (errorCode == kOCErrorServerUnauthorized || errorCode == kOCErrorServerForbidden) {
  879. [[OCNetworking sharedManager] checkRemoteUser:account function:@"set notification" errorCode:errorCode];
  880. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  881. [CCUtility setCertificateError:account error:YES];
  882. }
  883. // Error
  884. if (errorCode == 503) {
  885. message = NSLocalizedString(@"_server_error_retry_", nil);
  886. } else {
  887. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  888. }
  889. completion(account, message, errorCode);
  890. }];
  891. }
  892. - (void)getCapabilitiesWithAccount:(NSString *)account completion:(void (^)(NSString *account, OCCapabilities *capabilities, NSString *message, NSInteger errorCode))completion
  893. {
  894. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  895. if (tableAccount == nil) {
  896. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  897. } else if ([CCUtility getPassword:account].length == 0) {
  898. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  899. } else if ([CCUtility getCertificateError:account]) {
  900. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  901. }
  902. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  903. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  904. [communication setUserAgent:[CCUtility getUserAgent]];
  905. [communication getCapabilitiesOfServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, OCCapabilities *capabilities, NSString *redirectedServer) {
  906. completion(account, capabilities, nil, 0);
  907. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  908. NSString *message;
  909. NSInteger errorCode = response.statusCode;
  910. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  911. errorCode = error.code;
  912. // Server Unauthorized
  913. if (errorCode == kOCErrorServerUnauthorized || errorCode == kOCErrorServerForbidden) {
  914. [[OCNetworking sharedManager] checkRemoteUser:account function:@"get capabilities" errorCode:errorCode];
  915. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  916. [CCUtility setCertificateError:account error:YES];
  917. }
  918. // Error
  919. if (errorCode == 503) {
  920. message = NSLocalizedString(@"_server_error_retry_", nil);
  921. } else {
  922. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  923. }
  924. completion(account, nil, message, errorCode);
  925. }];
  926. }
  927. - (void)getUserProfileWithAccount:(NSString *)account completion:(void (^)(NSString *account, OCUserProfile *userProfile, NSString *message, NSInteger errorCode))completion
  928. {
  929. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  930. if (tableAccount == nil) {
  931. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  932. } else if ([CCUtility getPassword:account].length == 0) {
  933. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  934. } else if ([CCUtility getCertificateError:account]) {
  935. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  936. }
  937. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  938. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  939. [communication setUserAgent:[CCUtility getUserAgent]];
  940. [communication getUserProfileServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, OCUserProfile *userProfile, NSString *redirectedServer) {
  941. completion(account, userProfile, nil, 0);
  942. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  943. NSString *message;
  944. NSInteger errorCode = response.statusCode;
  945. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  946. errorCode = error.code;
  947. // Server Unauthorized
  948. if (errorCode == kOCErrorServerUnauthorized || errorCode == kOCErrorServerForbidden) {
  949. [[OCNetworking sharedManager] checkRemoteUser:account function:@"get user profile" errorCode:errorCode];
  950. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  951. [CCUtility setCertificateError:account error:YES];
  952. }
  953. // Error
  954. if (errorCode == 503) {
  955. message = NSLocalizedString(@"_server_error_retry_", nil);
  956. } else {
  957. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  958. }
  959. completion(account, nil, message, errorCode);
  960. }];
  961. }
  962. #pragma --------------------------------------------------------------------------------------------
  963. #pragma mark ===== Push Notification =====
  964. #pragma --------------------------------------------------------------------------------------------
  965. - (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
  966. {
  967. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  968. if (tableAccount == nil) {
  969. completion(account, nil, nil, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  970. } else if ([CCUtility getPassword:account].length == 0) {
  971. completion(account, nil, nil, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  972. } else if ([CCUtility getCertificateError:account]) {
  973. completion(account, nil, nil, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  974. }
  975. devicePublicKey = [CCUtility URLEncodeStringFromString:devicePublicKey];
  976. NSString *proxyServerPath = [NCBrandOptions sharedInstance].pushNotificationServerProxy;
  977. NSString *proxyServer = [NCBrandOptions sharedInstance].pushNotificationServerProxy;
  978. #ifdef DEBUG
  979. // proxyServerPath = @"http://127.0.0.1:8088";
  980. // proxyServer = @"https://10.132.0.37:8443/pushnotifications";
  981. #endif
  982. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  983. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  984. [communication setUserAgent:[CCUtility getUserAgent]];
  985. [communication subscribingNextcloudServerPush:url pushTokenHash:pushTokenHash devicePublicKey:devicePublicKey proxyServerPath: proxyServerPath onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *publicKey, NSString *deviceIdentifier, NSString *signature, NSString *redirectedServer) {
  986. deviceIdentifier = [CCUtility URLEncodeStringFromString:deviceIdentifier];
  987. signature = [CCUtility URLEncodeStringFromString:signature];
  988. publicKey = [CCUtility URLEncodeStringFromString:publicKey];
  989. [communication subscribingPushProxy:proxyServer pushToken:pushToken deviceIdentifier:deviceIdentifier deviceIdentifierSignature:signature publicKey:publicKey onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  990. completion(account, deviceIdentifier, signature, publicKey, nil, 0);
  991. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  992. NSString *message;
  993. NSInteger errorCode = response.statusCode;
  994. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  995. errorCode = error.code;
  996. // Error
  997. if (errorCode == 503)
  998. message = NSLocalizedString(@"_server_error_retry_", nil);
  999. else
  1000. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1001. completion(account, nil, nil, nil, message, errorCode);
  1002. }];
  1003. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1004. NSString *message;
  1005. NSInteger errorCode = response.statusCode;
  1006. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1007. errorCode = error.code;
  1008. // Error
  1009. if (errorCode == 503)
  1010. message = NSLocalizedString(@"_server_error_retry_", nil);
  1011. else
  1012. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1013. completion(account, nil, nil, nil, message, errorCode);
  1014. }];
  1015. }
  1016. - (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 {
  1017. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1018. if (tableAccount == nil) {
  1019. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1020. } else if ([CCUtility getPassword:account].length == 0) {
  1021. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1022. } else if ([CCUtility getCertificateError:account]) {
  1023. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1024. }
  1025. NSString *proxyServer = [NCBrandOptions sharedInstance].pushNotificationServerProxy;
  1026. #ifdef DEBUG
  1027. // proxyServer = @"https://10.132.0.37:8443/pushnotifications";
  1028. #endif
  1029. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1030. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1031. [communication setUserAgent:[CCUtility getUserAgent]];
  1032. [communication unsubscribingNextcloudServerPush:url onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1033. [communication unsubscribingPushProxy:proxyServer deviceIdentifier:deviceIdentifier deviceIdentifierSignature:deviceIdentifierSignature publicKey:publicKey onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1034. completion(account, nil, 0);
  1035. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1036. NSString *message;
  1037. NSInteger errorCode = response.statusCode;
  1038. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1039. errorCode = error.code;
  1040. // Error
  1041. if (errorCode == 503)
  1042. message = NSLocalizedString(@"_server_error_retry_", nil);
  1043. else
  1044. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1045. completion(account, message, errorCode);
  1046. }];
  1047. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1048. NSString *message;
  1049. NSInteger errorCode = response.statusCode;
  1050. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1051. errorCode = error.code;
  1052. // Error
  1053. if (errorCode == 503)
  1054. message = NSLocalizedString(@"_server_error_retry_", nil);
  1055. else
  1056. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1057. completion(account, message, errorCode);
  1058. }];
  1059. }
  1060. - (void)getServerNotification:(NSString *)serverUrl notificationId:(NSInteger)notificationId completion:(void(^)(NSDictionary*jsongParsed, NSString *message, NSInteger errorCode))completion
  1061. {
  1062. NSString *URLString = [NSString stringWithFormat:@"%@/ocs/v2.php/apps/notifications/api/v2/notifications/%ld?format=json", serverUrl, (long)notificationId];
  1063. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URLString] cachePolicy:0 timeoutInterval:20.0];
  1064. [request addValue:[CCUtility getUserAgent] forHTTPHeaderField:@"User-Agent"];
  1065. [request addValue:@"true" forHTTPHeaderField:@"OCS-APIRequest"];
  1066. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  1067. NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  1068. NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler: ^(NSData *data, NSURLResponse *response, NSError *error) {
  1069. if (error) {
  1070. NSString *message;
  1071. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
  1072. NSInteger errorCode = httpResponse.statusCode;
  1073. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1074. errorCode = error.code;
  1075. // Error
  1076. if (errorCode == 503)
  1077. message = NSLocalizedString(@"_server_error_retry_", nil);
  1078. else
  1079. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1080. completion(nil, message, errorCode);
  1081. } else {
  1082. NSDictionary *jsongParsed = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
  1083. completion(jsongParsed, nil, 0);
  1084. }
  1085. }];
  1086. [task resume];
  1087. }
  1088. - (void)deletingServerNotification:(NSString *)serverUrl notificationId:(NSInteger)notificationId completion:(void(^)(NSString *message, NSInteger errorCode))completion
  1089. {
  1090. // NSData *authData = [[NSString stringWithFormat:@"%@:%@", tableAccount.user, [CCUtility getPassword:tableAccount.account]] dataUsingEncoding:NSUTF8StringEncoding];
  1091. // NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];
  1092. // Delete
  1093. NSString *URLString = [NSString stringWithFormat:@"%@/ocs/v2.php/apps/notifications/api/v2/notifications/%ld", serverUrl, (long)notificationId];
  1094. // Delete-all
  1095. if (notificationId == 0) {
  1096. URLString = [NSString stringWithFormat:@"%@/ocs/v2.php/apps/notifications/api/v2/notifications", serverUrl];
  1097. }
  1098. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URLString] cachePolicy:0 timeoutInterval:20.0];
  1099. // [request setValue:authValue forHTTPHeaderField:@"Authorization"];
  1100. [request addValue:[CCUtility getUserAgent] forHTTPHeaderField:@"User-Agent"];
  1101. [request addValue:@"true" forHTTPHeaderField:@"OCS-APIRequest"];
  1102. [request setHTTPMethod: @"DELETE"];
  1103. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  1104. NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  1105. NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler: ^(NSData *data, NSURLResponse *response, NSError *error) {
  1106. if (error) {
  1107. NSString *message;
  1108. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
  1109. NSInteger errorCode = httpResponse.statusCode;
  1110. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1111. errorCode = error.code;
  1112. // Error
  1113. if (errorCode == 503)
  1114. message = NSLocalizedString(@"_server_error_retry_", nil);
  1115. else
  1116. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1117. completion(message, errorCode);
  1118. } else {
  1119. completion(nil, 0);
  1120. }
  1121. }];
  1122. [task resume];
  1123. }
  1124. #pragma --------------------------------------------------------------------------------------------
  1125. #pragma mark ===== Manage Mobile Editor OCS API =====
  1126. #pragma --------------------------------------------------------------------------------------------
  1127. - (void)createLinkRichdocumentsWithAccount:(NSString *)account fileId:(NSString *)fileId completion:(void(^)(NSString *account, NSString *link, NSString *message, NSInteger errorCode))completion
  1128. {
  1129. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1130. if (tableAccount == nil) {
  1131. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1132. } else if ([CCUtility getPassword:account].length == 0) {
  1133. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1134. } else if ([CCUtility getCertificateError:account]) {
  1135. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1136. }
  1137. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1138. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1139. [communication setUserAgent:[CCUtility getUserAgent]];
  1140. [communication createLinkRichdocuments:[tableAccount.url stringByAppendingString:@"/"] fileId:fileId onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *link, NSString *redirectedServer) {
  1141. completion(account, link, nil, 0);
  1142. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1143. NSString *message;
  1144. NSInteger errorCode = response.statusCode;
  1145. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1146. errorCode = error.code;
  1147. // Error
  1148. if (errorCode == 503)
  1149. message = NSLocalizedString(@"_server_error_retry_", nil);
  1150. else
  1151. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1152. completion(account, nil,message, errorCode);
  1153. }];
  1154. }
  1155. - (void)getTemplatesRichdocumentsWithAccount:(NSString *)account typeTemplate:(NSString *)typeTemplate completion:(void(^)(NSString *account, NSArray *listOfTemplate, NSString *message, NSInteger errorCode))completion
  1156. {
  1157. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1158. if (tableAccount == nil) {
  1159. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1160. } else if ([CCUtility getPassword:account].length == 0) {
  1161. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1162. } else if ([CCUtility getCertificateError:account]) {
  1163. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1164. }
  1165. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1166. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1167. [communication setUserAgent:[CCUtility getUserAgent]];
  1168. [communication getTemplatesRichdocuments:[tableAccount.url stringByAppendingString:@"/"] typeTemplate:typeTemplate onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfTemplate, NSString *redirectedServer) {
  1169. completion(account, listOfTemplate, nil, 0);
  1170. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1171. NSString *message;
  1172. NSInteger errorCode = response.statusCode;
  1173. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1174. errorCode = error.code;
  1175. // Error
  1176. if (errorCode == 503)
  1177. message = NSLocalizedString(@"_server_error_retry_", nil);
  1178. else
  1179. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1180. completion(account, nil, message, errorCode);
  1181. }];
  1182. }
  1183. - (void)createNewRichdocumentsWithAccount:(NSString *)account fileName:(NSString *)fileName serverUrl:(NSString *)serverUrl templateID:(NSString *)templateID completion:(void(^)(NSString *account, NSString *url, NSString *message, NSInteger errorCode))completion
  1184. {
  1185. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1186. if (tableAccount == nil) {
  1187. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1188. } else if ([CCUtility getPassword:account].length == 0) {
  1189. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1190. } else if ([CCUtility getCertificateError:account]) {
  1191. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1192. }
  1193. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1194. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1195. [communication setUserAgent:[CCUtility getUserAgent]];
  1196. [communication createNewRichdocuments:[tableAccount.url stringByAppendingString:@"/"] path:fileName templateID:templateID onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *url, NSString *redirectedServer) {
  1197. completion(account, url, nil, 0);
  1198. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1199. NSString *message;
  1200. NSInteger errorCode = response.statusCode;
  1201. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1202. errorCode = error.code;
  1203. // Error
  1204. if (errorCode == 503)
  1205. message = NSLocalizedString(@"_server_error_retry_", nil);
  1206. else
  1207. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1208. completion(account, nil, message, errorCode);
  1209. }];
  1210. }
  1211. - (void)createAssetRichdocumentsWithAccount:(NSString *)account fileName:(NSString *)fileName serverUrl:(NSString *)serverUrl completion:(void(^)(NSString *account, NSString *link, NSString *message, NSInteger errorCode))completion
  1212. {
  1213. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1214. if (tableAccount == nil) {
  1215. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1216. } else if ([CCUtility getPassword:account].length == 0) {
  1217. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1218. } else if ([CCUtility getCertificateError:account]) {
  1219. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1220. }
  1221. NSString *fileNamePath = [CCUtility returnFileNamePathFromFileName:fileName serverUrl:serverUrl activeUrl:tableAccount.url];
  1222. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1223. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1224. [communication setUserAgent:[CCUtility getUserAgent]];
  1225. [communication createAssetRichdocuments:[tableAccount.url stringByAppendingString:@"/"] path:fileNamePath onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *url, NSString *redirectedServer) {
  1226. completion(account, url, nil, 0);
  1227. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1228. NSString *message;
  1229. NSInteger errorCode = response.statusCode;
  1230. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1231. errorCode = error.code;
  1232. // Error
  1233. if (errorCode == 503)
  1234. message = NSLocalizedString(@"_server_error_retry_", nil);
  1235. else
  1236. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1237. completion(account, nil, message, errorCode);
  1238. }];
  1239. }
  1240. #pragma --------------------------------------------------------------------------------------------
  1241. #pragma mark ===== Full Text Search =====
  1242. #pragma --------------------------------------------------------------------------------------------
  1243. - (void)fullTextSearchWithAccount:(NSString *)account text:(NSString *)text page:(NSInteger)page completion:(void(^)(NSString *account, NSArray *items, NSString *message, NSInteger errorCode))completion
  1244. {
  1245. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1246. if (tableAccount == nil) {
  1247. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1248. } else if ([CCUtility getPassword:account].length == 0) {
  1249. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1250. } else if ([CCUtility getCertificateError:account]) {
  1251. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1252. }
  1253. // Create JSON
  1254. NSMutableDictionary *dataDic = [NSMutableDictionary new];
  1255. [dataDic setValue:@"files" forKey:@"providers"];
  1256. [dataDic setValue:text forKey:@"search"];
  1257. [dataDic setValue:[NSNumber numberWithInteger:page] forKey:@"page"];
  1258. [dataDic setValue:[NSNumber numberWithInt:20] forKey:@"size"];
  1259. NSMutableDictionary *options = [NSMutableDictionary new];
  1260. [options setValue:@"" forKey:@"files_within_dir"];
  1261. [options setValue:@"" forKey:@"files_local"];
  1262. [options setValue:@"" forKey:@"files_extension"];
  1263. [dataDic setValue:options forKey:@"options"];
  1264. NSString *data = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:dataDic options:0 error:nil] encoding:NSUTF8StringEncoding];
  1265. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1266. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1267. [communication setUserAgent:[CCUtility getUserAgent]];
  1268. [communication fullTextSearch:[tableAccount.url stringByAppendingString:@"/"] data:data onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  1269. completion(account, items, nil, 0);
  1270. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1271. NSString *message;
  1272. NSInteger errorCode = response.statusCode;
  1273. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1274. errorCode = error.code;
  1275. // Error
  1276. if (errorCode == 503)
  1277. message = NSLocalizedString(@"_server_error_retry_", nil);
  1278. else
  1279. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1280. completion(account, nil, message, errorCode);
  1281. }];
  1282. }
  1283. #pragma --------------------------------------------------------------------------------------------
  1284. #pragma mark ===== Check remote user =====
  1285. #pragma --------------------------------------------------------------------------------------------
  1286. - (void)checkRemoteUser:(NSString *)account function:(NSString *)function errorCode:(NSInteger)errorCode
  1287. {
  1288. #ifndef EXTENSION
  1289. @synchronized(self) {
  1290. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  1291. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilitesWithAccount:account];
  1292. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1293. NSString *token = [CCUtility getPassword:account];
  1294. if (self.checkRemoteUserInProgress || tableAccount == nil || token == nil) {
  1295. return;
  1296. } else {
  1297. self.checkRemoteUserInProgress = true;
  1298. }
  1299. if (capabilities != nil && capabilities.versionMajor >= k_nextcloud_version_17_0) {
  1300. [[OCNetworking sharedManager] getRemoteWipeStatusWithAccount:account token:token completion:^(NSString *account, BOOL wipe, NSString *message, NSInteger errorCode) {
  1301. if (wipe) {
  1302. [appDelegate deleteAccount:account wipe:true];
  1303. [[NCContentPresenter shared] messageNotification:tableAccount.user description:@"_wipe_account_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  1304. [[OCNetworking sharedManager] setRemoteWipeCompletitionWithUser:tableAccount.user userID:tableAccount.userID url:tableAccount.url token:token completion:^(NSString *message, NSInteger errorCode) {
  1305. NSLog(@"Wiped");
  1306. }];
  1307. } else {
  1308. if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive && [appDelegate.reachability isReachable]) {
  1309. [[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];
  1310. [CCUtility setPassword:account password:nil];
  1311. }
  1312. }
  1313. self.checkRemoteUserInProgress = false;
  1314. }];
  1315. } else if ([CCUtility getPassword:account] != nil) {
  1316. if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive && [appDelegate.reachability isReachable]) {
  1317. [[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];
  1318. [CCUtility setPassword:account password:nil];
  1319. }
  1320. }
  1321. }
  1322. #endif
  1323. }
  1324. - (void)getRemoteWipeStatusWithAccount:(NSString *)account token:(NSString *)token completion:(void(^)(NSString *account, BOOL wipe, NSString *message, NSInteger errorCode))completion
  1325. {
  1326. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1327. if (tableAccount == nil) {
  1328. completion(account, false, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1329. } else if ([CCUtility getPassword:account].length == 0) {
  1330. completion(account, false, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1331. } else if ([CCUtility getCertificateError:account]) {
  1332. completion(account, false, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1333. }
  1334. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1335. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1336. [communication setUserAgent:[CCUtility getUserAgent]];
  1337. [communication getRemoteWipeStatus:tableAccount.url token:token onCommunication:communication successRequest:^(NSHTTPURLResponse *response, BOOL wipe, NSString *redirectedServer) {
  1338. completion(account, wipe, nil, 0);
  1339. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1340. NSString *message;
  1341. NSInteger errorCode = response.statusCode;
  1342. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1343. errorCode = error.code;
  1344. // Server Unauthorized
  1345. if (errorCode == kOCErrorServerUnauthorized || errorCode == kOCErrorServerForbidden) {
  1346. [[OCNetworking sharedManager] checkRemoteUser:account function:@"get remote wipe status" errorCode:errorCode];
  1347. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  1348. [CCUtility setCertificateError:account error:YES];
  1349. }
  1350. // Error
  1351. if (errorCode == 503)
  1352. message = NSLocalizedString(@"_server_error_retry_", nil);
  1353. else
  1354. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1355. completion(account, false, message, errorCode);
  1356. }];
  1357. }
  1358. - (void)setRemoteWipeCompletitionWithUser:(NSString *)user userID:(NSString *)userID url:(NSString *)url token:(NSString *)token completion:(void(^)(NSString *message, NSInteger errorCode))completion
  1359. {
  1360. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1361. [communication setCredentialsWithUser:user andUserID:userID andPassword:token];
  1362. [communication setUserAgent:[CCUtility getUserAgent]];
  1363. [communication setRemoteWipeCompletition:url token:token onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1364. completion(nil, 0);
  1365. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1366. NSString *message;
  1367. NSInteger errorCode = response.statusCode;
  1368. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1369. errorCode = error.code;
  1370. // Error
  1371. if (errorCode == 503)
  1372. message = NSLocalizedString(@"_server_error_retry_", nil);
  1373. else
  1374. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1375. completion(message, errorCode);
  1376. }];
  1377. }
  1378. #pragma --------------------------------------------------------------------------------------------
  1379. #pragma mark ===== Trash =====
  1380. #pragma --------------------------------------------------------------------------------------------
  1381. - (void)listingTrashWithAccount:(NSString *)account path:(NSString *)path serverUrl:(NSString *)serverUrl depth:(NSString *)depth completion:(void (^)(NSString *account, NSArray *items, NSString *message, NSInteger errorCode))completion
  1382. {
  1383. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1384. if (tableAccount == nil) {
  1385. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1386. } else if ([CCUtility getPassword:account].length == 0) {
  1387. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1388. } else if ([CCUtility getCertificateError:account]) {
  1389. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1390. }
  1391. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1392. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1393. [communication setUserAgent:[CCUtility getUserAgent]];
  1394. [communication listingTrash:[serverUrl stringByAppendingString:path] depth:depth onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  1395. // Check items > 0
  1396. if ([items count] == 0) {
  1397. [[NCContentPresenter shared] messageNotification:@"Server error" description:@"Read Folder WebDAV : [items NULL] please fix" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  1398. completion(account, nil, NSLocalizedString(@"Read Folder WebDAV : [items NULL] please fix", nil), k_CCErrorInternalError);
  1399. } else {
  1400. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1401. NSMutableArray *listTrash = [NSMutableArray new];
  1402. //OCFileDto *itemDtoFolder = [items objectAtIndex:0];
  1403. if ([items count] > 1) {
  1404. for (NSUInteger i=1; i < [items count]; i++) {
  1405. OCFileDto *itemDto = [items objectAtIndex:i];
  1406. tableTrash *trash = [tableTrash new];
  1407. trash.account = account;
  1408. trash.date = [NSDate dateWithTimeIntervalSince1970:itemDto.date];
  1409. trash.directory = itemDto.isDirectory;
  1410. trash.fileId = itemDto.fileId;
  1411. trash.fileName = itemDto.fileName;
  1412. NSArray *array = [itemDto.filePath componentsSeparatedByString:path];
  1413. long len = [[array objectAtIndex:0] length];
  1414. trash.filePath = [itemDto.filePath substringFromIndex:len];
  1415. trash.hasPreview = itemDto.hasPreview;
  1416. trash.size = itemDto.size;
  1417. trash.trashbinFileName = itemDto.trashbinFileName;
  1418. trash.trashbinOriginalLocation = itemDto.trashbinOriginalLocation;
  1419. trash.trashbinDeletionTime = [NSDate dateWithTimeIntervalSince1970:itemDto.trashbinDeletionTime];
  1420. [CCUtility insertTypeFileIconName:trash.trashbinFileName metadata:(tableMetadata *)trash];
  1421. [listTrash addObject:trash];
  1422. }
  1423. }
  1424. dispatch_async(dispatch_get_main_queue(), ^{
  1425. completion(account, listTrash, nil, 0);
  1426. });
  1427. });
  1428. }
  1429. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1430. NSString *message;
  1431. NSInteger errorCode = response.statusCode;
  1432. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1433. errorCode = error.code;
  1434. // Error
  1435. if (errorCode == 503)
  1436. message = NSLocalizedString(@"_server_error_retry_", nil);
  1437. else
  1438. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1439. completion(account, nil,message, errorCode);
  1440. }];
  1441. }
  1442. - (void)emptyTrashWithAccount:(NSString *)account completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  1443. {
  1444. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1445. if (tableAccount == nil) {
  1446. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1447. } else if ([CCUtility getPassword:account].length == 0) {
  1448. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1449. } else if ([CCUtility getCertificateError:account]) {
  1450. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1451. }
  1452. NSString *path = [NSString stringWithFormat:@"%@%@/trashbin/%@/trash", tableAccount.url, k_dav, tableAccount.userID];
  1453. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1454. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1455. [communication setUserAgent:[CCUtility getUserAgent]];
  1456. [communication emptyTrash:path onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1457. completion(account, nil, 0);
  1458. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1459. NSString *message;
  1460. NSInteger errorCode = response.statusCode;
  1461. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1462. errorCode = error.code;
  1463. // Error
  1464. if (errorCode == 503)
  1465. message = NSLocalizedString(@"_server_error_retry_", nil);
  1466. else
  1467. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1468. completion(account, message, errorCode);
  1469. }];
  1470. }
  1471. #pragma --------------------------------------------------------------------------------------------
  1472. #pragma mark ===== Comments =====
  1473. #pragma --------------------------------------------------------------------------------------------
  1474. - (void)getCommentsWithAccount:(NSString *)account fileId:(NSString *)fileId completion:(void (^)(NSString *account, NSArray *items, NSString *message, NSInteger errorCode))completion
  1475. {
  1476. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1477. if (tableAccount == nil) {
  1478. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1479. } else if ([CCUtility getPassword:account].length == 0) {
  1480. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1481. } else if ([CCUtility getCertificateError:account]) {
  1482. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1483. }
  1484. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1485. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1486. [communication setUserAgent:[CCUtility getUserAgent]];
  1487. [communication getComments:[NSString stringWithFormat:@"%@%@", tableAccount.url, k_dav] fileId:fileId onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *list, NSString *redirectedServer) {
  1488. completion(account, list, nil, 0);
  1489. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1490. NSString *message;
  1491. NSInteger errorCode = response.statusCode;
  1492. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1493. errorCode = error.code;
  1494. // Error
  1495. if (errorCode == 503)
  1496. message = NSLocalizedString(@"_server_error_retry_", nil);
  1497. else
  1498. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1499. completion(account, nil,message, errorCode);
  1500. }];
  1501. }
  1502. - (void)putCommentsWithAccount:(NSString *)account fileId:(NSString *)fileId message:(NSString *)message completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  1503. {
  1504. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1505. if (tableAccount == nil) {
  1506. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1507. } else if ([CCUtility getPassword:account].length == 0) {
  1508. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1509. } else if ([CCUtility getCertificateError:account]) {
  1510. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1511. }
  1512. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1513. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1514. [communication setUserAgent:[CCUtility getUserAgent]];
  1515. [communication putComments:[NSString stringWithFormat:@"%@%@", tableAccount.url, k_dav] fileId:fileId message:message onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1516. completion(account, nil, 0);
  1517. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1518. NSString *message;
  1519. NSInteger errorCode = response.statusCode;
  1520. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1521. errorCode = error.code;
  1522. // Error
  1523. if (errorCode == 503)
  1524. message = NSLocalizedString(@"_server_error_retry_", nil);
  1525. else
  1526. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1527. completion(account, message, errorCode);
  1528. }];
  1529. }
  1530. - (void)updateCommentsWithAccount:(NSString *)account fileId:(NSString *)fileId messageID:(NSString *)messageID message:(NSString *)message completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  1531. {
  1532. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1533. if (tableAccount == nil) {
  1534. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1535. } else if ([CCUtility getPassword:account].length == 0) {
  1536. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1537. } else if ([CCUtility getCertificateError:account]) {
  1538. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1539. }
  1540. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1541. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1542. [communication setUserAgent:[CCUtility getUserAgent]];
  1543. [communication updateComments:[NSString stringWithFormat:@"%@%@", tableAccount.url, k_dav] fileId:fileId messageID:messageID message:message onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1544. completion(account, nil, 0);
  1545. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1546. NSString *message;
  1547. NSInteger errorCode = response.statusCode;
  1548. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1549. errorCode = error.code;
  1550. // Error
  1551. if (errorCode == 503)
  1552. message = NSLocalizedString(@"_server_error_retry_", nil);
  1553. else
  1554. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1555. completion(account, message, errorCode);
  1556. }];
  1557. }
  1558. - (void)readMarkCommentsWithAccount:(NSString *)account fileId:(NSString *)fileId completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  1559. {
  1560. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1561. if (tableAccount == nil) {
  1562. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1563. } else if ([CCUtility getPassword:account].length == 0) {
  1564. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1565. } else if ([CCUtility getCertificateError:account]) {
  1566. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1567. }
  1568. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1569. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1570. [communication setUserAgent:[CCUtility getUserAgent]];
  1571. [communication readMarkComments:[NSString stringWithFormat:@"%@%@", tableAccount.url, k_dav] fileId:fileId onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1572. completion(account, nil, 0);
  1573. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1574. NSString *message;
  1575. NSInteger errorCode = response.statusCode;
  1576. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1577. errorCode = error.code;
  1578. // Error
  1579. if (errorCode == 503)
  1580. message = NSLocalizedString(@"_server_error_retry_", nil);
  1581. else
  1582. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1583. completion(account, message, errorCode);
  1584. }];
  1585. }
  1586. - (void)deleteCommentsWithAccount:(NSString *)account fileId:(NSString *)fileId messageID:(NSString *)messageID completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  1587. {
  1588. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1589. if (tableAccount == nil) {
  1590. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1591. } else if ([CCUtility getPassword:account].length == 0) {
  1592. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1593. } else if ([CCUtility getCertificateError:account]) {
  1594. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1595. }
  1596. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1597. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1598. [communication setUserAgent:[CCUtility getUserAgent]];
  1599. [communication deleteComments:[NSString stringWithFormat:@"%@%@", tableAccount.url, k_dav] fileId:fileId messageID:messageID onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1600. completion(account, nil, 0);
  1601. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1602. NSString *message;
  1603. NSInteger errorCode = response.statusCode;
  1604. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1605. errorCode = error.code;
  1606. // Error
  1607. if (errorCode == 503)
  1608. message = NSLocalizedString(@"_server_error_retry_", nil);
  1609. else
  1610. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1611. completion(account, message, errorCode);
  1612. }];
  1613. }
  1614. #pragma --------------------------------------------------------------------------------------------
  1615. #pragma mark ===== Third Parts =====
  1616. #pragma --------------------------------------------------------------------------------------------
  1617. - (void)getHCUserProfileWithAccount:(NSString *)account serverUrl:(NSString *)serverUrl completion:(void (^)(NSString *account, OCUserProfile *userProfile, NSString *message, NSInteger errorCode))completion
  1618. {
  1619. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1620. if (tableAccount == nil) {
  1621. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1622. } else if ([CCUtility getPassword:account].length == 0) {
  1623. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1624. } else if ([CCUtility getCertificateError:account]) {
  1625. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1626. }
  1627. NSString *serverPath = [NSString stringWithFormat:@"%@/ocs/v2.php/apps/handwerkcloud/api/v1/settings/%@", serverUrl, tableAccount.userID];
  1628. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1629. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1630. [communication setUserAgent:[CCUtility getUserAgent]];
  1631. [communication getHCUserProfile:serverPath onCommunication:communication successRequest:^(NSHTTPURLResponse *response, OCUserProfile *userProfile, NSString *redirectedServer) {
  1632. completion(account, userProfile, nil, 0);
  1633. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1634. NSString *message;
  1635. NSInteger errorCode = response.statusCode;
  1636. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1637. errorCode = error.code;
  1638. // Server Unauthorized
  1639. if (errorCode == kOCErrorServerUnauthorized || errorCode == kOCErrorServerForbidden) {
  1640. [[OCNetworking sharedManager] checkRemoteUser:account function:@"get user profile" errorCode:errorCode];
  1641. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  1642. [CCUtility setCertificateError:account error:YES];
  1643. }
  1644. // Error
  1645. if (errorCode == 503)
  1646. message = NSLocalizedString(@"_server_error_retry_", nil);
  1647. else
  1648. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1649. completion(account, nil,message, errorCode);
  1650. }];
  1651. }
  1652. - (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
  1653. {
  1654. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1655. if (tableAccount == nil) {
  1656. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1657. } else if ([CCUtility getPassword:account].length == 0) {
  1658. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1659. } else if ([CCUtility getCertificateError:account]) {
  1660. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1661. }
  1662. // Create JSON
  1663. NSMutableDictionary *dataDic = [NSMutableDictionary new];
  1664. if (address) [dataDic setValue:address forKey:@"address"];
  1665. if (businesssize) {
  1666. if ([businesssize isEqualToString:@"1-4"]) { [dataDic setValue:[NSNumber numberWithInt:1] forKey:@"businesssize"]; }
  1667. else if ([businesssize isEqualToString:@"5-9"]) { [dataDic setValue:[NSNumber numberWithInt:5] forKey:@"businesssize"]; }
  1668. else if ([businesssize isEqualToString:@"10-19"]) { [dataDic setValue:[NSNumber numberWithInt:10] forKey:@"businesssize"]; }
  1669. else if ([businesssize isEqualToString:@"20-49"]) { [dataDic setValue:[NSNumber numberWithInt:20] forKey:@"businesssize"]; }
  1670. else if ([businesssize isEqualToString:@"50-99"]) { [dataDic setValue:[NSNumber numberWithInt:50] forKey:@"businesssize"]; }
  1671. else if ([businesssize isEqualToString:@"100-249"]) { [dataDic setValue:[NSNumber numberWithInt:100] forKey:@"businesssize"]; }
  1672. else if ([businesssize isEqualToString:@"250-499"]) { [dataDic setValue:[NSNumber numberWithInt:250] forKey:@"businesssize"]; }
  1673. else if ([businesssize isEqualToString:@"500-999"]) { [dataDic setValue:[NSNumber numberWithInt:500] forKey:@"businesssize"]; }
  1674. else if ([businesssize isEqualToString:@"1000+"]) { [dataDic setValue:[NSNumber numberWithInt:1000] forKey:@"businesssize"]; }
  1675. }
  1676. if (businesstype) [dataDic setValue:businesstype forKey:@"businesstype"];
  1677. if (city) [dataDic setValue:city forKey:@"city"];
  1678. if (company) [dataDic setValue:company forKey:@"company"];
  1679. if (country) [dataDic setValue:country forKey:@"country"];
  1680. if (displayname) [dataDic setValue:displayname forKey:@"displayname"];
  1681. if (email) [dataDic setValue:email forKey:@"email"];
  1682. if (phone) [dataDic setValue:phone forKey:@"phone"];
  1683. if (role_) [dataDic setValue:role_ forKey:@"role"];
  1684. if (twitter) [dataDic setValue:twitter forKey:@"twitter"];
  1685. if (website) [dataDic setValue:website forKey:@"website"];
  1686. if (zip) [dataDic setValue:zip forKey:@"zip"];
  1687. NSString *data = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:dataDic options:0 error:nil] encoding:NSUTF8StringEncoding];
  1688. NSString *serverPath = [NSString stringWithFormat:@"%@/ocs/v2.php/apps/handwerkcloud/api/v1/settings/%@", serverUrl, tableAccount.userID];
  1689. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1690. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1691. [communication setUserAgent:[CCUtility getUserAgent]];
  1692. [communication putHCUserProfile:serverPath data:data onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1693. completion(account, nil, 0);
  1694. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1695. NSString *message;
  1696. NSInteger errorCode = response.statusCode;
  1697. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1698. errorCode = error.code;
  1699. // Server Unauthorized
  1700. if (errorCode == kOCErrorServerUnauthorized || errorCode == kOCErrorServerForbidden) {
  1701. [[OCNetworking sharedManager] checkRemoteUser:account function:@"put user profile" errorCode:errorCode];
  1702. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  1703. [CCUtility setCertificateError:account error:YES];
  1704. }
  1705. // Error
  1706. if (errorCode == 503)
  1707. message = NSLocalizedString(@"_server_error_retry_", nil);
  1708. else
  1709. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1710. completion(account, message, errorCode);
  1711. }];
  1712. }
  1713. - (void)getHCFeaturesWithAccount:(NSString *)account serverUrl:(NSString *)serverUrl completion:(void (^)(NSString *account, HCFeatures *features, NSString *message, NSInteger errorCode))completion
  1714. {
  1715. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1716. if (tableAccount == nil) {
  1717. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1718. } else if ([CCUtility getPassword:account].length == 0) {
  1719. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1720. } else if ([CCUtility getCertificateError:account]) {
  1721. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1722. }
  1723. NSString *serverPath = [NSString stringWithFormat:@"%@/ocs/v2.php/apps/handwerkcloud/api/v1/features/%@", serverUrl, tableAccount.userID];
  1724. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1725. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1726. [communication setUserAgent:[CCUtility getUserAgent]];
  1727. [communication getHCFeatures:serverPath onCommunication:communication successRequest:^(NSHTTPURLResponse *response, HCFeatures *features, NSString *redirectedServer) {
  1728. completion(account, features, nil, 0);
  1729. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1730. NSString *message;
  1731. NSInteger errorCode = response.statusCode;
  1732. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1733. errorCode = error.code;
  1734. // Server Unauthorized
  1735. if (errorCode == kOCErrorServerUnauthorized || errorCode == kOCErrorServerForbidden) {
  1736. [[OCNetworking sharedManager] checkRemoteUser:account function:@"get features" errorCode:errorCode];
  1737. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  1738. [CCUtility setCertificateError:account error:YES];
  1739. }
  1740. // Error
  1741. if (errorCode == 503)
  1742. message = NSLocalizedString(@"_server_error_retry_", nil);
  1743. else
  1744. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1745. completion(account, nil,message, errorCode);
  1746. }];
  1747. }
  1748. /*
  1749. - (void)middlewarePing
  1750. {
  1751. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1752. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  1753. [communication setUserAgent:[CCUtility getUserAgent]];
  1754. [communication getMiddlewarePing:_metadataNet.serverUrl onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfExternalSites, NSString *redirectedServer) {
  1755. [self complete];
  1756. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1757. NSInteger errorCode = response.statusCode;
  1758. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1759. errorCode = error.code;
  1760. // Error
  1761. if ([self.delegate respondsToSelector:@selector(getExternalSitesServerFailure:message:errorCode:)]) {
  1762. if (errorCode == 503)
  1763. [self.delegate getExternalSitesServerFailure:_metadataNet message:NSLocalizedString(@"_server_error_retry_", nil) errorCode:errorCode];
  1764. else
  1765. [self.delegate getExternalSitesServerFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1766. }
  1767. // Request trusted certificated
  1768. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  1769. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1770. [self complete];
  1771. }];
  1772. }
  1773. */
  1774. #pragma --------------------------------------------------------------------------------------------
  1775. #pragma mark ===== didReceiveChallenge =====
  1776. #pragma --------------------------------------------------------------------------------------------
  1777. -(void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler
  1778. {
  1779. // The pinnning check
  1780. if ([[NCNetworking sharedInstance] checkTrustedChallengeWithChallenge:challenge directoryCertificate:[CCUtility getDirectoryCerificates]]) {
  1781. completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  1782. } else {
  1783. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  1784. }
  1785. }
  1786. @end
  1787. #pragma --------------------------------------------------------------------------------------------
  1788. #pragma mark ===== OCURLSessionManager =====
  1789. #pragma --------------------------------------------------------------------------------------------
  1790. @implementation OCURLSessionManager
  1791. - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
  1792. {
  1793. // The pinnning check
  1794. if ([[NCNetworking sharedInstance] checkTrustedChallengeWithChallenge:challenge directoryCertificate:[CCUtility getDirectoryCerificates]]) {
  1795. completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  1796. } else {
  1797. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  1798. }
  1799. }
  1800. @end