OCNetworking.m 162 KB

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