OCNetworking.m 97 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955
  1. //
  2. // OCnetworking.m
  3. // Nextcloud iOS
  4. //
  5. // Created by Marino Faggiana on 10/05/15.
  6. // Copyright (c) 2017 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "OCNetworking.h"
  24. #import "CCUtility.h"
  25. #import "CCGraphics.h"
  26. #import "CCCertificate.h"
  27. #import "NSString+Encode.h"
  28. #import "NCBridgeSwift.h"
  29. @implementation OCNetworking
  30. + (OCNetworking *)sharedManager {
  31. static OCNetworking *sharedManager;
  32. @synchronized(self)
  33. {
  34. if (!sharedManager) {
  35. sharedManager = [OCNetworking new];
  36. }
  37. return sharedManager;
  38. }
  39. }
  40. - (id)init
  41. {
  42. self = [super init];
  43. [self sharedOCCommunication];
  44. return self;
  45. }
  46. #pragma --------------------------------------------------------------------------------------------
  47. #pragma mark ===== OCCommunication =====
  48. #pragma --------------------------------------------------------------------------------------------
  49. - (OCCommunication *)sharedOCCommunication
  50. {
  51. static OCCommunication* sharedOCCommunication = nil;
  52. if (sharedOCCommunication == nil)
  53. {
  54. // Network
  55. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  56. configuration.allowsCellularAccess = YES;
  57. configuration.discretionary = NO;
  58. configuration.HTTPMaximumConnectionsPerHost = k_maxConcurrentOperation;
  59. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  60. OCURLSessionManager *networkSessionManager = [[OCURLSessionManager alloc] initWithSessionConfiguration:configuration];
  61. [networkSessionManager.operationQueue setMaxConcurrentOperationCount: k_maxConcurrentOperation];
  62. networkSessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
  63. // Download
  64. NSURLSessionConfiguration *configurationDownload = [NSURLSessionConfiguration defaultSessionConfiguration];
  65. configurationDownload.allowsCellularAccess = YES;
  66. configurationDownload.discretionary = NO;
  67. configurationDownload.HTTPMaximumConnectionsPerHost = k_maxHTTPConnectionsPerHost;
  68. configurationDownload.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  69. configurationDownload.timeoutIntervalForRequest = k_timeout_upload;
  70. OCURLSessionManager *downloadSessionManager = [[OCURLSessionManager alloc] initWithSessionConfiguration:configurationDownload];
  71. [downloadSessionManager.operationQueue setMaxConcurrentOperationCount:k_maxHTTPConnectionsPerHost];
  72. [downloadSessionManager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition (NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential) {
  73. return NSURLSessionAuthChallengePerformDefaultHandling;
  74. }];
  75. // Upload
  76. NSURLSessionConfiguration *configurationUpload = [NSURLSessionConfiguration defaultSessionConfiguration];
  77. configurationUpload.allowsCellularAccess = YES;
  78. configurationUpload.discretionary = NO;
  79. configurationUpload.HTTPMaximumConnectionsPerHost = k_maxHTTPConnectionsPerHost;
  80. configurationUpload.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  81. configurationUpload.timeoutIntervalForRequest = k_timeout_upload;
  82. OCURLSessionManager *uploadSessionManager = [[OCURLSessionManager alloc] initWithSessionConfiguration:configurationUpload];
  83. [uploadSessionManager.operationQueue setMaxConcurrentOperationCount:k_maxHTTPConnectionsPerHost];
  84. [uploadSessionManager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition (NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential) {
  85. return NSURLSessionAuthChallengePerformDefaultHandling;
  86. }];
  87. sharedOCCommunication = [[OCCommunication alloc] initWithUploadSessionManager:uploadSessionManager andDownloadSessionManager:downloadSessionManager andNetworkSessionManager:networkSessionManager];
  88. }
  89. return sharedOCCommunication;
  90. }
  91. - (OCCommunication *)sharedOCCommunicationExtensionDownload
  92. {
  93. static OCCommunication *sharedOCCommunicationExtensionDownload = nil;
  94. if (sharedOCCommunicationExtensionDownload == nil)
  95. {
  96. NSURLSessionConfiguration *config = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_download_session_extension];
  97. config.sharedContainerIdentifier = [NCBrandOptions sharedInstance].capabilitiesGroups;
  98. config.HTTPMaximumConnectionsPerHost = 1;
  99. config.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  100. config.timeoutIntervalForRequest = k_timeout_upload;
  101. config.sessionSendsLaunchEvents = YES;
  102. [config setAllowsCellularAccess:YES];
  103. OCURLSessionManager *sessionManager = [[OCURLSessionManager alloc] initWithSessionConfiguration:config];
  104. [sessionManager.operationQueue setMaxConcurrentOperationCount:1];
  105. [sessionManager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition (NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential) {
  106. return NSURLSessionAuthChallengePerformDefaultHandling;
  107. }];
  108. sharedOCCommunicationExtensionDownload = [[OCCommunication alloc] initWithUploadSessionManager:nil andDownloadSessionManager:sessionManager andNetworkSessionManager:nil];
  109. }
  110. return sharedOCCommunicationExtensionDownload;
  111. }
  112. #pragma --------------------------------------------------------------------------------------------
  113. #pragma mark ===== Server =====
  114. #pragma --------------------------------------------------------------------------------------------
  115. - (void)checkServerUrl:(NSString *)serverUrl user:(NSString *)user userID:(NSString *)userID password:(NSString *)password completion:(void (^)(NSString *message, NSInteger errorCode))completion
  116. {
  117. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  118. [communication setCredentialsWithUser:user andUserID:userID andPassword:password];
  119. [communication setUserAgent:[CCUtility getUserAgent]];
  120. [communication checkServer:serverUrl onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  121. completion(nil, 0);
  122. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  123. NSString *message;
  124. NSInteger errorCode = response.statusCode;
  125. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  126. errorCode = error.code;
  127. // Error
  128. if (errorCode == 503)
  129. message = NSLocalizedString(@"_server_error_retry_", nil);
  130. else
  131. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  132. completion(message, errorCode);
  133. }];
  134. }
  135. - (void)serverStatusUrl:(NSString *)serverUrl completion:(void(^)(NSString *serverProductName, NSInteger versionMajor, NSInteger versionMicro, NSInteger versionMinor, NSString *message, NSInteger errorCode))completion
  136. {
  137. NSString *urlTest = [serverUrl stringByAppendingString:k_serverStatus];
  138. // Remove stored cookies
  139. NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
  140. for (NSHTTPCookie *cookie in [storage cookies])
  141. {
  142. [storage deleteCookie:cookie];
  143. }
  144. NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlTest] cachePolicy:0 timeoutInterval:20.0];
  145. [request addValue:[CCUtility getUserAgent] forHTTPHeaderField:@"User-Agent"];
  146. [request addValue:@"true" forHTTPHeaderField:@"OCS-APIRequest"];
  147. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  148. NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  149. NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler: ^(NSData *data, NSURLResponse *response, NSError *error) {
  150. dispatch_sync(dispatch_get_main_queue(), ^{
  151. if (error) {
  152. NSString *message;
  153. NSInteger errorCode;
  154. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
  155. errorCode = httpResponse.statusCode;
  156. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  157. errorCode = error.code;
  158. // Error
  159. if (errorCode == 503)
  160. message = NSLocalizedString(@"_server_error_retry_", nil);
  161. else
  162. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  163. completion(nil, 0, 0, 0, message, errorCode);
  164. } else {
  165. NSString *serverProductName = @"";
  166. NSString *serverVersion = @"0.0.0";
  167. NSString *serverVersionString = @"0.0.0";
  168. NSInteger versionMajor = 0;
  169. NSInteger versionMicro = 0;
  170. NSInteger versionMinor = 0;
  171. NSError *error;
  172. NSDictionary *jsongParsed = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
  173. if (error) {
  174. completion(nil, 0, 0, 0, error.description, error.code);
  175. return;
  176. }
  177. serverProductName = [[jsongParsed valueForKey:@"productname"] lowercaseString];
  178. serverVersion = [jsongParsed valueForKey:@"version"];
  179. serverVersionString = [jsongParsed valueForKey:@"versionstring"];
  180. NSArray *arrayVersion = [serverVersionString componentsSeparatedByString:@"."];
  181. if (arrayVersion.count == 1) {
  182. versionMajor = [arrayVersion[0] integerValue];
  183. } else if (arrayVersion.count == 2) {
  184. versionMajor = [arrayVersion[0] integerValue];
  185. versionMinor = [arrayVersion[1] integerValue];
  186. } else if (arrayVersion.count >= 3) {
  187. versionMajor = [arrayVersion[0] integerValue];
  188. versionMinor = [arrayVersion[1] integerValue];
  189. versionMicro = [arrayVersion[2] integerValue];
  190. }
  191. completion(serverProductName, versionMajor, versionMicro, versionMinor, nil, 0);
  192. }
  193. });
  194. }];
  195. [task resume];
  196. }
  197. #pragma --------------------------------------------------------------------------------------------
  198. #pragma mark ===== download / upload =====
  199. #pragma --------------------------------------------------------------------------------------------
  200. - (NSURLSessionTask *)downloadWithAccount:(NSString *)account fileNameServerUrl:(NSString *)fileNameServerUrl fileNameLocalPath:(NSString *)fileNameLocalPath communication:(OCCommunication *)communication completion:(void (^)(NSString *account, int64_t length, NSString *etag, NSDate *date, NSString *message, NSInteger errorCode))completion
  201. {
  202. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  203. if (tableAccount == nil) {
  204. completion(account, 0, nil, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  205. }
  206. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  207. [communication setUserAgent:[CCUtility getUserAgent]];
  208. NSURLSessionTask *sessionTask = [communication downloadFileSession:fileNameServerUrl toDestiny:fileNameLocalPath defaultPriority:YES onCommunication:communication progress:^(NSProgress *progress) {
  209. //float percent = roundf (progress.fractionCompleted * 100);
  210. } successRequest:^(NSURLResponse *response, NSURL *filePath) {
  211. int64_t totalUnitCount = 0;
  212. NSDate *date = [NSDate date];
  213. NSDateFormatter *dateFormatter = [NSDateFormatter new];
  214. NSLocale *enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
  215. [dateFormatter setLocale:enUSPOSIXLocale];
  216. [dateFormatter setDateFormat:@"EEE, dd MMM y HH:mm:ss zzz"];
  217. NSError *error;
  218. NSDictionary *fields = [(NSHTTPURLResponse*)response allHeaderFields];
  219. NSString *contentLength = [fields objectForKey:@"Content-Length"];
  220. if(contentLength) {
  221. totalUnitCount = (int64_t) [contentLength longLongValue];
  222. }
  223. NSString *dateString = [fields objectForKey:@"Date"];
  224. if (dateString) {
  225. if (![dateFormatter getObjectValue:&date forString:dateString range:nil error:&error]) {
  226. date = [NSDate date];
  227. }
  228. } else {
  229. date = [NSDate date];
  230. }
  231. NSString *etag = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-ETag"]];
  232. if (etag == nil) {
  233. completion(account, 0, nil, nil, NSLocalizedString(@"Internal error", nil), k_CCErrorInternalError);
  234. } else {
  235. completion(account, totalUnitCount, etag, date, nil, 0);
  236. }
  237. } failureRequest:^(NSURLResponse *response, NSError *error) {
  238. NSString *message;
  239. NSInteger errorCode;
  240. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
  241. errorCode = httpResponse.statusCode;
  242. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  243. errorCode = error.code;
  244. // Error
  245. if (errorCode == 503)
  246. message = NSLocalizedString(@"_server_error_retry_", nil);
  247. else
  248. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  249. completion(account, 0, nil, nil, message, errorCode);
  250. }];
  251. return sessionTask;
  252. }
  253. - (NSURLSessionTask *)downloadWithAccount:(NSString *)account url:(NSString *)url fileNameLocalPath:(NSString *)fileNameLocalPath completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  254. {
  255. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  256. if (tableAccount == nil) {
  257. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  258. }
  259. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  260. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  261. [communication setUserAgent:[CCUtility getUserAgent]];
  262. NSURLSessionTask *sessionTask = [communication downloadFileSession:url toDestiny:fileNameLocalPath defaultPriority:YES onCommunication:communication progress:^(NSProgress *progress) {
  263. //float percent = roundf (progress.fractionCompleted * 100);
  264. } successRequest:^(NSURLResponse *response, NSURL *filePath) {
  265. completion(account, nil, 0);
  266. } failureRequest:^(NSURLResponse *response, NSError *error) {
  267. NSString *message;
  268. NSInteger errorCode;
  269. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
  270. errorCode = httpResponse.statusCode;
  271. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  272. errorCode = error.code;
  273. // Error
  274. if (errorCode == 503)
  275. message = NSLocalizedString(@"_server_error_retry_", nil);
  276. else
  277. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  278. completion(account, message, errorCode);
  279. }];
  280. return sessionTask;
  281. }
  282. - (NSURLSessionTask *)uploadWithAccount:(NSString *)account fileNameServerUrl:(NSString *)fileNameServerUrl fileNameLocalPath:(NSString *)fileNameLocalPath communication:(OCCommunication *)communication completion:(void(^)(NSString *account, NSString *fileID, NSString *etag, NSDate *date, NSString *message, NSInteger errorCode))completion
  283. {
  284. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  285. if (tableAccount == nil) {
  286. completion(account, nil, nil, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  287. }
  288. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  289. [communication setUserAgent:[CCUtility getUserAgent]];
  290. NSURLSessionTask *sessionTask = [communication uploadFileSession:fileNameLocalPath toDestiny:fileNameServerUrl onCommunication:communication progress:^(NSProgress *progress) {
  291. //float percent = roundf (progress.fractionCompleted * 100);
  292. } successRequest:^(NSURLResponse *response, NSString *redirectedServer) {
  293. NSDictionary *fields = [(NSHTTPURLResponse*)response allHeaderFields];
  294. NSString *fileID = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-FileId"]];
  295. NSString *etag = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-ETag"]];
  296. NSDate *date = [CCUtility dateEnUsPosixFromCloud:[fields objectForKey:@"Date"]];
  297. completion(account, fileID, etag, date, nil, 0);
  298. } failureRequest:^(NSURLResponse *response, NSString *redirectedServer, NSError *error) {
  299. NSString *message;
  300. NSInteger errorCode;
  301. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
  302. errorCode = httpResponse.statusCode;
  303. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  304. errorCode = error.code;
  305. // Error
  306. if (errorCode == 503)
  307. message = NSLocalizedString(@"_server_error_retry_", nil);
  308. else
  309. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  310. completion(account, nil, nil, nil, message, errorCode);
  311. } failureBeforeRequest:^(NSError *error) {
  312. completion(account, nil, nil, nil, error.description, error.code);
  313. }];
  314. return sessionTask;
  315. }
  316. #pragma --------------------------------------------------------------------------------------------
  317. #pragma mark ===== WebDav =====
  318. #pragma --------------------------------------------------------------------------------------------
  319. - (void)readFolderWithAccount:(NSString *)account serverUrl:(NSString *)serverUrl depth:(NSString *)depth completion:(void(^)(NSString *account, NSArray *metadatas, tableMetadata *metadataFolder, NSString *message, NSInteger errorCode))completion
  320. {
  321. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  322. if (tableAccount == nil) {
  323. completion(account, nil, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  324. }
  325. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  326. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  327. [communication setUserAgent:[CCUtility getUserAgent]];
  328. [communication readFolder:serverUrl depth:depth withUserSessionToken:nil onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer, NSString *token) {
  329. // Check items > 0
  330. if ([items count] == 0) {
  331. #ifndef EXTENSION
  332. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  333. [appDelegate messageNotification:@"Server error" description:@"Read Folder WebDAV : [items NULL] please fix" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  334. #endif
  335. completion(account, nil, nil, NSLocalizedString(@"Read Folder WebDAV : [items NULL] please fix", nil), k_CCErrorInternalError);
  336. } else {
  337. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  338. BOOL showHiddenFiles = [CCUtility getShowHiddenFiles];
  339. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:serverUrl account:account];
  340. // directory [0]
  341. OCFileDto *itemDtoFolder = [items objectAtIndex:0];
  342. //NSDate *date = [NSDate dateWithTimeIntervalSince1970:itemDtoDirectory.date];
  343. NSMutableArray *metadatas = [NSMutableArray new];
  344. tableMetadata *metadataFolder = [tableMetadata new];
  345. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  346. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:tableAccount.url];
  347. NSString *serverUrlFolder;
  348. // Metadata . (self Folder)
  349. if ([serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:tableAccount.url]]) {
  350. // root folder
  351. serverUrlFolder = k_serverUrl_root;
  352. metadataFolder = [CCUtility trasformedOCFileToCCMetadata:itemDtoFolder fileName:@"." serverUrl:serverUrlFolder autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:account isFolderEncrypted:isFolderEncrypted];
  353. } else {
  354. serverUrlFolder = [CCUtility deletingLastPathComponentFromServerUrl:serverUrl];
  355. metadataFolder = [CCUtility trasformedOCFileToCCMetadata:itemDtoFolder fileName:[serverUrl lastPathComponent] serverUrl:serverUrlFolder autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:account isFolderEncrypted:isFolderEncrypted];
  356. }
  357. // Add metadata folder
  358. (void)[[NCManageDatabase sharedInstance] addDirectoryWithEncrypted:itemDtoFolder.isEncrypted favorite:itemDtoFolder.isFavorite fileID:itemDtoFolder.ocId permissions:itemDtoFolder.permissions serverUrl:serverUrl account:account];
  359. NSArray *itemsSortedArray = [items sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
  360. NSString *first = [(OCFileDto*)a fileName];
  361. NSString *second = [(OCFileDto*)b fileName];
  362. return [[first lowercaseString] compare:[second lowercaseString]];
  363. }];
  364. for (NSUInteger i=1; i < [itemsSortedArray count]; i++) {
  365. OCFileDto *itemDto = [itemsSortedArray objectAtIndex:i];
  366. NSString *fileName = [itemDto.fileName stringByReplacingOccurrencesOfString:@"/" withString:@""];
  367. // Skip hidden files
  368. if (fileName.length > 0) {
  369. if (!showHiddenFiles && [[fileName substringToIndex:1] isEqualToString:@"."])
  370. continue;
  371. } else {
  372. continue;
  373. }
  374. if (itemDto.isDirectory) {
  375. (void)[[NCManageDatabase sharedInstance] addDirectoryWithEncrypted:itemDto.isEncrypted favorite:itemDto.isFavorite fileID:itemDto.ocId permissions:itemDto.permissions serverUrl:[CCUtility stringAppendServerUrl:serverUrl addFileName:fileName] account:account];
  376. }
  377. [metadatas addObject:[CCUtility trasformedOCFileToCCMetadata:itemDto fileName:itemDto.fileName serverUrl:serverUrl autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:account isFolderEncrypted:isFolderEncrypted]];
  378. }
  379. dispatch_async(dispatch_get_main_queue(), ^{
  380. completion(account, metadatas, metadataFolder, nil, 0);
  381. });
  382. });
  383. }
  384. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) {
  385. NSString *message;
  386. NSInteger errorCode = response.statusCode;
  387. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  388. errorCode = error.code;
  389. // Error
  390. if (errorCode == 503)
  391. message = NSLocalizedString(@"_server_error_retry_", nil);
  392. else
  393. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  394. // Activity
  395. [[NCManageDatabase sharedInstance] addActivityClient:serverUrl fileID:@"" action:k_activityDebugActionReadFolder selector:@"" note:[error.userInfo valueForKey:@"NSLocalizedDescription"] type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:tableAccount.url];
  396. completion(account, nil, nil, message, errorCode);
  397. }];
  398. }
  399. - (void)readFileWithAccount:(NSString *)account serverUrl:(NSString *)serverUrl fileName:(NSString *)fileName completion:(void(^)(NSString *account, tableMetadata *metadata, NSString *message, NSInteger errorCode))completion
  400. {
  401. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  402. if (tableAccount == nil) {
  403. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  404. }
  405. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  406. NSString *fileNamePath;
  407. if (fileName) {
  408. fileNamePath = [NSString stringWithFormat:@"%@/%@", serverUrl, fileName];
  409. } else {
  410. fileName= @".";
  411. fileNamePath = serverUrl;
  412. }
  413. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  414. [communication setUserAgent:[CCUtility getUserAgent]];
  415. [communication readFile:fileNamePath onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  416. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:serverUrl account:account];
  417. if ([items count] > 0) {
  418. tableMetadata *metadata = [tableMetadata new];
  419. OCFileDto *itemDto = [items objectAtIndex:0];
  420. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  421. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:tableAccount.url];
  422. metadata = [CCUtility trasformedOCFileToCCMetadata:itemDto fileName:fileName serverUrl:serverUrl autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:account isFolderEncrypted:isFolderEncrypted];
  423. completion(account, metadata, nil, 0);
  424. // BUG 1038 item == 0
  425. } else {
  426. #ifndef EXTENSION
  427. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  428. [appDelegate messageNotification:@"Server error" description:@"Read File WebDAV : [items NULL] please fix" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  429. #endif
  430. completion(account, nil, NSLocalizedString(@"Read File WebDAV : [items NULL] please fix", nil), k_CCErrorInternalError);
  431. }
  432. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  433. NSString *message;
  434. NSInteger errorCode = response.statusCode;
  435. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  436. errorCode = error.code;
  437. // Error
  438. if (errorCode == 503)
  439. message = NSLocalizedString(@"_server_error_retry_", nil);
  440. else
  441. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  442. completion(account, nil, message, errorCode);
  443. }];
  444. }
  445. - (void)createFolderWithAccount:(NSString *)account serverUrl:(NSString *)serverUrl fileName:(NSString *)fileName completion:(void(^)(NSString *account, NSString *fileID, NSDate *date, NSString *message, NSInteger errorCode))completion
  446. {
  447. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  448. if (tableAccount == nil) {
  449. completion(account, nil, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  450. }
  451. NSString *path = [NSString stringWithFormat:@"%@/%@", serverUrl, fileName];
  452. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  453. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:tableAccount.url];
  454. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  455. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  456. [communication setUserAgent:[CCUtility getUserAgent]];
  457. [communication createFolder:path onCommunication:communication withForbiddenCharactersSupported:YES successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  458. NSDictionary *fields = [response allHeaderFields];
  459. NSString *fileID = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-FileId"]];
  460. NSDate *date = [CCUtility dateEnUsPosixFromCloud:[fields objectForKey:@"Date"]];
  461. completion(account, fileID, date, nil, 0);
  462. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  463. NSString *message;
  464. if (([fileName isEqualToString:autoUploadFileName] && [serverUrl isEqualToString:autoUploadDirectory]))
  465. message = nil;
  466. else
  467. message = [CCError manageErrorOC:response.statusCode error:error];
  468. NSInteger errorCode = response.statusCode;
  469. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  470. errorCode = error.code;
  471. completion(account, nil, nil, message, errorCode);
  472. } errorBeforeRequest:^(NSError *error) {
  473. NSString *message;
  474. if (([fileName isEqualToString:autoUploadFileName] && [serverUrl isEqualToString:autoUploadDirectory]))
  475. message = nil;
  476. else {
  477. if (error.code == OCErrorForbidenCharacters)
  478. message = NSLocalizedString(@"_forbidden_characters_from_server_", nil);
  479. else
  480. message = NSLocalizedString(@"_unknow_response_server_", nil);
  481. }
  482. completion(account, nil, nil, message, error.code);
  483. }];
  484. }
  485. - (void)deleteFileOrFolderWithAccount:(NSString *)account path:(NSString *)path completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  486. {
  487. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  488. if (tableAccount == nil) {
  489. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  490. }
  491. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  492. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  493. [communication setUserAgent:[CCUtility getUserAgent]];
  494. [communication deleteFileOrFolder:path onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  495. completion(account, nil, 0);
  496. } failureRquest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  497. NSString *message;
  498. NSInteger errorCode = response.statusCode;
  499. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  500. errorCode = error.code;
  501. // Error
  502. if (errorCode == 503)
  503. message = NSLocalizedString(@"_server_error_retry_", nil);
  504. else
  505. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  506. completion(account, message, errorCode);
  507. }];
  508. }
  509. - (void)moveFileOrFolderWithAccount:(NSString *)account fileName:(NSString *)fileName fileNameTo:(NSString *)fileNameTo completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  510. {
  511. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  512. if (tableAccount == nil) {
  513. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  514. }
  515. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  516. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  517. [communication setUserAgent:[CCUtility getUserAgent]];
  518. [communication moveFileOrFolder:fileName toDestiny:fileNameTo onCommunication:communication withForbiddenCharactersSupported:YES successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  519. completion(account, nil, 0);
  520. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  521. NSInteger errorCode = response.statusCode;
  522. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  523. errorCode = error.code;
  524. NSString *message = [CCError manageErrorOC:response.statusCode error:error];
  525. completion(account, message, error.code);
  526. } errorBeforeRequest:^(NSError *error) {
  527. NSString *message;
  528. if (error.code == OCErrorMovingTheDestinyAndOriginAreTheSame) {
  529. message = NSLocalizedString(@"_error_folder_destiny_is_the_same_", nil);
  530. } else if (error.code == OCErrorMovingFolderInsideHimself) {
  531. message = NSLocalizedString(@"_error_folder_destiny_is_the_same_", nil);
  532. } else if (error.code == OCErrorMovingDestinyNameHaveForbiddenCharacters) {
  533. message = NSLocalizedString(@"_forbidden_characters_from_server_", nil);
  534. } else {
  535. message = NSLocalizedString(@"_unknow_response_server_", nil);
  536. }
  537. completion(account, message, error.code);
  538. }];
  539. }
  540. - (void)searchWithAccount:(NSString *)account fileName:(NSString *)fileName serverUrl:(NSString *)serverUrl contentType:(NSArray *)contentType date:(NSDate *)date depth:(NSString *)depth completion:(void(^)(NSString *account, NSArray *metadatas, NSString *message, NSInteger errorCode))completion
  541. {
  542. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  543. if (tableAccount == nil) {
  544. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  545. }
  546. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  547. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  548. [communication setUserAgent:[CCUtility getUserAgent]];
  549. NSString *path = [tableAccount.url stringByAppendingString:k_dav];
  550. NSString *folder = [serverUrl stringByReplacingOccurrencesOfString:[CCUtility getHomeServerUrlActiveUrl:tableAccount.url] withString:@""];
  551. NSString *dateLastModified;
  552. if (date) {
  553. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  554. NSLocale *enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
  555. [dateFormatter setLocale:enUSPOSIXLocale];
  556. [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZZ"];
  557. dateLastModified = [dateFormatter stringFromDate:date];
  558. }
  559. [communication search:path folder:folder fileName: [NSString stringWithFormat:@"%%%@%%", fileName] depth:depth dateLastModified:dateLastModified contentType:contentType withUserSessionToken:nil onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer, NSString *token) {
  560. NSMutableArray *metadatas = [NSMutableArray new];
  561. BOOL showHiddenFiles = [CCUtility getShowHiddenFiles];
  562. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  563. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:tableAccount.url];
  564. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  565. for (OCFileDto *itemDto in items) {
  566. NSString *serverUrl;
  567. BOOL isFolderEncrypted;
  568. NSString *fileName = [itemDto.fileName stringByReplacingOccurrencesOfString:@"/" withString:@""];
  569. // Skip hidden files
  570. if (fileName.length > 0) {
  571. if (!showHiddenFiles && [[fileName substringToIndex:1] isEqualToString:@"."])
  572. continue;
  573. } else
  574. continue;
  575. NSRange firstInstance = [itemDto.filePath rangeOfString:[NSString stringWithFormat:@"%@/files/%@", k_dav, tableAccount.userID]];
  576. NSString *serverPath = [itemDto.filePath substringFromIndex:firstInstance.length+firstInstance.location+1];
  577. if ([serverPath hasSuffix:@"/"]) serverPath = [serverPath substringToIndex:[serverPath length] - 1];
  578. serverUrl = [CCUtility stringAppendServerUrl:[tableAccount.url stringByAppendingString:k_webDAV] addFileName:serverPath];
  579. if (itemDto.isDirectory) {
  580. (void)[[NCManageDatabase sharedInstance] addDirectoryWithEncrypted:itemDto.isEncrypted favorite:itemDto.isFavorite fileID:itemDto.ocId permissions:itemDto.permissions serverUrl:[NSString stringWithFormat:@"%@/%@", serverUrl, fileName] account:account];
  581. }
  582. isFolderEncrypted = [CCUtility isFolderEncrypted:serverUrl account:account];
  583. [metadatas addObject:[CCUtility trasformedOCFileToCCMetadata:itemDto fileName:itemDto.fileName serverUrl:serverUrl autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:account isFolderEncrypted:isFolderEncrypted]];
  584. }
  585. dispatch_async(dispatch_get_main_queue(), ^{
  586. completion(account, metadatas, nil, 0);
  587. });
  588. });
  589. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) {
  590. NSString *message = @"";
  591. NSInteger errorCode = response.statusCode;
  592. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  593. errorCode = error.code;
  594. // Error
  595. if (errorCode == 503) {
  596. message = NSLocalizedString(@"_server_error_retry_", nil);
  597. } else {
  598. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  599. }
  600. completion(account, nil, message, errorCode);
  601. }];
  602. }
  603. #pragma --------------------------------------------------------------------------------------------
  604. #pragma mark ===== downloadPreview =====
  605. #pragma --------------------------------------------------------------------------------------------
  606. /*
  607. - (void)downloadThumbnailWithMetadata:(tableMetadata*)metadata withWidth:(CGFloat)width andHeight:(CGFloat)height completion:(void (^)(NSString *message, NSInteger errorCode))completion
  608. {
  609. NSString *file = [NSString stringWithFormat:@"%@/%@.ico", [CCUtility getDirectoryProviderStorageFileID:metadata.fileID], metadata.fileNameView];
  610. if ([[NSFileManager defaultManager] fileExistsAtPath:file]) {
  611. completion(nil, 0);
  612. } else {
  613. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  614. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  615. [communication setUserAgent:[CCUtility getUserAgent]];
  616. [communication getRemoteThumbnailByServer:_activeUrl ofFilePath:[CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:metadata.serverUrl activeUrl:_activeUrl] withWidth:width andHeight:height onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSData *thumbnail, NSString *redirectedServer) {
  617. [thumbnail writeToFile:file atomically:YES];
  618. completion(nil, 0);
  619. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  620. NSString *message;
  621. NSInteger errorCode = response.statusCode;
  622. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  623. errorCode = error.code;
  624. // Error
  625. if (errorCode == 503)
  626. message = NSLocalizedString(@"_server_error_retry_", nil);
  627. else
  628. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  629. completion(message, errorCode);
  630. }];
  631. }
  632. }
  633. */
  634. - (void)downloadPreviewWithAccount:(NSString *)account metadata:(tableMetadata*)metadata withWidth:(CGFloat)width andHeight:(CGFloat)height completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  635. {
  636. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  637. if (tableAccount == nil) {
  638. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  639. }
  640. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  641. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  642. [communication setUserAgent:[CCUtility getUserAgent]];
  643. NSString *file = [NSString stringWithFormat:@"%@/%@.ico", [CCUtility getDirectoryProviderStorageFileID:metadata.fileID], metadata.fileNameView];
  644. [communication getRemotePreviewByServer:tableAccount.url ofFilePath:[CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:metadata.serverUrl activeUrl:tableAccount.url] withWidth:width andHeight:height andA:1 andMode:@"cover" onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSData *preview, NSString *redirectedServer) {
  645. [preview writeToFile:file atomically:YES];
  646. completion(account, nil, 0);
  647. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  648. NSString *message;
  649. NSInteger errorCode = response.statusCode;
  650. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  651. errorCode = error.code;
  652. // Error
  653. if (errorCode == 503)
  654. message = NSLocalizedString(@"_server_error_retry_", nil);
  655. else
  656. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  657. completion(account, message, errorCode);
  658. }];
  659. }
  660. - (void)downloadPreviewTrashWithAccount:(NSString *)account FileID:(NSString *)fileID fileName:(NSString *)fileName completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  661. {
  662. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  663. if (tableAccount == nil) {
  664. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  665. }
  666. NSString *file = [NSString stringWithFormat:@"%@/%@.ico", [CCUtility getDirectoryProviderStorageFileID:fileID], fileName];
  667. if ([[NSFileManager defaultManager] fileExistsAtPath:file]) {
  668. completion(account, nil, 0);
  669. } else {
  670. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  671. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  672. [communication setUserAgent:[CCUtility getUserAgent]];
  673. [communication getRemotePreviewTrashByServer:tableAccount.url ofFileID:fileID onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSData *preview, NSString *redirectedServer) {
  674. [preview writeToFile:file atomically:YES];
  675. completion(account, nil, 0);
  676. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  677. NSString *message;
  678. NSInteger errorCode = response.statusCode;
  679. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  680. errorCode = error.code;
  681. // Error
  682. if (errorCode == 503)
  683. message = NSLocalizedString(@"_server_error_retry_", nil);
  684. else
  685. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  686. completion(account, message, errorCode);
  687. }];
  688. }
  689. }
  690. #pragma --------------------------------------------------------------------------------------------
  691. #pragma mark ===== Favorite =====
  692. #pragma --------------------------------------------------------------------------------------------
  693. - (void)listingFavoritesWithAccount:(NSString *)account completion:(void(^)(NSString *account, NSArray *metadatas, NSString *message, NSInteger errorCode))completion
  694. {
  695. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  696. if (tableAccount == nil) {
  697. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  698. }
  699. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  700. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  701. [communication setUserAgent:[CCUtility getUserAgent]];
  702. NSString *path = [tableAccount.url stringByAppendingString:k_dav];
  703. [communication listingFavorites:path folder:@"" withUserSessionToken:nil onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer, NSString *token) {
  704. NSMutableArray *metadatas = [NSMutableArray new];
  705. BOOL showHiddenFiles = [CCUtility getShowHiddenFiles];
  706. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  707. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:tableAccount.url];
  708. // Order by fileNamePath
  709. items = [items sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
  710. OCFileDto *record1 = obj1, *record2 = obj2;
  711. NSString *path1 = [[record1.filePath stringByAppendingString:record1.fileName] lowercaseString];
  712. NSString *path2 = [[record2.filePath stringByAppendingString:record2.fileName] lowercaseString];
  713. return [path1 compare:path2];
  714. }];
  715. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  716. for(OCFileDto *itemDto in items) {
  717. NSString *serverUrl;
  718. BOOL isFolderEncrypted;
  719. NSString *fileName = [itemDto.fileName stringByReplacingOccurrencesOfString:@"/" withString:@""];
  720. // Skip hidden files
  721. if (fileName.length > 0) {
  722. if (!showHiddenFiles && [[fileName substringToIndex:1] isEqualToString:@"."])
  723. continue;
  724. } else
  725. continue;
  726. NSRange firstInstance = [itemDto.filePath rangeOfString:[NSString stringWithFormat:@"%@/files/%@", k_dav, tableAccount.userID]];
  727. NSString *serverPath = [itemDto.filePath substringFromIndex:firstInstance.length+firstInstance.location+1];
  728. if ([serverPath hasSuffix:@"/"])
  729. serverPath = [serverPath substringToIndex:[serverPath length] - 1];
  730. serverUrl = [CCUtility stringAppendServerUrl:[tableAccount.url stringByAppendingString:k_webDAV] addFileName:serverPath];
  731. if (itemDto.isDirectory) {
  732. (void)[[NCManageDatabase sharedInstance] addDirectoryWithEncrypted:itemDto.isEncrypted favorite:itemDto.isFavorite fileID:itemDto.ocId permissions:itemDto.permissions serverUrl:[NSString stringWithFormat:@"%@/%@", serverUrl, fileName] account:account];
  733. }
  734. isFolderEncrypted = [CCUtility isFolderEncrypted:serverUrl account:account];
  735. [metadatas addObject:[CCUtility trasformedOCFileToCCMetadata:itemDto fileName:itemDto.fileName serverUrl:serverUrl autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:account isFolderEncrypted:isFolderEncrypted]];
  736. }
  737. dispatch_async(dispatch_get_main_queue(), ^{
  738. completion(account, metadatas, nil, 0);
  739. });
  740. });
  741. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) {
  742. NSString *message;
  743. NSInteger errorCode = response.statusCode;
  744. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  745. errorCode = error.code;
  746. // Error
  747. if (errorCode == 503)
  748. message = NSLocalizedString(@"_server_error_retry_", nil);
  749. else
  750. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  751. completion(account, nil, message, errorCode);
  752. }];
  753. }
  754. - (void)settingFavoriteWithAccount:(NSString *)account fileName:(NSString *)fileName favorite:(BOOL)favorite completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  755. {
  756. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  757. if (tableAccount == nil) {
  758. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  759. }
  760. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  761. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  762. [communication setUserAgent:[CCUtility getUserAgent]];
  763. NSString *server = [tableAccount.url stringByAppendingString:k_dav];
  764. [communication settingFavoriteServer:server andFileOrFolderPath:fileName favorite:favorite withUserSessionToken:nil onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer, NSString *token) {
  765. completion(account, nil, 0);
  766. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) {
  767. NSString *message;
  768. NSInteger errorCode = response.statusCode;
  769. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  770. errorCode = error.code;
  771. // Error
  772. if (errorCode == 503)
  773. message = NSLocalizedString(@"_server_error_retry_", nil);
  774. else
  775. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  776. completion(account, message, errorCode);
  777. }];
  778. }
  779. #pragma --------------------------------------------------------------------------------------------
  780. #pragma mark ===== Share =====
  781. #pragma --------------------------------------------------------------------------------------------
  782. - (void)readShareWithAccount:(NSString *)account completion:(void (^)(NSString *account, NSArray *items, NSString *message, NSInteger errorCode))completion
  783. {
  784. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  785. if (tableAccount == nil) {
  786. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  787. }
  788. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  789. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  790. [communication setUserAgent:[CCUtility getUserAgent]];
  791. [communication readSharedByServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  792. completion(account, items, nil, 0);
  793. } failureRequest :^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  794. NSString *message = @"";
  795. NSInteger errorCode = response.statusCode;
  796. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  797. errorCode = error.code;
  798. // Error
  799. if (errorCode == 503) {
  800. message = NSLocalizedString(@"_server_error_retry_", nil);
  801. } else {
  802. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  803. }
  804. completion(account, nil, message, errorCode);
  805. }];
  806. }
  807. - (void)shareWithAccount:(NSString *)account fileName:(NSString *)fileName password:(NSString *)password permission:(NSInteger)permission hideDownload:(BOOL)hideDownload completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  808. {
  809. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  810. if (tableAccount == nil) {
  811. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  812. }
  813. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  814. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  815. [communication setUserAgent:[CCUtility getUserAgent]];
  816. [communication shareFileOrFolderByServer:[tableAccount.url stringByAppendingString:@"/"] andFileOrFolderPath:[fileName encodeString:NSUTF8StringEncoding] andPassword:[password encodeString:NSUTF8StringEncoding] andPermission:permission andHideDownload:hideDownload onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *token, NSString *redirectedServer) {
  817. completion(account, nil, 0);
  818. } failureRequest :^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  819. NSString *message = @"";
  820. NSInteger errorCode = response.statusCode;
  821. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  822. errorCode = error.code;
  823. // Error
  824. if (errorCode == 503) {
  825. message = NSLocalizedString(@"_server_error_retry_", nil);
  826. } else {
  827. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  828. }
  829. completion(account, message, errorCode);
  830. }];
  831. }
  832. // * @param shareeType -> NSInteger: to set the type of sharee (user/group/federated)
  833. - (void)shareUserGroupWithAccount:(NSString *)account userOrGroup:(NSString *)userOrGroup fileName:(NSString *)fileName permission:(NSInteger)permission shareeType:(NSInteger)shareeType completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  834. {
  835. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  836. if (tableAccount == nil) {
  837. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  838. }
  839. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  840. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  841. [communication setUserAgent:[CCUtility getUserAgent]];
  842. [communication shareWith:userOrGroup shareeType:shareeType inServer:[tableAccount.url stringByAppendingString:@"/"] andFileOrFolderPath:[fileName encodeString:NSUTF8StringEncoding] andPermissions:permission onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  843. completion(account, nil, 0);
  844. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  845. NSString *message = @"";
  846. NSInteger errorCode = response.statusCode;
  847. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  848. errorCode = error.code;
  849. // Error
  850. if (errorCode == 503) {
  851. message = NSLocalizedString(@"_server_error_retry_", nil);
  852. } else {
  853. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  854. }
  855. completion(account, message, errorCode);
  856. }];
  857. }
  858. - (void)shareUpdateAccount:(NSString *)account shareID:(NSInteger)shareID password:(NSString *)password permission:(NSInteger)permission expirationTime:(NSString *)expirationTime hideDownload:(BOOL)hideDownload completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  859. {
  860. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  861. if (tableAccount == nil) {
  862. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  863. }
  864. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  865. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  866. [communication setUserAgent:[CCUtility getUserAgent]];
  867. [communication updateShare:shareID ofServerPath:[tableAccount.url stringByAppendingString:@"/"] withPasswordProtect:[password encodeString:NSUTF8StringEncoding] andExpirationTime:expirationTime andPermissions:permission andHideDownload:hideDownload onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  868. completion(account, nil, 0);
  869. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  870. NSString *message = @"";
  871. NSInteger errorCode = response.statusCode;
  872. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  873. errorCode = error.code;
  874. // Error
  875. if (errorCode == 503) {
  876. message = NSLocalizedString(@"_server_error_retry_", nil);
  877. } else {
  878. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  879. }
  880. completion(account, message, errorCode);
  881. }];
  882. }
  883. - (void)unshareAccount:(NSString *)account shareID:(NSInteger)shareID completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  884. {
  885. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  886. if (tableAccount == nil) {
  887. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  888. }
  889. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  890. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  891. [communication setUserAgent:[CCUtility getUserAgent]];
  892. [communication unShareFileOrFolderByServer:[tableAccount.url stringByAppendingString:@"/"] andIdRemoteShared:shareID onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  893. completion(account, nil, 0);
  894. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  895. NSString *message = @"";
  896. NSInteger errorCode = response.statusCode;
  897. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  898. errorCode = error.code;
  899. // Error
  900. if (errorCode == 503) {
  901. message = NSLocalizedString(@"_server_error_retry_", nil);
  902. } else {
  903. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  904. }
  905. completion(account, message, errorCode);
  906. }];
  907. }
  908. - (void)getUserGroupWithAccount:(NSString *)account searchString:(NSString *)searchString completion:(void (^)(NSString *account, NSArray *item, NSString *message, NSInteger errorCode))completion
  909. {
  910. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  911. if (tableAccount == nil) {
  912. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  913. }
  914. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  915. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  916. [communication setUserAgent:[CCUtility getUserAgent]];
  917. [communication searchUsersAndGroupsWith:searchString forPage:1 with:50 ofServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *itemList, NSString *redirectedServer) {
  918. completion(account, itemList, nil, 0);
  919. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  920. NSString *message = @"";
  921. NSInteger errorCode = response.statusCode;
  922. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  923. errorCode = error.code;
  924. // Error
  925. if (errorCode == 503) {
  926. message = NSLocalizedString(@"_server_error_retry_", nil);
  927. } else {
  928. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  929. }
  930. completion(account, nil, message, errorCode);
  931. }];
  932. }
  933. - (void)getSharePermissionsFileWithAccount:(NSString *)account fileNamePath:(NSString *)fileNamePath completion:(void (^)(NSString *account, NSString *permissions, NSString *message, NSInteger errorCode))completion
  934. {
  935. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  936. if (tableAccount == nil) {
  937. completion(account, 0, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  938. }
  939. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  940. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  941. [communication setUserAgent:[CCUtility getUserAgent]];
  942. [communication getSharePermissionsFile:fileNamePath onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *permissions, NSString *redirectedServer) {
  943. completion(account, permissions, nil ,0);
  944. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  945. NSString *message = @"";
  946. NSInteger errorCode = response.statusCode;
  947. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  948. errorCode = error.code;
  949. // Error
  950. if (errorCode == 503) {
  951. message = NSLocalizedString(@"_server_error_retry_", nil);
  952. } else {
  953. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  954. }
  955. completion(account, nil, message, errorCode);
  956. }];
  957. }
  958. #pragma --------------------------------------------------------------------------------------------
  959. #pragma mark ===== API =====
  960. #pragma --------------------------------------------------------------------------------------------
  961. - (void)getActivityWithAccount:(NSString *)account completion:(void(^)(NSString *account, NSArray *listOfActivity, NSString *message, NSInteger errorCode))completion
  962. {
  963. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  964. if (tableAccount == nil) {
  965. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  966. }
  967. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  968. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  969. [communication setUserAgent:[CCUtility getUserAgent]];
  970. [communication getActivityServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfActivity, NSString *redirectedServer) {
  971. completion(account, listOfActivity, nil, 0);
  972. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  973. NSString *message;
  974. NSInteger errorCode = response.statusCode;
  975. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  976. errorCode = error.code;
  977. // Error
  978. if (errorCode == 503)
  979. message = NSLocalizedString(@"_server_error_retry_", nil);
  980. else
  981. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  982. completion(account, nil, message, errorCode);
  983. }];
  984. }
  985. - (void)getExternalSitesWithAccount:(NSString *)account completion:(void (^)(NSString *account, NSArray *listOfExternalSites, NSString *message, NSInteger errorCode))completion
  986. {
  987. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  988. if (tableAccount == nil) {
  989. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  990. }
  991. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  992. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  993. [communication setUserAgent:[CCUtility getUserAgent]];
  994. [communication getExternalSitesServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfExternalSites, NSString *redirectedServer) {
  995. completion(account, listOfExternalSites, nil, 0);
  996. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  997. NSString *message = @"";
  998. NSInteger errorCode = response.statusCode;
  999. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1000. errorCode = error.code;
  1001. // Error
  1002. if (errorCode == 503) {
  1003. message = NSLocalizedString(@"_server_error_retry_", nil);
  1004. } else {
  1005. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1006. }
  1007. completion(account, nil, message, errorCode);
  1008. }];
  1009. }
  1010. /*
  1011. - (void)middlewarePing
  1012. {
  1013. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1014. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  1015. [communication setUserAgent:[CCUtility getUserAgent]];
  1016. [communication getMiddlewarePing:_metadataNet.serverUrl onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfExternalSites, NSString *redirectedServer) {
  1017. [self complete];
  1018. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1019. NSInteger errorCode = response.statusCode;
  1020. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1021. errorCode = error.code;
  1022. // Error
  1023. if ([self.delegate respondsToSelector:@selector(getExternalSitesServerFailure:message:errorCode:)]) {
  1024. if (errorCode == 503)
  1025. [self.delegate getExternalSitesServerFailure:_metadataNet message:NSLocalizedString(@"_server_error_retry_", nil) errorCode:errorCode];
  1026. else
  1027. [self.delegate getExternalSitesServerFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1028. }
  1029. // Request trusted certificated
  1030. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  1031. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1032. [self complete];
  1033. }];
  1034. }
  1035. */
  1036. - (void)getNotificationWithAccount:(NSString *)account completion:(void (^)(NSString *account, NSArray *listOfNotifications, NSString *message, NSInteger errorCode))completion
  1037. {
  1038. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1039. if (tableAccount == nil) {
  1040. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1041. }
  1042. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1043. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1044. [communication setUserAgent:[CCUtility getUserAgent]];
  1045. [communication getNotificationServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfNotifications, NSString *redirectedServer) {
  1046. completion(account, listOfNotifications, nil, 0);
  1047. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1048. NSString *message = @"";
  1049. NSInteger errorCode = response.statusCode;
  1050. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1051. errorCode = error.code;
  1052. // Error
  1053. if (errorCode == 503) {
  1054. message = NSLocalizedString(@"_server_error_retry_", nil);
  1055. } else {
  1056. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1057. }
  1058. completion(account, nil, message, errorCode);
  1059. }];
  1060. }
  1061. - (void)setNotificationWithAccount:(NSString *)account serverUrl:(NSString *)serverUrl type:(NSString *)type completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  1062. {
  1063. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1064. if (tableAccount == nil) {
  1065. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1066. }
  1067. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1068. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1069. [communication setUserAgent:[CCUtility getUserAgent]];
  1070. [communication setNotificationServer:serverUrl type:type onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1071. completion(account, nil, 0);
  1072. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1073. NSString *message = @"";
  1074. NSInteger errorCode = response.statusCode;
  1075. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1076. errorCode = error.code;
  1077. // Error
  1078. if (errorCode == 503) {
  1079. message = NSLocalizedString(@"_server_error_retry_", nil);
  1080. } else {
  1081. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1082. }
  1083. completion(account, message, errorCode);
  1084. }];
  1085. }
  1086. - (void)getCapabilitiesWithAccount:(NSString *)account completion:(void (^)(NSString *account, OCCapabilities *capabilities, NSString *message, NSInteger errorCode))completion
  1087. {
  1088. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1089. if (tableAccount == nil) {
  1090. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1091. }
  1092. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1093. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1094. [communication setUserAgent:[CCUtility getUserAgent]];
  1095. [communication getCapabilitiesOfServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, OCCapabilities *capabilities, NSString *redirectedServer) {
  1096. completion(account, capabilities, nil, 0);
  1097. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1098. NSString *message = @"";
  1099. NSInteger errorCode = response.statusCode;
  1100. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1101. errorCode = error.code;
  1102. // Error
  1103. if (errorCode == 503) {
  1104. message = NSLocalizedString(@"_server_error_retry_", nil);
  1105. } else {
  1106. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1107. }
  1108. completion(account, nil, message, errorCode);
  1109. }];
  1110. }
  1111. - (void)getUserProfileWithAccount:(NSString *)account completion:(void (^)(NSString *account, OCUserProfile *userProfile, NSString *message, NSInteger errorCode))completion
  1112. {
  1113. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1114. if (tableAccount == nil) {
  1115. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1116. }
  1117. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1118. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1119. [communication setUserAgent:[CCUtility getUserAgent]];
  1120. [communication getUserProfileServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, OCUserProfile *userProfile, NSString *redirectedServer) {
  1121. completion(account, userProfile, nil, 0);
  1122. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1123. NSString *message = @"";
  1124. NSInteger errorCode = response.statusCode;
  1125. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1126. errorCode = error.code;
  1127. // Error
  1128. if (errorCode == 503) {
  1129. message = NSLocalizedString(@"_server_error_retry_", nil);
  1130. } else {
  1131. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1132. }
  1133. completion(account, nil, message, errorCode);
  1134. }];
  1135. }
  1136. #pragma --------------------------------------------------------------------------------------------
  1137. #pragma mark ===== Push Notification =====
  1138. #pragma --------------------------------------------------------------------------------------------
  1139. - (void)subscribingPushNotificationWithAccount:(NSString *)account url:(NSString *)url pushToken:(NSString *)pushToken Hash:(NSString *)pushTokenHash devicePublicKey:(NSString *)devicePublicKey completion:(void(^)(NSString *account, NSString *deviceIdentifier, NSString *deviceIdentifierSignature, NSString *publicKey, NSString *message, NSInteger errorCode))completion
  1140. {
  1141. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1142. if (tableAccount == nil) {
  1143. completion(account, nil, nil, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1144. }
  1145. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1146. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1147. [communication setUserAgent:[CCUtility getUserAgent]];
  1148. devicePublicKey = [CCUtility URLEncodeStringFromString:devicePublicKey];
  1149. [communication subscribingNextcloudServerPush:url pushTokenHash:pushTokenHash devicePublicKey:devicePublicKey proxyServerPath: [NCBrandOptions sharedInstance].pushNotificationServerProxy onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *publicKey, NSString *deviceIdentifier, NSString *signature, NSString *redirectedServer) {
  1150. deviceIdentifier = [CCUtility URLEncodeStringFromString:deviceIdentifier];
  1151. signature = [CCUtility URLEncodeStringFromString:signature];
  1152. publicKey = [CCUtility URLEncodeStringFromString:publicKey];
  1153. [communication subscribingPushProxy:[NCBrandOptions sharedInstance].pushNotificationServerProxy pushToken:pushToken deviceIdentifier:deviceIdentifier deviceIdentifierSignature:signature publicKey:publicKey onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1154. // Activity
  1155. [[NCManageDatabase sharedInstance] addActivityClient:[NCBrandOptions sharedInstance].pushNotificationServerProxy fileID:@"" action:k_activityDebugActionSubscribingPushProxy selector:@"" note:@"Service registered." type:k_activityTypeSuccess verbose:k_activityVerboseHigh activeUrl:@""];
  1156. completion(account, deviceIdentifier, signature, publicKey, nil, 0);
  1157. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1158. NSString *message;
  1159. NSInteger errorCode = response.statusCode;
  1160. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1161. errorCode = error.code;
  1162. // Error
  1163. if (errorCode == 503)
  1164. message = NSLocalizedString(@"_server_error_retry_", nil);
  1165. else
  1166. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1167. // Activity
  1168. [[NCManageDatabase sharedInstance] addActivityClient:[NCBrandOptions sharedInstance].pushNotificationServerProxy fileID:@"" action:k_activityDebugActionSubscribingPushProxy selector:@"" note:[error.userInfo valueForKey:@"NSLocalizedDescription"] type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:@""];
  1169. completion(account, nil, nil, nil, message, errorCode);
  1170. }];
  1171. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1172. NSString *message;
  1173. NSInteger errorCode = response.statusCode;
  1174. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1175. errorCode = error.code;
  1176. // Error
  1177. if (errorCode == 503)
  1178. message = NSLocalizedString(@"_server_error_retry_", nil);
  1179. else
  1180. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1181. completion(account, nil, nil, nil, message, errorCode);
  1182. }];
  1183. }
  1184. - (void)unsubscribingPushNotificationWithAccount:(NSString *)account url:(NSString *)url deviceIdentifier:(NSString *)deviceIdentifier deviceIdentifierSignature:(NSString *)deviceIdentifierSignature publicKey:(NSString *)publicKey completion:(void (^)(NSString *account ,NSString *message, NSInteger errorCode))completion {
  1185. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1186. if (tableAccount == nil) {
  1187. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1188. }
  1189. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1190. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1191. [communication setUserAgent:[CCUtility getUserAgent]];
  1192. [communication unsubscribingNextcloudServerPush:url onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1193. [communication unsubscribingPushProxy:[NCBrandOptions sharedInstance].pushNotificationServerProxy deviceIdentifier:deviceIdentifier deviceIdentifierSignature:deviceIdentifierSignature publicKey:publicKey onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1194. completion(account, nil, 0);
  1195. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1196. NSString *message;
  1197. NSInteger errorCode = response.statusCode;
  1198. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1199. errorCode = error.code;
  1200. // Error
  1201. if (errorCode == 503)
  1202. message = NSLocalizedString(@"_server_error_retry_", nil);
  1203. else
  1204. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1205. completion(account, message, errorCode);
  1206. }];
  1207. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1208. NSString *message;
  1209. NSInteger errorCode = response.statusCode;
  1210. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1211. errorCode = error.code;
  1212. // Error
  1213. if (errorCode == 503)
  1214. message = NSLocalizedString(@"_server_error_retry_", nil);
  1215. else
  1216. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1217. completion(account, message, errorCode);
  1218. }];
  1219. }
  1220. #pragma --------------------------------------------------------------------------------------------
  1221. #pragma mark ===== Manage Mobile Editor OCS API =====
  1222. #pragma --------------------------------------------------------------------------------------------
  1223. - (void)createLinkRichdocumentsWithAccount:(NSString *)account fileID:(NSString *)fileID completion:(void(^)(NSString *account, NSString *link, NSString *message, NSInteger errorCode))completion
  1224. {
  1225. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1226. if (tableAccount == nil) {
  1227. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1228. }
  1229. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1230. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1231. [communication setUserAgent:[CCUtility getUserAgent]];
  1232. NSString *fileIDServer = [[NCUtility sharedInstance] convertFileIDClientToFileIDServer:fileID];
  1233. [communication createLinkRichdocuments:[tableAccount.url stringByAppendingString:@"/"] fileID:fileIDServer onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *link, NSString *redirectedServer) {
  1234. completion(account, link, nil, 0);
  1235. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1236. NSString *message;
  1237. NSInteger errorCode = response.statusCode;
  1238. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1239. errorCode = error.code;
  1240. // Error
  1241. if (errorCode == 503)
  1242. message = NSLocalizedString(@"_server_error_retry_", nil);
  1243. else
  1244. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1245. completion(account, nil,message, errorCode);
  1246. }];
  1247. }
  1248. - (void)geTemplatesRichdocumentsWithAccount:(NSString *)account typeTemplate:(NSString *)typeTemplate completion:(void(^)(NSString *account, NSArray *listOfTemplate, NSString *message, NSInteger errorCode))completion
  1249. {
  1250. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1251. if (tableAccount == nil) {
  1252. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1253. }
  1254. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1255. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1256. [communication setUserAgent:[CCUtility getUserAgent]];
  1257. [communication geTemplatesRichdocuments:[tableAccount.url stringByAppendingString:@"/"] typeTemplate:typeTemplate onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfTemplate, NSString *redirectedServer) {
  1258. completion(account, listOfTemplate, nil, 0);
  1259. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1260. NSString *message;
  1261. NSInteger errorCode = response.statusCode;
  1262. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1263. errorCode = error.code;
  1264. // Error
  1265. if (errorCode == 503)
  1266. message = NSLocalizedString(@"_server_error_retry_", nil);
  1267. else
  1268. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1269. completion(account, nil, message, errorCode);
  1270. }];
  1271. }
  1272. - (void)createNewRichdocumentsWithAccount:(NSString *)account fileName:(NSString *)fileName serverUrl:(NSString *)serverUrl templateID:(NSString *)templateID completion:(void(^)(NSString *account, NSString *url, NSString *message, NSInteger errorCode))completion
  1273. {
  1274. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1275. if (tableAccount == nil) {
  1276. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1277. }
  1278. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1279. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1280. [communication setUserAgent:[CCUtility getUserAgent]];
  1281. [communication createNewRichdocuments:[tableAccount.url stringByAppendingString:@"/"] path:fileName templateID:templateID onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *url, NSString *redirectedServer) {
  1282. completion(account, url, nil, 0);
  1283. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1284. NSString *message;
  1285. NSInteger errorCode = response.statusCode;
  1286. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1287. errorCode = error.code;
  1288. // Error
  1289. if (errorCode == 503)
  1290. message = NSLocalizedString(@"_server_error_retry_", nil);
  1291. else
  1292. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1293. completion(account, nil, message, errorCode);
  1294. }];
  1295. }
  1296. - (void)createAssetRichdocumentsWithAccount:(NSString *)account fileName:(NSString *)fileName serverUrl:(NSString *)serverUrl completion:(void(^)(NSString *account, NSString *link, NSString *message, NSInteger errorCode))completion
  1297. {
  1298. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1299. if (tableAccount == nil) {
  1300. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1301. }
  1302. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1303. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1304. [communication setUserAgent:[CCUtility getUserAgent]];
  1305. NSString *fileNamePath = [CCUtility returnFileNamePathFromFileName:fileName serverUrl:serverUrl activeUrl:tableAccount.url];
  1306. [communication createAssetRichdocuments:[tableAccount.url stringByAppendingString:@"/"] path:fileNamePath onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *url, NSString *redirectedServer) {
  1307. completion(account, url, nil, 0);
  1308. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1309. NSString *message;
  1310. NSInteger errorCode = response.statusCode;
  1311. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1312. errorCode = error.code;
  1313. // Error
  1314. if (errorCode == 503)
  1315. message = NSLocalizedString(@"_server_error_retry_", nil);
  1316. else
  1317. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1318. completion(account, nil, message, errorCode);
  1319. }];
  1320. }
  1321. #pragma --------------------------------------------------------------------------------------------
  1322. #pragma mark ===== Trash =====
  1323. #pragma --------------------------------------------------------------------------------------------
  1324. - (void)listingTrashWithAccount:(NSString *)account path:(NSString *)path serverUrl:(NSString *)serverUrl completion:(void (^)(NSString *account, NSArray *items, NSString *message, NSInteger errorCode))completion
  1325. {
  1326. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1327. if (tableAccount == nil) {
  1328. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1329. }
  1330. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1331. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1332. [communication setUserAgent:[CCUtility getUserAgent]];
  1333. [communication listingTrash:[serverUrl stringByAppendingString:path] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  1334. // Check items > 0
  1335. if ([items count] == 0) {
  1336. #ifndef EXTENSION
  1337. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  1338. [appDelegate messageNotification:@"Server error" description:@"Read Folder WebDAV : [items NULL] please fix" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  1339. #endif
  1340. completion(account, nil, NSLocalizedString(@"Read Folder WebDAV : [items NULL] please fix", nil), k_CCErrorInternalError);
  1341. } else {
  1342. NSMutableArray *listTrash = [NSMutableArray new];
  1343. //OCFileDto *itemDtoFolder = [items objectAtIndex:0];
  1344. if ([items count] > 1) {
  1345. for (NSUInteger i=1; i < [items count]; i++) {
  1346. OCFileDto *itemDto = [items objectAtIndex:i];
  1347. tableTrash *trash = [tableTrash new];
  1348. trash.account = account;
  1349. trash.date = [NSDate dateWithTimeIntervalSince1970:itemDto.date];
  1350. trash.directory = itemDto.isDirectory;
  1351. trash.fileID = itemDto.ocId;
  1352. trash.fileName = itemDto.fileName;
  1353. trash.filePath = itemDto.filePath;
  1354. trash.size = itemDto.size;
  1355. trash.trashbinFileName = itemDto.trashbinFileName;
  1356. trash.trashbinOriginalLocation = itemDto.trashbinOriginalLocation;
  1357. trash.trashbinDeletionTime = [NSDate dateWithTimeIntervalSince1970:itemDto.trashbinDeletionTime];
  1358. [CCUtility insertTypeFileIconName:trash.trashbinFileName metadata:(tableMetadata *)trash];
  1359. [listTrash addObject:trash];
  1360. }
  1361. }
  1362. completion(account, listTrash, nil, 0);
  1363. }
  1364. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1365. NSString *message;
  1366. NSInteger errorCode = response.statusCode;
  1367. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1368. errorCode = error.code;
  1369. // Error
  1370. if (errorCode == 503)
  1371. message = NSLocalizedString(@"_server_error_retry_", nil);
  1372. else
  1373. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1374. completion(account, nil,message, errorCode);
  1375. }];
  1376. }
  1377. - (void)emptyTrashWithAccount:(NSString *)account completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  1378. {
  1379. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1380. if (tableAccount == nil) {
  1381. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1382. }
  1383. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1384. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1385. [communication setUserAgent:[CCUtility getUserAgent]];
  1386. NSString *path = [NSString stringWithFormat:@"%@%@/trashbin/%@/trash", tableAccount.url, k_dav, tableAccount.userID];
  1387. [communication emptyTrash:path onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1388. completion(account, nil, 0);
  1389. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1390. NSString *message;
  1391. NSInteger errorCode = response.statusCode;
  1392. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1393. errorCode = error.code;
  1394. // Error
  1395. if (errorCode == 503)
  1396. message = NSLocalizedString(@"_server_error_retry_", nil);
  1397. else
  1398. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1399. completion(account, message, errorCode);
  1400. }];
  1401. }
  1402. @end
  1403. #pragma --------------------------------------------------------------------------------------------
  1404. #pragma mark ===== OCURLSessionManager =====
  1405. #pragma --------------------------------------------------------------------------------------------
  1406. @implementation OCURLSessionManager
  1407. - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
  1408. {
  1409. // The pinnning check
  1410. if ([[CCCertificate sharedManager] checkTrustedChallenge:challenge]) {
  1411. completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  1412. } else {
  1413. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  1414. }
  1415. }
  1416. @end