OCNetworking.m 162 KB

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