OCNetworking.m 160 KB

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