OCNetworking.m 153 KB

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