CCNetworking.m 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309
  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. }
  40. @end
  41. @implementation CCNetworking
  42. + (CCNetworking *)sharedNetworking {
  43. static CCNetworking *sharedNetworking;
  44. @synchronized(self)
  45. {
  46. if (!sharedNetworking) {
  47. sharedNetworking = [[CCNetworking alloc] init];
  48. }
  49. return sharedNetworking;
  50. }
  51. }
  52. - (id)init
  53. {
  54. self = [super init];
  55. _taskData = [[NSMutableDictionary alloc] init];
  56. _delegates = [[NSMutableDictionary alloc] init];
  57. // Initialization Sessions
  58. [self sessionDownload];
  59. [self sessionDownloadForeground];
  60. [self sessionWWanDownload];
  61. [self sessionUpload];
  62. [self sessionWWanUpload];
  63. [self sessionUploadForeground];
  64. // *** NOT Initialize ONLY for EXTENSION !!!!! ***
  65. // [self sessionUploadExtension];
  66. [self sharedOCCommunication];
  67. [self settingAccount];
  68. return self;
  69. }
  70. - (void)settingAccount
  71. {
  72. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  73. _activeAccount = tableAccount.account;
  74. _activePassword = tableAccount.password;
  75. _activeUser = tableAccount.user;
  76. _activeUserID = tableAccount.userID;
  77. _activeUrl = tableAccount.url;
  78. }
  79. #pragma --------------------------------------------------------------------------------------------
  80. #pragma mark ===== Session =====
  81. #pragma --------------------------------------------------------------------------------------------
  82. - (NSURLSession *)sessionDownload
  83. {
  84. static NSURLSession *sessionDownload = nil;
  85. if (sessionDownload == nil) {
  86. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_download_session];
  87. configuration.allowsCellularAccess = YES;
  88. configuration.sessionSendsLaunchEvents = YES;
  89. configuration.discretionary = NO;
  90. configuration.HTTPMaximumConnectionsPerHost = 1;
  91. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  92. sessionDownload = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  93. sessionDownload.sessionDescription = k_download_session;
  94. }
  95. return sessionDownload;
  96. }
  97. - (NSURLSession *)sessionDownloadForeground
  98. {
  99. static NSURLSession *sessionDownloadForeground = nil;
  100. if (sessionDownloadForeground == nil) {
  101. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  102. configuration.allowsCellularAccess = YES;
  103. configuration.discretionary = NO;
  104. configuration.HTTPMaximumConnectionsPerHost = 1;
  105. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  106. sessionDownloadForeground = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  107. sessionDownloadForeground.sessionDescription = k_download_session_foreground;
  108. }
  109. return sessionDownloadForeground;
  110. }
  111. - (NSURLSession *)sessionWWanDownload
  112. {
  113. static NSURLSession *sessionWWanDownload = nil;
  114. if (sessionWWanDownload == nil) {
  115. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_download_session_wwan];
  116. configuration.allowsCellularAccess = NO;
  117. configuration.sessionSendsLaunchEvents = YES;
  118. configuration.discretionary = NO;
  119. configuration.HTTPMaximumConnectionsPerHost = 1;
  120. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  121. sessionWWanDownload = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  122. sessionWWanDownload.sessionDescription = k_download_session_wwan;
  123. }
  124. return sessionWWanDownload;
  125. }
  126. - (NSURLSession *)sessionUpload
  127. {
  128. static NSURLSession *sessionUpload = nil;
  129. if (sessionUpload == nil) {
  130. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_upload_session];
  131. configuration.allowsCellularAccess = YES;
  132. configuration.sessionSendsLaunchEvents = YES;
  133. configuration.discretionary = NO;
  134. configuration.HTTPMaximumConnectionsPerHost = 1;
  135. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  136. sessionUpload = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  137. sessionUpload.sessionDescription = k_upload_session;
  138. }
  139. return sessionUpload;
  140. }
  141. - (NSURLSession *)sessionWWanUpload
  142. {
  143. static NSURLSession *sessionWWanUpload = nil;
  144. if (sessionWWanUpload == nil) {
  145. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_upload_session_wwan];
  146. configuration.allowsCellularAccess = NO;
  147. configuration.sessionSendsLaunchEvents = YES;
  148. configuration.discretionary = NO;
  149. configuration.HTTPMaximumConnectionsPerHost = 1;
  150. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  151. sessionWWanUpload = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  152. sessionWWanUpload.sessionDescription = k_upload_session_wwan;
  153. }
  154. return sessionWWanUpload;
  155. }
  156. - (NSURLSession *)sessionUploadForeground
  157. {
  158. static NSURLSession *sessionUploadForeground;
  159. if (sessionUploadForeground == nil) {
  160. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  161. configuration.allowsCellularAccess = YES;
  162. configuration.discretionary = NO;
  163. configuration.HTTPMaximumConnectionsPerHost = 1;
  164. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  165. sessionUploadForeground = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  166. sessionUploadForeground.sessionDescription = k_upload_session_foreground;
  167. }
  168. return sessionUploadForeground;
  169. }
  170. - (NSURLSession *)sessionUploadExtension
  171. {
  172. static NSURLSession *sessionUpload = nil;
  173. if (sessionUpload == nil) {
  174. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_upload_session_extension];
  175. configuration.allowsCellularAccess = YES;
  176. configuration.sessionSendsLaunchEvents = YES;
  177. configuration.discretionary = NO;
  178. configuration.HTTPMaximumConnectionsPerHost = 1;
  179. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  180. configuration.sharedContainerIdentifier = [NCBrandOptions sharedInstance].capabilitiesGroups;
  181. sessionUpload = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  182. sessionUpload.sessionDescription = k_upload_session_extension;
  183. }
  184. return sessionUpload;
  185. }
  186. - (OCCommunication *)sharedOCCommunication
  187. {
  188. static OCCommunication* sharedOCCommunication = nil;
  189. if (sharedOCCommunication == nil)
  190. {
  191. // Network
  192. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  193. configuration.allowsCellularAccess = YES;
  194. configuration.discretionary = NO;
  195. configuration.HTTPMaximumConnectionsPerHost = k_maxConcurrentOperation;
  196. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  197. OCURLSessionManager *networkSessionManager = [[OCURLSessionManager alloc] initWithSessionConfiguration:configuration];
  198. [networkSessionManager.operationQueue setMaxConcurrentOperationCount: k_maxConcurrentOperation];
  199. networkSessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
  200. // Download
  201. NSURLSessionConfiguration *configurationDownload = [NSURLSessionConfiguration defaultSessionConfiguration];
  202. configurationDownload.allowsCellularAccess = YES;
  203. configurationDownload.discretionary = NO;
  204. configurationDownload.HTTPMaximumConnectionsPerHost = 1;
  205. configurationDownload.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  206. configurationDownload.timeoutIntervalForRequest = k_timeout_upload;
  207. OCURLSessionManager *downloadSessionManager = [[OCURLSessionManager alloc] initWithSessionConfiguration:configurationDownload];
  208. [downloadSessionManager.operationQueue setMaxConcurrentOperationCount:1];
  209. [downloadSessionManager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition (NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential) {
  210. return NSURLSessionAuthChallengePerformDefaultHandling;
  211. }];
  212. // Upload
  213. NSURLSessionConfiguration *configurationUpload = [NSURLSessionConfiguration defaultSessionConfiguration];
  214. configurationUpload.allowsCellularAccess = YES;
  215. configurationUpload.discretionary = NO;
  216. configurationUpload.HTTPMaximumConnectionsPerHost = 1;
  217. configurationUpload.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  218. configurationUpload.timeoutIntervalForRequest = k_timeout_upload;
  219. OCURLSessionManager *uploadSessionManager = [[OCURLSessionManager alloc] initWithSessionConfiguration:configurationUpload];
  220. [uploadSessionManager.operationQueue setMaxConcurrentOperationCount:1];
  221. [uploadSessionManager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition (NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential) {
  222. return NSURLSessionAuthChallengePerformDefaultHandling;
  223. }];
  224. sharedOCCommunication = [[OCCommunication alloc] initWithUploadSessionManager:uploadSessionManager andDownloadSessionManager:downloadSessionManager andNetworkSessionManager:networkSessionManager];
  225. }
  226. return sharedOCCommunication;
  227. }
  228. - (OCCommunication *)sharedOCCommunicationExtensionDownload
  229. {
  230. static OCCommunication *sharedOCCommunicationExtensionDownload = nil;
  231. if (sharedOCCommunicationExtensionDownload == nil)
  232. {
  233. NSURLSessionConfiguration *config = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_download_session_extension];
  234. config.sharedContainerIdentifier = [NCBrandOptions sharedInstance].capabilitiesGroups;
  235. config.HTTPMaximumConnectionsPerHost = 1;
  236. config.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  237. config.timeoutIntervalForRequest = k_timeout_upload;
  238. config.sessionSendsLaunchEvents = YES;
  239. [config setAllowsCellularAccess:YES];
  240. OCURLSessionManager *sessionManager = [[OCURLSessionManager alloc] initWithSessionConfiguration:config];
  241. [sessionManager.operationQueue setMaxConcurrentOperationCount:1];
  242. [sessionManager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition (NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential) {
  243. return NSURLSessionAuthChallengePerformDefaultHandling;
  244. }];
  245. sharedOCCommunicationExtensionDownload = [[OCCommunication alloc] initWithUploadSessionManager:nil andDownloadSessionManager:sessionManager andNetworkSessionManager:nil];
  246. }
  247. return sharedOCCommunicationExtensionDownload;
  248. }
  249. - (NSURLSession *)getSessionfromSessionDescription:(NSString *)sessionDescription
  250. {
  251. if ([sessionDescription isEqualToString:k_download_session]) return [self sessionDownload];
  252. if ([sessionDescription isEqualToString:k_download_session_foreground]) return [self sessionDownloadForeground];
  253. if ([sessionDescription isEqualToString:k_download_session_wwan]) return [self sessionWWanDownload];
  254. if ([sessionDescription isEqualToString:k_upload_session]) return [self sessionUpload];
  255. if ([sessionDescription isEqualToString:k_upload_session_wwan]) return [self sessionWWanUpload];
  256. if ([sessionDescription isEqualToString:k_upload_session_foreground]) return [self sessionUploadForeground];
  257. return nil;
  258. }
  259. - (void)invalidateAndCancelAllSession
  260. {
  261. [[self sessionDownload] invalidateAndCancel];
  262. [[self sessionDownloadForeground] invalidateAndCancel];
  263. [[self sessionWWanDownload] invalidateAndCancel];
  264. [[self sessionUpload] invalidateAndCancel];
  265. [[self sessionWWanUpload] invalidateAndCancel];
  266. [[self sessionUploadForeground] invalidateAndCancel];
  267. }
  268. - (NSArray *)getUploadTasksExtensionSession
  269. {
  270. __block NSArray *tasks = [NSArray new];
  271. [[self sessionUploadExtension] getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  272. tasks = uploadTasks;
  273. }];
  274. return tasks;
  275. }
  276. #pragma --------------------------------------------------------------------------------------------
  277. #pragma mark ===== URLSession download/upload =====
  278. #pragma --------------------------------------------------------------------------------------------
  279. - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
  280. {
  281. // The pinnning check
  282. if ([[CCCertificate sharedManager] checkTrustedChallenge:challenge]) {
  283. completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  284. } else {
  285. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  286. }
  287. }
  288. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
  289. {
  290. NSString *url = [[[task currentRequest].URL absoluteString] stringByRemovingPercentEncoding];
  291. if (!url)
  292. return;
  293. NSString *fileName = [url lastPathComponent];
  294. NSString *serverUrl = [self getServerUrlFromUrl:url];
  295. if (!serverUrl) return;
  296. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  297. if (!directoryID) return;
  298. tableMetadata *metadata;
  299. NSInteger errorCode;
  300. NSDate *date = [NSDate date];
  301. NSDateFormatter *dateFormatter = [NSDateFormatter new];
  302. NSLocale *enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
  303. [dateFormatter setLocale:enUSPOSIXLocale];
  304. [dateFormatter setDateFormat:@"EEE, dd MMM y HH:mm:ss zzz"];
  305. NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)task.response;
  306. if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {
  307. errorCode = error.code;
  308. } else {
  309. if (httpResponse.statusCode > 0)
  310. errorCode = httpResponse.statusCode;
  311. else
  312. errorCode = error.code;
  313. }
  314. // ----------------------- DOWNLOAD -----------------------
  315. if ([task isKindOfClass:[NSURLSessionDownloadTask class]]) {
  316. metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"directoryID == %@ AND fileName == %@", directoryID, fileName]];
  317. if (metadata) {
  318. NSString *etag = metadata.etag;
  319. NSString *fileID = metadata.fileID;
  320. NSDictionary *fields = [httpResponse allHeaderFields];
  321. if (errorCode == 0) {
  322. etag = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-ETag"]];
  323. NSString *dateString = [fields objectForKey:@"Date"];
  324. if (dateString) {
  325. if (![dateFormatter getObjectValue:&date forString:dateString range:nil error:&error]) {
  326. date = [NSDate date];
  327. }
  328. } else {
  329. date = [NSDate date];
  330. }
  331. }
  332. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, task, nil];
  333. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  334. if (fileName.length > 0 && serverUrl.length > 0) {
  335. dispatch_async(dispatch_get_main_queue(), ^{
  336. [self downloadFileSuccessFailure:fileName fileID:metadata.fileID etag:etag date:date serverUrl:serverUrl selector:metadata.sessionSelector selectorPost:metadata.sessionSelectorPost errorCode:errorCode];
  337. });
  338. }
  339. } else {
  340. NSLog(@"[LOG] Remove record ? : metadata not found %@", url);
  341. dispatch_async(dispatch_get_main_queue(), ^{
  342. [self.delegate downloadFileSuccessFailure:fileName fileID:@"" serverUrl:serverUrl selector:@"" selectorPost:@"" errorMessage:@"Remove record ? : metadata not found" errorCode:k_CCErrorInternalError];
  343. });
  344. }
  345. }
  346. // ------------------------ UPLOAD -----------------------
  347. if ([task isKindOfClass:[NSURLSessionUploadTask class]]) {
  348. metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"directoryID == %@ AND fileName == %@", directoryID, fileName]];
  349. if (metadata) {
  350. NSDictionary *fields = [httpResponse allHeaderFields];
  351. NSString *fileID = metadata.fileID;
  352. NSString *etag = metadata.etag;
  353. if (errorCode == 0) {
  354. fileID = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-FileId"]];
  355. etag = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-ETag"]];
  356. NSString *dateString = [fields objectForKey:@"Date"];
  357. if (dateString) {
  358. if (![dateFormatter getObjectValue:&date forString:dateString range:nil error:&error]) {
  359. NSLog(@"[LOG] Date '%@' could not be parsed: %@", dateString, error);
  360. date = [NSDate date];
  361. }
  362. } else {
  363. date = [NSDate date];
  364. }
  365. }
  366. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, task, nil];
  367. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  368. if (fileName.length > 0 && fileID.length > 0 && serverUrl.length > 0) {
  369. dispatch_async(dispatch_get_main_queue(), ^{
  370. [self uploadFileSuccessFailure:metadata fileName:fileName fileID:fileID etag:etag date:date serverUrl:serverUrl errorCode:errorCode];
  371. });
  372. }
  373. } else {
  374. NSLog(@"[LOG] Remove record ? : metadata not found %@", url);
  375. dispatch_async(dispatch_get_main_queue(), ^{
  376. [self.delegate uploadFileSuccessFailure:fileName fileID:@"" assetLocalIdentifier:@"" serverUrl:serverUrl selector:@"" selectorPost:@"" errorMessage:@"Remove record ? : metadata not found" errorCode:k_CCErrorInternalError];
  377. });
  378. }
  379. }
  380. }
  381. #pragma --------------------------------------------------------------------------------------------
  382. #pragma mark ===== Download =====
  383. #pragma --------------------------------------------------------------------------------------------
  384. - (void)downloadFile:(tableMetadata *)metadata taskStatus:(NSInteger)taskStatus delegate:(id)delegate;
  385. {
  386. // add delegate
  387. [_delegates setObject:delegate forKey:metadata.fileID];
  388. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  389. // File exists ?
  390. tableLocalFile *localfile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  391. if (localfile != nil && [CCUtility fileProviderStorageExists:metadata.fileID fileName:metadata.fileNameView]) {
  392. [[NCManageDatabase sharedInstance] setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionSelectorPost:@"" sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusNormal predicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  393. [delegate downloadFileSuccessFailure:metadata.fileName fileID:metadata.fileID serverUrl:serverUrl selector:metadata.sessionSelector selectorPost:metadata.sessionSelectorPost errorMessage:@"" errorCode:0];
  394. return;
  395. }
  396. [self downloaURLSession:metadata serverUrl:serverUrl taskStatus:taskStatus];
  397. }
  398. - (void)downloaURLSession:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl taskStatus:(NSInteger)taskStatus
  399. {
  400. NSURLSession *sessionDownload;
  401. NSURL *url;
  402. NSMutableURLRequest *request;
  403. NSString *serverFileUrl = [[NSString stringWithFormat:@"%@/%@", serverUrl, metadata.fileName] encodeString:NSUTF8StringEncoding];
  404. url = [NSURL URLWithString:serverFileUrl];
  405. request = [NSMutableURLRequest requestWithURL:url];
  406. NSData *authData = [[NSString stringWithFormat:@"%@:%@", _activeUser, _activePassword] dataUsingEncoding:NSUTF8StringEncoding];
  407. NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];
  408. [request setValue:authValue forHTTPHeaderField:@"Authorization"];
  409. [request setValue:[CCUtility getUserAgent] forHTTPHeaderField:@"User-Agent"];
  410. if ([metadata.session isEqualToString:k_download_session]) sessionDownload = [self sessionDownload];
  411. else if ([metadata.session isEqualToString:k_download_session_foreground]) sessionDownload = [self sessionDownloadForeground];
  412. else if ([metadata.session isEqualToString:k_download_session_wwan]) sessionDownload = [self sessionWWanDownload];
  413. NSURLSessionDownloadTask *downloadTask = [sessionDownload downloadTaskWithRequest:request];
  414. if (downloadTask == nil) {
  415. [[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];
  416. [[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]];
  417. [self.delegate downloadFileSuccessFailure:metadata.fileName fileID:metadata.fileID serverUrl:serverUrl selector:metadata.sessionSelector selectorPost:@"" errorMessage:@"Serious internal error downloadTask not available" errorCode:k_CCErrorInternalError];
  418. } else {
  419. // Manage uploadTask cancel,suspend,resume
  420. if (taskStatus == k_taskStatusCancel) [downloadTask cancel];
  421. else if (taskStatus == k_taskStatusSuspend) [downloadTask suspend];
  422. else if (taskStatus == k_taskStatusResume) [downloadTask resume];
  423. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:nil sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:downloadTask.taskIdentifier status:k_metadataStatusDownloading predicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  424. NSLog(@"[LOG] downloadFileSession %@ Task [%lu]", metadata.fileID, (unsigned long)downloadTask.taskIdentifier);
  425. }
  426. dispatch_async(dispatch_get_main_queue(), ^{
  427. if ([[self getDelegate:metadata.fileID] respondsToSelector:@selector(downloadStart:account:task:serverUrl:)]) {
  428. [[self getDelegate:metadata.fileID] downloadStart:metadata.fileID account:metadata.account task:downloadTask serverUrl:serverUrl];
  429. }
  430. });
  431. }
  432. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
  433. {
  434. NSString *url = [[[downloadTask currentRequest].URL absoluteString] stringByRemovingPercentEncoding];
  435. NSString *fileName = [url lastPathComponent];
  436. NSString *serverUrl = [self getServerUrlFromUrl:url];
  437. if (!serverUrl) return;
  438. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  439. if (!directoryID) return;
  440. float progress = (float) totalBytesWritten / (float)totalBytesExpectedToWrite;
  441. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataInSessionFromFileName:fileName directoryID:directoryID];
  442. if (metadata) {
  443. NSDictionary* userInfo = @{@"fileID": (metadata.fileID), @"serverUrl": (serverUrl), @"progress": ([NSNumber numberWithFloat:progress])};
  444. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  445. } else {
  446. NSLog(@"[LOG] metadata not found");
  447. }
  448. }
  449. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
  450. {
  451. NSString *url = [[[downloadTask currentRequest].URL absoluteString] stringByRemovingPercentEncoding];
  452. if (!url)
  453. return;
  454. NSString *fileName = [url lastPathComponent];
  455. NSString *serverUrl = [self getServerUrlFromUrl:url];
  456. if (!serverUrl) return;
  457. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  458. if (!directoryID) return;
  459. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"directoryID == %@ AND fileName == %@", directoryID, fileName]];
  460. if (!metadata) {
  461. [[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];
  462. NSLog(@"[LOG] Serious error internal download : metadata not found %@ ", url);
  463. dispatch_async(dispatch_get_main_queue(), ^{
  464. [self.delegate downloadFileSuccessFailure:@"" fileID:@"" serverUrl:serverUrl selector:@"" selectorPost:@"" errorMessage:@"Serious error internal download : metadata not found" errorCode:k_CCErrorInternalError];
  465. });
  466. return;
  467. }
  468. NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)downloadTask.response;
  469. if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {
  470. NSString *destinationFilePath = [CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileName:metadata.fileName];
  471. NSURL *destinationURL = [NSURL fileURLWithPath:destinationFilePath];
  472. [[NSFileManager defaultManager] removeItemAtURL:destinationURL error:NULL];
  473. [[NSFileManager defaultManager] copyItemAtURL:location toURL:destinationURL error:nil];
  474. }
  475. }
  476. - (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
  477. {
  478. #ifndef EXTENSION
  479. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  480. [appDelegate.listProgressMetadata removeObjectForKey:fileID];
  481. #endif
  482. // Progress Task
  483. NSDictionary* userInfo = @{@"fileID": (fileID), @"serverUrl": (serverUrl), @"progress": ([NSNumber numberWithFloat:0.0])};
  484. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  485. if (errorCode != 0) {
  486. if (errorCode != kCFURLErrorCancelled) {
  487. [[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]];
  488. }
  489. [[self getDelegate:fileID] downloadFileSuccessFailure:fileName fileID:fileID serverUrl:serverUrl selector:selector selectorPost:selectorPost errorMessage:[CCError manageErrorKCF:errorCode withNumberError:YES] errorCode:errorCode];
  490. } else {
  491. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  492. if (!metadata) {
  493. [[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];
  494. NSLog(@"[LOG] Serious error internal download : metadata not found %@ ", fileName);
  495. [[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];
  496. return;
  497. }
  498. metadata.session = @"";
  499. metadata.sessionError = @"";
  500. metadata.sessionSelector = @"";
  501. metadata.sessionSelectorPost = @"";
  502. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  503. metadata.status = k_metadataStatusNormal;
  504. metadata = [[NCManageDatabase sharedInstance] updateMetadata:metadata];
  505. [[NCManageDatabase sharedInstance] addLocalFileWithMetadata:metadata];
  506. // E2EE Decrypted
  507. tableE2eEncryption *object = [[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"fileNameIdentifier == %@ AND serverUrl == %@", fileName, serverUrl]];
  508. if (object) {
  509. BOOL result = [[NCEndToEndEncryption sharedManager] decryptFileName:metadata.fileName fileNameView:metadata.fileNameView fileID:metadata.fileID key:object.key initializationVector:object.initializationVector authenticationTag:object.authenticationTag];
  510. if (!result) {
  511. [[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];
  512. [[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];
  513. return;
  514. }
  515. }
  516. // Exif
  517. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  518. [[CCExifGeo sharedInstance] setExifLocalTableEtag:metadata];
  519. // Icon
  520. [CCGraphics createNewImageFrom:metadata.fileNameView fileID:metadata.fileID extension:[metadata.fileNameView pathExtension] size:@"m" imageForUpload:NO typeFile:metadata.typeFile writeImage:YES optimizedFileName:[CCUtility getOptimizedPhoto]];
  521. // Activity
  522. [[NCManageDatabase sharedInstance] addActivityClient:metadata.fileNameView fileID:metadata.fileID action:k_activityDebugActionDownload selector:metadata.sessionSelector note:serverUrl type:k_activityTypeSuccess verbose:k_activityVerboseDefault activeUrl:_activeUrl];
  523. [[self getDelegate:fileID] downloadFileSuccessFailure:fileName fileID:fileID serverUrl:serverUrl selector:selector selectorPost:selectorPost errorMessage:@"" errorCode:0];
  524. }
  525. }
  526. #pragma --------------------------------------------------------------------------------------------
  527. #pragma mark ===== Upload =====
  528. #pragma --------------------------------------------------------------------------------------------
  529. - (void)uploadFile:(tableMetadata *)metadata taskStatus:(NSInteger)taskStatus delegate:(id)delegate
  530. {
  531. //delegate
  532. [_delegates setObject:delegate forKey:metadata.fileID];
  533. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  534. if ([CCUtility fileProviderStorageExists:metadata.fileID fileName:metadata.fileNameView] == NO) {
  535. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadata.assetLocalIdentifier] options:nil];
  536. if (!result.count) {
  537. [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];
  538. return;
  539. }
  540. PHAsset *asset= result[0];
  541. // IMAGE
  542. if (asset.mediaType == PHAssetMediaTypeImage) {
  543. PHImageRequestOptions *options = [PHImageRequestOptions new];
  544. options.networkAccessAllowed = YES; // iCloud
  545. options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
  546. options.synchronous = YES;
  547. options.progressHandler = ^(double progress, NSError *error, BOOL *stop, NSDictionary *info) {
  548. NSLog(@"cacheAsset: %f", progress);
  549. if (error)
  550. [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];
  551. };
  552. [[PHImageManager defaultManager] requestImageDataForAsset:asset options:options resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) {
  553. NSError *error = nil;
  554. if ([dataUTI isEqualToString:@"public.heic"] && [CCUtility getFormatCompatibility]) {
  555. UIImage *image = [UIImage imageWithData:imageData];
  556. imageData = UIImageJPEGRepresentation(image, 1.0);
  557. NSString *fileNameJPEG = [[metadata.fileName lastPathComponent] stringByDeletingPathExtension];
  558. metadata.fileName = [fileNameJPEG stringByAppendingString:@".jpg"];
  559. metadata.fileNameView = metadata.fileName;
  560. [imageData writeToFile:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileName:metadata.fileNameView] options:NSDataWritingAtomic error:&error];
  561. } else {
  562. [imageData writeToFile:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileName:metadata.fileNameView] 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:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileName:metadata.fileNameView]];
  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 fileID:metadata.fileID 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. tableMetadata *metadataEncrypted = [[NCManageDatabase sharedInstance] addMetadata:metadata];
  635. [self uploadURLSessionMetadata:metadataEncrypted 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 fileID:metadata.fileID extension:[metadata.fileNameView pathExtension] size:@"m" imageForUpload:YES typeFile:metadata.typeFile writeImage: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:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileName: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. BOOL isE2EEDirectory = false;
  751. // Progress Task
  752. NSDictionary* userInfo = @{@"fileID": (fileID), @"serverUrl": (serverUrl), @"progress": ([NSNumber numberWithFloat:0.0])};
  753. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  754. // E2EE Directory ?
  755. if ([CCUtility isFolderEncrypted:serverUrl account:_activeAccount] && [CCUtility isEndToEndEnabled:_activeAccount]) {
  756. isE2EEDirectory = true;
  757. }
  758. // ERRORE
  759. if (errorCode != 0) {
  760. #ifndef EXTENSION
  761. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  762. [appDelegate.listProgressMetadata removeObjectForKey:metadata.fileID];
  763. #endif
  764. // Mark error only if not Cancelled Task
  765. if (errorCode != kCFURLErrorCancelled) {
  766. [[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]];
  767. }
  768. errorMessage = [CCError manageErrorKCF:errorCode withNumberError:YES];
  769. } else {
  770. // Replace Metadata
  771. metadata.date = date;
  772. if (isE2EEDirectory) {
  773. metadata.e2eEncrypted = true;
  774. } else {
  775. metadata.e2eEncrypted = false;
  776. }
  777. metadata.etag = etag;
  778. metadata.fileID = fileID;
  779. metadata.session = @"";
  780. metadata.sessionError = @"";
  781. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  782. metadata.status = k_metadataStatusNormal;
  783. metadata = [[NCManageDatabase sharedInstance] addMetadata:metadata];
  784. if (![fileID isEqualToString:tempFileID])
  785. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", tempFileID] clearDateReadDirectoryID:nil];
  786. #ifndef EXTENSION
  787. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  788. [appDelegate.listProgressMetadata removeObjectForKey:metadata.fileID];
  789. #endif
  790. NSLog(@"[LOG] Insert new upload : %@ - fileID : %@", metadata.fileName, metadata.fileID);
  791. // Rename directory
  792. [[NSFileManager defaultManager] moveItemAtPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], tempFileID] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], metadata.fileID] error:nil];
  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];
  800. // Create ICON
  801. if (metadata.directory == NO)
  802. [CCGraphics createNewImageFrom:metadata.fileNameView fileID:metadata.fileID extension:[metadata.fileNameView pathExtension] size:@"m" imageForUpload:NO typeFile:metadata.typeFile writeImage:YES optimizedFileName:[CCUtility getOptimizedPhoto]];
  803. // Optimization
  804. if (([CCUtility getUploadAndRemovePhoto] || [metadata.sessionSelectorPost isEqualToString:selectorUploadRemovePhoto]) && isE2EEDirectory == NO && [metadata.typeFile isEqualToString:k_metadataTypeFile_document] == NO) {
  805. [[NSFileManager defaultManager] createFileAtPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileName:metadata.fileNameView] contents:nil attributes:nil];
  806. }
  807. // Copy photo or video in the photo album for auto upload
  808. if ([metadata.assetLocalIdentifier length] > 0 && ([metadata.sessionSelector isEqualToString:selectorUploadAutoUpload] || [metadata.sessionSelector isEqualToString:selectorUploadFile])) {
  809. PHAsset *asset;
  810. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadata.assetLocalIdentifier] options:nil];
  811. if(result.count){
  812. asset = result[0];
  813. [asset saveToAlbum:[NCBrandOptions sharedInstance].brand completionBlock:^(BOOL success) {
  814. if (success) NSLog(@"[LOG] Insert file %@ in %@", metadata.fileName, [NCBrandOptions sharedInstance].brand);
  815. else NSLog(@"[LOG] File %@ do not insert in %@", metadata.fileName, [NCBrandOptions sharedInstance].brand);
  816. }];
  817. }
  818. }
  819. #endif
  820. // Actvity
  821. [[NCManageDatabase sharedInstance] addActivityClient:metadata.fileNameView fileID:fileID action:k_activityDebugActionUpload selector:metadata.sessionSelector note:serverUrl type:k_activityTypeSuccess verbose:k_activityVerboseDefault activeUrl:_activeUrl];
  822. }
  823. // E2EE : UNLOCK
  824. if (isE2EEDirectory) {
  825. tableE2eEncryptionLock *tableLock = [[NCManageDatabase sharedInstance] getE2ETokenLockWithServerUrl:serverUrl];
  826. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  827. if (tableLock) {
  828. NSError *error = [[NCNetworkingEndToEnd sharedManager] unlockEndToEndFolderEncrypted:_activeUser userID:_activeUserID password:_activePassword url:_activeUrl serverUrl:serverUrl fileID:tableLock.fileID token:tableLock.token];
  829. if (error) {
  830. #ifndef EXTENSION
  831. dispatch_async(dispatch_get_main_queue(), ^{
  832. [(AppDelegate *)[[UIApplication sharedApplication] delegate] messageNotification:@"_e2e_error_unlock_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  833. });
  834. #endif
  835. }
  836. } else {
  837. NSLog(@"Error unlock not found");
  838. }
  839. dispatch_async(dispatch_get_main_queue(), ^{
  840. [[self getDelegate:tempFileID] uploadFileSuccessFailure:metadata.fileName fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:serverUrl selector:metadata.sessionSelector selectorPost:metadata.sessionSelectorPost errorMessage:errorMessage errorCode:errorCode];
  841. });
  842. });
  843. } else {
  844. [[self getDelegate:tempFileID] uploadFileSuccessFailure:metadata.fileName fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:serverUrl selector:metadata.sessionSelector selectorPost:metadata.sessionSelectorPost errorMessage:errorMessage errorCode:errorCode];
  845. }
  846. }
  847. #pragma --------------------------------------------------------------------------------------------
  848. #pragma mark ===== Utility =====
  849. #pragma --------------------------------------------------------------------------------------------
  850. - (id)getDelegate:(NSString *)fileID
  851. {
  852. id delegate = [_delegates objectForKey:fileID];
  853. if (delegate)
  854. return delegate;
  855. else
  856. return self.delegate;
  857. }
  858. - (NSString *)getServerUrlFromUrl:(NSString *)url
  859. {
  860. NSString *fileName = [url lastPathComponent];
  861. url = [url stringByReplacingOccurrencesOfString:[@"/" stringByAppendingString:fileName] withString:@""];
  862. return url;
  863. }
  864. #pragma --------------------------------------------------------------------------------------------
  865. #pragma mark ===== E2EE End To End Encryption =====
  866. #pragma --------------------------------------------------------------------------------------------
  867. // E2EE
  868. - (void)encryptedE2EFile:(NSString *)fileName fileID:(NSString *)fileID 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
  869. {
  870. __block NSError *error;
  871. NSString *key;
  872. NSString *initializationVector;
  873. NSString *authenticationTag;
  874. NSString *metadataKey;
  875. NSInteger metadataKeyIndex;
  876. // Verify File Size
  877. NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[CCUtility getDirectoryProviderStorageFileID:fileID fileName:fileName] error:&error];
  878. NSNumber *fileSizeNumber = [fileAttributes objectForKey:NSFileSize];
  879. long long fileSize = [fileSizeNumber longLongValue];
  880. if (fileSize > k_max_filesize_E2E) {
  881. // Error for uploadFileFailure
  882. *errorMessage = @"E2E Error file too big";
  883. return;
  884. }
  885. // if new file upload [directoryID + fileName] create a new encrypted filename
  886. if ([fileID isEqualToString:[directoryID stringByAppendingString:fileName]]) {
  887. *fileNameIdentifier = [CCUtility generateRandomIdentifier];
  888. } else {
  889. *fileNameIdentifier = fileName;
  890. }
  891. // Write to DB
  892. if ([[NCEndToEndEncryption sharedManager] encryptFileName:fileName fileNameIdentifier:*fileNameIdentifier directory:[CCUtility getDirectoryProviderStorageFileID:fileID] key:&key initializationVector:&initializationVector authenticationTag:&authenticationTag]) {
  893. tableE2eEncryption *object = [[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", _activeAccount, serverUrl]];
  894. if (object) {
  895. metadataKey = object.metadataKey;
  896. metadataKeyIndex = object.metadataKeyIndex;
  897. } else {
  898. metadataKey = [[[NCEndToEndEncryption sharedManager] generateKey:16] base64EncodedStringWithOptions:0]; // AES_KEY_128_LENGTH
  899. metadataKeyIndex = 0;
  900. }
  901. tableE2eEncryption *addObject = [tableE2eEncryption new];
  902. addObject.account = _activeAccount;
  903. addObject.authenticationTag = authenticationTag;
  904. addObject.fileName = fileName;
  905. addObject.fileNameIdentifier = *fileNameIdentifier;
  906. addObject.fileNamePath = [CCUtility returnFileNamePathFromFileName:fileName serverUrl:serverUrl activeUrl:_activeUrl];
  907. addObject.key = key;
  908. addObject.initializationVector = initializationVector;
  909. addObject.metadataKey = metadataKey;
  910. addObject.metadataKeyIndex = metadataKeyIndex;
  911. CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)[fileName pathExtension], NULL);
  912. CFStringRef mimeTypeRef = UTTypeCopyPreferredTagWithClass (UTI, kUTTagClassMIMEType);
  913. if (mimeTypeRef) {
  914. addObject.mimeType = (__bridge NSString *)mimeTypeRef;
  915. } else {
  916. addObject.mimeType = @"application/octet-stream";
  917. }
  918. addObject.serverUrl = serverUrl;
  919. addObject.version = [[NCManageDatabase sharedInstance] getEndToEndEncryptionVersion];
  920. // Get the last metadata
  921. NSString *metadata;
  922. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", account, serverUrl]];
  923. error = [[NCNetworkingEndToEnd sharedManager] getEndToEndMetadata:user userID:userID password:password url:url fileID:directory.fileID metadata:&metadata];
  924. if (error == nil) {
  925. if ([[NCEndToEndMetadata sharedInstance] decoderMetadata:metadata privateKey:[CCUtility getEndToEndPrivateKey:account] serverUrl:serverUrl account:account url:url] == false) {
  926. *errorMessage = NSLocalizedString(@"_e2e_error_decode_metadata_", nil);
  927. return;
  928. }
  929. }
  930. *e2eMetadata = metadata;
  931. // write new record e2ee
  932. if([[NCManageDatabase sharedInstance] addE2eEncryption:addObject] == NO)
  933. *errorMessage = NSLocalizedString(@"_e2e_error_create_encrypted_", nil);
  934. } else {
  935. *errorMessage = NSLocalizedString(@"_e2e_error_create_encrypted_", nil);
  936. }
  937. }
  938. @end
  939. #pragma --------------------------------------------------------------------------------------------
  940. #pragma mark ===== CCMetadataNet =====
  941. #pragma --------------------------------------------------------------------------------------------
  942. @implementation CCMetadataNet
  943. - (id)init
  944. {
  945. self = [super init];
  946. self.priority = NSOperationQueuePriorityNormal;
  947. return self;
  948. }
  949. - (id)initWithAccount:(NSString *)withAccount
  950. {
  951. self = [self init];
  952. if (self) {
  953. _account = withAccount;
  954. }
  955. return self;
  956. }
  957. - (id)copyWithZone: (NSZone *) zone
  958. {
  959. CCMetadataNet *metadataNet = [[CCMetadataNet allocWithZone: zone] init];
  960. [metadataNet setAccount: self.account];
  961. [metadataNet setAction: self.action];
  962. [metadataNet setContentType: self.contentType];
  963. [metadataNet setDate: self.date];
  964. [metadataNet setDelegate: self.delegate];
  965. [metadataNet setDepth: self.depth];
  966. [metadataNet setDirectory: self.directory];
  967. [metadataNet setDirectoryID: self.directoryID];
  968. [metadataNet setDirectoryIDTo: self.directoryIDTo];
  969. [metadataNet setEncryptedMetadata: self.encryptedMetadata];
  970. [metadataNet setEtag:self.etag];
  971. [metadataNet setExpirationTime: self.expirationTime];
  972. [metadataNet setFileID: self.fileID];
  973. [metadataNet setFileName: self.fileName];
  974. [metadataNet setFileNameTo: self.fileNameTo];
  975. [metadataNet setFileNameView: self.fileNameView];
  976. [metadataNet setKey: self.key];
  977. [metadataNet setKeyCipher: self.keyCipher];
  978. [metadataNet setOptionAny: self.optionAny];
  979. [metadataNet setOptionString: self.optionString];
  980. [metadataNet setPassword: self.password];
  981. [metadataNet setPriority: self.priority];
  982. [metadataNet setServerUrl: self.serverUrl];
  983. [metadataNet setServerUrlTo: self.serverUrlTo];
  984. [metadataNet setSelector: self.selector];
  985. [metadataNet setSelectorPost: self.selectorPost];
  986. [metadataNet setShare: self.share];
  987. [metadataNet setShareeType: self.shareeType];
  988. [metadataNet setSharePermission: self.sharePermission];
  989. [metadataNet setSize: self.size];
  990. return metadataNet;
  991. }
  992. @end