OCNetworking.m 162 KB

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