OCNetworking.m 142 KB

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