CCNetworking.m 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373
  1. //
  2. // CCNetworking.m
  3. // Nextcloud iOS
  4. //
  5. // Created by Marino Faggiana on 01/06/15.
  6. // Copyright (c) 2017 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  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 "CCNetworking.h"
  24. #import "NCEndToEndEncryption.h"
  25. #import "NCNetworkingEndToEnd.h"
  26. #import "AppDelegate.h"
  27. #import "CCCertificate.h"
  28. #import "NSDate+ISO8601.h"
  29. #import "NSString+Encode.h"
  30. #import "NCBridgeSwift.h"
  31. @interface CCNetworking ()
  32. {
  33. NSMutableDictionary *_taskData;
  34. NSString *_activeAccount;
  35. NSString *_activePassword;
  36. NSString *_activeUser;
  37. NSString *_activeUserID;
  38. NSString *_activeUrl;
  39. NSString *_directoryUser;
  40. }
  41. @end
  42. @implementation CCNetworking
  43. + (CCNetworking *)sharedNetworking {
  44. static CCNetworking *sharedNetworking;
  45. @synchronized(self)
  46. {
  47. if (!sharedNetworking) {
  48. sharedNetworking = [[CCNetworking alloc] init];
  49. }
  50. return sharedNetworking;
  51. }
  52. }
  53. - (id)init
  54. {
  55. self = [super init];
  56. _taskData = [[NSMutableDictionary alloc] init];
  57. _delegates = [[NSMutableDictionary alloc] init];
  58. // Initialization Sessions
  59. [self sessionDownload];
  60. [self sessionDownloadForeground];
  61. [self sessionWWanDownload];
  62. [self sessionUpload];
  63. [self sessionWWanUpload];
  64. [self sessionUploadForeground];
  65. // *** NOT Initialize ONLY for EXTENSION !!!!! ***
  66. // [self sessionUploadExtension];
  67. [self sharedOCCommunication];
  68. [self settingAccount];
  69. return self;
  70. }
  71. - (void)settingAccount
  72. {
  73. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  74. _activeAccount = tableAccount.account;
  75. _activePassword = tableAccount.password;
  76. _activeUser = tableAccount.user;
  77. _activeUserID = tableAccount.userID;
  78. _activeUrl = tableAccount.url;
  79. _directoryUser = [CCUtility getDirectoryActiveUser:_activeUser activeUrl:_activeUrl];
  80. }
  81. #pragma --------------------------------------------------------------------------------------------
  82. #pragma mark ===== Session =====
  83. #pragma --------------------------------------------------------------------------------------------
  84. - (NSURLSession *)sessionDownload
  85. {
  86. static NSURLSession *sessionDownload = nil;
  87. if (sessionDownload == nil) {
  88. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_download_session];
  89. configuration.allowsCellularAccess = YES;
  90. configuration.sessionSendsLaunchEvents = YES;
  91. configuration.discretionary = NO;
  92. configuration.HTTPMaximumConnectionsPerHost = 1;
  93. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  94. sessionDownload = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  95. sessionDownload.sessionDescription = k_download_session;
  96. }
  97. return sessionDownload;
  98. }
  99. - (NSURLSession *)sessionDownloadForeground
  100. {
  101. static NSURLSession *sessionDownloadForeground = nil;
  102. if (sessionDownloadForeground == nil) {
  103. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  104. configuration.allowsCellularAccess = YES;
  105. configuration.discretionary = NO;
  106. configuration.HTTPMaximumConnectionsPerHost = 1;
  107. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  108. sessionDownloadForeground = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  109. sessionDownloadForeground.sessionDescription = k_download_session_foreground;
  110. }
  111. return sessionDownloadForeground;
  112. }
  113. - (NSURLSession *)sessionWWanDownload
  114. {
  115. static NSURLSession *sessionWWanDownload = nil;
  116. if (sessionWWanDownload == nil) {
  117. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_download_session_wwan];
  118. configuration.allowsCellularAccess = NO;
  119. configuration.sessionSendsLaunchEvents = YES;
  120. configuration.discretionary = NO;
  121. configuration.HTTPMaximumConnectionsPerHost = 1;
  122. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  123. sessionWWanDownload = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  124. sessionWWanDownload.sessionDescription = k_download_session_wwan;
  125. }
  126. return sessionWWanDownload;
  127. }
  128. - (NSURLSession *)sessionUpload
  129. {
  130. static NSURLSession *sessionUpload = nil;
  131. if (sessionUpload == nil) {
  132. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_upload_session];
  133. configuration.allowsCellularAccess = YES;
  134. configuration.sessionSendsLaunchEvents = YES;
  135. configuration.discretionary = NO;
  136. configuration.HTTPMaximumConnectionsPerHost = 1;
  137. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  138. sessionUpload = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  139. sessionUpload.sessionDescription = k_upload_session;
  140. }
  141. return sessionUpload;
  142. }
  143. - (NSURLSession *)sessionWWanUpload
  144. {
  145. static NSURLSession *sessionWWanUpload = nil;
  146. if (sessionWWanUpload == nil) {
  147. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_upload_session_wwan];
  148. configuration.allowsCellularAccess = NO;
  149. configuration.sessionSendsLaunchEvents = YES;
  150. configuration.discretionary = NO;
  151. configuration.HTTPMaximumConnectionsPerHost = 1;
  152. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  153. sessionWWanUpload = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  154. sessionWWanUpload.sessionDescription = k_upload_session_wwan;
  155. }
  156. return sessionWWanUpload;
  157. }
  158. - (NSURLSession *)sessionUploadForeground
  159. {
  160. static NSURLSession *sessionUploadForeground;
  161. if (sessionUploadForeground == nil) {
  162. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  163. configuration.allowsCellularAccess = YES;
  164. configuration.discretionary = NO;
  165. configuration.HTTPMaximumConnectionsPerHost = 1;
  166. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  167. sessionUploadForeground = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  168. sessionUploadForeground.sessionDescription = k_upload_session_foreground;
  169. }
  170. return sessionUploadForeground;
  171. }
  172. - (NSURLSession *)sessionUploadExtension
  173. {
  174. static NSURLSession *sessionUpload = nil;
  175. if (sessionUpload == nil) {
  176. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_upload_session_extension];
  177. configuration.allowsCellularAccess = YES;
  178. configuration.sessionSendsLaunchEvents = YES;
  179. configuration.discretionary = NO;
  180. configuration.HTTPMaximumConnectionsPerHost = 1;
  181. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  182. configuration.sharedContainerIdentifier = [NCBrandOptions sharedInstance].capabilitiesGroups;
  183. sessionUpload = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  184. sessionUpload.sessionDescription = k_upload_session_extension;
  185. }
  186. return sessionUpload;
  187. }
  188. - (OCCommunication *)sharedOCCommunication
  189. {
  190. static OCCommunication* sharedOCCommunication = nil;
  191. if (sharedOCCommunication == nil)
  192. {
  193. // Network
  194. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  195. configuration.allowsCellularAccess = YES;
  196. configuration.discretionary = NO;
  197. configuration.HTTPMaximumConnectionsPerHost = k_maxConcurrentOperation;
  198. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  199. OCURLSessionManager *networkSessionManager = [[OCURLSessionManager alloc] initWithSessionConfiguration:configuration];
  200. [networkSessionManager.operationQueue setMaxConcurrentOperationCount: k_maxConcurrentOperation];
  201. networkSessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
  202. // Download
  203. NSURLSessionConfiguration *configurationDownload = [NSURLSessionConfiguration defaultSessionConfiguration];
  204. configurationDownload.allowsCellularAccess = YES;
  205. configurationDownload.discretionary = NO;
  206. configurationDownload.HTTPMaximumConnectionsPerHost = 1;
  207. configurationDownload.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  208. configurationDownload.timeoutIntervalForRequest = k_timeout_upload;
  209. OCURLSessionManager *downloadSessionManager = [[OCURLSessionManager alloc] initWithSessionConfiguration:configurationDownload];
  210. [downloadSessionManager.operationQueue setMaxConcurrentOperationCount:1];
  211. [downloadSessionManager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition (NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential) {
  212. return NSURLSessionAuthChallengePerformDefaultHandling;
  213. }];
  214. // Upload
  215. NSURLSessionConfiguration *configurationUpload = [NSURLSessionConfiguration defaultSessionConfiguration];
  216. configurationUpload.allowsCellularAccess = YES;
  217. configurationUpload.discretionary = NO;
  218. configurationUpload.HTTPMaximumConnectionsPerHost = 1;
  219. configurationUpload.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  220. configurationUpload.timeoutIntervalForRequest = k_timeout_upload;
  221. OCURLSessionManager *uploadSessionManager = [[OCURLSessionManager alloc] initWithSessionConfiguration:configurationUpload];
  222. [uploadSessionManager.operationQueue setMaxConcurrentOperationCount:1];
  223. [uploadSessionManager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition (NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential) {
  224. return NSURLSessionAuthChallengePerformDefaultHandling;
  225. }];
  226. sharedOCCommunication = [[OCCommunication alloc] initWithUploadSessionManager:uploadSessionManager andDownloadSessionManager:downloadSessionManager andNetworkSessionManager:networkSessionManager];
  227. }
  228. return sharedOCCommunication;
  229. }
  230. - (OCCommunication *)sharedOCCommunicationExtensionDownload
  231. {
  232. static OCCommunication *sharedOCCommunicationExtensionDownload = nil;
  233. if (sharedOCCommunicationExtensionDownload == nil)
  234. {
  235. NSURLSessionConfiguration *config = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_download_session_extension];
  236. config.sharedContainerIdentifier = [NCBrandOptions sharedInstance].capabilitiesGroups;
  237. config.HTTPMaximumConnectionsPerHost = 1;
  238. config.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  239. config.timeoutIntervalForRequest = k_timeout_upload;
  240. config.sessionSendsLaunchEvents = YES;
  241. [config setAllowsCellularAccess:YES];
  242. OCURLSessionManager *sessionManager = [[OCURLSessionManager alloc] initWithSessionConfiguration:config];
  243. [sessionManager.operationQueue setMaxConcurrentOperationCount:1];
  244. [sessionManager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition (NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential) {
  245. return NSURLSessionAuthChallengePerformDefaultHandling;
  246. }];
  247. sharedOCCommunicationExtensionDownload = [[OCCommunication alloc] initWithUploadSessionManager:nil andDownloadSessionManager:sessionManager andNetworkSessionManager:nil];
  248. }
  249. return sharedOCCommunicationExtensionDownload;
  250. }
  251. - (NSURLSession *)getSessionfromSessionDescription:(NSString *)sessionDescription
  252. {
  253. if ([sessionDescription isEqualToString:k_download_session]) return [self sessionDownload];
  254. if ([sessionDescription isEqualToString:k_download_session_foreground]) return [self sessionDownloadForeground];
  255. if ([sessionDescription isEqualToString:k_download_session_wwan]) return [self sessionWWanDownload];
  256. if ([sessionDescription isEqualToString:k_upload_session]) return [self sessionUpload];
  257. if ([sessionDescription isEqualToString:k_upload_session_wwan]) return [self sessionWWanUpload];
  258. if ([sessionDescription isEqualToString:k_upload_session_foreground]) return [self sessionUploadForeground];
  259. return nil;
  260. }
  261. - (void)invalidateAndCancelAllSession
  262. {
  263. [[self sessionDownload] invalidateAndCancel];
  264. [[self sessionDownloadForeground] invalidateAndCancel];
  265. [[self sessionWWanDownload] invalidateAndCancel];
  266. [[self sessionUpload] invalidateAndCancel];
  267. [[self sessionWWanUpload] invalidateAndCancel];
  268. [[self sessionUploadForeground] invalidateAndCancel];
  269. }
  270. - (NSArray *)getUploadTasksExtensionSession
  271. {
  272. __block NSArray *tasks = [NSArray new];
  273. [[self sessionUploadExtension] getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  274. tasks = uploadTasks;
  275. }];
  276. return tasks;
  277. }
  278. #pragma --------------------------------------------------------------------------------------------
  279. #pragma mark ===== URLSession download/upload =====
  280. #pragma --------------------------------------------------------------------------------------------
  281. - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
  282. {
  283. // The pinnning check
  284. if ([[CCCertificate sharedManager] checkTrustedChallenge:challenge]) {
  285. completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  286. } else {
  287. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  288. }
  289. }
  290. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
  291. {
  292. NSString *url = [[[task currentRequest].URL absoluteString] stringByRemovingPercentEncoding];
  293. if (!url)
  294. return;
  295. NSString *fileName = [url lastPathComponent];
  296. NSString *serverUrl = [self getServerUrlFromUrl:url];
  297. if (!serverUrl) return;
  298. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  299. if (!directoryID) return;
  300. tableMetadata *metadata;
  301. NSInteger errorCode;
  302. NSDate *date = [NSDate date];
  303. NSDateFormatter *dateFormatter = [NSDateFormatter new];
  304. NSLocale *enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
  305. [dateFormatter setLocale:enUSPOSIXLocale];
  306. [dateFormatter setDateFormat:@"EEE, dd MMM y HH:mm:ss zzz"];
  307. NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)task.response;
  308. if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {
  309. errorCode = error.code;
  310. } else {
  311. if (httpResponse.statusCode > 0)
  312. errorCode = httpResponse.statusCode;
  313. else
  314. errorCode = error.code;
  315. }
  316. // ----------------------- DOWNLOAD -----------------------
  317. if ([task isKindOfClass:[NSURLSessionDownloadTask class]]) {
  318. metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"directoryID == %@ AND fileName == %@", directoryID, fileName]];
  319. if (metadata) {
  320. NSString *etag = metadata.etag;
  321. NSString *fileID = metadata.fileID;
  322. NSDictionary *fields = [httpResponse allHeaderFields];
  323. if (errorCode == 0) {
  324. etag = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-ETag"]];
  325. NSString *dateString = [fields objectForKey:@"Date"];
  326. if (dateString) {
  327. if (![dateFormatter getObjectValue:&date forString:dateString range:nil error:&error]) {
  328. date = [NSDate date];
  329. }
  330. } else {
  331. date = [NSDate date];
  332. }
  333. }
  334. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, task, nil];
  335. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  336. if (fileName.length > 0 && serverUrl.length > 0) {
  337. dispatch_async(dispatch_get_main_queue(), ^{
  338. [self downloadFileSuccessFailure:fileName fileID:metadata.fileID etag:etag date:date serverUrl:serverUrl selector:metadata.sessionSelector selectorPost:metadata.sessionSelectorPost errorCode:errorCode];
  339. });
  340. }
  341. } else {
  342. NSLog(@"[LOG] Remove record ? : metadata not found %@", url);
  343. dispatch_async(dispatch_get_main_queue(), ^{
  344. [self.delegate downloadFileSuccessFailure:fileName fileID:@"" serverUrl:serverUrl selector:@"" selectorPost:@"" errorMessage:@"Remove record ? : metadata not found" errorCode:k_CCErrorInternalError];
  345. });
  346. }
  347. }
  348. // ------------------------ UPLOAD -----------------------
  349. if ([task isKindOfClass:[NSURLSessionUploadTask class]]) {
  350. metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"directoryID == %@ AND fileName == %@", directoryID, fileName]];
  351. if (metadata) {
  352. NSDictionary *fields = [httpResponse allHeaderFields];
  353. NSString *fileID = metadata.fileID;
  354. NSString *etag = metadata.etag;
  355. if (errorCode == 0) {
  356. fileID = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-FileId"]];
  357. etag = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-ETag"]];
  358. NSString *dateString = [fields objectForKey:@"Date"];
  359. if (dateString) {
  360. if (![dateFormatter getObjectValue:&date forString:dateString range:nil error:&error]) {
  361. NSLog(@"[LOG] Date '%@' could not be parsed: %@", dateString, error);
  362. date = [NSDate date];
  363. }
  364. } else {
  365. date = [NSDate date];
  366. }
  367. }
  368. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, task, nil];
  369. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  370. if (fileName.length > 0 && fileID.length > 0 && serverUrl.length > 0) {
  371. dispatch_async(dispatch_get_main_queue(), ^{
  372. [self uploadFileSuccessFailure:metadata fileName:fileName fileID:fileID etag:etag date:date serverUrl:serverUrl errorCode:errorCode];
  373. });
  374. }
  375. } else {
  376. NSLog(@"[LOG] Remove record ? : metadata not found %@", url);
  377. dispatch_async(dispatch_get_main_queue(), ^{
  378. [self.delegate uploadFileSuccessFailure:fileName fileID:@"" assetLocalIdentifier:@"" serverUrl:serverUrl selector:@"" selectorPost:@"" errorMessage:@"Remove record ? : metadata not found" errorCode:k_CCErrorInternalError];
  379. });
  380. }
  381. }
  382. }
  383. #pragma --------------------------------------------------------------------------------------------
  384. #pragma mark ===== Download =====
  385. #pragma --------------------------------------------------------------------------------------------
  386. - (void)downloadFile:(tableMetadata *)metadata taskStatus:(NSInteger)taskStatus delegate:(id)delegate;
  387. {
  388. // add delegate
  389. [_delegates setObject:delegate forKey:metadata.fileID];
  390. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  391. // File exists ?
  392. tableLocalFile *localfile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  393. if (localfile != nil && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.fileID]]) {
  394. [[NCManageDatabase sharedInstance] setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionSelectorPost:@"" sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusNormal predicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  395. [delegate downloadFileSuccessFailure:metadata.fileName fileID:metadata.fileID serverUrl:serverUrl selector:metadata.sessionSelector selectorPost:metadata.sessionSelectorPost errorMessage:@"" errorCode:0];
  396. return;
  397. }
  398. [self downloaURLSession:metadata serverUrl:serverUrl taskStatus:taskStatus];
  399. }
  400. - (void)downloaURLSession:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl taskStatus:(NSInteger)taskStatus
  401. {
  402. NSURLSession *sessionDownload;
  403. NSURL *url;
  404. NSMutableURLRequest *request;
  405. NSString *serverFileUrl = [[NSString stringWithFormat:@"%@/%@", serverUrl, metadata.fileName] encodeString:NSUTF8StringEncoding];
  406. url = [NSURL URLWithString:serverFileUrl];
  407. request = [NSMutableURLRequest requestWithURL:url];
  408. NSData *authData = [[NSString stringWithFormat:@"%@:%@", _activeUser, _activePassword] dataUsingEncoding:NSUTF8StringEncoding];
  409. NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];
  410. [request setValue:authValue forHTTPHeaderField:@"Authorization"];
  411. [request setValue:[CCUtility getUserAgent] forHTTPHeaderField:@"User-Agent"];
  412. if ([metadata.session isEqualToString:k_download_session]) sessionDownload = [self sessionDownload];
  413. else if ([metadata.session isEqualToString:k_download_session_foreground]) sessionDownload = [self sessionDownloadForeground];
  414. else if ([metadata.session isEqualToString:k_download_session_wwan]) sessionDownload = [self sessionWWanDownload];
  415. NSURLSessionDownloadTask *downloadTask = [sessionDownload downloadTaskWithRequest:request];
  416. if (downloadTask == nil) {
  417. [[NCManageDatabase sharedInstance] addActivityClient:metadata.fileName fileID:metadata.fileID action:k_activityDebugActionUpload selector:metadata.sessionSelector note:@"Serious internal error downloadTask not available" type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:_activeUrl];
  418. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:@"Serious internal error downloadTask not available" sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusDownloadError predicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  419. [self.delegate downloadFileSuccessFailure:metadata.fileName fileID:metadata.fileID serverUrl:serverUrl selector:metadata.sessionSelector selectorPost:@"" errorMessage:@"Serious internal error downloadTask not available" errorCode:k_CCErrorInternalError];
  420. } else {
  421. // Manage uploadTask cancel,suspend,resume
  422. if (taskStatus == k_taskStatusCancel) [downloadTask cancel];
  423. else if (taskStatus == k_taskStatusSuspend) [downloadTask suspend];
  424. else if (taskStatus == k_taskStatusResume) [downloadTask resume];
  425. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:nil sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:downloadTask.taskIdentifier status:k_metadataStatusDownloading predicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  426. NSLog(@"[LOG] downloadFileSession %@ Task [%lu]", metadata.fileID, (unsigned long)downloadTask.taskIdentifier);
  427. }
  428. dispatch_async(dispatch_get_main_queue(), ^{
  429. if ([[self getDelegate:metadata.fileID] respondsToSelector:@selector(downloadStart:account:task:serverUrl:)]) {
  430. [[self getDelegate:metadata.fileID] downloadStart:metadata.fileID account:metadata.account task:downloadTask serverUrl:serverUrl];
  431. }
  432. });
  433. }
  434. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
  435. {
  436. NSString *url = [[[downloadTask currentRequest].URL absoluteString] stringByRemovingPercentEncoding];
  437. NSString *fileName = [url lastPathComponent];
  438. NSString *serverUrl = [self getServerUrlFromUrl:url];
  439. if (!serverUrl) return;
  440. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  441. if (!directoryID) return;
  442. float progress = (float) totalBytesWritten / (float)totalBytesExpectedToWrite;
  443. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataInSessionFromFileName:fileName directoryID:directoryID];
  444. if (metadata) {
  445. NSDictionary* userInfo = @{@"fileID": (metadata.fileID), @"serverUrl": (serverUrl), @"progress": ([NSNumber numberWithFloat:progress])};
  446. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  447. } else {
  448. NSLog(@"[LOG] metadata not found");
  449. }
  450. }
  451. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
  452. {
  453. NSString *url = [[[downloadTask currentRequest].URL absoluteString] stringByRemovingPercentEncoding];
  454. if (!url)
  455. return;
  456. NSString *fileName = [url lastPathComponent];
  457. NSString *serverUrl = [self getServerUrlFromUrl:url];
  458. if (!serverUrl) return;
  459. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  460. if (!directoryID) return;
  461. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"directoryID == %@ AND fileName == %@", directoryID, fileName]];
  462. if (!metadata) {
  463. [[NCManageDatabase sharedInstance] addActivityClient:fileName fileID:@"" action:k_activityDebugActionUpload selector:@"" note:[NSString stringWithFormat:@"Serious error internal download : metadata not found %@", url] type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:_activeUrl];
  464. NSLog(@"[LOG] Serious error internal download : metadata not found %@ ", url);
  465. dispatch_async(dispatch_get_main_queue(), ^{
  466. [self.delegate downloadFileSuccessFailure:@"" fileID:@"" serverUrl:serverUrl selector:@"" selectorPost:@"" errorMessage:@"Serious error internal download : metadata not found" errorCode:k_CCErrorInternalError];
  467. });
  468. return;
  469. }
  470. NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)downloadTask.response;
  471. if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {
  472. NSString *destinationFilePath = [NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryActiveUser:_activeUser activeUrl:_activeUrl], metadata.fileID];
  473. NSURL *destinationURL = [NSURL fileURLWithPath:destinationFilePath];
  474. [[NSFileManager defaultManager] removeItemAtURL:destinationURL error:NULL];
  475. [[NSFileManager defaultManager] copyItemAtURL:location toURL:destinationURL error:nil];
  476. }
  477. }
  478. - (void)downloadFileSuccessFailure:(NSString *)fileName fileID:(NSString *)fileID etag:(NSString *)etag date:(NSDate *)date serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost errorCode:(NSInteger)errorCode
  479. {
  480. #ifndef EXTENSION
  481. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  482. [appDelegate.listProgressMetadata removeObjectForKey:fileID];
  483. #endif
  484. // Progress Task
  485. NSDictionary* userInfo = @{@"fileID": (fileID), @"serverUrl": (serverUrl), @"progress": ([NSNumber numberWithFloat:0.0])};
  486. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  487. if (errorCode != 0) {
  488. if (errorCode != kCFURLErrorCancelled) {
  489. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:[CCError manageErrorKCF:errorCode withNumberError:NO] sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusDownloadError predicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  490. }
  491. [[self getDelegate:fileID] downloadFileSuccessFailure:fileName fileID:fileID serverUrl:serverUrl selector:selector selectorPost:selectorPost errorMessage:[CCError manageErrorKCF:errorCode withNumberError:YES] errorCode:errorCode];
  492. } else {
  493. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  494. if (!metadata) {
  495. [[NCManageDatabase sharedInstance] addActivityClient:fileName fileID:fileID action:k_activityDebugActionUpload selector:@"" note:[NSString stringWithFormat:@"Serious error internal download : metadata not found %@", fileName] type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:_activeUrl];
  496. NSLog(@"[LOG] Serious error internal download : metadata not found %@ ", fileName);
  497. [[self getDelegate:fileID] downloadFileSuccessFailure:fileName fileID:fileID serverUrl:serverUrl selector:selector selectorPost:selectorPost errorMessage:[NSString stringWithFormat:@"Serious error internal download : metadata not found %@", fileName] errorCode:k_CCErrorInternalError];
  498. return;
  499. }
  500. metadata.session = @"";
  501. metadata.sessionError = @"";
  502. metadata.sessionSelector = @"";
  503. metadata.sessionSelectorPost = @"";
  504. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  505. metadata.status = k_metadataStatusNormal;
  506. metadata = [[NCManageDatabase sharedInstance] updateMetadata:metadata];
  507. [[NCManageDatabase sharedInstance] addLocalFileWithMetadata:metadata];
  508. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  509. [[CCExifGeo sharedInstance] setExifLocalTableEtag:metadata directoryUser:_directoryUser activeAccount:_activeAccount];
  510. // E2EE Decrypted
  511. tableE2eEncryption *object = [[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"fileNameIdentifier == %@ AND serverUrl == %@", fileName, serverUrl]];
  512. if (object) {
  513. BOOL result = [[NCEndToEndEncryption sharedManager] decryptFileID:fileID directoryUser:_directoryUser key:object.key initializationVector:object.initializationVector authenticationTag:object.authenticationTag];
  514. if (!result) {
  515. [[NCManageDatabase sharedInstance] addActivityClient:metadata.fileNameView fileID:fileID action:k_activityDebugActionUpload selector:@"" note:[NSString stringWithFormat:@"Serious error internal download : decrypt error %@", fileName] type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:_activeUrl];
  516. [[self getDelegate:fileID] downloadFileSuccessFailure:fileName fileID:fileID serverUrl:serverUrl selector:selector selectorPost:selectorPost errorMessage:[NSString stringWithFormat:@"Serious error internal download : decrypt error %@", fileName] errorCode:k_CCErrorInternalError];
  517. return;
  518. }
  519. }
  520. // Icon
  521. [CCGraphics createNewImageFrom:metadata.fileID directoryUser:_directoryUser fileNameTo:metadata.fileID extension:[metadata.fileNameView pathExtension] size:@"m" imageForUpload:NO typeFile:metadata.typeFile writePreview:YES optimizedFileName:[CCUtility getOptimizedPhoto]];
  522. // Activity
  523. [[NCManageDatabase sharedInstance] addActivityClient:metadata.fileNameView fileID:metadata.fileID action:k_activityDebugActionDownload selector:metadata.sessionSelector note:serverUrl type:k_activityTypeSuccess verbose:k_activityVerboseDefault activeUrl:_activeUrl];
  524. [[self getDelegate:fileID] downloadFileSuccessFailure:fileName fileID:fileID serverUrl:serverUrl selector:selector selectorPost:selectorPost errorMessage:@"" errorCode:0];
  525. }
  526. }
  527. #pragma --------------------------------------------------------------------------------------------
  528. #pragma mark ===== Upload =====
  529. #pragma --------------------------------------------------------------------------------------------
  530. - (void)uploadFile:(tableMetadata *)metadata taskStatus:(NSInteger)taskStatus delegate:(id)delegate
  531. {
  532. //delegate
  533. [_delegates setObject:delegate forKey:metadata.fileID];
  534. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  535. if (![[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", metadata.path, metadata.fileName]]) {
  536. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadata.assetLocalIdentifier] options:nil];
  537. if (!result.count) {
  538. [delegate uploadFileSuccessFailure:metadata.fileName fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:serverUrl selector:metadata.sessionSelector selectorPost:metadata.sessionSelectorPost errorMessage:@"Error photo/video not found, remove from upload" errorCode:k_CCErrorInternalError];
  539. return;
  540. }
  541. PHAsset *asset= result[0];
  542. // IMAGE
  543. if (asset.mediaType == PHAssetMediaTypeImage) {
  544. PHImageRequestOptions *options = [PHImageRequestOptions new];
  545. options.networkAccessAllowed = YES; // iCloud
  546. options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
  547. options.synchronous = YES;
  548. options.progressHandler = ^(double progress, NSError *error, BOOL *stop, NSDictionary *info) {
  549. NSLog(@"cacheAsset: %f", progress);
  550. if (error)
  551. [delegate uploadFileSuccessFailure:metadata.fileName fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:serverUrl selector:metadata.sessionSelector selectorPost:metadata.sessionSelectorPost errorMessage:[NSString stringWithFormat:@"Image request iCloud failed [%@]", error.description] errorCode:error.code];
  552. };
  553. [[PHImageManager defaultManager] requestImageDataForAsset:asset options:options resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) {
  554. NSError *error = nil;
  555. if ([dataUTI isEqualToString:@"public.heic"] && [CCUtility getFormatCompatibility]) {
  556. UIImage *image = [UIImage imageWithData:imageData];
  557. imageData = UIImageJPEGRepresentation(image, 1.0);
  558. NSString *fileNameJPEG = [[metadata.fileName lastPathComponent] stringByDeletingPathExtension];
  559. metadata.fileName = [fileNameJPEG stringByAppendingString:@".jpg"];
  560. [imageData writeToFile:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.fileName] options:NSDataWritingAtomic error:&error];
  561. } else {
  562. [imageData writeToFile:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.fileName] options:NSDataWritingAtomic error:&error];
  563. }
  564. if (error) {
  565. [delegate uploadFileSuccessFailure:metadata.fileName fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:serverUrl selector:metadata.sessionSelector selectorPost:metadata.sessionSelectorPost errorMessage:[NSString stringWithFormat:@"Image request failed [%@]", error.description] errorCode:error.code];
  566. } else {
  567. // create Metadata for Upload
  568. tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] addMetadata:[CCUtility insertFileSystemInMetadata:metadata]];
  569. // OOOOOK
  570. if ([CCUtility isFolderEncrypted:serverUrl account:_activeAccount] && [CCUtility isEndToEndEnabled:_activeAccount]) {
  571. [self e2eEncryptedFile:metadataForUpload serverUrl:serverUrl taskStatus:taskStatus];
  572. } else {
  573. [self uploadURLSessionMetadata:metadataForUpload serverUrl:serverUrl taskStatus:taskStatus];
  574. }
  575. }
  576. }];
  577. }
  578. // VIDEO
  579. if (asset.mediaType == PHAssetMediaTypeVideo) {
  580. PHVideoRequestOptions *options = [PHVideoRequestOptions new];
  581. options.networkAccessAllowed = YES;
  582. options.version = PHVideoRequestOptionsVersionOriginal;
  583. options.progressHandler = ^(double progress, NSError *error, BOOL *stop, NSDictionary *info) {
  584. NSLog(@"cacheAsset: %f", progress);
  585. if (error)
  586. [delegate uploadFileSuccessFailure:metadata.fileName fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:serverUrl selector:metadata.sessionSelector selectorPost:metadata.sessionSelectorPost errorMessage:[NSString stringWithFormat:@"Video request iCloud failed [%@]", error.description] errorCode:error.code];
  587. };
  588. [[PHImageManager defaultManager] requestAVAssetForVideo:asset options:options resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
  589. if ([asset isKindOfClass:[AVURLAsset class]]) {
  590. NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.fileName]];
  591. NSError *error = nil;
  592. [[NSFileManager defaultManager] removeItemAtURL:fileURL error:nil];
  593. [[NSFileManager defaultManager] copyItemAtURL:[(AVURLAsset *)asset URL] toURL:fileURL error:&error];
  594. if (error) {
  595. dispatch_async(dispatch_get_main_queue(), ^{
  596. [delegate uploadFileSuccessFailure:metadata.fileName fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:serverUrl selector:metadata.sessionSelector selectorPost:metadata.sessionSelectorPost errorMessage:[NSString stringWithFormat:@"Video request failed [%@]", error.description] errorCode:error.code];
  597. });
  598. } else {
  599. dispatch_async(dispatch_get_main_queue(), ^{
  600. // create Metadata for Upload
  601. tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] addMetadata:[CCUtility insertFileSystemInMetadata:metadata]];
  602. // OOOOOK
  603. if ([CCUtility isFolderEncrypted:serverUrl account:_activeAccount] && [CCUtility isEndToEndEnabled:_activeAccount]) {
  604. [self e2eEncryptedFile:metadataForUpload serverUrl:serverUrl taskStatus:taskStatus];
  605. } else {
  606. [self uploadURLSessionMetadata:metadataForUpload serverUrl:serverUrl taskStatus:taskStatus];
  607. }
  608. });
  609. }
  610. }
  611. }];
  612. }
  613. } else {
  614. // create Metadata for Upload
  615. tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] addMetadata:[CCUtility insertFileSystemInMetadata:metadata]];
  616. [self uploadURLSessionMetadata:metadataForUpload serverUrl:serverUrl taskStatus:taskStatus];
  617. }
  618. }
  619. - (void)e2eEncryptedFile:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl taskStatus:(NSInteger)taskStatus
  620. {
  621. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  622. NSString *errorMessage;
  623. NSString *fileNameIdentifier;
  624. NSString *e2eMetadata;
  625. [self encryptedE2EFile:metadata.fileName serverUrl:serverUrl directoryID:metadata.directoryID account:_activeAccount user:_activeUser userID:_activeUserID password:_activePassword url:_activeUrl errorMessage:&errorMessage fileNameIdentifier:&fileNameIdentifier e2eMetadata:&e2eMetadata];
  626. if (errorMessage != nil || fileNameIdentifier == nil) {
  627. [[self getDelegate:metadata.fileID] uploadFileSuccessFailure:metadata.fileName fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:serverUrl selector:metadata.sessionSelector selectorPost:metadata.sessionSelectorPost errorMessage:errorMessage errorCode:k_CCErrorInternalError];
  628. } else {
  629. dispatch_async(dispatch_get_main_queue(), ^{
  630. // Now the fileName is fileNameIdentifier && flag e2eEncrypted
  631. metadata.fileName = fileNameIdentifier;
  632. metadata.e2eEncrypted = YES;
  633. // Update Metadata
  634. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  635. [self uploadURLSessionMetadata:metadata serverUrl:serverUrl taskStatus:taskStatus];
  636. });
  637. }
  638. });
  639. }
  640. - (void)uploadURLSessionMetadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl taskStatus:(NSInteger)taskStatus
  641. {
  642. NSURL *url;
  643. NSMutableURLRequest *request;
  644. PHAsset *asset;
  645. NSString *fileNamePath = [[NSString stringWithFormat:@"%@/%@", serverUrl, metadata.fileName] encodeString:NSUTF8StringEncoding];
  646. url = [NSURL URLWithString:fileNamePath];
  647. request = [NSMutableURLRequest requestWithURL:url];
  648. NSData *authData = [[NSString stringWithFormat:@"%@:%@", _activeUser, _activePassword] dataUsingEncoding:NSUTF8StringEncoding];
  649. NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];
  650. [request setHTTPMethod:@"PUT"];
  651. [request setValue:authValue forHTTPHeaderField:@"Authorization"];
  652. [request setValue:[CCUtility getUserAgent] forHTTPHeaderField:@"User-Agent"];
  653. // Create Image for Upload
  654. #ifndef EXTENSION
  655. [CCGraphics createNewImageFrom:metadata.fileNameView directoryUser:_directoryUser fileNameTo:metadata.fileID extension:[metadata.fileNameView pathExtension] size:@"m" imageForUpload:YES typeFile:metadata.typeFile writePreview:YES optimizedFileName:NO];
  656. #endif
  657. // Change date file upload with header : X-OC-Mtime (ctime assetLocalIdentifier) image/video
  658. if (metadata.assetLocalIdentifier) {
  659. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadata.assetLocalIdentifier] options:nil];
  660. if (result.count) {
  661. asset = result[0];
  662. long dateFileCreation = [asset.creationDate timeIntervalSince1970];
  663. [request setValue:[NSString stringWithFormat:@"%ld", dateFileCreation] forHTTPHeaderField:@"X-OC-Mtime"];
  664. }
  665. }
  666. NSURLSession *sessionUpload;
  667. // NSURLSession
  668. if ([metadata.session isEqualToString:k_upload_session]) sessionUpload = [self sessionUpload];
  669. else if ([metadata.session isEqualToString:k_upload_session_wwan]) sessionUpload = [self sessionWWanUpload];
  670. else if ([metadata.session isEqualToString:k_upload_session_foreground]) sessionUpload = [self sessionUploadForeground];
  671. else if ([metadata.session isEqualToString:k_upload_session_extension]) sessionUpload = [self sessionUploadExtension];
  672. NSURLSessionUploadTask *uploadTask = [sessionUpload uploadTaskWithRequest:request fromFile:[NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.fileName]]];
  673. // Error
  674. if (uploadTask == nil) {
  675. NSString *messageError = @"Serious internal error uploadTask not available";
  676. [[NCManageDatabase sharedInstance] setMetadataSession:metadata.session sessionError:messageError sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusUploadError predicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  677. [[self getDelegate:metadata.fileID] uploadFileSuccessFailure:metadata.fileNameView fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:serverUrl selector:metadata.sessionSelector selectorPost:metadata.sessionSelectorPost errorMessage:messageError errorCode:k_CCErrorInternalError];
  678. } else {
  679. // E2EE : CREATE AND SEND METADATA
  680. if ([CCUtility isFolderEncrypted:serverUrl account:_activeAccount] && [CCUtility isEndToEndEnabled:_activeAccount]) {
  681. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  682. // Send Metadata
  683. NSError *error = [[NCNetworkingEndToEnd sharedManager] sendEndToEndMetadataOnServerUrl:serverUrl account:_activeAccount user:_activeUser userID:_activeUserID password:_activePassword url:_activeUrl fileNameRename:nil fileNameNewRename:nil];
  684. dispatch_async(dispatch_get_main_queue(), ^{
  685. if (error) {
  686. [uploadTask cancel];
  687. NSString *messageError = [NSString stringWithFormat:@"%@ (%d)", error.localizedDescription, (int)error.code];
  688. [[NCManageDatabase sharedInstance] setMetadataSession:metadata.session sessionError:messageError sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusUploadError predicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  689. [[self getDelegate:metadata.fileID] uploadFileSuccessFailure:metadata.fileNameView fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:serverUrl selector:metadata.sessionSelector selectorPost:metadata.sessionSelectorPost errorMessage:messageError errorCode:k_CCErrorInternalError];
  690. } else {
  691. // Manage uploadTask cancel,suspend,resume
  692. if (taskStatus == k_taskStatusCancel) [uploadTask cancel];
  693. else if (taskStatus == k_taskStatusSuspend) [uploadTask suspend];
  694. else if (taskStatus == k_taskStatusResume) [uploadTask resume];
  695. // *** E2EE ***
  696. [[NCManageDatabase sharedInstance] setMetadataSession:metadata.session sessionError:@"" sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:uploadTask.taskIdentifier status:k_metadataStatusUploading predicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  697. NSLog(@"[LOG] Upload file %@ TaskIdentifier %lu", metadata.fileName, (unsigned long)uploadTask.taskIdentifier);
  698. dispatch_async(dispatch_get_main_queue(), ^{
  699. if ([[self getDelegate:metadata.fileID] respondsToSelector:@selector(uploadStart:account:task:serverUrl:)]) {
  700. [[self getDelegate:metadata.fileID] uploadStart:metadata.fileID account:metadata.account task:uploadTask serverUrl:serverUrl];
  701. }
  702. });
  703. }
  704. });
  705. });
  706. } else {
  707. // Manage uploadTask cancel,suspend,resume
  708. if (taskStatus == k_taskStatusCancel) [uploadTask cancel];
  709. else if (taskStatus == k_taskStatusSuspend) [uploadTask suspend];
  710. else if (taskStatus == k_taskStatusResume) [uploadTask resume];
  711. // *** PLAIN ***
  712. [[NCManageDatabase sharedInstance] setMetadataSession:metadata.session sessionError:@"" sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:uploadTask.taskIdentifier status:k_metadataStatusUploading predicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  713. NSLog(@"[LOG] Upload file %@ TaskIdentifier %lu", metadata.fileName, (unsigned long)uploadTask.taskIdentifier);
  714. dispatch_async(dispatch_get_main_queue(), ^{
  715. if ([[self getDelegate:metadata.fileID] respondsToSelector:@selector(uploadStart:account:task:serverUrl:)]) {
  716. [[self getDelegate:metadata.fileID] uploadStart:metadata.fileID account:metadata.account task:uploadTask serverUrl:serverUrl];
  717. }
  718. });
  719. }
  720. }
  721. }
  722. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
  723. {
  724. NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)dataTask.response;
  725. if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {
  726. NSNumber *taskIdentifier = [NSNumber numberWithLong:dataTask.taskIdentifier];
  727. if (data)
  728. [_taskData setObject:[data copy] forKey:taskIdentifier];
  729. }
  730. }
  731. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
  732. {
  733. NSString *url = [[[task currentRequest].URL absoluteString] stringByRemovingPercentEncoding];
  734. NSString *fileName = [url lastPathComponent];
  735. NSString *serverUrl = [self getServerUrlFromUrl:url];
  736. if (!serverUrl) return;
  737. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  738. if (!directoryID) return;
  739. float progress = (float) totalBytesSent / (float)totalBytesExpectedToSend;
  740. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataInSessionFromFileName:fileName directoryID:directoryID];
  741. if (metadata) {
  742. NSDictionary* userInfo = @{@"fileID": (metadata.fileID), @"serverUrl": (serverUrl), @"progress": ([NSNumber numberWithFloat:progress])};
  743. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  744. }
  745. }
  746. - (void)uploadFileSuccessFailure:(tableMetadata *)metadata fileName:(NSString *)fileName fileID:(NSString *)fileID etag:(NSString *)etag date:(NSDate *)date serverUrl:(NSString *)serverUrl errorCode:(NSInteger)errorCode
  747. {
  748. NSString *tempFileID = metadata.fileID;
  749. NSString *errorMessage = @"";
  750. // Progress Task
  751. NSDictionary* userInfo = @{@"fileID": (fileID), @"serverUrl": (serverUrl), @"progress": ([NSNumber numberWithFloat:0.0])};
  752. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  753. // ERRORE
  754. if (errorCode != 0) {
  755. #ifndef EXTENSION
  756. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  757. [appDelegate.listProgressMetadata removeObjectForKey:metadata.fileID];
  758. #endif
  759. // Mark error only if not Cancelled Task
  760. if (errorCode != kCFURLErrorCancelled) {
  761. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:[CCError manageErrorKCF:errorCode withNumberError:NO] sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusUploadError predicate:[NSPredicate predicateWithFormat:@"fileID == %@", tempFileID]];
  762. }
  763. errorMessage = [CCError manageErrorKCF:errorCode withNumberError:YES];
  764. } else {
  765. // Replace Metadata
  766. metadata.date = date;
  767. metadata.e2eEncrypted = false;
  768. metadata.etag = etag;
  769. metadata.fileID = fileID;
  770. metadata.session = @"";
  771. metadata.sessionError = @"";
  772. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  773. metadata.status = k_metadataStatusNormal;
  774. metadata = [[NCManageDatabase sharedInstance] addMetadata:metadata];
  775. if (![fileID isEqualToString:tempFileID])
  776. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", tempFileID] clearDateReadDirectoryID:nil];
  777. #ifndef EXTENSION
  778. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  779. [appDelegate.listProgressMetadata removeObjectForKey:metadata.fileID];
  780. #endif
  781. NSLog(@"[LOG] Insert new upload : %@ - fileID : %@", metadata.fileName, metadata.fileID);
  782. if ([CCUtility isFolderEncrypted:serverUrl account:_activeAccount]) {
  783. // rename file fileNameView (original file) -> fileID
  784. [CCUtility moveFileAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.fileNameView] toPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.fileID]];
  785. // remove encrypted file
  786. // [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, sessionID] error:nil];
  787. } else {
  788. // rename file fileName -> fileID
  789. [CCUtility moveFileAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.fileName] toPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.fileID]];
  790. // remove ico B/N
  791. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.ico", _directoryUser, tempFileID] error:nil];
  792. }
  793. // Local
  794. if (metadata.directory == NO)
  795. [[NCManageDatabase sharedInstance] addLocalFileWithMetadata:metadata];
  796. #ifndef EXTENSION
  797. // EXIF
  798. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  799. [[CCExifGeo sharedInstance] setExifLocalTableEtag:metadata directoryUser:_directoryUser activeAccount:_activeAccount];
  800. // Create ICON
  801. if (metadata.directory == NO)
  802. [CCGraphics createNewImageFrom:metadata.fileID directoryUser:_directoryUser fileNameTo:metadata.fileID extension:[metadata.fileNameView pathExtension] size:@"m" imageForUpload:NO typeFile:metadata.typeFile writePreview:YES optimizedFileName:[CCUtility getOptimizedPhoto]];
  803. // Optimization
  804. if (([CCUtility getUploadAndRemovePhoto] || [metadata.sessionSelectorPost isEqualToString:selectorUploadRemovePhoto]) && [metadata.typeFile isEqualToString:k_metadataTypeFile_document] == NO)
  805. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.fileID] error:nil];
  806. // Copy photo or video in the photo album for auto upload
  807. if ([metadata.assetLocalIdentifier length] > 0 && ([metadata.sessionSelector isEqualToString:selectorUploadAutoUpload] || [metadata.sessionSelector isEqualToString:selectorUploadFile])) {
  808. PHAsset *asset;
  809. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadata.assetLocalIdentifier] options:nil];
  810. if(result.count){
  811. asset = result[0];
  812. [asset saveToAlbum:[NCBrandOptions sharedInstance].brand completionBlock:^(BOOL success) {
  813. if (success) NSLog(@"[LOG] Insert file %@ in %@", metadata.fileName, [NCBrandOptions sharedInstance].brand);
  814. else NSLog(@"[LOG] File %@ do not insert in %@", metadata.fileName, [NCBrandOptions sharedInstance].brand);
  815. }];
  816. }
  817. }
  818. #endif
  819. // Actvity
  820. [[NCManageDatabase sharedInstance] addActivityClient:metadata.fileNameView fileID:fileID action:k_activityDebugActionUpload selector:metadata.sessionSelector note:serverUrl type:k_activityTypeSuccess verbose:k_activityVerboseDefault activeUrl:_activeUrl];
  821. }
  822. // E2EE : UNLOCK
  823. if ([CCUtility isFolderEncrypted:serverUrl account:_activeAccount] && [CCUtility isEndToEndEnabled:_activeAccount]) {
  824. tableE2eEncryptionLock *tableLock = [[NCManageDatabase sharedInstance] getE2ETokenLockWithServerUrl:serverUrl];
  825. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  826. if (tableLock) {
  827. NSError *error = [[NCNetworkingEndToEnd sharedManager] unlockEndToEndFolderEncrypted:_activeUser userID:_activeUserID password:_activePassword url:_activeUrl serverUrl:serverUrl fileID:tableLock.fileID token:tableLock.token];
  828. if (error) {
  829. #ifndef EXTENSION
  830. dispatch_async(dispatch_get_main_queue(), ^{
  831. [(AppDelegate *)[[UIApplication sharedApplication] delegate] messageNotification:@"_e2e_error_unlock_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  832. });
  833. #endif
  834. }
  835. } else {
  836. NSLog(@"Error unlock not found");
  837. }
  838. dispatch_async(dispatch_get_main_queue(), ^{
  839. [[self getDelegate:tempFileID] uploadFileSuccessFailure:metadata.fileName fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:serverUrl selector:metadata.sessionSelector selectorPost:metadata.sessionSelectorPost errorMessage:errorMessage errorCode:errorCode];
  840. });
  841. });
  842. } else {
  843. [[self getDelegate:tempFileID] uploadFileSuccessFailure:metadata.fileName fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:serverUrl selector:metadata.sessionSelector selectorPost:metadata.sessionSelectorPost errorMessage:errorMessage errorCode:errorCode];
  844. }
  845. }
  846. #pragma --------------------------------------------------------------------------------------------
  847. #pragma mark ===== Utility =====
  848. #pragma --------------------------------------------------------------------------------------------
  849. - (id)getDelegate:(NSString *)fileID
  850. {
  851. id delegate = [_delegates objectForKey:fileID];
  852. if (delegate)
  853. return delegate;
  854. else
  855. return self.delegate;
  856. }
  857. - (NSString *)getServerUrlFromUrl:(NSString *)url
  858. {
  859. NSString *fileName = [url lastPathComponent];
  860. url = [url stringByReplacingOccurrencesOfString:[@"/" stringByAppendingString:fileName] withString:@""];
  861. return url;
  862. }
  863. - (NSString *)getTitleFromPlistName:(NSString *)fileName
  864. {
  865. if ([[fileName lastPathComponent] isEqualToString:@"plist"] == NO)
  866. fileName = [fileName stringByAppendingString:@".plist"];
  867. if (![[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileName]]) return nil;
  868. NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileName]];
  869. return [data objectForKey:@"title"];
  870. }
  871. #pragma --------------------------------------------------------------------------------------------
  872. #pragma mark ===== E2EE End To End Encryption =====
  873. #pragma --------------------------------------------------------------------------------------------
  874. // E2EE
  875. - (void)encryptedE2EFile:(NSString *)fileName serverUrl:(NSString *)serverUrl directoryID:(NSString *)directoryID account:(NSString *)account user:(NSString *)user userID:(NSString *)userID password:(NSString *)password url:(NSString *)url errorMessage:(NSString * __autoreleasing *)errorMessage fileNameIdentifier:(NSString **)fileNameIdentifier e2eMetadata:(NSString * __autoreleasing *)e2eMetadata
  876. {
  877. __block NSError *error;
  878. NSString *key;
  879. NSString *initializationVector;
  880. NSString *authenticationTag;
  881. NSString *metadataKey;
  882. NSInteger metadataKeyIndex;
  883. // Verify File Size
  884. NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileName] error:&error];
  885. NSNumber *fileSizeNumber = [fileAttributes objectForKey:NSFileSize];
  886. long long fileSize = [fileSizeNumber longLongValue];
  887. if (fileSize > k_max_filesize_E2E) {
  888. // Error for uploadFileFailure
  889. *errorMessage = @"E2E Error file too big";
  890. return;
  891. }
  892. // if exists overwrite file else create a new encrypted filename
  893. tableMetadata *overwriteMetadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND directoryID == %@ AND fileNameView == %@", _activeAccount, directoryID, fileName]];
  894. if (overwriteMetadata)
  895. *fileNameIdentifier = overwriteMetadata.fileName;
  896. else
  897. *fileNameIdentifier = [CCUtility generateRandomIdentifier];
  898. // Write to DB
  899. if ([[NCEndToEndEncryption sharedManager] encryptFileName:fileName fileNameIdentifier:*fileNameIdentifier directoryUser: _directoryUser key:&key initializationVector:&initializationVector authenticationTag:&authenticationTag]) {
  900. tableE2eEncryption *object = [[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", _activeAccount, serverUrl]];
  901. if (object) {
  902. metadataKey = object.metadataKey;
  903. metadataKeyIndex = object.metadataKeyIndex;
  904. } else {
  905. metadataKey = [[[NCEndToEndEncryption sharedManager] generateKey:16] base64EncodedStringWithOptions:0]; // AES_KEY_128_LENGTH
  906. metadataKeyIndex = 0;
  907. }
  908. tableE2eEncryption *addObject = [tableE2eEncryption new];
  909. addObject.account = _activeAccount;
  910. addObject.authenticationTag = authenticationTag;
  911. addObject.fileName = fileName;
  912. addObject.fileNameIdentifier = *fileNameIdentifier;
  913. addObject.fileNamePath = [CCUtility returnFileNamePathFromFileName:fileName serverUrl:serverUrl activeUrl:_activeUrl];
  914. addObject.key = key;
  915. addObject.initializationVector = initializationVector;
  916. addObject.metadataKey = metadataKey;
  917. addObject.metadataKeyIndex = metadataKeyIndex;
  918. CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)[fileName pathExtension], NULL);
  919. CFStringRef mimeTypeRef = UTTypeCopyPreferredTagWithClass (UTI, kUTTagClassMIMEType);
  920. if (mimeTypeRef) {
  921. addObject.mimeType = (__bridge NSString *)mimeTypeRef;
  922. } else {
  923. addObject.mimeType = @"application/octet-stream";
  924. }
  925. addObject.serverUrl = serverUrl;
  926. addObject.version = [[NCManageDatabase sharedInstance] getEndToEndEncryptionVersion];
  927. // Get the last metadata
  928. NSString *metadata;
  929. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", account, serverUrl]];
  930. error = [[NCNetworkingEndToEnd sharedManager] getEndToEndMetadata:user userID:userID password:password url:url fileID:directory.fileID metadata:&metadata];
  931. if (error == nil) {
  932. if ([[NCEndToEndMetadata sharedInstance] decoderMetadata:metadata privateKey:[CCUtility getEndToEndPrivateKey:account] serverUrl:serverUrl account:account url:url] == false) {
  933. *errorMessage = NSLocalizedString(@"_e2e_error_decode_metadata_", nil);
  934. return;
  935. }
  936. }
  937. *e2eMetadata = metadata;
  938. // write new record e2ee
  939. if([[NCManageDatabase sharedInstance] addE2eEncryption:addObject] == NO)
  940. *errorMessage = NSLocalizedString(@"_e2e_error_create_encrypted_", nil);
  941. } else {
  942. *errorMessage = NSLocalizedString(@"_e2e_error_create_encrypted_", nil);
  943. }
  944. }
  945. #pragma --------------------------------------------------------------------------------------------
  946. #pragma mark ===== Utility =====
  947. #pragma --------------------------------------------------------------------------------------------
  948. - (NSInteger)getNumDownloadInProgressWWan:(BOOL)WWan
  949. {
  950. NSInteger numTableMetadataDownload, numTableQueueDownload;
  951. /*
  952. if (WWan) {
  953. numTableMetadataDownload = [[[NCManageDatabase sharedInstance] getTableMetadataDownloadWWan] count];
  954. numTableQueueDownload = [[NCManageDatabase sharedInstance] countQueueDownloadWithSession:k_download_session_wwan];
  955. } else {
  956. numTableMetadataDownload = [[[NCManageDatabase sharedInstance] getTableMetadataDownload] count];
  957. numTableQueueDownload = [[NCManageDatabase sharedInstance] countQueueDownloadWithSession:k_download_session] + [[NCManageDatabase sharedInstance] countQueueDownloadWithSession:k_download_session_foreground];
  958. }
  959. */
  960. return numTableMetadataDownload + numTableQueueDownload;
  961. }
  962. - (NSInteger)getNumUploadInProgressWWan:(BOOL)WWan
  963. {
  964. /*
  965. NSMutableArray *recordsInUpload = [NSMutableArray new];
  966. if (WWan) {
  967. for (tableQueueUpload *record in [[NCManageDatabase sharedInstance] getQueueUploadWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND session = %@", _activeAccount, k_upload_session_wwan]]) {
  968. [recordsInUpload addObject:[record.fileName stringByAppendingString:record.assetLocalIdentifier]];
  969. }
  970. for (tableMetadata *record in [[NCManageDatabase sharedInstance] getTableMetadataUploadWWan]) {
  971. if (![recordsInUpload containsObject:[record.fileNameView stringByAppendingString:record.assetLocalIdentifier]])
  972. [recordsInUpload addObject:[record.fileNameView stringByAppendingString:record.assetLocalIdentifier]];
  973. }
  974. } else {
  975. for (tableQueueUpload *record in [[NCManageDatabase sharedInstance] getQueueUploadWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND (session = %@ OR session = %@)", _activeAccount, k_upload_session, k_upload_session_foreground]]) {
  976. [recordsInUpload addObject:[record.fileName stringByAppendingString:record.assetLocalIdentifier]];
  977. }
  978. for (tableMetadata *record in [[NCManageDatabase sharedInstance] getTableMetadataUpload]) {
  979. if (![recordsInUpload containsObject:[record.fileNameView stringByAppendingString:record.assetLocalIdentifier]])
  980. [recordsInUpload addObject:[record.fileNameView stringByAppendingString:record.assetLocalIdentifier]];
  981. }
  982. }
  983. return recordsInUpload.count;
  984. */
  985. return 0;
  986. }
  987. @end
  988. #pragma --------------------------------------------------------------------------------------------
  989. #pragma mark ===== CCMetadataNet =====
  990. #pragma --------------------------------------------------------------------------------------------
  991. @implementation CCMetadataNet
  992. - (id)init
  993. {
  994. self = [super init];
  995. self.priority = NSOperationQueuePriorityNormal;
  996. return self;
  997. }
  998. - (id)initWithAccount:(NSString *)withAccount
  999. {
  1000. self = [self init];
  1001. if (self) {
  1002. _account = withAccount;
  1003. }
  1004. return self;
  1005. }
  1006. - (id)copyWithZone: (NSZone *) zone
  1007. {
  1008. CCMetadataNet *metadataNet = [[CCMetadataNet allocWithZone: zone] init];
  1009. [metadataNet setAccount: self.account];
  1010. [metadataNet setAction: self.action];
  1011. [metadataNet setContentType: self.contentType];
  1012. [metadataNet setDate: self.date];
  1013. [metadataNet setDelegate: self.delegate];
  1014. [metadataNet setDepth: self.depth];
  1015. [metadataNet setDirectory: self.directory];
  1016. [metadataNet setDirectoryID: self.directoryID];
  1017. [metadataNet setDirectoryIDTo: self.directoryIDTo];
  1018. [metadataNet setEncryptedMetadata: self.encryptedMetadata];
  1019. [metadataNet setEtag:self.etag];
  1020. [metadataNet setExpirationTime: self.expirationTime];
  1021. [metadataNet setFileID: self.fileID];
  1022. [metadataNet setFileName: self.fileName];
  1023. [metadataNet setFileNameTo: self.fileNameTo];
  1024. [metadataNet setFileNameView: self.fileNameView];
  1025. [metadataNet setKey: self.key];
  1026. [metadataNet setKeyCipher: self.keyCipher];
  1027. [metadataNet setOptionAny: self.optionAny];
  1028. [metadataNet setOptionString: self.optionString];
  1029. [metadataNet setPassword: self.password];
  1030. [metadataNet setPriority: self.priority];
  1031. [metadataNet setServerUrl: self.serverUrl];
  1032. [metadataNet setServerUrlTo: self.serverUrlTo];
  1033. [metadataNet setSelector: self.selector];
  1034. [metadataNet setSelectorPost: self.selectorPost];
  1035. [metadataNet setShare: self.share];
  1036. [metadataNet setShareeType: self.shareeType];
  1037. [metadataNet setSharePermission: self.sharePermission];
  1038. [metadataNet setSize: self.size];
  1039. return metadataNet;
  1040. }
  1041. @end