OCNetworking.m 129 KB

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