OCNetworking.m 159 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021
  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 ===== Favorite =====
  925. #pragma --------------------------------------------------------------------------------------------
  926. - (void)listingFavoritesWithAccount:(NSString *)account completion:(void(^)(NSString *account, NSArray *metadatas, 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. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  937. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:tableAccount.url];
  938. NSString *url = tableAccount.url;
  939. NSString *userID = tableAccount.userID;
  940. NSString *path = [url stringByAppendingString:k_dav];
  941. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  942. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  943. [communication setUserAgent:[CCUtility getUserAgent]];
  944. [communication listingFavorites:path folder:@"" withUserSessionToken:nil onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer, NSString *token) {
  945. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  946. NSMutableArray *metadatas = [NSMutableArray new];
  947. BOOL showHiddenFiles = [CCUtility getShowHiddenFiles];
  948. // Order by fileNamePath
  949. NSArray *itemsSortedArray = [items sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
  950. OCFileDto *record1 = obj1, *record2 = obj2;
  951. NSString *path1 = [[record1.filePath stringByAppendingString:record1.fileName] lowercaseString];
  952. NSString *path2 = [[record2.filePath stringByAppendingString:record2.fileName] lowercaseString];
  953. return [path1 compare:path2];
  954. }];
  955. for(OCFileDto *itemDto in itemsSortedArray) {
  956. NSString *serverUrl;
  957. BOOL isFolderEncrypted;
  958. NSString *fileName = [itemDto.fileName stringByReplacingOccurrencesOfString:@"/" withString:@""];
  959. // Skip hidden files
  960. if (fileName.length > 0) {
  961. if (!showHiddenFiles && [[fileName substringToIndex:1] isEqualToString:@"."])
  962. continue;
  963. } else
  964. continue;
  965. NSRange firstInstance = [itemDto.filePath rangeOfString:[NSString stringWithFormat:@"%@/files/%@", k_dav, userID]];
  966. NSString *serverPath = [itemDto.filePath substringFromIndex:firstInstance.length+firstInstance.location+1];
  967. if ([serverPath hasSuffix:@"/"])
  968. serverPath = [serverPath substringToIndex:[serverPath length] - 1];
  969. serverUrl = [CCUtility stringAppendServerUrl:[url stringByAppendingString:k_webDAV] addFileName:serverPath];
  970. if (itemDto.isDirectory) {
  971. (void)[[NCManageDatabase sharedInstance] addDirectoryWithEncrypted:itemDto.isEncrypted favorite:itemDto.isFavorite ocId:itemDto.ocId permissions:itemDto.permissions serverUrl:[NSString stringWithFormat:@"%@/%@", serverUrl, fileName] richWorkspace:nil account:account];
  972. }
  973. isFolderEncrypted = [CCUtility isFolderEncrypted:serverUrl account:account];
  974. [metadatas addObject:[CCUtility trasformedOCFileToCCMetadata:itemDto fileName:itemDto.fileName serverUrl:serverUrl autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory account:account isFolderEncrypted:isFolderEncrypted]];
  975. }
  976. dispatch_async(dispatch_get_main_queue(), ^{
  977. completion(account, metadatas, nil, 0);
  978. });
  979. });
  980. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) {
  981. NSString *message;
  982. NSInteger errorCode = response.statusCode;
  983. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  984. errorCode = error.code;
  985. // Error
  986. if (errorCode == 503)
  987. message = NSLocalizedString(@"_server_error_retry_", nil);
  988. else
  989. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  990. completion(account, nil, message, errorCode);
  991. }];
  992. }
  993. - (void)settingFavoriteWithAccount:(NSString *)account fileName:(NSString *)fileName favorite:(BOOL)favorite completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  994. {
  995. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  996. if (tableAccount == nil) {
  997. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  998. } else if ([CCUtility getPassword:account].length == 0) {
  999. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1000. } else if ([CCUtility getCertificateError:account]) {
  1001. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1002. }
  1003. NSString *server = [tableAccount.url stringByAppendingString:k_dav];
  1004. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1005. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1006. [communication setUserAgent:[CCUtility getUserAgent]];
  1007. [communication settingFavoriteServer:server andFileOrFolderPath:fileName favorite:favorite withUserSessionToken:nil onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer, NSString *token) {
  1008. completion(account, nil, 0);
  1009. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) {
  1010. NSString *message;
  1011. NSInteger errorCode = response.statusCode;
  1012. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1013. errorCode = error.code;
  1014. // Server Unauthorized
  1015. if (errorCode == kOCErrorServerUnauthorized || errorCode == kOCErrorServerForbidden) {
  1016. [[OCNetworking sharedManager] checkRemoteUser:account function:@"setting favorite" errorCode:errorCode];
  1017. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  1018. [CCUtility setCertificateError:account error:YES];
  1019. }
  1020. // Error
  1021. if (errorCode == 503)
  1022. message = NSLocalizedString(@"_server_error_retry_", nil);
  1023. else
  1024. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1025. completion(account, message, errorCode);
  1026. }];
  1027. }
  1028. #pragma --------------------------------------------------------------------------------------------
  1029. #pragma mark ===== Share =====
  1030. #pragma --------------------------------------------------------------------------------------------
  1031. - (void)readShareWithAccount:(NSString *)account completion:(void (^)(NSString *account, NSArray *items, NSString *message, NSInteger errorCode))completion
  1032. {
  1033. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1034. if (tableAccount == nil) {
  1035. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1036. } else if ([CCUtility getPassword:account].length == 0) {
  1037. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1038. } else if ([CCUtility getCertificateError:account]) {
  1039. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1040. }
  1041. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1042. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1043. [communication setUserAgent:[CCUtility getUserAgent]];
  1044. [communication readSharedByServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  1045. completion(account, items, nil, 0);
  1046. } failureRequest :^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1047. NSString *message;
  1048. NSInteger errorCode = response.statusCode;
  1049. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1050. errorCode = error.code;
  1051. // Error
  1052. if (errorCode == 503) {
  1053. message = NSLocalizedString(@"_server_error_retry_", nil);
  1054. } else {
  1055. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1056. }
  1057. completion(account, nil, message, errorCode);
  1058. }];
  1059. }
  1060. - (void)readShareWithAccount:(NSString *)account path:(NSString *)path completion:(void (^)(NSString *account, NSArray *items, NSString *message, NSInteger errorCode))completion
  1061. {
  1062. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1063. if (tableAccount == nil) {
  1064. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1065. } else if ([CCUtility getPassword:account].length == 0) {
  1066. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1067. } else if ([CCUtility getCertificateError:account]) {
  1068. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1069. }
  1070. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1071. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1072. [communication setUserAgent:[CCUtility getUserAgent]];
  1073. [communication readSharedByServer:[tableAccount.url stringByAppendingString:@"/"] andPath:path onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfShared, NSString *redirectedServer) {
  1074. completion(account, listOfShared, nil, 0);
  1075. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1076. NSString *message;
  1077. NSInteger errorCode = response.statusCode;
  1078. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1079. errorCode = error.code;
  1080. // Error
  1081. if (errorCode == 503) {
  1082. message = NSLocalizedString(@"_server_error_retry_", nil);
  1083. } else {
  1084. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1085. }
  1086. completion(account, nil, message, errorCode);
  1087. }];
  1088. }
  1089. - (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
  1090. {
  1091. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1092. if (tableAccount == nil) {
  1093. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1094. } else if ([CCUtility getPassword:account].length == 0) {
  1095. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1096. } else if ([CCUtility getCertificateError:account]) {
  1097. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1098. }
  1099. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1100. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1101. [communication setUserAgent:[CCUtility getUserAgent]];
  1102. [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) {
  1103. completion(account, nil, 0);
  1104. } failureRequest :^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1105. NSString *message;
  1106. NSInteger errorCode = response.statusCode;
  1107. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1108. errorCode = error.code;
  1109. // Error
  1110. if (errorCode == 503) {
  1111. message = NSLocalizedString(@"_server_error_retry_", nil);
  1112. } else {
  1113. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1114. }
  1115. completion(account, message, errorCode);
  1116. }];
  1117. }
  1118. // * @param shareeType -> NSInteger: to set the type of sharee (user/group/federated)
  1119. - (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
  1120. {
  1121. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1122. if (tableAccount == nil) {
  1123. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1124. } else if ([CCUtility getPassword:account].length == 0) {
  1125. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1126. } else if ([CCUtility getCertificateError:account]) {
  1127. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1128. }
  1129. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1130. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1131. [communication setUserAgent:[CCUtility getUserAgent]];
  1132. [communication shareWith:userOrGroup shareeType:shareeType inServer:[tableAccount.url stringByAppendingString:@"/"] andFileOrFolderPath:[fileName encodeString:NSUTF8StringEncoding] andPermissions:permission onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1133. completion(account, nil, 0);
  1134. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1135. NSString *message;
  1136. NSInteger errorCode = response.statusCode;
  1137. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1138. errorCode = error.code;
  1139. // Error
  1140. if (errorCode == 503) {
  1141. message = NSLocalizedString(@"_server_error_retry_", nil);
  1142. } else {
  1143. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1144. }
  1145. completion(account, message, errorCode);
  1146. }];
  1147. }
  1148. - (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
  1149. {
  1150. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1151. if (tableAccount == nil) {
  1152. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1153. } else if ([CCUtility getPassword:account].length == 0) {
  1154. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1155. } else if ([CCUtility getCertificateError:account]) {
  1156. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1157. }
  1158. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1159. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1160. [communication setUserAgent:[CCUtility getUserAgent]];
  1161. [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) {
  1162. completion(account, nil, 0);
  1163. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1164. NSString *message;
  1165. NSInteger errorCode = response.statusCode;
  1166. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1167. errorCode = error.code;
  1168. // Error
  1169. if (errorCode == 503) {
  1170. message = NSLocalizedString(@"_server_error_retry_", nil);
  1171. } else {
  1172. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1173. }
  1174. completion(account, message, errorCode);
  1175. }];
  1176. }
  1177. - (void)unshareAccount:(NSString *)account shareID:(NSInteger)shareID completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  1178. {
  1179. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1180. if (tableAccount == nil) {
  1181. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1182. } else if ([CCUtility getPassword:account].length == 0) {
  1183. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1184. } else if ([CCUtility getCertificateError:account]) {
  1185. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1186. }
  1187. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1188. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1189. [communication setUserAgent:[CCUtility getUserAgent]];
  1190. [communication unShareFileOrFolderByServer:[tableAccount.url stringByAppendingString:@"/"] andIdRemoteShared:shareID onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1191. completion(account, nil, 0);
  1192. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1193. NSString *message;
  1194. NSInteger errorCode = response.statusCode;
  1195. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1196. errorCode = error.code;
  1197. // Error
  1198. if (errorCode == 503) {
  1199. message = NSLocalizedString(@"_server_error_retry_", nil);
  1200. } else {
  1201. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1202. }
  1203. completion(account, message, errorCode);
  1204. }];
  1205. }
  1206. - (void)getUserGroupWithAccount:(NSString *)account searchString:(NSString *)searchString completion:(void (^)(NSString *account, NSArray *item, NSString *message, NSInteger errorCode))completion
  1207. {
  1208. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1209. if (tableAccount == nil) {
  1210. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1211. } else if ([CCUtility getPassword:account].length == 0) {
  1212. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1213. } else if ([CCUtility getCertificateError:account]) {
  1214. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1215. }
  1216. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1217. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1218. [communication setUserAgent:[CCUtility getUserAgent]];
  1219. [communication searchUsersAndGroupsWith:searchString forPage:1 with:50 ofServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *itemList, NSString *redirectedServer) {
  1220. completion(account, itemList, nil, 0);
  1221. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1222. NSString *message;
  1223. NSInteger errorCode = response.statusCode;
  1224. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1225. errorCode = error.code;
  1226. // Error
  1227. if (errorCode == 503) {
  1228. message = NSLocalizedString(@"_server_error_retry_", nil);
  1229. } else {
  1230. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1231. }
  1232. completion(account, nil, message, errorCode);
  1233. }];
  1234. }
  1235. #pragma --------------------------------------------------------------------------------------------
  1236. #pragma mark ===== VAR =====
  1237. #pragma --------------------------------------------------------------------------------------------
  1238. - (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
  1239. {
  1240. BOOL previews = false;
  1241. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1242. if (tableAccount == nil) {
  1243. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1244. } else if ([CCUtility getPassword:account].length == 0) {
  1245. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1246. } else if ([CCUtility getCertificateError:account]) {
  1247. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1248. }
  1249. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilitesWithAccount:account];
  1250. if (capabilities != nil && capabilities.versionMajor >= k_nextcloud_version_15_0) {
  1251. previews = true;
  1252. }
  1253. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1254. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1255. [communication setUserAgent:[CCUtility getUserAgent]];
  1256. [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) {
  1257. completion(account, listOfActivity, nil, 0);
  1258. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1259. NSString *message;
  1260. NSInteger errorCode = response.statusCode;
  1261. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1262. errorCode = error.code;
  1263. // Server Unauthorized
  1264. if (errorCode == kOCErrorServerUnauthorized || errorCode == kOCErrorServerForbidden) {
  1265. [[OCNetworking sharedManager] checkRemoteUser:account function:@"get activity" errorCode:errorCode];
  1266. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  1267. [CCUtility setCertificateError:account error:YES];
  1268. }
  1269. // Error
  1270. if (errorCode == 503)
  1271. message = NSLocalizedString(@"_server_error_retry_", nil);
  1272. else
  1273. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1274. completion(account, nil, message, errorCode);
  1275. }];
  1276. }
  1277. - (void)getExternalSitesWithAccount:(NSString *)account completion:(void (^)(NSString *account, NSArray *listOfExternalSites, 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 getExternalSitesServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfExternalSites, NSString *redirectedServer) {
  1291. completion(account, listOfExternalSites, 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 external sites" 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)getNotificationWithAccount:(NSString *)account completion:(void (^)(NSString *account, NSArray *listOfNotifications, 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 getNotificationServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfNotifications, NSString *redirectedServer) {
  1326. completion(account, listOfNotifications, 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 notification" 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. - (void)setNotificationWithAccount:(NSString *)account serverUrl:(NSString *)serverUrl type:(NSString *)type completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  1348. {
  1349. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1350. if (tableAccount == nil) {
  1351. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1352. } else if ([CCUtility getPassword:account].length == 0) {
  1353. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1354. } else if ([CCUtility getCertificateError:account]) {
  1355. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1356. }
  1357. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1358. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1359. [communication setUserAgent:[CCUtility getUserAgent]];
  1360. [communication setNotificationServer:serverUrl type:type onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1361. completion(account, nil, 0);
  1362. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1363. NSString *message;
  1364. NSInteger errorCode = response.statusCode;
  1365. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1366. errorCode = error.code;
  1367. // Server Unauthorized
  1368. if (errorCode == kOCErrorServerUnauthorized || errorCode == kOCErrorServerForbidden) {
  1369. [[OCNetworking sharedManager] checkRemoteUser:account function:@"set notification" errorCode:errorCode];
  1370. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  1371. [CCUtility setCertificateError:account error:YES];
  1372. }
  1373. // Error
  1374. if (errorCode == 503) {
  1375. message = NSLocalizedString(@"_server_error_retry_", nil);
  1376. } else {
  1377. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1378. }
  1379. completion(account, message, errorCode);
  1380. }];
  1381. }
  1382. - (void)getCapabilitiesWithAccount:(NSString *)account completion:(void (^)(NSString *account, OCCapabilities *capabilities, NSString *message, NSInteger errorCode))completion
  1383. {
  1384. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1385. if (tableAccount == nil) {
  1386. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1387. } else if ([CCUtility getPassword:account].length == 0) {
  1388. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1389. } else if ([CCUtility getCertificateError:account]) {
  1390. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1391. }
  1392. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1393. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1394. [communication setUserAgent:[CCUtility getUserAgent]];
  1395. [communication getCapabilitiesOfServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, OCCapabilities *capabilities, NSString *redirectedServer) {
  1396. completion(account, capabilities, nil, 0);
  1397. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1398. NSString *message;
  1399. NSInteger errorCode = response.statusCode;
  1400. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1401. errorCode = error.code;
  1402. // Server Unauthorized
  1403. if (errorCode == kOCErrorServerUnauthorized || errorCode == kOCErrorServerForbidden) {
  1404. [[OCNetworking sharedManager] checkRemoteUser:account function:@"get capabilities" errorCode:errorCode];
  1405. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  1406. [CCUtility setCertificateError:account error:YES];
  1407. }
  1408. // Error
  1409. if (errorCode == 503) {
  1410. message = NSLocalizedString(@"_server_error_retry_", nil);
  1411. } else {
  1412. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1413. }
  1414. completion(account, nil, message, errorCode);
  1415. }];
  1416. }
  1417. - (void)getUserProfileWithAccount:(NSString *)account completion:(void (^)(NSString *account, OCUserProfile *userProfile, NSString *message, NSInteger errorCode))completion
  1418. {
  1419. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1420. if (tableAccount == nil) {
  1421. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1422. } else if ([CCUtility getPassword:account].length == 0) {
  1423. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1424. } else if ([CCUtility getCertificateError:account]) {
  1425. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1426. }
  1427. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1428. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1429. [communication setUserAgent:[CCUtility getUserAgent]];
  1430. [communication getUserProfileServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, OCUserProfile *userProfile, NSString *redirectedServer) {
  1431. completion(account, userProfile, nil, 0);
  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. // Server Unauthorized
  1438. if (errorCode == kOCErrorServerUnauthorized || errorCode == kOCErrorServerForbidden) {
  1439. [[OCNetworking sharedManager] checkRemoteUser:account function:@"get user profile" errorCode:errorCode];
  1440. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  1441. [CCUtility setCertificateError:account error:YES];
  1442. }
  1443. // Error
  1444. if (errorCode == 503) {
  1445. message = NSLocalizedString(@"_server_error_retry_", nil);
  1446. } else {
  1447. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1448. }
  1449. completion(account, nil, message, errorCode);
  1450. }];
  1451. }
  1452. #pragma --------------------------------------------------------------------------------------------
  1453. #pragma mark ===== Push Notification =====
  1454. #pragma --------------------------------------------------------------------------------------------
  1455. - (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
  1456. {
  1457. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1458. if (tableAccount == nil) {
  1459. completion(account, nil, nil, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1460. } else if ([CCUtility getPassword:account].length == 0) {
  1461. completion(account, nil, nil, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1462. } else if ([CCUtility getCertificateError:account]) {
  1463. completion(account, nil, nil, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1464. }
  1465. devicePublicKey = [CCUtility URLEncodeStringFromString:devicePublicKey];
  1466. NSString *proxyServerPath = [NCBrandOptions sharedInstance].pushNotificationServerProxy;
  1467. NSString *proxyServer = [NCBrandOptions sharedInstance].pushNotificationServerProxy;
  1468. #ifdef DEBUG
  1469. // proxyServerPath = @"http://127.0.0.1:8088";
  1470. // proxyServer = @"https://10.132.0.37:8443/pushnotifications";
  1471. #endif
  1472. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1473. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1474. [communication setUserAgent:[CCUtility getUserAgent]];
  1475. [communication subscribingNextcloudServerPush:url pushTokenHash:pushTokenHash devicePublicKey:devicePublicKey proxyServerPath: proxyServerPath onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *publicKey, NSString *deviceIdentifier, NSString *signature, NSString *redirectedServer) {
  1476. deviceIdentifier = [CCUtility URLEncodeStringFromString:deviceIdentifier];
  1477. signature = [CCUtility URLEncodeStringFromString:signature];
  1478. publicKey = [CCUtility URLEncodeStringFromString:publicKey];
  1479. [communication subscribingPushProxy:proxyServer pushToken:pushToken deviceIdentifier:deviceIdentifier deviceIdentifierSignature:signature publicKey:publicKey onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1480. completion(account, deviceIdentifier, signature, publicKey, nil, 0);
  1481. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1482. NSString *message;
  1483. NSInteger errorCode = response.statusCode;
  1484. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1485. errorCode = error.code;
  1486. // Error
  1487. if (errorCode == 503)
  1488. message = NSLocalizedString(@"_server_error_retry_", nil);
  1489. else
  1490. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1491. completion(account, nil, nil, nil, message, errorCode);
  1492. }];
  1493. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1494. NSString *message;
  1495. NSInteger errorCode = response.statusCode;
  1496. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1497. errorCode = error.code;
  1498. // Error
  1499. if (errorCode == 503)
  1500. message = NSLocalizedString(@"_server_error_retry_", nil);
  1501. else
  1502. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1503. completion(account, nil, nil, nil, message, errorCode);
  1504. }];
  1505. }
  1506. - (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 {
  1507. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1508. if (tableAccount == nil) {
  1509. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1510. } else if ([CCUtility getPassword:account].length == 0) {
  1511. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1512. } else if ([CCUtility getCertificateError:account]) {
  1513. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1514. }
  1515. NSString *proxyServer = [NCBrandOptions sharedInstance].pushNotificationServerProxy;
  1516. #ifdef DEBUG
  1517. // proxyServer = @"https://10.132.0.37:8443/pushnotifications";
  1518. #endif
  1519. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1520. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1521. [communication setUserAgent:[CCUtility getUserAgent]];
  1522. [communication unsubscribingNextcloudServerPush:url onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1523. [communication unsubscribingPushProxy:proxyServer deviceIdentifier:deviceIdentifier deviceIdentifierSignature:deviceIdentifierSignature publicKey:publicKey onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1524. completion(account, nil, 0);
  1525. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1526. NSString *message;
  1527. NSInteger errorCode = response.statusCode;
  1528. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1529. errorCode = error.code;
  1530. // Error
  1531. if (errorCode == 503)
  1532. message = NSLocalizedString(@"_server_error_retry_", nil);
  1533. else
  1534. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1535. completion(account, message, errorCode);
  1536. }];
  1537. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1538. NSString *message;
  1539. NSInteger errorCode = response.statusCode;
  1540. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1541. errorCode = error.code;
  1542. // Error
  1543. if (errorCode == 503)
  1544. message = NSLocalizedString(@"_server_error_retry_", nil);
  1545. else
  1546. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1547. completion(account, message, errorCode);
  1548. }];
  1549. }
  1550. - (void)getServerNotification:(NSString *)serverUrl notificationId:(NSInteger)notificationId completion:(void(^)(NSDictionary*jsongParsed, NSString *message, NSInteger errorCode))completion
  1551. {
  1552. NSString *URLString = [NSString stringWithFormat:@"%@/ocs/v2.php/apps/notifications/api/v2/notifications/%ld?format=json", serverUrl, (long)notificationId];
  1553. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URLString] cachePolicy:0 timeoutInterval:20.0];
  1554. [request addValue:[CCUtility getUserAgent] forHTTPHeaderField:@"User-Agent"];
  1555. [request addValue:@"true" forHTTPHeaderField:@"OCS-APIRequest"];
  1556. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  1557. NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  1558. NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler: ^(NSData *data, NSURLResponse *response, NSError *error) {
  1559. if (error) {
  1560. NSString *message;
  1561. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
  1562. NSInteger errorCode = httpResponse.statusCode;
  1563. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1564. errorCode = error.code;
  1565. // Error
  1566. if (errorCode == 503)
  1567. message = NSLocalizedString(@"_server_error_retry_", nil);
  1568. else
  1569. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1570. completion(nil, message, errorCode);
  1571. } else {
  1572. NSDictionary *jsongParsed = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
  1573. completion(jsongParsed, nil, 0);
  1574. }
  1575. }];
  1576. [task resume];
  1577. }
  1578. - (void)deletingServerNotification:(NSString *)serverUrl notificationId:(NSInteger)notificationId completion:(void(^)(NSString *message, NSInteger errorCode))completion
  1579. {
  1580. // NSData *authData = [[NSString stringWithFormat:@"%@:%@", tableAccount.user, [CCUtility getPassword:tableAccount.account]] dataUsingEncoding:NSUTF8StringEncoding];
  1581. // NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];
  1582. // Delete
  1583. NSString *URLString = [NSString stringWithFormat:@"%@/ocs/v2.php/apps/notifications/api/v2/notifications/%ld", serverUrl, (long)notificationId];
  1584. // Delete-all
  1585. if (notificationId == 0) {
  1586. URLString = [NSString stringWithFormat:@"%@/ocs/v2.php/apps/notifications/api/v2/notifications", serverUrl];
  1587. }
  1588. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URLString] cachePolicy:0 timeoutInterval:20.0];
  1589. // [request setValue:authValue forHTTPHeaderField:@"Authorization"];
  1590. [request addValue:[CCUtility getUserAgent] forHTTPHeaderField:@"User-Agent"];
  1591. [request addValue:@"true" forHTTPHeaderField:@"OCS-APIRequest"];
  1592. [request setHTTPMethod: @"DELETE"];
  1593. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  1594. NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  1595. NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler: ^(NSData *data, NSURLResponse *response, NSError *error) {
  1596. if (error) {
  1597. NSString *message;
  1598. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
  1599. NSInteger errorCode = httpResponse.statusCode;
  1600. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1601. errorCode = error.code;
  1602. // Error
  1603. if (errorCode == 503)
  1604. message = NSLocalizedString(@"_server_error_retry_", nil);
  1605. else
  1606. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1607. completion(message, errorCode);
  1608. } else {
  1609. completion(nil, 0);
  1610. }
  1611. }];
  1612. [task resume];
  1613. }
  1614. #pragma --------------------------------------------------------------------------------------------
  1615. #pragma mark ===== Manage Mobile Editor OCS API =====
  1616. #pragma --------------------------------------------------------------------------------------------
  1617. - (void)createLinkRichdocumentsWithAccount:(NSString *)account fileId:(NSString *)fileId completion:(void(^)(NSString *account, NSString *link, NSString *message, NSInteger errorCode))completion
  1618. {
  1619. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1620. if (tableAccount == nil) {
  1621. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1622. } else if ([CCUtility getPassword:account].length == 0) {
  1623. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1624. } else if ([CCUtility getCertificateError:account]) {
  1625. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1626. }
  1627. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1628. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1629. [communication setUserAgent:[CCUtility getUserAgent]];
  1630. [communication createLinkRichdocuments:[tableAccount.url stringByAppendingString:@"/"] fileId:fileId onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *link, NSString *redirectedServer) {
  1631. completion(account, link, nil, 0);
  1632. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1633. NSString *message;
  1634. NSInteger errorCode = response.statusCode;
  1635. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1636. errorCode = error.code;
  1637. // Error
  1638. if (errorCode == 503)
  1639. message = NSLocalizedString(@"_server_error_retry_", nil);
  1640. else
  1641. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1642. completion(account, nil,message, errorCode);
  1643. }];
  1644. }
  1645. - (void)getTemplatesRichdocumentsWithAccount:(NSString *)account typeTemplate:(NSString *)typeTemplate completion:(void(^)(NSString *account, NSArray *listOfTemplate, NSString *message, NSInteger errorCode))completion
  1646. {
  1647. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1648. if (tableAccount == nil) {
  1649. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1650. } else if ([CCUtility getPassword:account].length == 0) {
  1651. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1652. } else if ([CCUtility getCertificateError:account]) {
  1653. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1654. }
  1655. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1656. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1657. [communication setUserAgent:[CCUtility getUserAgent]];
  1658. [communication getTemplatesRichdocuments:[tableAccount.url stringByAppendingString:@"/"] typeTemplate:typeTemplate onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfTemplate, NSString *redirectedServer) {
  1659. completion(account, listOfTemplate, nil, 0);
  1660. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1661. NSString *message;
  1662. NSInteger errorCode = response.statusCode;
  1663. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1664. errorCode = error.code;
  1665. // Error
  1666. if (errorCode == 503)
  1667. message = NSLocalizedString(@"_server_error_retry_", nil);
  1668. else
  1669. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1670. completion(account, nil, message, errorCode);
  1671. }];
  1672. }
  1673. - (void)createNewRichdocumentsWithAccount:(NSString *)account fileName:(NSString *)fileName serverUrl:(NSString *)serverUrl templateID:(NSString *)templateID completion:(void(^)(NSString *account, NSString *url, NSString *message, NSInteger errorCode))completion
  1674. {
  1675. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1676. if (tableAccount == nil) {
  1677. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1678. } else if ([CCUtility getPassword:account].length == 0) {
  1679. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1680. } else if ([CCUtility getCertificateError:account]) {
  1681. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1682. }
  1683. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1684. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1685. [communication setUserAgent:[CCUtility getUserAgent]];
  1686. [communication createNewRichdocuments:[tableAccount.url stringByAppendingString:@"/"] path:fileName templateID:templateID onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *url, NSString *redirectedServer) {
  1687. completion(account, url, nil, 0);
  1688. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1689. NSString *message;
  1690. NSInteger errorCode = response.statusCode;
  1691. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1692. errorCode = error.code;
  1693. // Error
  1694. if (errorCode == 503)
  1695. message = NSLocalizedString(@"_server_error_retry_", nil);
  1696. else
  1697. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1698. completion(account, nil, message, errorCode);
  1699. }];
  1700. }
  1701. - (void)createAssetRichdocumentsWithAccount:(NSString *)account fileName:(NSString *)fileName serverUrl:(NSString *)serverUrl completion:(void(^)(NSString *account, NSString *link, NSString *message, NSInteger errorCode))completion
  1702. {
  1703. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1704. if (tableAccount == nil) {
  1705. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1706. } else if ([CCUtility getPassword:account].length == 0) {
  1707. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1708. } else if ([CCUtility getCertificateError:account]) {
  1709. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1710. }
  1711. NSString *fileNamePath = [CCUtility returnFileNamePathFromFileName:fileName serverUrl:serverUrl activeUrl:tableAccount.url];
  1712. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1713. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1714. [communication setUserAgent:[CCUtility getUserAgent]];
  1715. [communication createAssetRichdocuments:[tableAccount.url stringByAppendingString:@"/"] path:fileNamePath onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *url, NSString *redirectedServer) {
  1716. completion(account, url, nil, 0);
  1717. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1718. NSString *message;
  1719. NSInteger errorCode = response.statusCode;
  1720. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1721. errorCode = error.code;
  1722. // Error
  1723. if (errorCode == 503)
  1724. message = NSLocalizedString(@"_server_error_retry_", nil);
  1725. else
  1726. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1727. completion(account, nil, message, errorCode);
  1728. }];
  1729. }
  1730. #pragma --------------------------------------------------------------------------------------------
  1731. #pragma mark ===== Full Text Search =====
  1732. #pragma --------------------------------------------------------------------------------------------
  1733. - (void)fullTextSearchWithAccount:(NSString *)account text:(NSString *)text page:(NSInteger)page completion:(void(^)(NSString *account, NSArray *items, NSString *message, NSInteger errorCode))completion
  1734. {
  1735. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1736. if (tableAccount == nil) {
  1737. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1738. } else if ([CCUtility getPassword:account].length == 0) {
  1739. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1740. } else if ([CCUtility getCertificateError:account]) {
  1741. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1742. }
  1743. // Create JSON
  1744. NSMutableDictionary *dataDic = [NSMutableDictionary new];
  1745. [dataDic setValue:@"files" forKey:@"providers"];
  1746. [dataDic setValue:text forKey:@"search"];
  1747. [dataDic setValue:[NSNumber numberWithInteger:page] forKey:@"page"];
  1748. [dataDic setValue:[NSNumber numberWithInt:20] forKey:@"size"];
  1749. NSMutableDictionary *options = [NSMutableDictionary new];
  1750. [options setValue:@"" forKey:@"files_within_dir"];
  1751. [options setValue:@"" forKey:@"files_local"];
  1752. [options setValue:@"" forKey:@"files_extension"];
  1753. [dataDic setValue:options forKey:@"options"];
  1754. NSString *data = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:dataDic options:0 error:nil] encoding:NSUTF8StringEncoding];
  1755. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1756. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1757. [communication setUserAgent:[CCUtility getUserAgent]];
  1758. [communication fullTextSearch:[tableAccount.url stringByAppendingString:@"/"] data:data onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  1759. completion(account, items, nil, 0);
  1760. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1761. NSString *message;
  1762. NSInteger errorCode = response.statusCode;
  1763. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1764. errorCode = error.code;
  1765. // Error
  1766. if (errorCode == 503)
  1767. message = NSLocalizedString(@"_server_error_retry_", nil);
  1768. else
  1769. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1770. completion(account, nil, message, errorCode);
  1771. }];
  1772. }
  1773. #pragma --------------------------------------------------------------------------------------------
  1774. #pragma mark ===== Check remote user =====
  1775. #pragma --------------------------------------------------------------------------------------------
  1776. - (void)checkRemoteUser:(NSString *)account function:(NSString *)function errorCode:(NSInteger)errorCode
  1777. {
  1778. #ifndef EXTENSION
  1779. @synchronized(self) {
  1780. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  1781. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilitesWithAccount:account];
  1782. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1783. NSString *token = [CCUtility getPassword:account];
  1784. if (self.checkRemoteUserInProgress || tableAccount == nil || token == nil) {
  1785. return;
  1786. } else {
  1787. self.checkRemoteUserInProgress = true;
  1788. }
  1789. if (capabilities != nil && capabilities.versionMajor >= k_nextcloud_version_17_0) {
  1790. [[OCNetworking sharedManager] getRemoteWipeStatusWithAccount:account token:token completion:^(NSString *account, BOOL wipe, NSString *message, NSInteger errorCode) {
  1791. if (wipe) {
  1792. [appDelegate deleteAccount:account wipe:true];
  1793. [[NCContentPresenter shared] messageNotification:tableAccount.user description:@"_wipe_account_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  1794. [[OCNetworking sharedManager] setRemoteWipeCompletitionWithUser:tableAccount.user userID:tableAccount.userID url:tableAccount.url token:token completion:^(NSString *message, NSInteger errorCode) {
  1795. NSLog(@"Wiped");
  1796. }];
  1797. } else {
  1798. if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive && [appDelegate.reachability isReachable]) {
  1799. [[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];
  1800. [CCUtility setPassword:account password:nil];
  1801. }
  1802. }
  1803. self.checkRemoteUserInProgress = false;
  1804. }];
  1805. } else if ([CCUtility getPassword:account] != nil) {
  1806. if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive && [appDelegate.reachability isReachable]) {
  1807. [[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];
  1808. [CCUtility setPassword:account password:nil];
  1809. }
  1810. }
  1811. }
  1812. #endif
  1813. }
  1814. - (void)getRemoteWipeStatusWithAccount:(NSString *)account token:(NSString *)token completion:(void(^)(NSString *account, BOOL wipe, NSString *message, NSInteger errorCode))completion
  1815. {
  1816. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1817. if (tableAccount == nil) {
  1818. completion(account, false, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1819. } else if ([CCUtility getPassword:account].length == 0) {
  1820. completion(account, false, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1821. } else if ([CCUtility getCertificateError:account]) {
  1822. completion(account, false, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1823. }
  1824. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1825. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1826. [communication setUserAgent:[CCUtility getUserAgent]];
  1827. [communication getRemoteWipeStatus:tableAccount.url token:token onCommunication:communication successRequest:^(NSHTTPURLResponse *response, BOOL wipe, NSString *redirectedServer) {
  1828. completion(account, wipe, nil, 0);
  1829. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1830. NSString *message;
  1831. NSInteger errorCode = response.statusCode;
  1832. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1833. errorCode = error.code;
  1834. // Server Unauthorized
  1835. if (errorCode == kOCErrorServerUnauthorized || errorCode == kOCErrorServerForbidden) {
  1836. [[OCNetworking sharedManager] checkRemoteUser:account function:@"get remote wipe status" errorCode:errorCode];
  1837. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  1838. [CCUtility setCertificateError:account error:YES];
  1839. }
  1840. // Error
  1841. if (errorCode == 503)
  1842. message = NSLocalizedString(@"_server_error_retry_", nil);
  1843. else
  1844. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1845. completion(account, false, message, errorCode);
  1846. }];
  1847. }
  1848. - (void)setRemoteWipeCompletitionWithUser:(NSString *)user userID:(NSString *)userID url:(NSString *)url token:(NSString *)token completion:(void(^)(NSString *message, NSInteger errorCode))completion
  1849. {
  1850. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1851. [communication setCredentialsWithUser:user andUserID:userID andPassword:token];
  1852. [communication setUserAgent:[CCUtility getUserAgent]];
  1853. [communication setRemoteWipeCompletition:url token:token onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1854. completion(nil, 0);
  1855. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1856. NSString *message;
  1857. NSInteger errorCode = response.statusCode;
  1858. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1859. errorCode = error.code;
  1860. // Error
  1861. if (errorCode == 503)
  1862. message = NSLocalizedString(@"_server_error_retry_", nil);
  1863. else
  1864. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1865. completion(message, errorCode);
  1866. }];
  1867. }
  1868. #pragma --------------------------------------------------------------------------------------------
  1869. #pragma mark ===== Trash =====
  1870. #pragma --------------------------------------------------------------------------------------------
  1871. - (void)listingTrashWithAccount:(NSString *)account path:(NSString *)path serverUrl:(NSString *)serverUrl depth:(NSString *)depth completion:(void (^)(NSString *account, NSArray *items, NSString *message, NSInteger errorCode))completion
  1872. {
  1873. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1874. if (tableAccount == nil) {
  1875. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1876. } else if ([CCUtility getPassword:account].length == 0) {
  1877. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1878. } else if ([CCUtility getCertificateError:account]) {
  1879. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1880. }
  1881. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1882. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1883. [communication setUserAgent:[CCUtility getUserAgent]];
  1884. [communication listingTrash:[serverUrl stringByAppendingString:path] depth:depth onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  1885. // Check items > 0
  1886. if ([items count] == 0) {
  1887. [[NCContentPresenter shared] messageNotification:@"Server error" description:@"Read Folder WebDAV : [items NULL] please fix" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  1888. completion(account, nil, NSLocalizedString(@"Read Folder WebDAV : [items NULL] please fix", nil), k_CCErrorInternalError);
  1889. } else {
  1890. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1891. NSMutableArray *listTrash = [NSMutableArray new];
  1892. //OCFileDto *itemDtoFolder = [items objectAtIndex:0];
  1893. if ([items count] > 1) {
  1894. for (NSUInteger i=1; i < [items count]; i++) {
  1895. OCFileDto *itemDto = [items objectAtIndex:i];
  1896. tableTrash *trash = [tableTrash new];
  1897. trash.account = account;
  1898. trash.date = [NSDate dateWithTimeIntervalSince1970:itemDto.date];
  1899. trash.directory = itemDto.isDirectory;
  1900. trash.fileId = itemDto.fileId;
  1901. trash.fileName = itemDto.fileName;
  1902. NSArray *array = [itemDto.filePath componentsSeparatedByString:path];
  1903. long len = [[array objectAtIndex:0] length];
  1904. trash.filePath = [itemDto.filePath substringFromIndex:len];
  1905. trash.hasPreview = itemDto.hasPreview;
  1906. trash.size = itemDto.size;
  1907. trash.trashbinFileName = itemDto.trashbinFileName;
  1908. trash.trashbinOriginalLocation = itemDto.trashbinOriginalLocation;
  1909. trash.trashbinDeletionTime = [NSDate dateWithTimeIntervalSince1970:itemDto.trashbinDeletionTime];
  1910. [CCUtility insertTypeFileIconName:trash.trashbinFileName metadata:(tableMetadata *)trash];
  1911. [listTrash addObject:trash];
  1912. }
  1913. }
  1914. dispatch_async(dispatch_get_main_queue(), ^{
  1915. completion(account, listTrash, nil, 0);
  1916. });
  1917. });
  1918. }
  1919. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1920. NSString *message;
  1921. NSInteger errorCode = response.statusCode;
  1922. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1923. errorCode = error.code;
  1924. // Error
  1925. if (errorCode == 503)
  1926. message = NSLocalizedString(@"_server_error_retry_", nil);
  1927. else
  1928. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1929. completion(account, nil,message, errorCode);
  1930. }];
  1931. }
  1932. - (void)emptyTrashWithAccount:(NSString *)account completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  1933. {
  1934. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1935. if (tableAccount == nil) {
  1936. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1937. } else if ([CCUtility getPassword:account].length == 0) {
  1938. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1939. } else if ([CCUtility getCertificateError:account]) {
  1940. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1941. }
  1942. NSString *path = [NSString stringWithFormat:@"%@%@/trashbin/%@/trash", tableAccount.url, k_dav, tableAccount.userID];
  1943. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1944. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1945. [communication setUserAgent:[CCUtility getUserAgent]];
  1946. [communication emptyTrash:path onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1947. completion(account, nil, 0);
  1948. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1949. NSString *message;
  1950. NSInteger errorCode = response.statusCode;
  1951. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1952. errorCode = error.code;
  1953. // Error
  1954. if (errorCode == 503)
  1955. message = NSLocalizedString(@"_server_error_retry_", nil);
  1956. else
  1957. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1958. completion(account, message, errorCode);
  1959. }];
  1960. }
  1961. #pragma --------------------------------------------------------------------------------------------
  1962. #pragma mark ===== Comments =====
  1963. #pragma --------------------------------------------------------------------------------------------
  1964. - (void)getCommentsWithAccount:(NSString *)account fileId:(NSString *)fileId completion:(void (^)(NSString *account, NSArray *items, NSString *message, NSInteger errorCode))completion
  1965. {
  1966. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1967. if (tableAccount == nil) {
  1968. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1969. } else if ([CCUtility getPassword:account].length == 0) {
  1970. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1971. } else if ([CCUtility getCertificateError:account]) {
  1972. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  1973. }
  1974. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1975. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  1976. [communication setUserAgent:[CCUtility getUserAgent]];
  1977. [communication getComments:[NSString stringWithFormat:@"%@%@", tableAccount.url, k_dav] fileId:fileId onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *list, NSString *redirectedServer) {
  1978. completion(account, list, nil, 0);
  1979. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1980. NSString *message;
  1981. NSInteger errorCode = response.statusCode;
  1982. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1983. errorCode = error.code;
  1984. // Error
  1985. if (errorCode == 503)
  1986. message = NSLocalizedString(@"_server_error_retry_", nil);
  1987. else
  1988. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1989. completion(account, nil,message, errorCode);
  1990. }];
  1991. }
  1992. - (void)putCommentsWithAccount:(NSString *)account fileId:(NSString *)fileId message:(NSString *)message completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  1993. {
  1994. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1995. if (tableAccount == nil) {
  1996. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1997. } else if ([CCUtility getPassword:account].length == 0) {
  1998. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  1999. } else if ([CCUtility getCertificateError:account]) {
  2000. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  2001. }
  2002. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  2003. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  2004. [communication setUserAgent:[CCUtility getUserAgent]];
  2005. [communication putComments:[NSString stringWithFormat:@"%@%@", tableAccount.url, k_dav] fileId:fileId message:message onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  2006. completion(account, nil, 0);
  2007. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  2008. NSString *message;
  2009. NSInteger errorCode = response.statusCode;
  2010. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  2011. errorCode = error.code;
  2012. // Error
  2013. if (errorCode == 503)
  2014. message = NSLocalizedString(@"_server_error_retry_", nil);
  2015. else
  2016. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  2017. completion(account, message, errorCode);
  2018. }];
  2019. }
  2020. - (void)updateCommentsWithAccount:(NSString *)account fileId:(NSString *)fileId messageID:(NSString *)messageID message:(NSString *)message completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  2021. {
  2022. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  2023. if (tableAccount == nil) {
  2024. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  2025. } else if ([CCUtility getPassword:account].length == 0) {
  2026. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  2027. } else if ([CCUtility getCertificateError:account]) {
  2028. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  2029. }
  2030. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  2031. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  2032. [communication setUserAgent:[CCUtility getUserAgent]];
  2033. [communication updateComments:[NSString stringWithFormat:@"%@%@", tableAccount.url, k_dav] fileId:fileId messageID:messageID message:message onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  2034. completion(account, nil, 0);
  2035. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  2036. NSString *message;
  2037. NSInteger errorCode = response.statusCode;
  2038. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  2039. errorCode = error.code;
  2040. // Error
  2041. if (errorCode == 503)
  2042. message = NSLocalizedString(@"_server_error_retry_", nil);
  2043. else
  2044. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  2045. completion(account, message, errorCode);
  2046. }];
  2047. }
  2048. - (void)readMarkCommentsWithAccount:(NSString *)account fileId:(NSString *)fileId completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  2049. {
  2050. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  2051. if (tableAccount == nil) {
  2052. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  2053. } else if ([CCUtility getPassword:account].length == 0) {
  2054. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  2055. } else if ([CCUtility getCertificateError:account]) {
  2056. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  2057. }
  2058. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  2059. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  2060. [communication setUserAgent:[CCUtility getUserAgent]];
  2061. [communication readMarkComments:[NSString stringWithFormat:@"%@%@", tableAccount.url, k_dav] fileId:fileId onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  2062. completion(account, nil, 0);
  2063. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  2064. NSString *message;
  2065. NSInteger errorCode = response.statusCode;
  2066. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  2067. errorCode = error.code;
  2068. // Error
  2069. if (errorCode == 503)
  2070. message = NSLocalizedString(@"_server_error_retry_", nil);
  2071. else
  2072. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  2073. completion(account, message, errorCode);
  2074. }];
  2075. }
  2076. - (void)deleteCommentsWithAccount:(NSString *)account fileId:(NSString *)fileId messageID:(NSString *)messageID completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  2077. {
  2078. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  2079. if (tableAccount == nil) {
  2080. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  2081. } else if ([CCUtility getPassword:account].length == 0) {
  2082. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  2083. } else if ([CCUtility getCertificateError:account]) {
  2084. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  2085. }
  2086. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  2087. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  2088. [communication setUserAgent:[CCUtility getUserAgent]];
  2089. [communication deleteComments:[NSString stringWithFormat:@"%@%@", tableAccount.url, k_dav] fileId:fileId messageID:messageID onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  2090. completion(account, nil, 0);
  2091. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  2092. NSString *message;
  2093. NSInteger errorCode = response.statusCode;
  2094. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  2095. errorCode = error.code;
  2096. // Error
  2097. if (errorCode == 503)
  2098. message = NSLocalizedString(@"_server_error_retry_", nil);
  2099. else
  2100. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  2101. completion(account, message, errorCode);
  2102. }];
  2103. }
  2104. #pragma --------------------------------------------------------------------------------------------
  2105. #pragma mark ===== Third Parts =====
  2106. #pragma --------------------------------------------------------------------------------------------
  2107. - (void)getHCUserProfileWithAccount:(NSString *)account serverUrl:(NSString *)serverUrl completion:(void (^)(NSString *account, OCUserProfile *userProfile, NSString *message, NSInteger errorCode))completion
  2108. {
  2109. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  2110. if (tableAccount == nil) {
  2111. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  2112. } else if ([CCUtility getPassword:account].length == 0) {
  2113. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  2114. } else if ([CCUtility getCertificateError:account]) {
  2115. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  2116. }
  2117. NSString *serverPath = [NSString stringWithFormat:@"%@/ocs/v2.php/apps/handwerkcloud/api/v1/settings/%@", serverUrl, tableAccount.userID];
  2118. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  2119. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  2120. [communication setUserAgent:[CCUtility getUserAgent]];
  2121. [communication getHCUserProfile:serverPath onCommunication:communication successRequest:^(NSHTTPURLResponse *response, OCUserProfile *userProfile, NSString *redirectedServer) {
  2122. completion(account, userProfile, nil, 0);
  2123. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  2124. NSString *message;
  2125. NSInteger errorCode = response.statusCode;
  2126. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  2127. errorCode = error.code;
  2128. // Server Unauthorized
  2129. if (errorCode == kOCErrorServerUnauthorized || errorCode == kOCErrorServerForbidden) {
  2130. [[OCNetworking sharedManager] checkRemoteUser:account function:@"get user profile" errorCode:errorCode];
  2131. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  2132. [CCUtility setCertificateError:account error:YES];
  2133. }
  2134. // Error
  2135. if (errorCode == 503)
  2136. message = NSLocalizedString(@"_server_error_retry_", nil);
  2137. else
  2138. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  2139. completion(account, nil,message, errorCode);
  2140. }];
  2141. }
  2142. - (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
  2143. {
  2144. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  2145. if (tableAccount == nil) {
  2146. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  2147. } else if ([CCUtility getPassword:account].length == 0) {
  2148. completion(account, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  2149. } else if ([CCUtility getCertificateError:account]) {
  2150. completion(account, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  2151. }
  2152. // Create JSON
  2153. NSMutableDictionary *dataDic = [NSMutableDictionary new];
  2154. if (address) [dataDic setValue:address forKey:@"address"];
  2155. if (businesssize) {
  2156. if ([businesssize isEqualToString:@"1-4"]) { [dataDic setValue:[NSNumber numberWithInt:1] forKey:@"businesssize"]; }
  2157. else if ([businesssize isEqualToString:@"5-9"]) { [dataDic setValue:[NSNumber numberWithInt:5] forKey:@"businesssize"]; }
  2158. else if ([businesssize isEqualToString:@"10-19"]) { [dataDic setValue:[NSNumber numberWithInt:10] forKey:@"businesssize"]; }
  2159. else if ([businesssize isEqualToString:@"20-49"]) { [dataDic setValue:[NSNumber numberWithInt:20] forKey:@"businesssize"]; }
  2160. else if ([businesssize isEqualToString:@"50-99"]) { [dataDic setValue:[NSNumber numberWithInt:50] forKey:@"businesssize"]; }
  2161. else if ([businesssize isEqualToString:@"100-249"]) { [dataDic setValue:[NSNumber numberWithInt:100] forKey:@"businesssize"]; }
  2162. else if ([businesssize isEqualToString:@"250-499"]) { [dataDic setValue:[NSNumber numberWithInt:250] forKey:@"businesssize"]; }
  2163. else if ([businesssize isEqualToString:@"500-999"]) { [dataDic setValue:[NSNumber numberWithInt:500] forKey:@"businesssize"]; }
  2164. else if ([businesssize isEqualToString:@"1000+"]) { [dataDic setValue:[NSNumber numberWithInt:1000] forKey:@"businesssize"]; }
  2165. }
  2166. if (businesstype) [dataDic setValue:businesstype forKey:@"businesstype"];
  2167. if (city) [dataDic setValue:city forKey:@"city"];
  2168. if (company) [dataDic setValue:company forKey:@"company"];
  2169. if (country) [dataDic setValue:country forKey:@"country"];
  2170. if (displayname) [dataDic setValue:displayname forKey:@"displayname"];
  2171. if (email) [dataDic setValue:email forKey:@"email"];
  2172. if (phone) [dataDic setValue:phone forKey:@"phone"];
  2173. if (role_) [dataDic setValue:role_ forKey:@"role"];
  2174. if (twitter) [dataDic setValue:twitter forKey:@"twitter"];
  2175. if (website) [dataDic setValue:website forKey:@"website"];
  2176. if (zip) [dataDic setValue:zip forKey:@"zip"];
  2177. NSString *data = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:dataDic options:0 error:nil] encoding:NSUTF8StringEncoding];
  2178. NSString *serverPath = [NSString stringWithFormat:@"%@/ocs/v2.php/apps/handwerkcloud/api/v1/settings/%@", serverUrl, tableAccount.userID];
  2179. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  2180. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  2181. [communication setUserAgent:[CCUtility getUserAgent]];
  2182. [communication putHCUserProfile:serverPath data:data onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  2183. completion(account, nil, 0);
  2184. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  2185. NSString *message;
  2186. NSInteger errorCode = response.statusCode;
  2187. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  2188. errorCode = error.code;
  2189. // Server Unauthorized
  2190. if (errorCode == kOCErrorServerUnauthorized || errorCode == kOCErrorServerForbidden) {
  2191. [[OCNetworking sharedManager] checkRemoteUser:account function:@"put user profile" errorCode:errorCode];
  2192. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  2193. [CCUtility setCertificateError:account error:YES];
  2194. }
  2195. // Error
  2196. if (errorCode == 503)
  2197. message = NSLocalizedString(@"_server_error_retry_", nil);
  2198. else
  2199. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  2200. completion(account, message, errorCode);
  2201. }];
  2202. }
  2203. - (void)getHCFeaturesWithAccount:(NSString *)account serverUrl:(NSString *)serverUrl completion:(void (^)(NSString *account, HCFeatures *features, NSString *message, NSInteger errorCode))completion
  2204. {
  2205. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  2206. if (tableAccount == nil) {
  2207. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  2208. } else if ([CCUtility getPassword:account].length == 0) {
  2209. completion(account, nil, NSLocalizedString(@"_bad_username_password_", nil), kOCErrorServerUnauthorized);
  2210. } else if ([CCUtility getCertificateError:account]) {
  2211. completion(account, nil, NSLocalizedString(@"_ssl_certificate_untrusted_", nil), NSURLErrorServerCertificateUntrusted);
  2212. }
  2213. NSString *serverPath = [NSString stringWithFormat:@"%@/ocs/v2.php/apps/handwerkcloud/api/v1/features/%@", serverUrl, tableAccount.userID];
  2214. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  2215. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:[CCUtility getPassword:account]];
  2216. [communication setUserAgent:[CCUtility getUserAgent]];
  2217. [communication getHCFeatures:serverPath onCommunication:communication successRequest:^(NSHTTPURLResponse *response, HCFeatures *features, NSString *redirectedServer) {
  2218. completion(account, features, nil, 0);
  2219. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  2220. NSString *message;
  2221. NSInteger errorCode = response.statusCode;
  2222. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  2223. errorCode = error.code;
  2224. // Server Unauthorized
  2225. if (errorCode == kOCErrorServerUnauthorized || errorCode == kOCErrorServerForbidden) {
  2226. [[OCNetworking sharedManager] checkRemoteUser:account function:@"get features" errorCode:errorCode];
  2227. } else if (errorCode == NSURLErrorServerCertificateUntrusted) {
  2228. [CCUtility setCertificateError:account error:YES];
  2229. }
  2230. // Error
  2231. if (errorCode == 503)
  2232. message = NSLocalizedString(@"_server_error_retry_", nil);
  2233. else
  2234. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  2235. completion(account, nil,message, errorCode);
  2236. }];
  2237. }
  2238. /*
  2239. - (void)middlewarePing
  2240. {
  2241. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  2242. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  2243. [communication setUserAgent:[CCUtility getUserAgent]];
  2244. [communication getMiddlewarePing:_metadataNet.serverUrl onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfExternalSites, NSString *redirectedServer) {
  2245. [self complete];
  2246. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  2247. NSInteger errorCode = response.statusCode;
  2248. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  2249. errorCode = error.code;
  2250. // Error
  2251. if ([self.delegate respondsToSelector:@selector(getExternalSitesServerFailure:message:errorCode:)]) {
  2252. if (errorCode == 503)
  2253. [self.delegate getExternalSitesServerFailure:_metadataNet message:NSLocalizedString(@"_server_error_retry_", nil) errorCode:errorCode];
  2254. else
  2255. [self.delegate getExternalSitesServerFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  2256. }
  2257. // Request trusted certificated
  2258. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  2259. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  2260. [self complete];
  2261. }];
  2262. }
  2263. */
  2264. #pragma --------------------------------------------------------------------------------------------
  2265. #pragma mark ===== didReceiveChallenge =====
  2266. #pragma --------------------------------------------------------------------------------------------
  2267. -(void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler
  2268. {
  2269. // The pinnning check
  2270. if ([[NCNetworking sharedInstance] checkTrustedChallengeWithChallenge:challenge directoryCertificate:[CCUtility getDirectoryCerificates]]) {
  2271. completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  2272. } else {
  2273. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  2274. }
  2275. }
  2276. @end
  2277. #pragma --------------------------------------------------------------------------------------------
  2278. #pragma mark ===== OCURLSessionManager =====
  2279. #pragma --------------------------------------------------------------------------------------------
  2280. @implementation OCURLSessionManager
  2281. - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
  2282. {
  2283. // The pinnning check
  2284. if ([[NCNetworking sharedInstance] checkTrustedChallengeWithChallenge:challenge directoryCertificate:[CCUtility getDirectoryCerificates]]) {
  2285. completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  2286. } else {
  2287. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  2288. }
  2289. }
  2290. @end