OCNetworking.m 158 KB

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