OCNetworking.m 146 KB

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