OCNetworking.m 160 KB

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