OCNetworking.m 161 KB

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