OCNetworking.m 152 KB

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