OCNetworking.m 118 KB

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