OCNetworking.m 99 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997
  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 delegate:(id)delegate 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:delegate 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, NSLocalizedString(@"_no_nextcloud_found_", nil), k_CCErrorInternalError);
  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 progress:(void(^)(NSProgress *progress))uploadProgress 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. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  289. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  290. [communication setUserAgent:[CCUtility getUserAgent]];
  291. NSURLSessionTask *sessionTask = [communication uploadFileSession:fileNameLocalPath toDestiny:fileNameServerUrl onCommunication:communication progress:^(NSProgress *progress) {
  292. uploadProgress(progress);
  293. //float percent = roundf (progress.fractionCompleted * 100);
  294. } successRequest:^(NSURLResponse *response, NSString *redirectedServer) {
  295. NSDictionary *fields = [(NSHTTPURLResponse*)response allHeaderFields];
  296. NSString *fileID = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-FileId"]];
  297. NSString *etag = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-ETag"]];
  298. NSDate *date = [CCUtility dateEnUsPosixFromCloud:[fields objectForKey:@"Date"]];
  299. completion(account, fileID, etag, date, nil, 0);
  300. } failureRequest:^(NSURLResponse *response, NSString *redirectedServer, NSError *error) {
  301. NSString *message;
  302. NSInteger errorCode;
  303. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
  304. errorCode = httpResponse.statusCode;
  305. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  306. errorCode = error.code;
  307. // Error
  308. if (errorCode == 503)
  309. message = NSLocalizedString(@"_server_error_retry_", nil);
  310. else
  311. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  312. completion(account, nil, nil, nil, message, errorCode);
  313. } failureBeforeRequest:^(NSError *error) {
  314. completion(account, nil, nil, nil, error.description, error.code);
  315. }];
  316. return sessionTask;
  317. }
  318. #pragma --------------------------------------------------------------------------------------------
  319. #pragma mark ===== WebDav =====
  320. #pragma --------------------------------------------------------------------------------------------
  321. - (void)readFolderWithAccount:(NSString *)account serverUrl:(NSString *)serverUrl selector:(NSString *)selector depth:(NSString *)depth delegate:(id)delegate
  322. {
  323. [self readFolderWithAccount:account serverUrl:serverUrl depth:depth completion:^(NSString *account, NSArray *metadatas, tableMetadata *metadataFolder, NSString *message, NSInteger errorCode) {
  324. if ([delegate respondsToSelector:@selector(readFolderSuccessFailureWithAccount:serverUrl:metadataFolder:metadatas:selector:message:errorCode:)])
  325. [delegate readFolderSuccessFailureWithAccount:account serverUrl:serverUrl metadataFolder:metadataFolder metadatas:metadatas selector:selector message:message errorCode:errorCode];
  326. }];
  327. }
  328. - (void)readFolderWithAccount:(NSString *)account serverUrl:(NSString *)serverUrl depth:(NSString *)depth completion:(void(^)(NSString *account, NSArray *metadatas, tableMetadata *metadataFolder, NSString *message, NSInteger errorCode))completion
  329. {
  330. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  331. if (tableAccount == nil) {
  332. completion(account, nil, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  333. }
  334. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  335. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  336. [communication setUserAgent:[CCUtility getUserAgent]];
  337. [communication readFolder:serverUrl depth:depth withUserSessionToken:nil onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer, NSString *token) {
  338. // Check items > 0
  339. if ([items count] == 0) {
  340. #ifndef EXTENSION
  341. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  342. [appDelegate messageNotification:@"Server error" description:@"Read Folder WebDAV : [items NULL] please fix" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  343. #endif
  344. completion(account, nil, nil, NSLocalizedString(@"Read Folder WebDAV : [items NULL] please fix", nil), k_CCErrorInternalError);
  345. } else {
  346. BOOL showHiddenFiles = [CCUtility getShowHiddenFiles];
  347. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:serverUrl account:account];
  348. // directory [0]
  349. OCFileDto *itemDtoFolder = [items objectAtIndex:0];
  350. //NSDate *date = [NSDate dateWithTimeIntervalSince1970:itemDtoDirectory.date];
  351. NSMutableArray *metadatas = [NSMutableArray new];
  352. tableMetadata *metadataFolder = [tableMetadata new];
  353. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  354. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:tableAccount.url];
  355. NSString *serverUrlFolder;
  356. // Metadata . (self Folder)
  357. if ([serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:tableAccount.url]]) {
  358. // root folder
  359. serverUrlFolder = k_serverUrl_root;
  360. metadataFolder = [CCUtility trasformedOCFileToCCMetadata:itemDtoFolder fileName:@"." serverUrl:serverUrlFolder autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:account isFolderEncrypted:isFolderEncrypted];
  361. } else {
  362. serverUrlFolder = [CCUtility deletingLastPathComponentFromServerUrl:serverUrl];
  363. metadataFolder = [CCUtility trasformedOCFileToCCMetadata:itemDtoFolder fileName:[serverUrl lastPathComponent] serverUrl:serverUrlFolder autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:account isFolderEncrypted:isFolderEncrypted];
  364. }
  365. // Add metadata folder
  366. (void)[[NCManageDatabase sharedInstance] addDirectoryWithEncrypted:itemDtoFolder.isEncrypted favorite:itemDtoFolder.isFavorite fileID:itemDtoFolder.ocId permissions:itemDtoFolder.permissions serverUrl:serverUrl account:account];
  367. NSArray *itemsSortedArray = [items sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
  368. NSString *first = [(OCFileDto*)a fileName];
  369. NSString *second = [(OCFileDto*)b fileName];
  370. return [[first lowercaseString] compare:[second lowercaseString]];
  371. }];
  372. for (NSUInteger i=1; i < [itemsSortedArray count]; i++) {
  373. OCFileDto *itemDto = [itemsSortedArray objectAtIndex:i];
  374. NSString *fileName = [itemDto.fileName stringByReplacingOccurrencesOfString:@"/" withString:@""];
  375. // Skip hidden files
  376. if (fileName.length > 0) {
  377. if (!showHiddenFiles && [[fileName substringToIndex:1] isEqualToString:@"."])
  378. continue;
  379. } else {
  380. continue;
  381. }
  382. if (itemDto.isDirectory) {
  383. (void)[[NCManageDatabase sharedInstance] addDirectoryWithEncrypted:itemDto.isEncrypted favorite:itemDto.isFavorite fileID:itemDto.ocId permissions:itemDto.permissions serverUrl:[CCUtility stringAppendServerUrl:serverUrl addFileName:fileName] account:account];
  384. }
  385. [metadatas addObject:[CCUtility trasformedOCFileToCCMetadata:itemDto fileName:itemDto.fileName serverUrl:serverUrl autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:account isFolderEncrypted:isFolderEncrypted]];
  386. }
  387. completion(account, metadatas, metadataFolder, nil, 0);
  388. }
  389. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) {
  390. NSString *message;
  391. NSInteger errorCode = response.statusCode;
  392. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  393. errorCode = error.code;
  394. // Error
  395. if (errorCode == 503)
  396. message = NSLocalizedString(@"_server_error_retry_", nil);
  397. else
  398. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  399. completion(account, nil, nil, message, errorCode);
  400. }];
  401. }
  402. - (void)readFileWithAccount:(NSString *)account serverUrl:(NSString *)serverUrl fileName:(NSString *)fileName completion:(void(^)(NSString *account, tableMetadata *metadata, NSString *message, NSInteger errorCode))completion
  403. {
  404. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  405. if (tableAccount == nil) {
  406. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  407. }
  408. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  409. NSString *fileNamePath;
  410. if (fileName) {
  411. fileNamePath = [NSString stringWithFormat:@"%@/%@", serverUrl, fileName];
  412. } else {
  413. fileName= @".";
  414. fileNamePath = serverUrl;
  415. }
  416. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  417. [communication setUserAgent:[CCUtility getUserAgent]];
  418. [communication readFile:fileNamePath onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  419. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:serverUrl account:account];
  420. if ([items count] > 0) {
  421. tableMetadata *metadata = [tableMetadata new];
  422. OCFileDto *itemDto = [items objectAtIndex:0];
  423. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  424. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:tableAccount.url];
  425. metadata = [CCUtility trasformedOCFileToCCMetadata:itemDto fileName:fileName serverUrl:serverUrl autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:account isFolderEncrypted:isFolderEncrypted];
  426. completion(account, metadata, nil, 0);
  427. // BUG 1038 item == 0
  428. } else {
  429. #ifndef EXTENSION
  430. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  431. [appDelegate messageNotification:@"Server error" description:@"Read File WebDAV : [items NULL] please fix" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  432. #endif
  433. completion(account, nil, NSLocalizedString(@"Read File WebDAV : [items NULL] please fix", nil), k_CCErrorInternalError);
  434. }
  435. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  436. NSString *message;
  437. NSInteger errorCode = response.statusCode;
  438. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  439. errorCode = error.code;
  440. // Error
  441. if (errorCode == 503)
  442. message = NSLocalizedString(@"_server_error_retry_", nil);
  443. else
  444. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  445. completion(account, nil, message, errorCode);
  446. }];
  447. }
  448. - (void)createFolderWithAccount:(NSString *)account serverUrl:(NSString *)serverUrl fileName:(NSString *)fileName completion:(void(^)(NSString *account, NSString *fileID, NSDate *date, NSString *message, NSInteger errorCode))completion
  449. {
  450. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  451. if (tableAccount == nil) {
  452. completion(account, nil, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  453. }
  454. NSString *path = [NSString stringWithFormat:@"%@/%@", serverUrl, fileName];
  455. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  456. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:tableAccount.url];
  457. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  458. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  459. [communication setUserAgent:[CCUtility getUserAgent]];
  460. [communication createFolder:path onCommunication:communication withForbiddenCharactersSupported:YES successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  461. NSDictionary *fields = [response allHeaderFields];
  462. NSString *fileID = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-FileId"]];
  463. NSDate *date = [CCUtility dateEnUsPosixFromCloud:[fields objectForKey:@"Date"]];
  464. completion(account, fileID, date, nil, 0);
  465. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  466. NSString *message;
  467. if (([fileName isEqualToString:autoUploadFileName] && [serverUrl isEqualToString:autoUploadDirectory]))
  468. message = nil;
  469. else
  470. message = [CCError manageErrorOC:response.statusCode error:error];
  471. NSInteger errorCode = response.statusCode;
  472. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  473. errorCode = error.code;
  474. completion(account, nil, nil, message, errorCode);
  475. } errorBeforeRequest:^(NSError *error) {
  476. NSString *message;
  477. if (([fileName isEqualToString:autoUploadFileName] && [serverUrl isEqualToString:autoUploadDirectory]))
  478. message = nil;
  479. else {
  480. if (error.code == OCErrorForbidenCharacters)
  481. message = NSLocalizedString(@"_forbidden_characters_from_server_", nil);
  482. else
  483. message = NSLocalizedString(@"_unknow_response_server_", nil);
  484. }
  485. completion(account, nil, nil, message, error.code);
  486. }];
  487. }
  488. - (void)deleteFileOrFolderWithAccount:(NSString *)account path:(NSString *)path completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  489. {
  490. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  491. if (tableAccount == nil) {
  492. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  493. }
  494. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  495. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  496. [communication setUserAgent:[CCUtility getUserAgent]];
  497. [communication deleteFileOrFolder:path onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  498. completion(account, nil, 0);
  499. } failureRquest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  500. NSString *message;
  501. NSInteger errorCode = response.statusCode;
  502. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  503. errorCode = error.code;
  504. // Error
  505. if (errorCode == 503)
  506. message = NSLocalizedString(@"_server_error_retry_", nil);
  507. else
  508. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  509. completion(account, message, errorCode);
  510. }];
  511. }
  512. - (void)moveFileOrFolderWithAccount:(NSString *)account fileName:(NSString *)fileName fileNameTo:(NSString *)fileNameTo completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  513. {
  514. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  515. if (tableAccount == nil) {
  516. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  517. }
  518. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  519. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  520. [communication setUserAgent:[CCUtility getUserAgent]];
  521. [communication moveFileOrFolder:fileName toDestiny:fileNameTo onCommunication:communication withForbiddenCharactersSupported:YES successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  522. completion(account, nil, 0);
  523. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  524. NSInteger errorCode = response.statusCode;
  525. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  526. errorCode = error.code;
  527. NSString *message = [CCError manageErrorOC:response.statusCode error:error];
  528. completion(account, message, error.code);
  529. } errorBeforeRequest:^(NSError *error) {
  530. NSString *message;
  531. if (error.code == OCErrorMovingTheDestinyAndOriginAreTheSame) {
  532. message = NSLocalizedString(@"_error_folder_destiny_is_the_same_", nil);
  533. } else if (error.code == OCErrorMovingFolderInsideHimself) {
  534. message = NSLocalizedString(@"_error_folder_destiny_is_the_same_", nil);
  535. } else if (error.code == OCErrorMovingDestinyNameHaveForbiddenCharacters) {
  536. message = NSLocalizedString(@"_forbidden_characters_from_server_", nil);
  537. } else {
  538. message = NSLocalizedString(@"_unknow_response_server_", nil);
  539. }
  540. completion(account, message, error.code);
  541. }];
  542. }
  543. - (void)searchWithAccount:(NSString *)account fileName:(NSString *)fileName serverUrl:(NSString *)serverUrl contentType:(NSArray *)contentType lteDateLastModified:(NSDate *)lteDateLastModified gteDateLastModified:(NSDate *)gteDateLastModified depth:(NSString *)depth completion:(void(^)(NSString *account, NSArray *metadatas, NSString *message, NSInteger errorCode))completion
  544. {
  545. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  546. if (tableAccount == nil) {
  547. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  548. }
  549. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  550. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  551. [communication setUserAgent:[CCUtility getUserAgent]];
  552. NSString *path = [tableAccount.url stringByAppendingString:k_dav];
  553. NSString *folder = [serverUrl stringByReplacingOccurrencesOfString:[CCUtility getHomeServerUrlActiveUrl:tableAccount.url] withString:@""];
  554. NSString *lteDateLastModifiedString;
  555. NSString *gteDateLastModifiedString;
  556. if (lteDateLastModified) {
  557. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  558. NSLocale *enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
  559. [dateFormatter setLocale:enUSPOSIXLocale];
  560. [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZZ"];
  561. lteDateLastModifiedString = [dateFormatter stringFromDate:lteDateLastModified];
  562. }
  563. if (gteDateLastModified) {
  564. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  565. NSLocale *enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
  566. [dateFormatter setLocale:enUSPOSIXLocale];
  567. [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZZ"];
  568. gteDateLastModifiedString = [dateFormatter stringFromDate:gteDateLastModified];
  569. }
  570. [communication search:path folder:folder fileName: [NSString stringWithFormat:@"%%%@%%", fileName] depth:depth lteDateLastModified:lteDateLastModifiedString gteDateLastModified:gteDateLastModifiedString contentType:contentType withUserSessionToken:nil onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer, NSString *token) {
  571. NSMutableArray *metadatas = [NSMutableArray new];
  572. BOOL showHiddenFiles = [CCUtility getShowHiddenFiles];
  573. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  574. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:tableAccount.url];
  575. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  576. for (OCFileDto *itemDto in items) {
  577. NSString *serverUrl;
  578. BOOL isFolderEncrypted;
  579. NSString *fileName = [itemDto.fileName stringByReplacingOccurrencesOfString:@"/" withString:@""];
  580. // Skip hidden files
  581. if (fileName.length > 0) {
  582. if (!showHiddenFiles && [[fileName substringToIndex:1] isEqualToString:@"."])
  583. continue;
  584. } else
  585. continue;
  586. NSRange firstInstance = [itemDto.filePath rangeOfString:[NSString stringWithFormat:@"%@/files/%@", k_dav, tableAccount.userID]];
  587. NSString *serverPath = [itemDto.filePath substringFromIndex:firstInstance.length+firstInstance.location+1];
  588. if ([serverPath hasSuffix:@"/"]) serverPath = [serverPath substringToIndex:[serverPath length] - 1];
  589. serverUrl = [CCUtility stringAppendServerUrl:[tableAccount.url stringByAppendingString:k_webDAV] addFileName:serverPath];
  590. if (itemDto.isDirectory) {
  591. (void)[[NCManageDatabase sharedInstance] addDirectoryWithEncrypted:itemDto.isEncrypted favorite:itemDto.isFavorite fileID:itemDto.ocId permissions:itemDto.permissions serverUrl:[NSString stringWithFormat:@"%@/%@", serverUrl, fileName] account:account];
  592. }
  593. isFolderEncrypted = [CCUtility isFolderEncrypted:serverUrl account:account];
  594. [metadatas addObject:[CCUtility trasformedOCFileToCCMetadata:itemDto fileName:itemDto.fileName serverUrl:serverUrl autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:account isFolderEncrypted:isFolderEncrypted]];
  595. }
  596. dispatch_async(dispatch_get_main_queue(), ^{
  597. completion(account, metadatas, nil, 0);
  598. });
  599. });
  600. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) {
  601. NSString *message = @"";
  602. NSInteger errorCode = response.statusCode;
  603. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  604. errorCode = error.code;
  605. // Error
  606. if (errorCode == 503) {
  607. message = NSLocalizedString(@"_server_error_retry_", nil);
  608. } else {
  609. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  610. }
  611. completion(account, nil, message, errorCode);
  612. }];
  613. }
  614. #pragma --------------------------------------------------------------------------------------------
  615. #pragma mark ===== downloadPreview =====
  616. #pragma --------------------------------------------------------------------------------------------
  617. /*
  618. - (void)downloadThumbnailWithMetadata:(tableMetadata*)metadata withWidth:(CGFloat)width andHeight:(CGFloat)height completion:(void (^)(NSString *message, NSInteger errorCode))completion
  619. {
  620. NSString *file = [NSString stringWithFormat:@"%@/%@.ico", [CCUtility getDirectoryProviderStorageFileID:metadata.fileID], metadata.fileNameView];
  621. if ([[NSFileManager defaultManager] fileExistsAtPath:file]) {
  622. completion(nil, 0);
  623. } else {
  624. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  625. [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
  626. [communication setUserAgent:[CCUtility getUserAgent]];
  627. [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) {
  628. [thumbnail writeToFile:file atomically:YES];
  629. completion(nil, 0);
  630. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  631. NSString *message;
  632. NSInteger errorCode = response.statusCode;
  633. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  634. errorCode = error.code;
  635. // Error
  636. if (errorCode == 503)
  637. message = NSLocalizedString(@"_server_error_retry_", nil);
  638. else
  639. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  640. completion(message, errorCode);
  641. }];
  642. }
  643. }
  644. */
  645. - (void)downloadPreviewWithAccount:(NSString *)account metadata:(tableMetadata*)metadata withWidth:(CGFloat)width andHeight:(CGFloat)height completion:(void (^)(NSString *account, UIImage *image, NSString *message, NSInteger errorCode))completion
  646. {
  647. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  648. if (tableAccount == nil) {
  649. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  650. }
  651. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  652. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  653. [communication setUserAgent:[CCUtility getUserAgent]];
  654. NSString *file = [NSString stringWithFormat:@"%@/%@.ico", [CCUtility getDirectoryProviderStorageFileID:metadata.fileID], metadata.fileNameView];
  655. [communication getRemotePreviewByServer:tableAccount.url ofFilePath:[CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:metadata.serverUrl activeUrl:tableAccount.url] withWidth:width andHeight:height andA:1 andMode:@"cover" path:@"" onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSData *preview, NSString *redirectedServer) {
  656. [preview writeToFile:file atomically:YES];
  657. completion(account, [UIImage imageWithData:preview], nil, 0);
  658. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  659. NSString *message;
  660. NSInteger errorCode = response.statusCode;
  661. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  662. errorCode = error.code;
  663. // Error
  664. if (errorCode == 503)
  665. message = NSLocalizedString(@"_server_error_retry_", nil);
  666. else
  667. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  668. completion(account, nil, message, errorCode);
  669. }];
  670. }
  671. - (void)downloadPreviewWithAccount:(NSString *)account serverPath:(NSString *)serverPath fileNamePath:(NSString *)fileNamePath completion:(void (^)(NSString *account, UIImage *image, NSString *message, NSInteger errorCode))completion
  672. {
  673. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  674. if (tableAccount == nil) {
  675. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  676. }
  677. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  678. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  679. [communication setUserAgent:[CCUtility getUserAgent]];
  680. [communication getRemotePreviewByServer:tableAccount.url ofFilePath:@"" withWidth:0 andHeight:0 andA:0 andMode:@"" path:serverPath onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSData *preview, NSString *redirectedServer) {
  681. [preview writeToFile:fileNamePath atomically:YES];
  682. completion(account, [UIImage imageWithData:preview], nil, 0);
  683. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  684. NSString *message;
  685. NSInteger errorCode = response.statusCode;
  686. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  687. errorCode = error.code;
  688. // Error
  689. if (errorCode == 503)
  690. message = NSLocalizedString(@"_server_error_retry_", nil);
  691. else
  692. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  693. completion(account, nil, message, errorCode);
  694. }];
  695. }
  696. - (void)downloadPreviewTrashWithAccount:(NSString *)account FileID:(NSString *)fileID fileName:(NSString *)fileName completion:(void (^)(NSString *account, UIImage *image, NSString *message, NSInteger errorCode))completion
  697. {
  698. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  699. if (tableAccount == nil) {
  700. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  701. }
  702. NSString *file = [NSString stringWithFormat:@"%@/%@.ico", [CCUtility getDirectoryProviderStorageFileID:fileID], fileName];
  703. if ([[NSFileManager defaultManager] fileExistsAtPath:file]) {
  704. completion(account, [UIImage imageWithContentsOfFile:file], nil, 0);
  705. } else {
  706. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  707. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  708. [communication setUserAgent:[CCUtility getUserAgent]];
  709. [communication getRemotePreviewTrashByServer:tableAccount.url ofFileID:fileID onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSData *preview, NSString *redirectedServer) {
  710. [preview writeToFile:file atomically:YES];
  711. completion(account, [UIImage imageWithData:preview], nil, 0);
  712. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  713. NSString *message;
  714. NSInteger errorCode = response.statusCode;
  715. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  716. errorCode = error.code;
  717. // Error
  718. if (errorCode == 503)
  719. message = NSLocalizedString(@"_server_error_retry_", nil);
  720. else
  721. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  722. completion(account, nil, message, errorCode);
  723. }];
  724. }
  725. }
  726. #pragma --------------------------------------------------------------------------------------------
  727. #pragma mark ===== Favorite =====
  728. #pragma --------------------------------------------------------------------------------------------
  729. - (void)listingFavoritesWithAccount:(NSString *)account completion:(void(^)(NSString *account, NSArray *metadatas, NSString *message, NSInteger errorCode))completion
  730. {
  731. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  732. if (tableAccount == nil) {
  733. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  734. }
  735. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  736. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  737. [communication setUserAgent:[CCUtility getUserAgent]];
  738. NSString *path = [tableAccount.url stringByAppendingString:k_dav];
  739. [communication listingFavorites:path folder:@"" withUserSessionToken:nil onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer, NSString *token) {
  740. NSMutableArray *metadatas = [NSMutableArray new];
  741. BOOL showHiddenFiles = [CCUtility getShowHiddenFiles];
  742. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  743. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:tableAccount.url];
  744. // Order by fileNamePath
  745. items = [items sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
  746. OCFileDto *record1 = obj1, *record2 = obj2;
  747. NSString *path1 = [[record1.filePath stringByAppendingString:record1.fileName] lowercaseString];
  748. NSString *path2 = [[record2.filePath stringByAppendingString:record2.fileName] lowercaseString];
  749. return [path1 compare:path2];
  750. }];
  751. for(OCFileDto *itemDto in items) {
  752. NSString *serverUrl;
  753. BOOL isFolderEncrypted;
  754. NSString *fileName = [itemDto.fileName stringByReplacingOccurrencesOfString:@"/" withString:@""];
  755. // Skip hidden files
  756. if (fileName.length > 0) {
  757. if (!showHiddenFiles && [[fileName substringToIndex:1] isEqualToString:@"."])
  758. continue;
  759. } else
  760. continue;
  761. NSRange firstInstance = [itemDto.filePath rangeOfString:[NSString stringWithFormat:@"%@/files/%@", k_dav, tableAccount.userID]];
  762. NSString *serverPath = [itemDto.filePath substringFromIndex:firstInstance.length+firstInstance.location+1];
  763. if ([serverPath hasSuffix:@"/"])
  764. serverPath = [serverPath substringToIndex:[serverPath length] - 1];
  765. serverUrl = [CCUtility stringAppendServerUrl:[tableAccount.url stringByAppendingString:k_webDAV] addFileName:serverPath];
  766. if (itemDto.isDirectory) {
  767. (void)[[NCManageDatabase sharedInstance] addDirectoryWithEncrypted:itemDto.isEncrypted favorite:itemDto.isFavorite fileID:itemDto.ocId permissions:itemDto.permissions serverUrl:[NSString stringWithFormat:@"%@/%@", serverUrl, fileName] account:account];
  768. }
  769. isFolderEncrypted = [CCUtility isFolderEncrypted:serverUrl account:account];
  770. [metadatas addObject:[CCUtility trasformedOCFileToCCMetadata:itemDto fileName:itemDto.fileName serverUrl:serverUrl autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory activeAccount:account isFolderEncrypted:isFolderEncrypted]];
  771. }
  772. completion(account, metadatas, nil, 0);
  773. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) {
  774. NSString *message;
  775. NSInteger errorCode = response.statusCode;
  776. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  777. errorCode = error.code;
  778. // Error
  779. if (errorCode == 503)
  780. message = NSLocalizedString(@"_server_error_retry_", nil);
  781. else
  782. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  783. completion(account, nil, message, errorCode);
  784. }];
  785. }
  786. - (void)settingFavoriteWithAccount:(NSString *)account fileName:(NSString *)fileName favorite:(BOOL)favorite completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  787. {
  788. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  789. if (tableAccount == nil) {
  790. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  791. }
  792. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  793. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  794. [communication setUserAgent:[CCUtility getUserAgent]];
  795. NSString *server = [tableAccount.url stringByAppendingString:k_dav];
  796. [communication settingFavoriteServer:server andFileOrFolderPath:fileName favorite:favorite withUserSessionToken:nil onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer, NSString *token) {
  797. completion(account, nil, 0);
  798. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) {
  799. NSString *message;
  800. NSInteger errorCode = response.statusCode;
  801. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  802. errorCode = error.code;
  803. // Error
  804. if (errorCode == 503)
  805. message = NSLocalizedString(@"_server_error_retry_", nil);
  806. else
  807. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  808. completion(account, message, errorCode);
  809. }];
  810. }
  811. #pragma --------------------------------------------------------------------------------------------
  812. #pragma mark ===== Share =====
  813. #pragma --------------------------------------------------------------------------------------------
  814. - (void)readShareWithAccount:(NSString *)account completion:(void (^)(NSString *account, NSArray *items, NSString *message, NSInteger errorCode))completion
  815. {
  816. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  817. if (tableAccount == nil) {
  818. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  819. }
  820. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  821. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  822. [communication setUserAgent:[CCUtility getUserAgent]];
  823. [communication readSharedByServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  824. completion(account, items, nil, 0);
  825. } failureRequest :^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  826. NSString *message = @"";
  827. NSInteger errorCode = response.statusCode;
  828. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  829. errorCode = error.code;
  830. // Error
  831. if (errorCode == 503) {
  832. message = NSLocalizedString(@"_server_error_retry_", nil);
  833. } else {
  834. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  835. }
  836. completion(account, nil, message, errorCode);
  837. }];
  838. }
  839. - (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
  840. {
  841. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  842. if (tableAccount == nil) {
  843. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  844. }
  845. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  846. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  847. [communication setUserAgent:[CCUtility getUserAgent]];
  848. [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) {
  849. completion(account, nil, 0);
  850. } failureRequest :^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  851. NSString *message = @"";
  852. NSInteger errorCode = response.statusCode;
  853. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  854. errorCode = error.code;
  855. // Error
  856. if (errorCode == 503) {
  857. message = NSLocalizedString(@"_server_error_retry_", nil);
  858. } else {
  859. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  860. }
  861. completion(account, message, errorCode);
  862. }];
  863. }
  864. // * @param shareeType -> NSInteger: to set the type of sharee (user/group/federated)
  865. - (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
  866. {
  867. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  868. if (tableAccount == nil) {
  869. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  870. }
  871. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  872. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  873. [communication setUserAgent:[CCUtility getUserAgent]];
  874. [communication shareWith:userOrGroup shareeType:shareeType inServer:[tableAccount.url stringByAppendingString:@"/"] andFileOrFolderPath:[fileName encodeString:NSUTF8StringEncoding] andPermissions:permission onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  875. completion(account, nil, 0);
  876. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  877. NSString *message = @"";
  878. NSInteger errorCode = response.statusCode;
  879. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  880. errorCode = error.code;
  881. // Error
  882. if (errorCode == 503) {
  883. message = NSLocalizedString(@"_server_error_retry_", nil);
  884. } else {
  885. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  886. }
  887. completion(account, message, errorCode);
  888. }];
  889. }
  890. - (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
  891. {
  892. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  893. if (tableAccount == nil) {
  894. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  895. }
  896. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  897. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  898. [communication setUserAgent:[CCUtility getUserAgent]];
  899. [communication updateShare:shareID ofServerPath:[tableAccount.url stringByAppendingString:@"/"] withPasswordProtect:[password encodeString:NSUTF8StringEncoding] andExpirationTime:expirationTime andPermissions:permission andHideDownload:hideDownload onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  900. completion(account, nil, 0);
  901. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  902. NSString *message = @"";
  903. NSInteger errorCode = response.statusCode;
  904. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  905. errorCode = error.code;
  906. // Error
  907. if (errorCode == 503) {
  908. message = NSLocalizedString(@"_server_error_retry_", nil);
  909. } else {
  910. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  911. }
  912. completion(account, message, errorCode);
  913. }];
  914. }
  915. - (void)unshareAccount:(NSString *)account shareID:(NSInteger)shareID completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  916. {
  917. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  918. if (tableAccount == nil) {
  919. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  920. }
  921. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  922. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  923. [communication setUserAgent:[CCUtility getUserAgent]];
  924. [communication unShareFileOrFolderByServer:[tableAccount.url stringByAppendingString:@"/"] andIdRemoteShared:shareID onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  925. completion(account, nil, 0);
  926. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  927. NSString *message = @"";
  928. NSInteger errorCode = response.statusCode;
  929. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  930. errorCode = error.code;
  931. // Error
  932. if (errorCode == 503) {
  933. message = NSLocalizedString(@"_server_error_retry_", nil);
  934. } else {
  935. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  936. }
  937. completion(account, message, errorCode);
  938. }];
  939. }
  940. - (void)getUserGroupWithAccount:(NSString *)account searchString:(NSString *)searchString completion:(void (^)(NSString *account, NSArray *item, NSString *message, NSInteger errorCode))completion
  941. {
  942. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  943. if (tableAccount == nil) {
  944. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  945. }
  946. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  947. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  948. [communication setUserAgent:[CCUtility getUserAgent]];
  949. [communication searchUsersAndGroupsWith:searchString forPage:1 with:50 ofServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *itemList, NSString *redirectedServer) {
  950. completion(account, itemList, nil, 0);
  951. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  952. NSString *message = @"";
  953. NSInteger errorCode = response.statusCode;
  954. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  955. errorCode = error.code;
  956. // Error
  957. if (errorCode == 503) {
  958. message = NSLocalizedString(@"_server_error_retry_", nil);
  959. } else {
  960. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  961. }
  962. completion(account, nil, message, errorCode);
  963. }];
  964. }
  965. - (void)getSharePermissionsFileWithAccount:(NSString *)account fileNamePath:(NSString *)fileNamePath completion:(void (^)(NSString *account, NSString *permissions, NSString *message, NSInteger errorCode))completion
  966. {
  967. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  968. if (tableAccount == nil) {
  969. completion(account, 0, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  970. }
  971. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  972. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  973. [communication setUserAgent:[CCUtility getUserAgent]];
  974. [communication getSharePermissionsFile:fileNamePath onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *permissions, NSString *redirectedServer) {
  975. completion(account, permissions, nil ,0);
  976. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  977. NSString *message = @"";
  978. NSInteger errorCode = response.statusCode;
  979. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  980. errorCode = error.code;
  981. // Error
  982. if (errorCode == 503) {
  983. message = NSLocalizedString(@"_server_error_retry_", nil);
  984. } else {
  985. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  986. }
  987. completion(account, nil, message, errorCode);
  988. }];
  989. }
  990. #pragma --------------------------------------------------------------------------------------------
  991. #pragma mark ===== API =====
  992. #pragma --------------------------------------------------------------------------------------------
  993. - (void)getActivityWithAccount:(NSString *)account since:(NSInteger)since limit:(NSInteger)limit link:(NSString *)link completion:(void(^)(NSString *account, NSArray *listOfActivity, NSString *message, NSInteger errorCode))completion
  994. {
  995. BOOL previews = false;
  996. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  997. if (tableAccount == nil) {
  998. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  999. }
  1000. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1001. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1002. [communication setUserAgent:[CCUtility getUserAgent]];
  1003. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilitesWithAccount:account];
  1004. if (capabilities != nil && capabilities.versionMajor >= k_nextcloud_version_15_0) {
  1005. previews = true;
  1006. }
  1007. [communication getActivityServer:[tableAccount.url stringByAppendingString:@"/"] since:since limit:limit previews:previews link:link onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfActivity, NSString *redirectedServer) {
  1008. completion(account, listOfActivity, nil, 0);
  1009. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1010. NSString *message;
  1011. NSInteger errorCode = response.statusCode;
  1012. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1013. errorCode = error.code;
  1014. // Error
  1015. if (errorCode == 503)
  1016. message = NSLocalizedString(@"_server_error_retry_", nil);
  1017. else
  1018. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1019. completion(account, nil, message, errorCode);
  1020. }];
  1021. }
  1022. - (void)getExternalSitesWithAccount:(NSString *)account completion:(void (^)(NSString *account, NSArray *listOfExternalSites, NSString *message, NSInteger errorCode))completion
  1023. {
  1024. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1025. if (tableAccount == nil) {
  1026. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1027. }
  1028. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1029. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1030. [communication setUserAgent:[CCUtility getUserAgent]];
  1031. [communication getExternalSitesServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfExternalSites, NSString *redirectedServer) {
  1032. completion(account, listOfExternalSites, nil, 0);
  1033. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1034. NSString *message = @"";
  1035. NSInteger errorCode = response.statusCode;
  1036. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1037. errorCode = error.code;
  1038. // Error
  1039. if (errorCode == 503) {
  1040. message = NSLocalizedString(@"_server_error_retry_", nil);
  1041. } else {
  1042. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1043. }
  1044. completion(account, nil, message, errorCode);
  1045. }];
  1046. }
  1047. /*
  1048. - (void)middlewarePing
  1049. {
  1050. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  1051. [communication setCredentialsWithUser:_activeUser andPassword:_activePassword];
  1052. [communication setUserAgent:[CCUtility getUserAgent]];
  1053. [communication getMiddlewarePing:_metadataNet.serverUrl onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfExternalSites, NSString *redirectedServer) {
  1054. [self complete];
  1055. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1056. NSInteger errorCode = response.statusCode;
  1057. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1058. errorCode = error.code;
  1059. // Error
  1060. if ([self.delegate respondsToSelector:@selector(getExternalSitesServerFailure:message:errorCode:)]) {
  1061. if (errorCode == 503)
  1062. [self.delegate getExternalSitesServerFailure:_metadataNet message:NSLocalizedString(@"_server_error_retry_", nil) errorCode:errorCode];
  1063. else
  1064. [self.delegate getExternalSitesServerFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
  1065. }
  1066. // Request trusted certificated
  1067. if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
  1068. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  1069. [self complete];
  1070. }];
  1071. }
  1072. */
  1073. - (void)getNotificationWithAccount:(NSString *)account completion:(void (^)(NSString *account, NSArray *listOfNotifications, NSString *message, NSInteger errorCode))completion
  1074. {
  1075. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1076. if (tableAccount == nil) {
  1077. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1078. }
  1079. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1080. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1081. [communication setUserAgent:[CCUtility getUserAgent]];
  1082. [communication getNotificationServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfNotifications, NSString *redirectedServer) {
  1083. completion(account, listOfNotifications, nil, 0);
  1084. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1085. NSString *message = @"";
  1086. NSInteger errorCode = response.statusCode;
  1087. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1088. errorCode = error.code;
  1089. // Error
  1090. if (errorCode == 503) {
  1091. message = NSLocalizedString(@"_server_error_retry_", nil);
  1092. } else {
  1093. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1094. }
  1095. completion(account, nil, message, errorCode);
  1096. }];
  1097. }
  1098. - (void)setNotificationWithAccount:(NSString *)account serverUrl:(NSString *)serverUrl type:(NSString *)type completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  1099. {
  1100. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1101. if (tableAccount == nil) {
  1102. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1103. }
  1104. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1105. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1106. [communication setUserAgent:[CCUtility getUserAgent]];
  1107. [communication setNotificationServer:serverUrl type:type onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1108. completion(account, nil, 0);
  1109. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1110. NSString *message = @"";
  1111. NSInteger errorCode = response.statusCode;
  1112. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1113. errorCode = error.code;
  1114. // Error
  1115. if (errorCode == 503) {
  1116. message = NSLocalizedString(@"_server_error_retry_", nil);
  1117. } else {
  1118. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1119. }
  1120. completion(account, message, errorCode);
  1121. }];
  1122. }
  1123. - (void)getCapabilitiesWithAccount:(NSString *)account completion:(void (^)(NSString *account, OCCapabilities *capabilities, NSString *message, NSInteger errorCode))completion
  1124. {
  1125. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1126. if (tableAccount == nil) {
  1127. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1128. }
  1129. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1130. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1131. [communication setUserAgent:[CCUtility getUserAgent]];
  1132. [communication getCapabilitiesOfServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, OCCapabilities *capabilities, NSString *redirectedServer) {
  1133. completion(account, capabilities, nil, 0);
  1134. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1135. NSString *message = @"";
  1136. NSInteger errorCode = response.statusCode;
  1137. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1138. errorCode = error.code;
  1139. // Error
  1140. if (errorCode == 503) {
  1141. message = NSLocalizedString(@"_server_error_retry_", nil);
  1142. } else {
  1143. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1144. }
  1145. completion(account, nil, message, errorCode);
  1146. }];
  1147. }
  1148. - (void)getUserProfileWithAccount:(NSString *)account completion:(void (^)(NSString *account, OCUserProfile *userProfile, NSString *message, NSInteger errorCode))completion
  1149. {
  1150. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1151. if (tableAccount == nil) {
  1152. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1153. }
  1154. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1155. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1156. [communication setUserAgent:[CCUtility getUserAgent]];
  1157. [communication getUserProfileServer:[tableAccount.url stringByAppendingString:@"/"] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, OCUserProfile *userProfile, NSString *redirectedServer) {
  1158. completion(account, userProfile, nil, 0);
  1159. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1160. NSString *message = @"";
  1161. NSInteger errorCode = response.statusCode;
  1162. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1163. errorCode = error.code;
  1164. // Error
  1165. if (errorCode == 503) {
  1166. message = NSLocalizedString(@"_server_error_retry_", nil);
  1167. } else {
  1168. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1169. }
  1170. completion(account, nil, message, errorCode);
  1171. }];
  1172. }
  1173. #pragma --------------------------------------------------------------------------------------------
  1174. #pragma mark ===== Push Notification =====
  1175. #pragma --------------------------------------------------------------------------------------------
  1176. - (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
  1177. {
  1178. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1179. if (tableAccount == nil) {
  1180. completion(account, nil, nil, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1181. }
  1182. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1183. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1184. [communication setUserAgent:[CCUtility getUserAgent]];
  1185. devicePublicKey = [CCUtility URLEncodeStringFromString:devicePublicKey];
  1186. [communication subscribingNextcloudServerPush:url pushTokenHash:pushTokenHash devicePublicKey:devicePublicKey proxyServerPath: [NCBrandOptions sharedInstance].pushNotificationServerProxy onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *publicKey, NSString *deviceIdentifier, NSString *signature, NSString *redirectedServer) {
  1187. deviceIdentifier = [CCUtility URLEncodeStringFromString:deviceIdentifier];
  1188. signature = [CCUtility URLEncodeStringFromString:signature];
  1189. publicKey = [CCUtility URLEncodeStringFromString:publicKey];
  1190. [communication subscribingPushProxy:[NCBrandOptions sharedInstance].pushNotificationServerProxy pushToken:pushToken deviceIdentifier:deviceIdentifier deviceIdentifierSignature:signature publicKey:publicKey onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1191. completion(account, deviceIdentifier, signature, publicKey, nil, 0);
  1192. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1193. NSString *message;
  1194. NSInteger errorCode = response.statusCode;
  1195. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1196. errorCode = error.code;
  1197. // Error
  1198. if (errorCode == 503)
  1199. message = NSLocalizedString(@"_server_error_retry_", nil);
  1200. else
  1201. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1202. completion(account, nil, nil, nil, message, errorCode);
  1203. }];
  1204. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1205. NSString *message;
  1206. NSInteger errorCode = response.statusCode;
  1207. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1208. errorCode = error.code;
  1209. // Error
  1210. if (errorCode == 503)
  1211. message = NSLocalizedString(@"_server_error_retry_", nil);
  1212. else
  1213. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1214. completion(account, nil, nil, nil, message, errorCode);
  1215. }];
  1216. }
  1217. - (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 {
  1218. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1219. if (tableAccount == nil) {
  1220. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1221. }
  1222. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1223. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1224. [communication setUserAgent:[CCUtility getUserAgent]];
  1225. [communication unsubscribingNextcloudServerPush:url onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1226. [communication unsubscribingPushProxy:[NCBrandOptions sharedInstance].pushNotificationServerProxy deviceIdentifier:deviceIdentifier deviceIdentifierSignature:deviceIdentifierSignature publicKey:publicKey onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1227. completion(account, nil, 0);
  1228. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1229. NSString *message;
  1230. NSInteger errorCode = response.statusCode;
  1231. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1232. errorCode = error.code;
  1233. // Error
  1234. if (errorCode == 503)
  1235. message = NSLocalizedString(@"_server_error_retry_", nil);
  1236. else
  1237. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1238. completion(account, message, errorCode);
  1239. }];
  1240. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1241. NSString *message;
  1242. NSInteger errorCode = response.statusCode;
  1243. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1244. errorCode = error.code;
  1245. // Error
  1246. if (errorCode == 503)
  1247. message = NSLocalizedString(@"_server_error_retry_", nil);
  1248. else
  1249. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1250. completion(account, message, errorCode);
  1251. }];
  1252. }
  1253. #pragma --------------------------------------------------------------------------------------------
  1254. #pragma mark ===== Manage Mobile Editor OCS API =====
  1255. #pragma --------------------------------------------------------------------------------------------
  1256. - (void)createLinkRichdocumentsWithAccount:(NSString *)account fileID:(NSString *)fileID completion:(void(^)(NSString *account, NSString *link, NSString *message, NSInteger errorCode))completion
  1257. {
  1258. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1259. if (tableAccount == nil) {
  1260. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1261. }
  1262. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1263. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1264. [communication setUserAgent:[CCUtility getUserAgent]];
  1265. NSString *fileIDServer = [[NCUtility sharedInstance] convertFileIDClientToFileIDServer:fileID];
  1266. [communication createLinkRichdocuments:[tableAccount.url stringByAppendingString:@"/"] fileID:fileIDServer onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *link, NSString *redirectedServer) {
  1267. completion(account, link, nil, 0);
  1268. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1269. NSString *message;
  1270. NSInteger errorCode = response.statusCode;
  1271. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1272. errorCode = error.code;
  1273. // Error
  1274. if (errorCode == 503)
  1275. message = NSLocalizedString(@"_server_error_retry_", nil);
  1276. else
  1277. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1278. completion(account, nil,message, errorCode);
  1279. }];
  1280. }
  1281. - (void)geTemplatesRichdocumentsWithAccount:(NSString *)account typeTemplate:(NSString *)typeTemplate completion:(void(^)(NSString *account, NSArray *listOfTemplate, NSString *message, NSInteger errorCode))completion
  1282. {
  1283. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1284. if (tableAccount == nil) {
  1285. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1286. }
  1287. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1288. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1289. [communication setUserAgent:[CCUtility getUserAgent]];
  1290. [communication geTemplatesRichdocuments:[tableAccount.url stringByAppendingString:@"/"] typeTemplate:typeTemplate onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *listOfTemplate, NSString *redirectedServer) {
  1291. completion(account, listOfTemplate, nil, 0);
  1292. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1293. NSString *message;
  1294. NSInteger errorCode = response.statusCode;
  1295. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1296. errorCode = error.code;
  1297. // Error
  1298. if (errorCode == 503)
  1299. message = NSLocalizedString(@"_server_error_retry_", nil);
  1300. else
  1301. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1302. completion(account, nil, message, errorCode);
  1303. }];
  1304. }
  1305. - (void)createNewRichdocumentsWithAccount:(NSString *)account fileName:(NSString *)fileName serverUrl:(NSString *)serverUrl templateID:(NSString *)templateID completion:(void(^)(NSString *account, NSString *url, NSString *message, NSInteger errorCode))completion
  1306. {
  1307. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1308. if (tableAccount == nil) {
  1309. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1310. }
  1311. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1312. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1313. [communication setUserAgent:[CCUtility getUserAgent]];
  1314. [communication createNewRichdocuments:[tableAccount.url stringByAppendingString:@"/"] path:fileName templateID:templateID onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *url, NSString *redirectedServer) {
  1315. completion(account, url, nil, 0);
  1316. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1317. NSString *message;
  1318. NSInteger errorCode = response.statusCode;
  1319. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1320. errorCode = error.code;
  1321. // Error
  1322. if (errorCode == 503)
  1323. message = NSLocalizedString(@"_server_error_retry_", nil);
  1324. else
  1325. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1326. completion(account, nil, message, errorCode);
  1327. }];
  1328. }
  1329. - (void)createAssetRichdocumentsWithAccount:(NSString *)account fileName:(NSString *)fileName serverUrl:(NSString *)serverUrl completion:(void(^)(NSString *account, NSString *link, NSString *message, NSInteger errorCode))completion
  1330. {
  1331. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1332. if (tableAccount == nil) {
  1333. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1334. }
  1335. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1336. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1337. [communication setUserAgent:[CCUtility getUserAgent]];
  1338. NSString *fileNamePath = [CCUtility returnFileNamePathFromFileName:fileName serverUrl:serverUrl activeUrl:tableAccount.url];
  1339. [communication createAssetRichdocuments:[tableAccount.url stringByAppendingString:@"/"] path:fileNamePath onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *url, NSString *redirectedServer) {
  1340. completion(account, url, nil, 0);
  1341. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1342. NSString *message;
  1343. NSInteger errorCode = response.statusCode;
  1344. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1345. errorCode = error.code;
  1346. // Error
  1347. if (errorCode == 503)
  1348. message = NSLocalizedString(@"_server_error_retry_", nil);
  1349. else
  1350. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1351. completion(account, nil, message, errorCode);
  1352. }];
  1353. }
  1354. #pragma --------------------------------------------------------------------------------------------
  1355. #pragma mark ===== Trash =====
  1356. #pragma --------------------------------------------------------------------------------------------
  1357. - (void)listingTrashWithAccount:(NSString *)account path:(NSString *)path serverUrl:(NSString *)serverUrl completion:(void (^)(NSString *account, NSArray *items, NSString *message, NSInteger errorCode))completion
  1358. {
  1359. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1360. if (tableAccount == nil) {
  1361. completion(account, nil, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1362. }
  1363. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1364. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1365. [communication setUserAgent:[CCUtility getUserAgent]];
  1366. [communication listingTrash:[serverUrl stringByAppendingString:path] onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  1367. // Check items > 0
  1368. if ([items count] == 0) {
  1369. #ifndef EXTENSION
  1370. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  1371. [appDelegate messageNotification:@"Server error" description:@"Read Folder WebDAV : [items NULL] please fix" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  1372. #endif
  1373. completion(account, nil, NSLocalizedString(@"Read Folder WebDAV : [items NULL] please fix", nil), k_CCErrorInternalError);
  1374. } else {
  1375. NSMutableArray *listTrash = [NSMutableArray new];
  1376. //OCFileDto *itemDtoFolder = [items objectAtIndex:0];
  1377. if ([items count] > 1) {
  1378. for (NSUInteger i=1; i < [items count]; i++) {
  1379. OCFileDto *itemDto = [items objectAtIndex:i];
  1380. tableTrash *trash = [tableTrash new];
  1381. trash.account = account;
  1382. trash.date = [NSDate dateWithTimeIntervalSince1970:itemDto.date];
  1383. trash.directory = itemDto.isDirectory;
  1384. trash.fileID = itemDto.ocId;
  1385. trash.fileName = itemDto.fileName;
  1386. trash.filePath = itemDto.filePath;
  1387. trash.size = itemDto.size;
  1388. trash.trashbinFileName = itemDto.trashbinFileName;
  1389. trash.trashbinOriginalLocation = itemDto.trashbinOriginalLocation;
  1390. trash.trashbinDeletionTime = [NSDate dateWithTimeIntervalSince1970:itemDto.trashbinDeletionTime];
  1391. [CCUtility insertTypeFileIconName:trash.trashbinFileName metadata:(tableMetadata *)trash];
  1392. [listTrash addObject:trash];
  1393. }
  1394. }
  1395. completion(account, listTrash, nil, 0);
  1396. }
  1397. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1398. NSString *message;
  1399. NSInteger errorCode = response.statusCode;
  1400. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1401. errorCode = error.code;
  1402. // Error
  1403. if (errorCode == 503)
  1404. message = NSLocalizedString(@"_server_error_retry_", nil);
  1405. else
  1406. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1407. completion(account, nil,message, errorCode);
  1408. }];
  1409. }
  1410. - (void)emptyTrashWithAccount:(NSString *)account completion:(void (^)(NSString *account, NSString *message, NSInteger errorCode))completion
  1411. {
  1412. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  1413. if (tableAccount == nil) {
  1414. completion(account, NSLocalizedString(@"_error_user_not_available_", nil), k_CCErrorUserNotAvailble);
  1415. }
  1416. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  1417. [communication setCredentialsWithUser:tableAccount.user andUserID:tableAccount.userID andPassword:tableAccount.password];
  1418. [communication setUserAgent:[CCUtility getUserAgent]];
  1419. NSString *path = [NSString stringWithFormat:@"%@%@/trashbin/%@/trash", tableAccount.url, k_dav, tableAccount.userID];
  1420. [communication emptyTrash:path onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  1421. completion(account, nil, 0);
  1422. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  1423. NSString *message;
  1424. NSInteger errorCode = response.statusCode;
  1425. if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
  1426. errorCode = error.code;
  1427. // Error
  1428. if (errorCode == 503)
  1429. message = NSLocalizedString(@"_server_error_retry_", nil);
  1430. else
  1431. message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
  1432. completion(account, message, errorCode);
  1433. }];
  1434. }
  1435. @end
  1436. #pragma --------------------------------------------------------------------------------------------
  1437. #pragma mark ===== OCURLSessionManager =====
  1438. #pragma --------------------------------------------------------------------------------------------
  1439. @implementation OCURLSessionManager
  1440. - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
  1441. {
  1442. // The pinnning check
  1443. if ([[CCCertificate sharedManager] checkTrustedChallenge:challenge]) {
  1444. completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  1445. } else {
  1446. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  1447. }
  1448. }
  1449. @end