OCNetworking.m 122 KB

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