OCCommunication.m 96 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013
  1. //
  2. // OCCommunication.m
  3. // Owncloud iOs Client
  4. //
  5. // Copyright (C) 2016, ownCloud GmbH. ( http://www.owncloud.org/ )
  6. //
  7. // Permission is hereby granted, free of charge, to any person obtaining a copy
  8. // of this software and associated documentation files (the "Software"), to deal
  9. // in the Software without restriction, including without limitation the rights
  10. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. // copies of the Software, and to permit persons to whom the Software is
  12. // furnished to do so, subject to the following conditions:
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. //
  24. // Add : getNotificationServer & setNotificationServer
  25. // Add : getUserProfileServer
  26. // Add : Support for Favorite
  27. // Add : getActivityServer
  28. //
  29. // Author Marino Faggiana <m.faggiana@twsweb.it>
  30. // Copyright (c) 2017 TWS. All rights reserved.
  31. //
  32. #import "OCCommunication.h"
  33. #import "OCHTTPRequestOperation.h"
  34. #import "UtilsFramework.h"
  35. #import "OCXMLParser.h"
  36. #import "OCXMLSharedParser.h"
  37. #import "OCXMLServerErrorsParser.h"
  38. #import "OCXMLListParser.h"
  39. #import "NSString+Encode.h"
  40. #import "OCFrameworkConstants.h"
  41. #import "OCWebDAVClient.h"
  42. #import "OCXMLShareByLinkParser.h"
  43. #import "OCErrorMsg.h"
  44. #import "AFURLSessionManager.h"
  45. #import "OCShareUser.h"
  46. #import "OCActivity.h"
  47. #import "OCExternalSites.h"
  48. #import "OCCapabilities.h"
  49. #import "OCNotifications.h"
  50. #import "OCNotificationsAction.h"
  51. #import "OCRichObjectStrings.h"
  52. #import "OCUserProfile.h"
  53. @interface OCCommunication ()
  54. @property (nonatomic, strong) NSString *currentServerVersion;
  55. @end
  56. @implementation OCCommunication
  57. -(id) init {
  58. self = [super init];
  59. if (self) {
  60. //Init the Donwload queue array
  61. self.downloadTaskNetworkQueueArray = [NSMutableArray new];
  62. //Credentials not set yet
  63. self.kindOfCredential = credentialNotSet;
  64. [self setSecurityPolicyManagers:[self createSecurityPolicy]];
  65. self.isCookiesAvailable = YES;
  66. self.isForbiddenCharactersAvailable = NO;
  67. #ifdef UNIT_TEST
  68. self.uploadSessionManager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
  69. self.downloadSessionManager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
  70. self.networkSessionManager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
  71. self.networkSessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
  72. #else
  73. //Network Upload queue for NSURLSession (iOS 7)
  74. NSURLSessionConfiguration *uploadConfiguration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_session_name];
  75. uploadConfiguration.HTTPShouldUsePipelining = YES;
  76. uploadConfiguration.HTTPMaximumConnectionsPerHost = 1;
  77. uploadConfiguration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  78. self.uploadSessionManager = [[AFURLSessionManager alloc] initWithSessionConfiguration:uploadConfiguration];
  79. [self.uploadSessionManager.operationQueue setMaxConcurrentOperationCount:1];
  80. //Network Download queue for NSURLSession (iOS 7)
  81. NSURLSessionConfiguration *downConfiguration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_download_session_name];
  82. downConfiguration.HTTPShouldUsePipelining = YES;
  83. downConfiguration.HTTPMaximumConnectionsPerHost = 1;
  84. downConfiguration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  85. self.downloadSessionManager = [[AFURLSessionManager alloc] initWithSessionConfiguration:downConfiguration];
  86. [self.downloadSessionManager.operationQueue setMaxConcurrentOperationCount:1];
  87. //Network Download queue for NSURLSession (iOS 7)
  88. NSURLSessionConfiguration *networkConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
  89. networkConfiguration.HTTPShouldUsePipelining = YES;
  90. networkConfiguration.HTTPMaximumConnectionsPerHost = 1;
  91. networkConfiguration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  92. self.networkSessionManager = [[AFURLSessionManager alloc] initWithSessionConfiguration:networkConfiguration];
  93. [self.networkSessionManager.operationQueue setMaxConcurrentOperationCount:1];
  94. self.networkSessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
  95. #endif
  96. }
  97. return self;
  98. }
  99. -(id) initWithUploadSessionManager:(AFURLSessionManager *) uploadSessionManager {
  100. self = [super init];
  101. if (self) {
  102. //Init the Donwload queue array
  103. self.downloadTaskNetworkQueueArray = [NSMutableArray new];
  104. self.isCookiesAvailable = YES;
  105. self.isForbiddenCharactersAvailable = NO;
  106. //Credentials not set yet
  107. self.kindOfCredential = credentialNotSet;
  108. [self setSecurityPolicyManagers:[self createSecurityPolicy]];
  109. self.uploadSessionManager = uploadSessionManager;
  110. }
  111. return self;
  112. }
  113. -(id) initWithUploadSessionManager:(AFURLSessionManager *) uploadSessionManager andDownloadSessionManager:(AFURLSessionManager *) downloadSessionManager andNetworkSessionManager:(AFURLSessionManager *) networkSessionManager {
  114. self = [super init];
  115. if (self) {
  116. //Init the Donwload queue array
  117. self.downloadTaskNetworkQueueArray = [NSMutableArray new];
  118. //Credentials not set yet
  119. self.kindOfCredential = credentialNotSet;
  120. [self setSecurityPolicyManagers:[self createSecurityPolicy]];
  121. self.uploadSessionManager = uploadSessionManager;
  122. self.downloadSessionManager = downloadSessionManager;
  123. self.networkSessionManager = networkSessionManager;
  124. }
  125. return self;
  126. }
  127. - (AFSecurityPolicy *) createSecurityPolicy {
  128. return [AFSecurityPolicy defaultPolicy];
  129. }
  130. - (void)setSecurityPolicyManagers:(AFSecurityPolicy *)securityPolicy {
  131. self.securityPolicy = securityPolicy;
  132. self.uploadSessionManager.securityPolicy = securityPolicy;
  133. self.downloadSessionManager.securityPolicy = securityPolicy;
  134. }
  135. #pragma mark - Setting Credentials
  136. - (void) setCredentialsWithUser:(NSString*) user andPassword:(NSString*) password {
  137. self.kindOfCredential = credentialNormal;
  138. self.user = user;
  139. self.password = password;
  140. }
  141. - (void) setCredentialsWithCookie:(NSString*) cookie {
  142. self.kindOfCredential = credentialCookie;
  143. self.password = cookie;
  144. }
  145. - (void) setCredentialsOauthWithToken:(NSString*) token {
  146. self.kindOfCredential = credentialOauth;
  147. self.password = token;
  148. }
  149. ///-----------------------------------
  150. /// @name getRequestWithCredentials
  151. ///-----------------------------------
  152. /**
  153. * Method to return the request with the right credential
  154. *
  155. * @param OCWebDAVClient like a dinamic typed
  156. *
  157. * @return OCWebDAVClient like a dinamic typed
  158. *
  159. */
  160. - (id) getRequestWithCredentials:(id) request {
  161. if ([request isKindOfClass:[NSMutableURLRequest class]]) {
  162. NSMutableURLRequest *myRequest = (NSMutableURLRequest *)request;
  163. switch (self.kindOfCredential) {
  164. case credentialNotSet:
  165. //Without credentials
  166. break;
  167. case credentialNormal:
  168. {
  169. NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", self.user, self.password];
  170. [myRequest addValue:[NSString stringWithFormat:@"Basic %@", [UtilsFramework AFBase64EncodedStringFromString:basicAuthCredentials]] forHTTPHeaderField:@"Authorization"];
  171. break;
  172. }
  173. case credentialCookie:
  174. NSLog(@"Cookie: %@", self.password);
  175. [myRequest addValue:self.password forHTTPHeaderField:@"Cookie"];
  176. break;
  177. case credentialOauth:
  178. [myRequest addValue:[NSString stringWithFormat:@"Bearer %@", self.password] forHTTPHeaderField:@"Authorization"];
  179. break;
  180. default:
  181. break;
  182. }
  183. if (self.userAgent) {
  184. [myRequest addValue:self.userAgent forHTTPHeaderField:@"User-Agent"];
  185. }
  186. return myRequest;
  187. } else if([request isKindOfClass:[OCWebDAVClient class]]) {
  188. OCWebDAVClient *myRequest = (OCWebDAVClient *)request;
  189. switch (self.kindOfCredential) {
  190. case credentialNotSet:
  191. //Without credentials
  192. break;
  193. case credentialNormal:
  194. [myRequest setAuthorizationHeaderWithUsername:self.user password:self.password];
  195. break;
  196. case credentialCookie:
  197. [myRequest setAuthorizationHeaderWithCookie:self.password];
  198. break;
  199. case credentialOauth:
  200. [myRequest setAuthorizationHeaderWithToken:[NSString stringWithFormat:@"Bearer %@", self.password]];
  201. break;
  202. default:
  203. break;
  204. }
  205. if (self.userAgent) {
  206. [myRequest setUserAgent:self.userAgent];
  207. }
  208. return request;
  209. } else {
  210. NSLog(@"We do not know witch kind of object is");
  211. return request;
  212. }
  213. }
  214. #pragma mark - WebDav network Operations
  215. ///-----------------------------------
  216. /// @name Check Server
  217. ///-----------------------------------
  218. - (void) checkServer: (NSString *) path
  219. onCommunication:(OCCommunication *)sharedOCCommunication
  220. successRequest:(void(^)(NSHTTPURLResponse *response, NSString *redirectedServer)) successRequest
  221. failureRequest:(void(^)(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer)) failureRequest {
  222. OCWebDAVClient *request = [OCWebDAVClient new];
  223. request = [self getRequestWithCredentials:request];
  224. if (self.userAgent) {
  225. [request setUserAgent:self.userAgent];
  226. }
  227. path = [path encodeString:NSUTF8StringEncoding];
  228. [request checkServer:path onCommunication:sharedOCCommunication
  229. success:^(NSHTTPURLResponse *response, id responseObject) {
  230. if (successRequest) {
  231. successRequest(response, request.redirectedServer);
  232. }
  233. } failure:^(NSHTTPURLResponse *response, NSData *responseData, NSError *error) {
  234. failureRequest(response, error, request.redirectedServer);
  235. }];
  236. }
  237. ///-----------------------------------
  238. /// @name Create a folder
  239. ///-----------------------------------
  240. - (void) createFolder: (NSString *) path
  241. onCommunication:(OCCommunication *)sharedOCCommunication withForbiddenCharactersSupported:(BOOL)isFCSupported
  242. successRequest:(void(^)(NSHTTPURLResponse *response, NSString *redirectedServer)) successRequest
  243. failureRequest:(void(^)(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer)) failureRequest
  244. errorBeforeRequest:(void(^)(NSError *error)) errorBeforeRequest {
  245. if ([UtilsFramework isForbiddenCharactersInFileName:[UtilsFramework getFileNameOrFolderByPath:path] withForbiddenCharactersSupported:isFCSupported]) {
  246. NSError *error = [UtilsFramework getErrorByCodeId:OCErrorForbidenCharacters];
  247. errorBeforeRequest(error);
  248. } else {
  249. OCWebDAVClient *request = [OCWebDAVClient new];
  250. request = [self getRequestWithCredentials:request];
  251. path = [path encodeString:NSUTF8StringEncoding];
  252. [request makeCollection:path onCommunication:sharedOCCommunication
  253. success:^(NSHTTPURLResponse *response, id responseObject) {
  254. if (successRequest) {
  255. successRequest(response, request.redirectedServer);
  256. }
  257. } failure:^(NSHTTPURLResponse *response, NSData *responseData, NSError *error) {
  258. OCXMLServerErrorsParser *serverErrorParser = [OCXMLServerErrorsParser new];
  259. [serverErrorParser startToParseWithData:responseData withCompleteBlock:^(NSError *err) {
  260. if (err) {
  261. failureRequest(response, err, request.redirectedServer);
  262. }else{
  263. failureRequest(response, error, request.redirectedServer);
  264. }
  265. }];
  266. }];
  267. }
  268. }
  269. ///-----------------------------------
  270. /// @name Move a file or a folder
  271. ///-----------------------------------
  272. - (void) moveFileOrFolder:(NSString *)sourcePath
  273. toDestiny:(NSString *)destinyPath
  274. onCommunication:(OCCommunication *)sharedOCCommunication withForbiddenCharactersSupported:(BOOL)isFCSupported
  275. successRequest:(void (^)(NSHTTPURLResponse *response, NSString *redirectServer))successRequest
  276. failureRequest:(void (^)(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer))failureRequest
  277. errorBeforeRequest:(void (^)(NSError *error))errorBeforeRequest {
  278. if ([UtilsFramework isTheSameFileOrFolderByNewURLString:destinyPath andOriginURLString:sourcePath]) {
  279. //We check that we are not trying to move the file to the same place
  280. NSError *error = [UtilsFramework getErrorByCodeId:OCErrorMovingTheDestinyAndOriginAreTheSame];
  281. errorBeforeRequest(error);
  282. } else if ([UtilsFramework isAFolderUnderItByNewURLString:destinyPath andOriginURLString:sourcePath]) {
  283. //We check we are not trying to move a folder inside himself
  284. NSError *error = [UtilsFramework getErrorByCodeId:OCErrorMovingFolderInsideHimself];
  285. errorBeforeRequest(error);
  286. } else if ([UtilsFramework isForbiddenCharactersInFileName:[UtilsFramework getFileNameOrFolderByPath:destinyPath] withForbiddenCharactersSupported:isFCSupported]) {
  287. //We check that we are making a move not a rename to prevent special characters problems
  288. NSError *error = [UtilsFramework getErrorByCodeId:OCErrorMovingDestinyNameHaveForbiddenCharacters];
  289. errorBeforeRequest(error);
  290. } else {
  291. sourcePath = [sourcePath encodeString:NSUTF8StringEncoding];
  292. destinyPath = [destinyPath encodeString:NSUTF8StringEncoding];
  293. OCWebDAVClient *request = [OCWebDAVClient new];
  294. request = [self getRequestWithCredentials:request];
  295. [request movePath:sourcePath toPath:destinyPath onCommunication:sharedOCCommunication success:^(NSHTTPURLResponse *response, id responseObject) {
  296. if (successRequest) {
  297. successRequest(response, request.redirectedServer);
  298. }
  299. } failure:^(NSHTTPURLResponse *response, NSData *responseData, NSError *error) {
  300. OCXMLServerErrorsParser *serverErrorParser = [OCXMLServerErrorsParser new];
  301. [serverErrorParser startToParseWithData:responseData withCompleteBlock:^(NSError *err) {
  302. if (err) {
  303. failureRequest(response, err, request.redirectedServer);
  304. }else{
  305. failureRequest(response, error, request.redirectedServer);
  306. }
  307. }];
  308. }];
  309. }
  310. }
  311. ///-----------------------------------
  312. /// @name Delete a file or a folder
  313. ///-----------------------------------
  314. - (void) deleteFileOrFolder:(NSString *)path
  315. onCommunication:(OCCommunication *)sharedOCCommunication
  316. successRequest:(void (^)(NSHTTPURLResponse *response, NSString *redirectedServer))successRequest
  317. failureRquest:(void (^)(NSHTTPURLResponse *resposne, NSError *error, NSString *redirectedServer))failureRequest {
  318. path = [path encodeString:NSUTF8StringEncoding];
  319. OCWebDAVClient *request = [OCWebDAVClient new];
  320. request = [self getRequestWithCredentials:request];
  321. [request deletePath:path onCommunication:sharedOCCommunication success:^(NSHTTPURLResponse *response, id responseObject) {
  322. if (successRequest) {
  323. successRequest(response, request.redirectedServer);
  324. }
  325. } failure:^(NSHTTPURLResponse *response, NSData *responseData, NSError *error) {
  326. failureRequest(response, error, request.redirectedServer);
  327. }];
  328. }
  329. ///-----------------------------------
  330. /// @name Read folder
  331. ///-----------------------------------
  332. - (void) readFolder: (NSString *) path depth:(NSString *)depth withUserSessionToken:(NSString *)token
  333. onCommunication:(OCCommunication *)sharedOCCommunication
  334. successRequest:(void(^)(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer, NSString *token)) successRequest
  335. failureRequest:(void(^)(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer)) failureRequest{
  336. if (!token){
  337. token = @"no token";
  338. }
  339. path = [path encodeString:NSUTF8StringEncoding];
  340. OCWebDAVClient *request = [OCWebDAVClient new];
  341. request = [self getRequestWithCredentials:request];
  342. [request listPath:path depth:depth onCommunication:sharedOCCommunication withUserSessionToken:token success:^(NSHTTPURLResponse *response, id responseObject, NSString *token) {
  343. if (successRequest) {
  344. NSData *responseData = (NSData*) responseObject;
  345. // NSString* newStr = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
  346. // NSLog(@"newStrReadFolder: %@", newStr);
  347. OCXMLParser *parser = [[OCXMLParser alloc]init];
  348. [parser initParserWithData:responseData];
  349. NSMutableArray *directoryList = [parser.directoryList mutableCopy];
  350. //Return success
  351. successRequest(response, directoryList, request.redirectedServer, token);
  352. }
  353. } failure:^(NSHTTPURLResponse *response, id responseData, NSError *error, NSString *token) {
  354. NSLog(@"Failure");
  355. failureRequest(response, error, token, request.redirectedServer);
  356. }];
  357. }
  358. ///-----------------------------------
  359. /// @name Download File Session
  360. ///-----------------------------------
  361. - (NSURLSessionDownloadTask *) downloadFileSession:(NSString *)remotePath toDestiny:(NSString *)localPath defaultPriority:(BOOL)defaultPriority onCommunication:(OCCommunication *)sharedOCCommunication progress:(void(^)(NSProgress *progress))downloadProgress successRequest:(void(^)(NSURLResponse *response, NSURL *filePath)) successRequest failureRequest:(void(^)(NSURLResponse *response, NSError *error)) failureRequest {
  362. OCWebDAVClient *request = [OCWebDAVClient new];
  363. request = [self getRequestWithCredentials:request];
  364. remotePath = [remotePath encodeString:NSUTF8StringEncoding];
  365. NSURLSessionDownloadTask *downloadTask = [request downloadWithSessionPath:remotePath toPath:localPath defaultPriority:defaultPriority onCommunication:sharedOCCommunication progress:^(NSProgress *progress) {
  366. downloadProgress(progress);
  367. } success:^(NSURLResponse *response, NSURL *filePath) {
  368. [UtilsFramework addCookiesToStorageFromResponse:(NSURLResponse *) response andPath:[NSURL URLWithString:remotePath]];
  369. successRequest(response,filePath);
  370. } failure:^(NSURLResponse *response, NSError *error) {
  371. [UtilsFramework addCookiesToStorageFromResponse:(NSURLResponse *) response andPath:[NSURL URLWithString:remotePath]];
  372. failureRequest(response,error);
  373. }];
  374. return downloadTask;
  375. }
  376. ///-----------------------------------
  377. /// @name Set Download Task Complete Block
  378. ///-----------------------------------
  379. - (void)setDownloadTaskComleteBlock: (NSURL * (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location))block{
  380. [self.downloadSessionManager setDownloadTaskDidFinishDownloadingBlock:block];
  381. }
  382. ///-----------------------------------
  383. /// @name Set Download Task Did Get Body Data Block
  384. ///-----------------------------------
  385. - (void) setDownloadTaskDidGetBodyDataBlock: (void(^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite)) block{
  386. [self.downloadSessionManager setDownloadTaskDidWriteDataBlock:^(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite) {
  387. block(session,downloadTask,bytesWritten,totalBytesWritten,totalBytesExpectedToWrite);
  388. }];
  389. }
  390. ///-----------------------------------
  391. /// @name Upload File Session
  392. ///-----------------------------------
  393. - (NSURLSessionUploadTask *) uploadFileSession:(NSString *) localPath toDestiny:(NSString *) remotePath onCommunication:(OCCommunication *)sharedOCCommunication progress:(void(^)(NSProgress *progress))uploadProgress successRequest:(void(^)(NSURLResponse *response, NSString *redirectedServer)) successRequest failureRequest:(void(^)(NSURLResponse *response, NSString *redirectedServer, NSError *error)) failureRequest failureBeforeRequest:(void(^)(NSError *error)) failureBeforeRequest {
  394. OCWebDAVClient *request = [OCWebDAVClient new];
  395. request = [self getRequestWithCredentials:request];
  396. remotePath = [remotePath encodeString:NSUTF8StringEncoding];
  397. NSURLSessionUploadTask *uploadTask = [request putWithSessionLocalPath:localPath atRemotePath:remotePath onCommunication:sharedOCCommunication progress:^(NSProgress *progress) {
  398. uploadProgress(progress);
  399. } success:^(NSURLResponse *response, id responseObjec){
  400. [UtilsFramework addCookiesToStorageFromResponse:(NSURLResponse *) response andPath:[NSURL URLWithString:remotePath]];
  401. //TODO: The second parameter is the redirected server
  402. successRequest(response, @"");
  403. } failure:^(NSURLResponse *response, id responseObject, NSError *error) {
  404. [UtilsFramework addCookiesToStorageFromResponse:(NSURLResponse *) response andPath:[NSURL URLWithString:remotePath]];
  405. //TODO: The second parameter is the redirected server
  406. NSData *responseData = (NSData*) responseObject;
  407. OCXMLServerErrorsParser *serverErrorParser = [OCXMLServerErrorsParser new];
  408. [serverErrorParser startToParseWithData:responseData withCompleteBlock:^(NSError *err) {
  409. if (err) {
  410. failureRequest(response, @"", err);
  411. }else{
  412. failureRequest(response, @"", error);
  413. }
  414. }];
  415. } failureBeforeRequest:^(NSError *error) {
  416. failureBeforeRequest(error);
  417. }];
  418. return uploadTask;
  419. }
  420. ///-----------------------------------
  421. /// @name Set Task Did Complete Block
  422. ///-----------------------------------
  423. - (void) setTaskDidCompleteBlock: (void(^)(NSURLSession *session, NSURLSessionTask *task, NSError *error)) block{
  424. [self.uploadSessionManager setTaskDidCompleteBlock:^(NSURLSession *session, NSURLSessionTask *task, NSError *error) {
  425. block(session, task, error);
  426. }];
  427. }
  428. ///-----------------------------------
  429. /// @name Set Task Did Send Body Data Block
  430. ///-----------------------------------
  431. - (void) setTaskDidSendBodyDataBlock: (void(^)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend)) block{
  432. [self.uploadSessionManager setTaskDidSendBodyDataBlock:^(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend) {
  433. block(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend);
  434. }];
  435. }
  436. ///-----------------------------------
  437. /// @name Read File
  438. ///-----------------------------------
  439. - (void) readFile: (NSString *) path
  440. onCommunication:(OCCommunication *)sharedOCCommunication
  441. successRequest:(void(^)(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer)) successRequest
  442. failureRequest:(void(^)(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer)) failureRequest {
  443. path = [path encodeString:NSUTF8StringEncoding];
  444. OCWebDAVClient *request = [OCWebDAVClient new];
  445. request = [self getRequestWithCredentials:request];
  446. [request propertiesOfPath:path onCommunication:sharedOCCommunication success:^(NSHTTPURLResponse *response, id responseObject) {
  447. if (successRequest) {
  448. NSData *responseData = (NSData*) responseObject;
  449. // NSString* newStr = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
  450. // NSLog(@"newStrReadFile: %@", newStr);
  451. OCXMLParser *parser = [[OCXMLParser alloc]init];
  452. [parser initParserWithData:responseData];
  453. NSMutableArray *directoryList = [parser.directoryList mutableCopy];
  454. //Return success
  455. successRequest(response, directoryList, request.redirectedServer);
  456. }
  457. } failure:^(NSHTTPURLResponse *response, NSData *responseData, NSError *error) {
  458. failureRequest(response, error, request.redirectedServer);
  459. }];
  460. }
  461. ///-----------------------------------
  462. /// @name search
  463. ///-----------------------------------
  464. - (void)search:(NSString *)path folder:(NSString *)folder fileName:(NSString *)fileName depth:(NSString *)depth dateLastModified:(NSString *)dateLastModified withUserSessionToken:(NSString *)token onCommunication:(OCCommunication *)sharedOCCommunication successRequest:(void(^)(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer, NSString *token)) successRequest failureRequest:(void(^)(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer)) failureRequest{
  465. if (!token){
  466. token = @"no token";
  467. }
  468. path = [path encodeString:NSUTF8StringEncoding];
  469. OCWebDAVClient *request = [OCWebDAVClient new];
  470. request = [self getRequestWithCredentials:request];
  471. [request search:path folder:folder fileName:fileName depth:depth dateLastModified:dateLastModified user:_user onCommunication:sharedOCCommunication withUserSessionToken:token success:^(NSHTTPURLResponse *response, id responseObject, NSString *token) {
  472. if (successRequest) {
  473. NSData *responseData = (NSData*) responseObject;
  474. OCXMLListParser *parser = [OCXMLListParser new];
  475. [parser initParserWithData:responseData];
  476. NSMutableArray *searchList = [parser.searchList mutableCopy];
  477. //Return success
  478. successRequest(response, searchList, request.redirectedServer, token);
  479. }
  480. } failure:^(NSHTTPURLResponse *response, id responseData, NSError *error, NSString *token) {
  481. failureRequest(response, error, token, request.redirectedServer);
  482. }];
  483. }
  484. ///-----------------------------------
  485. /// @name Setting favorite
  486. ///-----------------------------------
  487. - (void)settingFavoriteServer:(NSString *)path andFileOrFolderPath:(NSString *)filePath favorite:(BOOL)favorite withUserSessionToken:(NSString *)token onCommunication:(OCCommunication *)sharedOCCommunication successRequest:(void(^)(NSHTTPURLResponse *response, NSString *redirectedServer, NSString *token)) successRequest failureRequest:(void(^)(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer)) failureRequest {
  488. if (!token){
  489. token = @"no token";
  490. }
  491. path = [NSString stringWithFormat:@"%@/files/%@/%@", path, _user, filePath];
  492. path = [path encodeString:NSUTF8StringEncoding];
  493. OCWebDAVClient *request = [OCWebDAVClient new];
  494. request = [self getRequestWithCredentials:request];
  495. [request settingFavorite:path favorite:favorite onCommunication:sharedOCCommunication withUserSessionToken:token success:^(NSHTTPURLResponse *response, id responseObject, NSString *token) {
  496. if (successRequest) {
  497. //Return success
  498. successRequest(response, request.redirectedServer, token);
  499. }
  500. } failure:^(NSHTTPURLResponse *response, id responseData, NSError *error, NSString *token) {
  501. NSLog(@"Failure");
  502. failureRequest(response, error, token, request.redirectedServer);
  503. }];
  504. }
  505. ///-----------------------------------
  506. /// @name Listing favorites
  507. ///-----------------------------------
  508. - (void)listingFavorites:(NSString *)path folder:(NSString *)folder withUserSessionToken:(NSString *)token onCommunication:(OCCommunication *)sharedOCCommunication successRequest:(void(^)(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer, NSString *token)) successRequest failureRequest:(void(^)(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer)) failureRequest{
  509. if (!token){
  510. token = @"no token";
  511. }
  512. path = [path encodeString:NSUTF8StringEncoding];
  513. OCWebDAVClient *request = [OCWebDAVClient new];
  514. request = [self getRequestWithCredentials:request];
  515. [request listingFavorites:path folder:folder user:_user onCommunication:sharedOCCommunication withUserSessionToken:token success:^(NSHTTPURLResponse *response, id responseObject, NSString *token) {
  516. if (successRequest) {
  517. NSData *responseData = (NSData*) responseObject;
  518. OCXMLListParser *parser = [OCXMLListParser new];
  519. [parser initParserWithData:responseData];
  520. NSMutableArray *searchList = [parser.searchList mutableCopy];
  521. //Return success
  522. successRequest(response, searchList, request.redirectedServer, token);
  523. }
  524. } failure:^(NSHTTPURLResponse *response, id responseData, NSError *error, NSString *token) {
  525. failureRequest(response, error, token, request.redirectedServer);
  526. }];
  527. }
  528. #pragma mark - OC API Calls
  529. - (NSString *) getCurrentServerVersion {
  530. return self.currentServerVersion;
  531. }
  532. - (void) getServerVersionWithPath:(NSString*) path onCommunication:(OCCommunication *)sharedOCCommunication
  533. successRequest:(void(^)(NSHTTPURLResponse *response, NSString *serverVersion, NSString *redirectedServer)) success
  534. failureRequest:(void(^)(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer)) failure{
  535. OCWebDAVClient *request = [OCWebDAVClient new];
  536. if (self.userAgent) {
  537. [request setUserAgent:self.userAgent];
  538. }
  539. [request getStatusOfTheServer:path onCommunication:sharedOCCommunication success:^(NSHTTPURLResponse *response, id responseObject) {
  540. NSData *data = (NSData*) responseObject;
  541. NSString *versionString = [NSString new];
  542. NSError* error=nil;
  543. if (data) {
  544. NSMutableDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &error];
  545. if(error) {
  546. NSLog(@"Error parsing JSON: %@", error);
  547. } else {
  548. //Obtain the server version from the version field
  549. versionString = [jsonArray valueForKey:@"version"];
  550. self.currentServerVersion = versionString;
  551. }
  552. } else {
  553. NSLog(@"Error parsing JSON: data is null");
  554. }
  555. success(response, versionString, request.redirectedServer);
  556. } failure:^(NSHTTPURLResponse *response, NSData *responseData, NSError *error) {
  557. failure(response, error, request.redirectedServer);
  558. }];
  559. }
  560. ///-----------------------------------
  561. /// @name Get UserName by cookie
  562. ///-----------------------------------
  563. - (void) getUserNameByCookie:(NSString *) cookieString ofServerPath:(NSString *)path onCommunication:
  564. (OCCommunication *)sharedOCCommunication success:(void(^)(NSHTTPURLResponse *response, NSData *responseData, NSString *redirectedServer))success
  565. failure:(void(^)(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer))failure{
  566. OCWebDAVClient *request = [OCWebDAVClient new];
  567. request = [self getRequestWithCredentials:request];
  568. [request requestUserNameOfServer: path byCookie:cookieString onCommunication:sharedOCCommunication success:^(NSHTTPURLResponse *response, id responseObject) {
  569. success(response, responseObject, request.redirectedServer);
  570. } failure:^(NSHTTPURLResponse *response, NSData *responseData, NSError *error) {
  571. failure(response, error, request.redirectedServer);
  572. }];
  573. }
  574. - (void) getFeaturesSupportedByServer:(NSString*) path onCommunication:(OCCommunication *)sharedOCCommunication
  575. successRequest:(void(^)(NSHTTPURLResponse *response, BOOL hasShareSupport, BOOL hasShareeSupport, BOOL hasCookiesSupport, BOOL hasForbiddenCharactersSupport, BOOL hasCapabilitiesSupport, BOOL hasFedSharesOptionShareSupport, NSString *redirectedServer)) success
  576. failureRequest:(void(^)(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer)) failure{
  577. OCWebDAVClient *request = [OCWebDAVClient new];
  578. if (self.userAgent) {
  579. [request setUserAgent:self.userAgent];
  580. }
  581. [request getStatusOfTheServer:path onCommunication:sharedOCCommunication success:^(NSHTTPURLResponse *response, id responseObject) {
  582. if (responseObject) {
  583. NSError* error = nil;
  584. NSMutableDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData: (NSData*) responseObject options: NSJSONReadingMutableContainers error: &error];
  585. if(error) {
  586. // NSLog(@"Error parsing JSON: %@", error);
  587. failure(response, error, request.redirectedServer);
  588. }else{
  589. self.currentServerVersion = [jsonArray valueForKey:@"version"];
  590. BOOL hasShareSupport = [UtilsFramework isServerVersion:self.currentServerVersion higherThanLimitVersion:k_version_support_shared];
  591. BOOL hasShareeSupport = [UtilsFramework isServerVersion:self.currentServerVersion higherThanLimitVersion:k_version_support_sharee_api];
  592. BOOL hasCookiesSupport = [UtilsFramework isServerVersion:self.currentServerVersion higherThanLimitVersion:k_version_support_cookies];
  593. BOOL hasForbiddenCharactersSupport = [UtilsFramework isServerVersion:self.currentServerVersion higherThanLimitVersion:k_version_support_forbidden_characters];
  594. BOOL hasCapabilitiesSupport = [UtilsFramework isServerVersion:self.currentServerVersion higherThanLimitVersion:k_version_support_capabilities];
  595. BOOL hasFedSharesOptionShareSupport = [UtilsFramework isServerVersion:self.currentServerVersion higherThanLimitVersion:k_version_support_share_option_fed_share];
  596. success(response, hasShareSupport, hasShareeSupport, hasCookiesSupport, hasForbiddenCharactersSupport, hasCapabilitiesSupport, hasFedSharesOptionShareSupport, request.redirectedServer);
  597. }
  598. } else {
  599. // NSLog(@"Error parsing JSON: data is null");
  600. failure(response, nil, request.redirectedServer);
  601. }
  602. } failure:^(NSHTTPURLResponse *response, NSData *responseData, NSError *error) {
  603. failure(response, error, request.redirectedServer);
  604. }];
  605. }
  606. - (void) readSharedByServer: (NSString *) path
  607. onCommunication:(OCCommunication *)sharedOCCommunication
  608. successRequest:(void(^)(NSHTTPURLResponse *response, NSArray *listOfShared, NSString *redirectedServer)) successRequest
  609. failureRequest:(void(^)(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer)) failureRequest {
  610. path = [path encodeString:NSUTF8StringEncoding];
  611. path = [path stringByAppendingString:k_url_acces_shared_api];
  612. OCWebDAVClient *request = [OCWebDAVClient new];
  613. request = [self getRequestWithCredentials:request];
  614. [request listSharedByServer:path onCommunication:sharedOCCommunication success:^(NSHTTPURLResponse *response, id responseObject) {
  615. if (successRequest) {
  616. NSData *responseData = (NSData*) responseObject;
  617. OCXMLSharedParser *parser = [[OCXMLSharedParser alloc]init];
  618. //NSLog(@"response: %@", [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]);
  619. [parser initParserWithData:responseData];
  620. NSMutableArray *sharedList = [parser.shareList mutableCopy];
  621. //Return success
  622. successRequest(response, sharedList, request.redirectedServer);
  623. }
  624. } failure:^(NSHTTPURLResponse *response, NSData *responseData, NSError *error) {
  625. failureRequest(response, error, request.redirectedServer);
  626. }];
  627. }
  628. - (void) readSharedByServer: (NSString *) serverPath andPath: (NSString *) path
  629. onCommunication:(OCCommunication *)sharedOCCommunication
  630. successRequest:(void(^)(NSHTTPURLResponse *response, NSArray *listOfShared, NSString *redirectedServer)) successRequest
  631. failureRequest:(void(^)(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer)) failureRequest {
  632. serverPath = [serverPath encodeString:NSUTF8StringEncoding];
  633. serverPath = [serverPath stringByAppendingString:k_url_acces_shared_api];
  634. path = [path encodeString:NSUTF8StringEncoding];
  635. OCWebDAVClient *request = [OCWebDAVClient new];
  636. request = [self getRequestWithCredentials:request];
  637. [request listSharedByServer:serverPath andPath:path onCommunication:sharedOCCommunication success:^(NSHTTPURLResponse *response, id responseObject) {
  638. if (successRequest) {
  639. NSData *responseData = (NSData*) responseObject;
  640. OCXMLSharedParser *parser = [[OCXMLSharedParser alloc]init];
  641. // NSString *str = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
  642. // NSLog(@"responseDataReadSharedByServer:andPath: %@", str);
  643. // NSLog(@"pathFolders: %@", path);
  644. // NSLog(@"serverPath: %@", serverPath);
  645. [parser initParserWithData:responseData];
  646. NSMutableArray *sharedList = [parser.shareList mutableCopy];
  647. //Return success
  648. successRequest(response, sharedList, request.redirectedServer);
  649. }
  650. } failure:^(NSHTTPURLResponse *response, NSData *responseData, NSError *error) {
  651. failureRequest(response, error, request.redirectedServer);
  652. }];
  653. }
  654. - (void) shareFileOrFolderByServer: (NSString *) serverPath andFileOrFolderPath: (NSString *) filePath andPassword:(NSString *)password
  655. onCommunication:(OCCommunication *)sharedOCCommunication
  656. successRequest:(void(^)(NSHTTPURLResponse *response, NSString *token, NSString *redirectedServer)) successRequest
  657. failureRequest:(void(^)(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer)) failureRequest {
  658. serverPath = [serverPath encodeString:NSUTF8StringEncoding];
  659. serverPath = [serverPath stringByAppendingString:k_url_acces_shared_api];
  660. OCWebDAVClient *request = [OCWebDAVClient new];
  661. request = [self getRequestWithCredentials:request];
  662. [request shareByLinkFileOrFolderByServer:serverPath andPath:filePath andPassword:password onCommunication:sharedOCCommunication success:^(NSHTTPURLResponse *response, id responseObject) {
  663. NSData *responseData = (NSData*) responseObject;
  664. OCXMLShareByLinkParser *parser = [[OCXMLShareByLinkParser alloc]init];
  665. // NSLog(@"response: %@", [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]);
  666. [parser initParserWithData:responseData];
  667. switch (parser.statusCode) {
  668. case kOCSharedAPISuccessful:
  669. {
  670. NSString *url = parser.url;
  671. NSString *token = parser.token;
  672. if (url != nil) {
  673. successRequest(response, url, request.redirectedServer);
  674. }else if (token != nil){
  675. //We remove the \n and the empty spaces " "
  676. token = [token stringByReplacingOccurrencesOfString:@"\n" withString:@""];
  677. token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
  678. successRequest(response, token, request.redirectedServer);
  679. }else{
  680. NSError *error = [UtilsFramework getErrorWithCode:parser.statusCode andCustomMessageFromTheServer:parser.message];
  681. failureRequest(response, error, request.redirectedServer);
  682. }
  683. break;
  684. }
  685. default:
  686. {
  687. NSError *error = [UtilsFramework getErrorWithCode:parser.statusCode andCustomMessageFromTheServer:parser.message];
  688. failureRequest(response, error, request.redirectedServer);
  689. }
  690. }
  691. } failure:^(NSHTTPURLResponse *response, NSData *responseData, NSError *error) {
  692. failureRequest(response, error, request.redirectedServer);
  693. }];
  694. }
  695. - (void) shareFileOrFolderByServer: (NSString *) serverPath andFileOrFolderPath: (NSString *) filePath
  696. onCommunication:(OCCommunication *)sharedOCCommunication
  697. successRequest:(void(^)(NSHTTPURLResponse *response, NSString *shareLink, NSString *redirectedServer)) successRequest
  698. failureRequest:(void(^)(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer)) failureRequest {
  699. serverPath = [serverPath encodeString:NSUTF8StringEncoding];
  700. serverPath = [serverPath stringByAppendingString:k_url_acces_shared_api];
  701. OCWebDAVClient *request = [OCWebDAVClient new];
  702. request = [self getRequestWithCredentials:request];
  703. [request shareByLinkFileOrFolderByServer:serverPath andPath:filePath onCommunication:sharedOCCommunication success:^(NSHTTPURLResponse *response, id responseObject) {
  704. NSData *responseData = (NSData*) responseObject;
  705. OCXMLShareByLinkParser *parser = [[OCXMLShareByLinkParser alloc]init];
  706. // NSLog(@"response: %@", [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]);
  707. [parser initParserWithData:responseData];
  708. switch (parser.statusCode) {
  709. case kOCSharedAPISuccessful:
  710. {
  711. NSString *url = parser.url;
  712. NSString *token = parser.token;
  713. if (url != nil) {
  714. successRequest(response, url, request.redirectedServer);
  715. }else if (token != nil){
  716. //We remove the \n and the empty spaces " "
  717. token = [token stringByReplacingOccurrencesOfString:@"\n" withString:@""];
  718. token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
  719. successRequest(response, token, request.redirectedServer);
  720. }else{
  721. NSError *error = [UtilsFramework getErrorWithCode:parser.statusCode andCustomMessageFromTheServer:parser.message];
  722. failureRequest(response, error, request.redirectedServer);
  723. }
  724. break;
  725. }
  726. default:
  727. {
  728. NSError *error = [UtilsFramework getErrorWithCode:parser.statusCode andCustomMessageFromTheServer:parser.message];
  729. failureRequest(response, error, request.redirectedServer);
  730. }
  731. }
  732. } failure:^(NSHTTPURLResponse *response, NSData *responseData, NSError *error) {
  733. failureRequest(response, error, request.redirectedServer);
  734. }];
  735. }
  736. - (void)shareWith:(NSString *)userOrGroup shareeType:(NSInteger)shareeType inServer:(NSString *) serverPath andFileOrFolderPath:(NSString *) filePath andPermissions:(NSInteger) permissions onCommunication:(OCCommunication *)sharedOCCommunication
  737. successRequest:(void(^)(NSHTTPURLResponse *response, NSString *redirectedServer))successRequest
  738. failureRequest:(void(^)(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer))failureRequest{
  739. serverPath = [serverPath encodeString:NSUTF8StringEncoding];
  740. serverPath = [serverPath stringByAppendingString:k_url_acces_shared_api];
  741. userOrGroup = [userOrGroup encodeString:NSUTF8StringEncoding];
  742. OCWebDAVClient *request = [OCWebDAVClient new];
  743. request = [self getRequestWithCredentials:request];
  744. [request shareWith:userOrGroup shareeType:shareeType inServer:serverPath andPath:filePath andPermissions:permissions onCommunication:sharedOCCommunication success:^(NSHTTPURLResponse *response, id responseObject) {
  745. NSData *responseData = (NSData*) responseObject;
  746. OCXMLShareByLinkParser *parser = [[OCXMLShareByLinkParser alloc]init];
  747. // NSLog(@"response: %@", [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]);
  748. [parser initParserWithData:responseData];
  749. switch (parser.statusCode) {
  750. case kOCSharedAPISuccessful:
  751. {
  752. successRequest(response, request.redirectedServer);
  753. break;
  754. }
  755. default:
  756. {
  757. NSError *error = [UtilsFramework getErrorWithCode:parser.statusCode andCustomMessageFromTheServer:parser.message];
  758. failureRequest(response, error, request.redirectedServer);
  759. }
  760. }
  761. } failure:^(NSHTTPURLResponse *response, NSData *responseData, NSError *error) {
  762. failureRequest(response, error, request.redirectedServer);
  763. }];
  764. }
  765. - (void) unShareFileOrFolderByServer: (NSString *) path andIdRemoteShared: (NSInteger) idRemoteShared
  766. onCommunication:(OCCommunication *)sharedOCCommunication
  767. successRequest:(void(^)(NSHTTPURLResponse *response, NSString *redirectedServer)) successRequest
  768. failureRequest:(void(^)(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer)) failureRequest{
  769. path = [path encodeString:NSUTF8StringEncoding];
  770. path = [path stringByAppendingString:k_url_acces_shared_api];
  771. path = [path stringByAppendingString:[NSString stringWithFormat:@"/%ld",(long)idRemoteShared]];
  772. OCWebDAVClient *request = [OCWebDAVClient new];
  773. request = [self getRequestWithCredentials:request];
  774. [request unShareFileOrFolderByServer:path onCommunication:sharedOCCommunication success:^(NSHTTPURLResponse *response, id responseObject) {
  775. if (successRequest) {
  776. //Return success
  777. successRequest(response, request.redirectedServer);
  778. }
  779. } failure:^(NSHTTPURLResponse *response, NSData *responseData, NSError *error) {
  780. failureRequest(response, error, request.redirectedServer);
  781. }];
  782. }
  783. - (void) isShareFileOrFolderByServer: (NSString *) path andIdRemoteShared: (NSInteger) idRemoteShared
  784. onCommunication:(OCCommunication *)sharedOCCommunication
  785. successRequest:(void(^)(NSHTTPURLResponse *response, NSString *redirectedServer, BOOL isShared, id shareDto)) successRequest
  786. failureRequest:(void(^)(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer)) failureRequest {
  787. path = [path encodeString:NSUTF8StringEncoding];
  788. path = [path stringByAppendingString:k_url_acces_shared_api];
  789. path = [path stringByAppendingString:[NSString stringWithFormat:@"/%ld",(long)idRemoteShared]];
  790. OCWebDAVClient *request = [OCWebDAVClient new];
  791. request = [self getRequestWithCredentials:request];
  792. [request isShareFileOrFolderByServer:path onCommunication:sharedOCCommunication success:^(NSHTTPURLResponse *response, id responseObject) {
  793. if (successRequest) {
  794. NSData *responseData = (NSData*) responseObject;
  795. OCXMLSharedParser *parser = [[OCXMLSharedParser alloc]init];
  796. // NSLog(@"response: %@", [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]);
  797. [parser initParserWithData:responseData];
  798. BOOL isShared = NO;
  799. OCSharedDto *shareDto = nil;
  800. if (parser.shareList) {
  801. NSMutableArray *sharedList = [parser.shareList mutableCopy];
  802. if ([sharedList count] > 0) {
  803. isShared = YES;
  804. shareDto = [sharedList objectAtIndex:0];
  805. }
  806. }
  807. //Return success
  808. successRequest(response, request.redirectedServer, isShared, shareDto);
  809. }
  810. } failure:^(NSHTTPURLResponse *response, NSData *responseData, NSError *error) {
  811. failureRequest(response, error, request.redirectedServer);
  812. }];
  813. }
  814. - (void) updateShare:(NSInteger)shareId ofServerPath:(NSString *)serverPath withPasswordProtect:(NSString*)password andExpirationTime:(NSString*)expirationTime andPermissions:(NSInteger)permissions
  815. onCommunication:(OCCommunication *)sharedOCCommunication
  816. successRequest:(void(^)(NSHTTPURLResponse *response, NSString *redirectedServer)) successRequest
  817. failureRequest:(void(^)(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer)) failureRequest{
  818. serverPath = [serverPath encodeString:NSUTF8StringEncoding];
  819. serverPath = [serverPath stringByAppendingString:k_url_acces_shared_api];
  820. serverPath = [serverPath stringByAppendingString:[NSString stringWithFormat:@"/%ld",(long)shareId]];
  821. OCWebDAVClient *request = [OCWebDAVClient new];
  822. request = [self getRequestWithCredentials:request];
  823. [request updateShareItem:shareId ofServerPath:serverPath withPasswordProtect:password andExpirationTime:expirationTime andPermissions:permissions onCommunication:sharedOCCommunication success:^(NSHTTPURLResponse *response, id responseObject) {
  824. NSData *responseData = (NSData*) responseObject;
  825. OCXMLShareByLinkParser *parser = [[OCXMLShareByLinkParser alloc]init];
  826. // NSLog(@"response: %@", [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]);
  827. [parser initParserWithData:responseData];
  828. switch (parser.statusCode) {
  829. case kOCSharedAPISuccessful:
  830. {
  831. successRequest(response, request.redirectedServer);
  832. break;
  833. }
  834. default:
  835. {
  836. NSError *error = [UtilsFramework getErrorWithCode:parser.statusCode andCustomMessageFromTheServer:parser.message];
  837. failureRequest(response, error, request.redirectedServer);
  838. }
  839. }
  840. } failure:^(NSHTTPURLResponse *response, NSData *responseData, NSError *error) {
  841. failureRequest(response, error, request.redirectedServer);
  842. }];
  843. }
  844. - (void) searchUsersAndGroupsWith:(NSString *)searchString forPage:(NSInteger)page with:(NSInteger)resultsPerPage ofServer:(NSString*)serverPath onCommunication:(OCCommunication *)sharedOCComunication successRequest:(void(^)(NSHTTPURLResponse *response, NSArray *itemList, NSString *redirectedServer)) successRequest failureRequest:(void(^)(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer)) failureRequest{
  845. serverPath = [serverPath encodeString:NSUTF8StringEncoding];
  846. serverPath = [serverPath stringByAppendingString:k_url_access_sharee_api];
  847. searchString = [searchString encodeString:NSUTF8StringEncoding];
  848. OCWebDAVClient *request = [OCWebDAVClient new];
  849. request = [self getRequestWithCredentials:request];
  850. [request searchUsersAndGroupsWith:searchString forPage:page with:resultsPerPage ofServer:serverPath onCommunication:sharedOCComunication success:^(NSHTTPURLResponse *response, id responseObject) {
  851. NSData *responseData = (NSData*) responseObject;
  852. NSMutableArray *itemList = [NSMutableArray new];
  853. //Parse
  854. NSError *error;
  855. NSDictionary *jsongParsed = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error];
  856. if (error == nil) {
  857. NSDictionary *ocsDict = [jsongParsed valueForKey:@"ocs"];
  858. NSDictionary *metaDict = [ocsDict valueForKey:@"meta"];
  859. NSInteger statusCode = [[metaDict valueForKey:@"statuscode"] integerValue];
  860. if (statusCode == kOCShareeAPISuccessful || statusCode == kOCSharedAPISuccessful) {
  861. NSDictionary *dataDict = [ocsDict valueForKey:@"data"];
  862. NSArray *exactDict = [dataDict valueForKey:@"exact"];
  863. NSArray *usersFounded = [dataDict valueForKey:@"users"];
  864. NSArray *groupsFounded = [dataDict valueForKey:@"groups"];
  865. NSArray *usersRemote = [dataDict valueForKey:@"remotes"];
  866. NSArray *usersExact = [exactDict valueForKey:@"users"];
  867. NSArray *groupsExact = [exactDict valueForKey:@"groups"];
  868. NSArray *remotesExact = [exactDict valueForKey:@"remotes"];
  869. [self addUserItemOfType:shareTypeUser fromArray:usersFounded ToList:itemList];
  870. [self addUserItemOfType:shareTypeUser fromArray:usersExact ToList:itemList];
  871. [self addUserItemOfType:shareTypeRemote fromArray:usersRemote ToList:itemList];
  872. [self addUserItemOfType:shareTypeRemote fromArray:remotesExact ToList:itemList];
  873. [self addGroupItemFromArray:groupsFounded ToList:itemList];
  874. [self addGroupItemFromArray:groupsExact ToList:itemList];
  875. }else{
  876. NSString *message = (NSString*)[metaDict objectForKey:@"message"];
  877. if ([message isKindOfClass:[NSNull class]]) {
  878. message = @"";
  879. }
  880. NSError *error = [UtilsFramework getErrorWithCode:statusCode andCustomMessageFromTheServer:message];
  881. failureRequest(response, error, request.redirectedServer);
  882. }
  883. //Return success
  884. successRequest(response, itemList, request.redirectedServer);
  885. }
  886. } failure:^(NSHTTPURLResponse *response, NSData *responseData, NSError *error) {
  887. failureRequest(response, error, request.redirectedServer);
  888. }];
  889. }
  890. - (void)getSharePermissionsFile:(NSString *)fileName onCommunication:(OCCommunication *)sharedOCComunication successRequest:(void(^)(NSHTTPURLResponse *response, NSString *permissions, NSString *redirectedServer)) successRequest failureRequest:(void(^)(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer)) failureRequest{
  891. fileName = [fileName encodeString:NSUTF8StringEncoding];
  892. OCWebDAVClient *request = [OCWebDAVClient new];
  893. request = [self getRequestWithCredentials:request];
  894. [request getSharePermissionsFile:fileName onCommunication:sharedOCComunication success:^(NSHTTPURLResponse *response, id responseObject) {
  895. if (successRequest) {
  896. NSString *permissions;
  897. NSData *responseData = (NSData *)responseObject;
  898. NSString *newStr = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
  899. NSLog(@"newStrReadFolder: %@", newStr);
  900. OCXMLParser *parser = [[OCXMLParser alloc]init];
  901. [parser initParserWithData:responseData];
  902. NSMutableArray *directoryList = [parser.directoryList mutableCopy];
  903. if ([directoryList count] == 1) {
  904. OCFileDto *file = [directoryList objectAtIndex:0];
  905. permissions = file.permissions;
  906. }
  907. //Return success
  908. successRequest(response, permissions, request.redirectedServer);
  909. }
  910. } failure:^(NSHTTPURLResponse *response, NSData *responseData, NSError *error) {
  911. failureRequest(response, error, request.redirectedServer);
  912. }];
  913. }
  914. - (void) getCapabilitiesOfServer:(NSString*)serverPath onCommunication:(OCCommunication *)sharedOCComunication successRequest:(void(^)(NSHTTPURLResponse *response, OCCapabilities *capabilities, NSString *redirectedServer)) successRequest failureRequest:(void(^)(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer)) failureRequest{
  915. serverPath = [serverPath encodeString:NSUTF8StringEncoding];
  916. serverPath = [serverPath stringByAppendingString:k_url_capabilities];
  917. OCWebDAVClient *request = [OCWebDAVClient new];
  918. request = [self getRequestWithCredentials:request];
  919. [request getCapabilitiesOfServer:serverPath onCommunication:sharedOCComunication success:^(NSHTTPURLResponse *response, id responseObject) {
  920. NSData *responseData = (NSData*) responseObject;
  921. //Parse
  922. NSError *error;
  923. NSDictionary *jsongParsed = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error];
  924. NSLog(@"dic: %@",jsongParsed);
  925. OCCapabilities *capabilities = [OCCapabilities new];
  926. if (jsongParsed.allKeys > 0) {
  927. NSDictionary *ocs = [jsongParsed valueForKey:@"ocs"];
  928. NSDictionary *data = [ocs valueForKey:@"data"];
  929. NSDictionary *version = [data valueForKey:@"version"];
  930. if (ocs.count > 0 && data.count > 0 && version.count > 0) {
  931. //VERSION
  932. NSNumber *versionMajorNumber = (NSNumber*) [version valueForKey:@"major"];
  933. NSNumber *versionMinorNumber = (NSNumber*) [version valueForKey:@"minor"];
  934. NSNumber *versionMicroNumber = (NSNumber*) [version valueForKey:@"micro"];
  935. capabilities.versionMajor = versionMajorNumber.integerValue;
  936. capabilities.versionMinor = versionMinorNumber.integerValue;
  937. capabilities.versionMicro = versionMicroNumber.integerValue;
  938. capabilities.versionString = (NSString*)[version valueForKey:@"string"];
  939. capabilities.versionEdition = (NSString*)[version valueForKey:@"edition"];
  940. NSDictionary *capabilitiesDict = [data valueForKey:@"capabilities"];
  941. NSDictionary *core = [capabilitiesDict valueForKey:@"core"];
  942. //CORE
  943. NSNumber *corePollIntervalNumber = (NSNumber*)[core valueForKey:@"pollinterval"];
  944. capabilities.corePollInterval = corePollIntervalNumber.integerValue;
  945. NSDictionary *fileSharing = [capabilitiesDict valueForKey:@"files_sharing"];
  946. //FILE SHARING
  947. NSNumber *fileSharingAPIEnabledNumber = (NSNumber*)[fileSharing valueForKey:@"api_enabled"];
  948. NSNumber *filesSharingReSharingEnabledNumber = (NSNumber*)[fileSharing valueForKey:@"resharing"];
  949. capabilities.isFilesSharingAPIEnabled = fileSharingAPIEnabledNumber.boolValue;
  950. capabilities.isFilesSharingReSharingEnabled = filesSharingReSharingEnabledNumber.boolValue;
  951. NSDictionary *fileSharingPublic = [fileSharing valueForKey:@"public"];
  952. NSNumber *filesSharingShareLinkEnabledNumber = (NSNumber*)[fileSharingPublic valueForKey:@"enabled"];
  953. NSNumber *filesSharingAllowPublicUploadsEnabledNumber = (NSNumber*)[fileSharingPublic valueForKey:@"upload"];
  954. NSNumber *filesSharingAllowUserSendMailNotificationAboutShareLinkEnabledNumber = (NSNumber*)[fileSharingPublic valueForKey:@"send_mail"];
  955. capabilities.isFilesSharingShareLinkEnabled = filesSharingShareLinkEnabledNumber.boolValue;
  956. capabilities.isFilesSharingAllowPublicUploadsEnabled = filesSharingAllowPublicUploadsEnabledNumber.boolValue;
  957. capabilities.isFilesSharingAllowUserSendMailNotificationAboutShareLinkEnabled = filesSharingAllowUserSendMailNotificationAboutShareLinkEnabledNumber.boolValue;
  958. NSDictionary *fileSharingPublicExpireDate = [fileSharingPublic valueForKey:@"expire_date"];
  959. NSNumber *filesSharingExpireDateByDefaultEnabledNumber = (NSNumber*)[fileSharingPublicExpireDate valueForKey:@"enabled"];
  960. NSNumber *filesSharingExpireDateEnforceEnabledNumber = (NSNumber*)[fileSharingPublicExpireDate valueForKey:@"enforced"];
  961. NSNumber *filesSharingExpireDateDaysNumber = (NSNumber*)[fileSharingPublicExpireDate valueForKey:@"days"];
  962. capabilities.isFilesSharingExpireDateByDefaultEnabled = filesSharingExpireDateByDefaultEnabledNumber.boolValue;
  963. capabilities.isFilesSharingExpireDateEnforceEnabled = filesSharingExpireDateEnforceEnabledNumber.boolValue;
  964. capabilities.filesSharingExpireDateDaysNumber = filesSharingExpireDateDaysNumber.integerValue;
  965. NSDictionary *fileSharingPublicPassword = [fileSharingPublic valueForKey:@"password"];
  966. NSNumber *filesSharingPasswordEnforcedEnabledNumber = (NSNumber*)[fileSharingPublicPassword valueForKey:@"enforced"];
  967. capabilities.isFilesSharingPasswordEnforcedEnabled = filesSharingPasswordEnforcedEnabledNumber.boolValue;;
  968. NSDictionary *fileSharingUser = [fileSharing valueForKey:@"user"];
  969. NSNumber *filesSharingAllowUserSendMailNotificationAboutOtherUsersEnabledNumber = (NSNumber*)[fileSharingUser valueForKey:@"send_mail"];
  970. capabilities.isFilesSharingAllowUserSendMailNotificationAboutOtherUsersEnabled = filesSharingAllowUserSendMailNotificationAboutOtherUsersEnabledNumber.boolValue;
  971. //FEDERATION
  972. NSDictionary *fileSharingFederation = [fileSharing valueForKey:@"federation"];
  973. NSNumber *filesSharingAllowUserSendSharesToOtherServersEnabledNumber = (NSNumber*)[fileSharingFederation valueForKey:@"outgoing"];
  974. NSNumber *filesSharingAllowUserReceiveSharesToOtherServersEnabledNumber = (NSNumber*)[fileSharingFederation valueForKey:@"incoming"];
  975. capabilities.isFilesSharingAllowUserSendSharesToOtherServersEnabled = filesSharingAllowUserSendSharesToOtherServersEnabledNumber.boolValue;
  976. capabilities.isFilesSharingAllowUserReceiveSharesToOtherServersEnabled = filesSharingAllowUserReceiveSharesToOtherServersEnabledNumber.boolValue;
  977. // EXTERNAL SITES
  978. NSDictionary *externalSitesDic = [capabilitiesDict valueForKey:@"external"];
  979. if (externalSitesDic) {
  980. NSArray *externalSitesArray = [externalSitesDic valueForKey:@"v1"];
  981. if (externalSitesArray)
  982. if ([[externalSitesArray objectAtIndex:0] isEqualToString:@"sites"])
  983. capabilities.isExternalSitesServerEnabled = YES;
  984. }
  985. //FILES
  986. NSDictionary *files = [capabilitiesDict valueForKey:@"files"];
  987. NSNumber *fileBigFileChunkingEnabledNumber = (NSNumber*)[files valueForKey:@"bigfilechunking"];
  988. NSNumber *fileUndeleteEnabledNumber = (NSNumber*)[files valueForKey:@"undelete"];
  989. NSNumber *fileVersioningEnabledNumber = (NSNumber*)[files valueForKey:@"versioning"];
  990. capabilities.isFileBigFileChunkingEnabled = fileBigFileChunkingEnabledNumber.boolValue;
  991. capabilities.isFileUndeleteEnabled = fileUndeleteEnabledNumber.boolValue;
  992. capabilities.isFileVersioningEnabled = fileVersioningEnabledNumber.boolValue;
  993. //THEMING
  994. NSDictionary *theming = [capabilitiesDict valueForKey:@"theming"];
  995. if ([theming count] > 0) {
  996. if ([theming valueForKey:@"background"] && ![[theming valueForKey:@"background"] isEqual:[NSNull null]])
  997. capabilities.themingBackground = [theming valueForKey:@"background"];
  998. if ([theming valueForKey:@"color"] && ![[theming valueForKey:@"color"] isEqual:[NSNull null]])
  999. capabilities.themingColor = [theming valueForKey:@"color"];
  1000. if ([theming valueForKey:@"logo"] && ![[theming valueForKey:@"logo"] isEqual:[NSNull null]])
  1001. capabilities.themingLogo = [theming valueForKey:@"logo"];
  1002. if ([theming valueForKey:@"name"] && ![[theming valueForKey:@"name"] isEqual:[NSNull null]])
  1003. capabilities.themingName = [theming valueForKey:@"name"];
  1004. if ([theming valueForKey:@"slogan"] && ![[theming valueForKey:@"slogan"] isEqual:[NSNull null]])
  1005. capabilities.themingSlogan = [theming valueForKey:@"slogan"];
  1006. if ([theming valueForKey:@"url"] && ![[theming valueForKey:@"url"] isEqual:[NSNull null]])
  1007. capabilities.themingUrl = [theming valueForKey:@"url"];
  1008. }
  1009. //CLIENT SIDE ENCRYPTION
  1010. NSDictionary *clientSideEncryption = [capabilitiesDict valueForKey:@"client-side-encryption"];
  1011. if ([clientSideEncryption count] > 0) {
  1012. NSNumber *clientSideEncryptionEnabled = (NSNumber*)[clientSideEncryption valueForKey:@"enabled"];
  1013. capabilities.isClientSideEncryptionEnabled = clientSideEncryptionEnabled.boolValue;
  1014. if ([clientSideEncryption valueForKey:@"api-version"] && ![[clientSideEncryption valueForKey:@"api-version"] isEqual:[NSNull null]])
  1015. capabilities.clientSideEncryptionVersion = [clientSideEncryption valueForKey:@"api-version"];
  1016. }
  1017. }
  1018. successRequest(response, capabilities, request.redirectedServer);
  1019. } else {
  1020. failureRequest(response, error, request.redirectedServer);
  1021. }
  1022. } failure:^(NSHTTPURLResponse *response, NSData *responseData, NSError *error) {
  1023. failureRequest(response, error, request.redirectedServer);
  1024. }];
  1025. }
  1026. #pragma mark - Remote thumbnails
  1027. - (NSURLSessionTask *) getRemoteThumbnailByServer:(NSString*)serverPath ofFilePath:(NSString *)filePath withWidth:(NSInteger)fileWidth andHeight:(NSInteger)fileHeight onCommunication:(OCCommunication *)sharedOCComunication
  1028. successRequest:(void(^)(NSHTTPURLResponse *response, NSData *thumbnail, NSString *redirectedServer)) successRequest
  1029. failureRequest:(void(^)(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer)) failureRequest {
  1030. serverPath = [serverPath encodeString:NSUTF8StringEncoding];
  1031. serverPath = [serverPath stringByAppendingString:k_url_thumbnails];
  1032. filePath = [filePath encodeString:NSUTF8StringEncoding];
  1033. OCWebDAVClient *request = [OCWebDAVClient new];
  1034. request = [self getRequestWithCredentials:request];
  1035. OCHTTPRequestOperation *operation = [request getRemoteThumbnailByServer:serverPath ofFilePath:filePath withWidth:fileWidth andHeight:fileHeight onCommunication:sharedOCComunication
  1036. success:^(NSHTTPURLResponse *response, id responseObject) {
  1037. NSData *responseData = (NSData*) responseObject;
  1038. successRequest(response, responseData, request.redirectedServer);
  1039. } failure:^(NSHTTPURLResponse *response, id _Nullable responseObject, NSError * _Nonnull error) {
  1040. failureRequest(response, error, request.redirectedServer);
  1041. }];
  1042. [operation resume];
  1043. return operation;
  1044. }
  1045. #pragma mark - Notification Server
  1046. - (void)getNotificationServer:(NSString*)serverPath onCommunication:(OCCommunication *)sharedOCComunication successRequest:(void(^)(NSHTTPURLResponse *response, NSArray *listOfNotifications, NSString *redirectedServer)) successRequest failureRequest:(void(^)(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer)) failureRequest {
  1047. serverPath = [serverPath encodeString:NSUTF8StringEncoding];
  1048. serverPath = [serverPath stringByAppendingString:k_url_acces_remote_notification_api];
  1049. OCWebDAVClient *request = [OCWebDAVClient new];
  1050. request = [self getRequestWithCredentials:request];
  1051. [request getNotificationServer:serverPath onCommunication:sharedOCComunication success:^(NSHTTPURLResponse *response, id responseObject) {
  1052. NSData *responseData = (NSData*) responseObject;
  1053. //Parse
  1054. NSError *error;
  1055. NSDictionary *jsongParsed = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error];
  1056. NSLog(@"[LOG] Notifications : %@",jsongParsed);
  1057. NSMutableArray *listOfNotifications = [NSMutableArray new];
  1058. if (jsongParsed.allKeys > 0) {
  1059. NSDictionary *ocs = [jsongParsed valueForKey:@"ocs"];
  1060. NSDictionary *meta = [ocs valueForKey:@"meta"];
  1061. NSDictionary *datas = [ocs valueForKey:@"data"];
  1062. NSInteger statusCode = [[meta valueForKey:@"statuscode"] integerValue];
  1063. if (statusCode == kOCNotificationAPINoContent || statusCode == kOCNotificationAPISuccessful) {
  1064. for (NSDictionary *data in datas) {
  1065. OCNotifications *notification = [OCNotifications new];
  1066. if ([data valueForKey:@"notification_id"] && ![[data valueForKey:@"notification_id"] isEqual:[NSNull null]])
  1067. notification.idNotification = [[data valueForKey:@"notification_id"] integerValue];
  1068. if ([data valueForKey:@"app"] && ![[data valueForKey:@"app"] isEqual:[NSNull null]])
  1069. notification.application = [data valueForKey:@"app"];
  1070. if ([data valueForKey:@"user"] && ![[data valueForKey:@"user"] isEqual:[NSNull null]])
  1071. notification.user = [data valueForKey:@"user"];
  1072. if ([data valueForKey:@"datetime"] && ![[data valueForKey:@"datetime"] isEqual:[NSNull null]]) {
  1073. NSString *dateString = [data valueForKey:@"datetime"];
  1074. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  1075. NSLocale *enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
  1076. [dateFormatter setLocale:enUSPOSIXLocale];
  1077. [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZZ"];
  1078. notification.date = [dateFormatter dateFromString:dateString];
  1079. }
  1080. if ([data valueForKey:@"object_type"] && ![[data valueForKey:@"object_type"] isEqual:[NSNull null]])
  1081. notification.typeObject = [data valueForKey:@"object_type"];
  1082. if ([data valueForKey:@"object_id"] && ![[data valueForKey:@"object_id"] isEqual:[NSNull null]])
  1083. notification.idObject = [data valueForKey:@"object_id"];
  1084. if ([data valueForKey:@"subject"] && ![[data valueForKey:@"subject"] isEqual:[NSNull null]])
  1085. notification.subject = [data valueForKey:@"subject"];
  1086. if ([data valueForKey:@"subjectRich"] && ![[data valueForKey:@"subjectRich"] isEqual:[NSNull null]])
  1087. notification.subjectRich = [data valueForKey:@"subjectRich"];
  1088. if ([data valueForKey:@"subjectRichParameters"] && ![[data valueForKey:@"subjectRichParameters"] isEqual:[NSNull null]])
  1089. notification.subjectRichParameters = [data valueForKey:@"subjectRichParameters"];
  1090. if ([data valueForKey:@"message"] && ![[data valueForKey:@"message"] isEqual:[NSNull null]])
  1091. notification.message = [data valueForKey:@"message"];
  1092. if ([data valueForKey:@"messageRich"] && ![[data valueForKey:@"messageRich"] isEqual:[NSNull null]])
  1093. notification.messageRich = [data valueForKey:@"messageRich"];
  1094. if ([data valueForKey:@"messageRichParameters"] && ![[data valueForKey:@"messageRichParameters"] isEqual:[NSNull null]])
  1095. notification.messageRichParameters = [data valueForKey:@"messageRichParameters"];
  1096. if ([data valueForKey:@"link"] && ![[data valueForKey:@"link"] isEqual:[NSNull null]])
  1097. notification.link = [data valueForKey:@"link"];
  1098. if ([data valueForKey:@"icon"] && ![[data valueForKey:@"icon"] isEqual:[NSNull null]])
  1099. notification.icon = [data valueForKey:@"icon"];
  1100. /* ACTION */
  1101. NSMutableArray *actionsArr = [NSMutableArray new];
  1102. NSDictionary *actions = [data valueForKey:@"actions"];
  1103. for (NSDictionary *action in actions) {
  1104. OCNotificationsAction *notificationAction = [OCNotificationsAction new];
  1105. if ([action valueForKey:@"label"] && ![[action valueForKey:@"label"] isEqual:[NSNull null]])
  1106. notificationAction.label = [action valueForKey:@"label"];
  1107. if ([action valueForKey:@"link"] && ![[action valueForKey:@"link"] isEqual:[NSNull null]])
  1108. notificationAction.link = [action valueForKey:@"link"];
  1109. if ([action valueForKey:@"primary"] && ![[action valueForKey:@"primary"] isEqual:[NSNull null]])
  1110. notificationAction.primary = [[action valueForKey:@"primary"] boolValue];
  1111. if ([action valueForKey:@"type"] && ![[action valueForKey:@"type"] isEqual:[NSNull null]])
  1112. notificationAction.type = [action valueForKey:@"type"];
  1113. [actionsArr addObject:notificationAction];
  1114. }
  1115. notification.actions = [[NSArray alloc] initWithArray:actionsArr];
  1116. [listOfNotifications addObject:notification];
  1117. }
  1118. } else {
  1119. NSString *message = (NSString*)[meta objectForKey:@"message"];
  1120. if ([message isKindOfClass:[NSNull class]]) {
  1121. message = @"";
  1122. }
  1123. NSError *error = [UtilsFramework getErrorWithCode:statusCode andCustomMessageFromTheServer:message];
  1124. failureRequest(response, error, request.redirectedServer);
  1125. }
  1126. }
  1127. //Return success
  1128. successRequest(response, listOfNotifications, request.redirectedServer);
  1129. } failure:^(NSHTTPURLResponse *response, NSData *responseData, NSError *error) {
  1130. failureRequest(response, error, request.redirectedServer);
  1131. }];
  1132. }
  1133. - (void)setNotificationServer:(NSString*)serverPath type:(NSString *)type onCommunication:(OCCommunication *)sharedOCComunication successRequest:(void (^)(NSHTTPURLResponse *, NSString *))successRequest failureRequest:(void (^)(NSHTTPURLResponse *, NSError *, NSString *))failureRequest {
  1134. serverPath = [serverPath encodeString:NSUTF8StringEncoding];
  1135. OCWebDAVClient *request = [OCWebDAVClient new];
  1136. request = [self getRequestWithCredentials:request];
  1137. __weak OCWebDAVClient *wrequest = request;
  1138. [request setNotificationServer:serverPath type:type onCommunication:sharedOCComunication success:^(NSHTTPURLResponse *response, id responseObject) {
  1139. successRequest(response, wrequest.redirectedServer);
  1140. } failure:^(NSHTTPURLResponse *response, NSData *responseData, NSError *error) {
  1141. failureRequest(response, error, wrequest.redirectedServer);
  1142. }];
  1143. }
  1144. - (void)subscribingNextcloudServerPush:(NSString *)serverPath pushTokenHash:(NSString *)pushTokenHash devicePublicKey:(NSString *)devicePublicKey proxyServerPath:(NSString *)proxyServerPath onCommunication:(OCCommunication *)sharedOCComunication successRequest:(void(^)(NSHTTPURLResponse *response, NSString *publicKey, NSString *deviceIdentifier, NSString *signature, NSString *redirectedServer)) successRequest failureRequest:(void (^)(NSHTTPURLResponse *, NSError *, NSString *))failureRequest {
  1145. serverPath = [serverPath encodeString:NSUTF8StringEncoding];
  1146. serverPath = [serverPath stringByAppendingString:k_url_acces_remote_subscribing_nextcloud_server_api];
  1147. OCWebDAVClient *request = [OCWebDAVClient new];
  1148. request = [self getRequestWithCredentials:request];
  1149. [request subscribingNextcloudServerPush:serverPath authorizationToken:_password pushTokenHash:pushTokenHash devicePublicKey:devicePublicKey proxyServerPath:proxyServerPath onCommunication:sharedOCComunication success:^(NSHTTPURLResponse *response, id responseObject) {
  1150. NSData *responseData = (NSData*) responseObject;
  1151. //Parse
  1152. NSError *error;
  1153. NSDictionary *jsongParsed = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error];
  1154. NSLog(@"[LOG] Subscribing at the Nextcloud server : %@",jsongParsed);
  1155. NSString *publicKey = [jsongParsed objectForKey:@"publicKey"];
  1156. NSString *deviceIdentifier = [jsongParsed objectForKey:@"deviceIdentifier"];
  1157. NSString *signature = [jsongParsed objectForKey:@"signature"];
  1158. successRequest(response, publicKey, deviceIdentifier, signature, request.redirectedServer);
  1159. } failure:^(NSHTTPURLResponse *response, NSData *responseData, NSError *error) {
  1160. failureRequest(response, error, request.redirectedServer);
  1161. }];
  1162. }
  1163. - (void)subscribingPushProxy:(NSString *)serverPath pushToken:(NSString *)pushToken deviceIdentifier:(NSString *)deviceIdentifier deviceIdentifierSignature:(NSString *)deviceIdentifierSignature userPublicKey:(NSString *)userPublicKey onCommunication:(OCCommunication *)sharedOCComunication successRequest:(void (^)(NSHTTPURLResponse *, NSString *redirectedServer))successRequest failureRequest:(void (^)(NSHTTPURLResponse *, NSError *, NSString *))failureRequest {
  1164. serverPath = [serverPath encodeString:NSUTF8StringEncoding];
  1165. serverPath = [serverPath stringByAppendingString:@"/devices"];
  1166. OCWebDAVClient *request = [OCWebDAVClient new];
  1167. request = [self getRequestWithCredentials:request];
  1168. [request subscribingPushProxy:serverPath authorizationToken:_password pushToken:pushToken deviceIdentifier:deviceIdentifier deviceIdentifierSignature:deviceIdentifierSignature userPublicKey:userPublicKey onCommunication:sharedOCComunication success:^(NSHTTPURLResponse *response, id responseObject) {
  1169. if (successRequest) {
  1170. //Return success
  1171. successRequest(response, request.redirectedServer);
  1172. }
  1173. } failure:^(NSHTTPURLResponse *response, NSData *responseData, NSError *error) {
  1174. failureRequest(response, error, request.redirectedServer);
  1175. }];
  1176. }
  1177. #pragma mark - Activity
  1178. - (void) getActivityServer:(NSString*)serverPath onCommunication:(OCCommunication *)sharedOCComunication successRequest:(void(^)(NSHTTPURLResponse *response, NSArray *listOfActivity, NSString *redirectedServer)) successRequest failureRequest:(void(^)(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer)) failureRequest {
  1179. serverPath = [serverPath encodeString:NSUTF8StringEncoding];
  1180. serverPath = [serverPath stringByAppendingString:k_url_acces_remote_activity_api];
  1181. OCWebDAVClient *request = [OCWebDAVClient new];
  1182. request = [self getRequestWithCredentials:request];
  1183. [request getActivityServer:serverPath onCommunication:sharedOCComunication success:^(NSHTTPURLResponse *response, id responseObject) {
  1184. NSData *responseData = (NSData*) responseObject;
  1185. //Parse
  1186. NSError *error;
  1187. NSDictionary *jsongParsed = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error];
  1188. NSLog(@"[LOG] Activity : %@",jsongParsed);
  1189. NSMutableArray *listOfActivity = [NSMutableArray new];
  1190. if (jsongParsed.allKeys > 0) {
  1191. NSDictionary *ocs = [jsongParsed valueForKey:@"ocs"];
  1192. NSDictionary *meta = [ocs valueForKey:@"meta"];
  1193. NSDictionary *datas = [ocs valueForKey:@"data"];
  1194. NSInteger statusCode = [[meta valueForKey:@"statuscode"] integerValue];
  1195. if (statusCode == kOCNotificationAPINoContent || statusCode == kOCNotificationAPISuccessful) {
  1196. for (NSDictionary *data in datas) {
  1197. OCActivity *activity = [OCActivity new];
  1198. if ([data valueForKey:@"id"] && ![[data valueForKey:@"id"] isEqual:[NSNull null]])
  1199. activity.idActivity = [[data valueForKey:@"id"] integerValue];
  1200. if ([data valueForKey:@"date"] && ![[data valueForKey:@"date"] isEqual:[NSNull null]]) {
  1201. NSString *dateString = [data valueForKey:@"date"];
  1202. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  1203. NSLocale *enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
  1204. [dateFormatter setLocale:enUSPOSIXLocale];
  1205. [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZZ"];
  1206. activity.date = [dateFormatter dateFromString:dateString];
  1207. }
  1208. if ([data valueForKey:@"file"] && ![[data valueForKey:@"file"] isEqual:[NSNull null]])
  1209. activity.file = [data valueForKey:@"file"];
  1210. if ([data valueForKey:@"link"] && ![[data valueForKey:@"link"] isEqual:[NSNull null]])
  1211. activity.link = [data valueForKey:@"link"];
  1212. if ([data valueForKey:@"message"] && ![[data valueForKey:@"message"] isEqual:[NSNull null]])
  1213. activity.message = [data valueForKey:@"message"];
  1214. if ([data valueForKey:@"subject"] && ![[data valueForKey:@"subject"] isEqual:[NSNull null]])
  1215. activity.subject = [data valueForKey:@"subject"];
  1216. [listOfActivity addObject:activity];
  1217. }
  1218. } else {
  1219. NSString *message = (NSString*)[meta objectForKey:@"message"];
  1220. if ([message isKindOfClass:[NSNull class]]) {
  1221. message = @"";
  1222. }
  1223. NSError *error = [UtilsFramework getErrorWithCode:statusCode andCustomMessageFromTheServer:message];
  1224. failureRequest(response, error, request.redirectedServer);
  1225. }
  1226. }
  1227. //Return success
  1228. successRequest(response, listOfActivity, request.redirectedServer);
  1229. } failure:^(NSHTTPURLResponse *response, NSData *responseData, NSError *error) {
  1230. failureRequest(response, error, request.redirectedServer);
  1231. }];
  1232. }
  1233. #pragma mark - External sites
  1234. - (void) getExternalSitesServer:(NSString*)serverPath onCommunication:(OCCommunication *)sharedOCComunication successRequest:(void(^)(NSHTTPURLResponse *response, NSArray *listOfExternalSites, NSString *redirectedServer)) successRequest failureRequest:(void(^)(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer)) failureRequest {
  1235. serverPath = [serverPath encodeString:NSUTF8StringEncoding];
  1236. serverPath = [serverPath stringByAppendingString:k_url_acces_external_sites_api];
  1237. OCWebDAVClient *request = [OCWebDAVClient new];
  1238. request = [self getRequestWithCredentials:request];
  1239. [request getExternalSitesServer:serverPath onCommunication:sharedOCComunication success:^(NSHTTPURLResponse *response, id responseObject) {
  1240. NSData *responseData = (NSData*) responseObject;
  1241. //Parse
  1242. NSError *error;
  1243. NSDictionary *jsongParsed = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error];
  1244. NSLog(@"[LOG] External Sites : %@",jsongParsed);
  1245. NSMutableArray *listOfExternalSites = [NSMutableArray new];
  1246. if (jsongParsed.allKeys > 0) {
  1247. NSDictionary *ocs = [jsongParsed valueForKey:@"ocs"];
  1248. NSDictionary *meta = [ocs valueForKey:@"meta"];
  1249. NSDictionary *datas = [ocs valueForKey:@"data"];
  1250. NSInteger statusCode = [[meta valueForKey:@"statuscode"] integerValue];
  1251. if (statusCode == kOCNotificationAPINoContent || statusCode == kOCNotificationAPISuccessful) {
  1252. for (NSDictionary *data in datas) {
  1253. OCExternalSites *externalSites = [OCExternalSites new];
  1254. externalSites.idExternalSite = [[data valueForKey:@"id"] integerValue];
  1255. if ([data valueForKey:@"icon"] && ![[data valueForKey:@"icon"] isEqual:[NSNull null]])
  1256. externalSites.icon = [data valueForKey:@"icon"];
  1257. if ([data valueForKey:@"lang"] && ![[data valueForKey:@"lang"] isEqual:[NSNull null]])
  1258. externalSites.lang = [data valueForKey:@"lang"];
  1259. if ([data valueForKey:@"name"] && ![[data valueForKey:@"name"] isEqual:[NSNull null]])
  1260. externalSites.name = [data valueForKey:@"name"];
  1261. if ([data valueForKey:@"url"] && ![[data valueForKey:@"url"] isEqual:[NSNull null]])
  1262. externalSites.url = [data valueForKey:@"url"];
  1263. if ([data valueForKey:@"type"] && ![[data valueForKey:@"type"] isEqual:[NSNull null]])
  1264. externalSites.type = [data valueForKey:@"type"];
  1265. [listOfExternalSites addObject:externalSites];
  1266. }
  1267. } else {
  1268. NSString *message = (NSString*)[meta objectForKey:@"message"];
  1269. if ([message isKindOfClass:[NSNull class]]) {
  1270. message = @"";
  1271. }
  1272. NSError *error = [UtilsFramework getErrorWithCode:statusCode andCustomMessageFromTheServer:message];
  1273. failureRequest(response, error, request.redirectedServer);
  1274. }
  1275. }
  1276. //Return success
  1277. successRequest(response, listOfExternalSites, request.redirectedServer);
  1278. } failure:^(NSHTTPURLResponse *response, NSData *responseData, NSError *error) {
  1279. failureRequest(response, error, request.redirectedServer);
  1280. }];
  1281. }
  1282. #pragma mark - User Profile
  1283. - (void) getUserProfileServer:(NSString*)serverPath onCommunication:(OCCommunication *)sharedOCComunication successRequest:(void(^)(NSHTTPURLResponse *response, OCUserProfile *userProfile, NSString *redirectedServer)) successRequest failureRequest:(void(^)(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer)) failureRequest {
  1284. serverPath = [serverPath stringByAppendingString:k_url_acces_remote_userprofile_api];
  1285. serverPath = [serverPath encodeString:NSUTF8StringEncoding];
  1286. OCWebDAVClient *request = [OCWebDAVClient new];
  1287. request = [self getRequestWithCredentials:request];
  1288. [request getUserProfileServer:serverPath onCommunication:sharedOCComunication success:^(NSHTTPURLResponse *response, id responseObject) {
  1289. NSData *responseData = (NSData*) responseObject;
  1290. //Parse
  1291. NSError *error;
  1292. NSDictionary *jsongParsed = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error];
  1293. NSLog(@"[LOG] User Profile : %@",jsongParsed);
  1294. OCUserProfile *userProfile = [OCUserProfile new];
  1295. if (jsongParsed.allKeys > 0) {
  1296. NSDictionary *ocs = [jsongParsed valueForKey:@"ocs"];
  1297. NSDictionary *meta = [ocs valueForKey:@"meta"];
  1298. NSDictionary *data = [ocs valueForKey:@"data"];
  1299. NSInteger statusCode = [[meta valueForKey:@"statuscode"] integerValue];
  1300. if (statusCode == kOCUserProfileAPISuccessful) {
  1301. if ([data valueForKey:@"address"] && ![[data valueForKey:@"address"] isKindOfClass:[NSNull class]])
  1302. userProfile.address = [data valueForKey:@"address"];
  1303. if ([data valueForKey:@"displayname"] && ![[data valueForKey:@"displayname"] isKindOfClass:[NSNull class]])
  1304. userProfile.displayName = [data valueForKey:@"displayname"];
  1305. if ([data valueForKey:@"email"] && ![[data valueForKey:@"email"] isKindOfClass:[NSNull class]])
  1306. userProfile.email = [data valueForKey:@"email"];
  1307. if ([data valueForKey:@"enabled"] && ![[data valueForKey:@"enabled"] isKindOfClass:[NSNull class]])
  1308. userProfile.enabled = [[data valueForKey:@"enabled"] boolValue];
  1309. if ([data valueForKey:@"id"] && ![[data valueForKey:@"id"] isKindOfClass:[NSNull class]])
  1310. userProfile.id = [data valueForKey:@"id"];
  1311. if ([data valueForKey:@"phone"] && ![[data valueForKey:@"phone"] isKindOfClass:[NSNull class]])
  1312. userProfile.phone = [data valueForKey:@"phone"];
  1313. if ([data valueForKey:@"twitter"] && ![[data valueForKey:@"twitter"] isKindOfClass:[NSNull class]])
  1314. userProfile.twitter = [data valueForKey:@"twitter"];
  1315. if ([data valueForKey:@"webpage"] && ![[data valueForKey:@"webpage"] isKindOfClass:[NSNull class]])
  1316. userProfile.webpage = [data valueForKey:@"webpage"];
  1317. /* QUOTA */
  1318. NSDictionary *quota = [data valueForKey:@"quota"];
  1319. if ([quota count] > 0) {
  1320. if ([quota valueForKey:@"free"] && ![[quota valueForKey:@"free"] isKindOfClass:[NSNull class]])
  1321. userProfile.quotaFree = [[quota valueForKey:@"free"] doubleValue];
  1322. if ([quota valueForKey:@"quota"] && ![[quota valueForKey:@"quota"] isKindOfClass:[NSNull class]])
  1323. userProfile.quota = [[quota valueForKey:@"quota"] doubleValue];
  1324. if ([quota valueForKey:@"relative"] && ![[quota valueForKey:@"relative"] isKindOfClass:[NSNull class]])
  1325. userProfile.quotaRelative = [[quota valueForKey:@"relative"] doubleValue];
  1326. if ([quota valueForKey:@"total"] && ![[quota valueForKey:@"total"] isKindOfClass:[NSNull class]])
  1327. userProfile.quotaTotal = [[quota valueForKey:@"total"] doubleValue];
  1328. if ([quota valueForKey:@"used"] && ![[quota valueForKey:@"used"] isKindOfClass:[NSNull class]])
  1329. userProfile.quotaUsed = [[quota valueForKey:@"used"] doubleValue];
  1330. }
  1331. } else {
  1332. NSString *message = (NSString*)[meta objectForKey:@"message"];
  1333. if ([message isKindOfClass:[NSNull class]]) {
  1334. message = @"";
  1335. }
  1336. NSError *error = [UtilsFramework getErrorWithCode:statusCode andCustomMessageFromTheServer:message];
  1337. failureRequest(response, error, request.redirectedServer);
  1338. }
  1339. }
  1340. //Return success
  1341. successRequest(response, userProfile, request.redirectedServer);
  1342. } failure:^(NSHTTPURLResponse *response, NSData *responseData, NSError *error) {
  1343. failureRequest(response, error, request.redirectedServer);
  1344. }];
  1345. }
  1346. #pragma mark - Clear Cache
  1347. - (void)eraseURLCache
  1348. {
  1349. [[NSURLCache sharedURLCache] setMemoryCapacity:0];
  1350. [[NSURLCache sharedURLCache] setDiskCapacity:0];
  1351. }
  1352. #pragma mark - Utils
  1353. - (void) addUserItemOfType:(NSInteger) shareeType fromArray:(NSArray*) usersArray ToList: (NSMutableArray *) itemList
  1354. {
  1355. for (NSDictionary *userFound in usersArray) {
  1356. OCShareUser *user = [OCShareUser new];
  1357. if ([[userFound valueForKey:@"label"] isKindOfClass:[NSNumber class]]) {
  1358. NSNumber *number = [userFound valueForKey:@"label"];
  1359. user.displayName = [NSString stringWithFormat:@"%ld", number.longValue];
  1360. }else{
  1361. user.displayName = [userFound valueForKey:@"label"];
  1362. }
  1363. NSDictionary *userValues = [userFound valueForKey:@"value"];
  1364. if ([[userValues valueForKey:@"shareWith"] isKindOfClass:[NSNumber class]]) {
  1365. NSNumber *number = [userValues valueForKey:@"shareWith"];
  1366. user.name = [NSString stringWithFormat:@"%ld", number.longValue];
  1367. }else{
  1368. user.name = [userValues valueForKey:@"shareWith"];
  1369. }
  1370. user.shareeType = shareeType;
  1371. user.server = [userValues valueForKey:@"server"];
  1372. [itemList addObject:user];
  1373. }
  1374. }
  1375. - (void) addGroupItemFromArray:(NSArray*) groupsArray ToList: (NSMutableArray *) itemList
  1376. {
  1377. for (NSDictionary *groupFound in groupsArray) {
  1378. OCShareUser *group = [OCShareUser new];
  1379. NSDictionary *groupValues = [groupFound valueForKey:@"value"];
  1380. if ([[groupValues valueForKey:@"shareWith"] isKindOfClass:[NSNumber class]]) {
  1381. NSNumber *number = [groupValues valueForKey:@"shareWith"];
  1382. group.name = [NSString stringWithFormat:@"%ld", number.longValue];
  1383. }else{
  1384. group.name = [groupValues valueForKey:@"shareWith"];
  1385. }
  1386. group.shareeType = shareTypeGroup;
  1387. [itemList addObject:group];
  1388. }
  1389. }
  1390. @end