OCNetworking.m 157 KB

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