CCNetworking.m 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624
  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 "AppDelegate.h"
  26. #import "CCCertificate.h"
  27. #import "NSDate+ISO8601.h"
  28. #import "NSString+Encode.h"
  29. #import "NCBridgeSwift.h"
  30. @interface CCNetworking ()
  31. {
  32. NSMutableDictionary *_taskData;
  33. NSString *_activeAccount;
  34. NSString *_activePassword;
  35. NSString *_activeUser;
  36. NSString *_activeUserID;
  37. NSString *_activeUrl;
  38. NSString *_directoryUser;
  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 sessionUploadForeground];
  63. [self sessionWWanUpload];
  64. [self sharedOCCommunication];
  65. [self settingAccount];
  66. return self;
  67. }
  68. - (void)settingAccount
  69. {
  70. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  71. _activeAccount = tableAccount.account;
  72. _activePassword = tableAccount.password;
  73. _activeUser = tableAccount.user;
  74. _activeUserID = tableAccount.userID;
  75. _activeUrl = tableAccount.url;
  76. _directoryUser = [CCUtility getDirectoryActiveUser:_activeUser activeUrl:_activeUrl];
  77. }
  78. #pragma --------------------------------------------------------------------------------------------
  79. #pragma mark ===== Session =====
  80. #pragma --------------------------------------------------------------------------------------------
  81. - (NSURLSession *)sessionDownload
  82. {
  83. static NSURLSession *sessionDownload = nil;
  84. if (sessionDownload == nil) {
  85. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_download_session];
  86. configuration.allowsCellularAccess = YES;
  87. configuration.sessionSendsLaunchEvents = YES;
  88. configuration.discretionary = NO;
  89. configuration.HTTPMaximumConnectionsPerHost = 1;
  90. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  91. sessionDownload = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  92. sessionDownload.sessionDescription = k_download_session;
  93. }
  94. return sessionDownload;
  95. }
  96. - (NSURLSession *)sessionDownloadForeground
  97. {
  98. static NSURLSession *sessionDownloadForeground = nil;
  99. if (sessionDownloadForeground == nil) {
  100. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  101. configuration.allowsCellularAccess = YES;
  102. configuration.discretionary = NO;
  103. configuration.HTTPMaximumConnectionsPerHost = 1;
  104. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  105. sessionDownloadForeground = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  106. sessionDownloadForeground.sessionDescription = k_download_session_foreground;
  107. }
  108. return sessionDownloadForeground;
  109. }
  110. - (NSURLSession *)sessionWWanDownload
  111. {
  112. static NSURLSession *sessionWWanDownload = nil;
  113. if (sessionWWanDownload == nil) {
  114. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_download_session_wwan];
  115. configuration.allowsCellularAccess = NO;
  116. configuration.sessionSendsLaunchEvents = YES;
  117. configuration.discretionary = NO;
  118. configuration.HTTPMaximumConnectionsPerHost = 1;
  119. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  120. sessionWWanDownload = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  121. sessionWWanDownload.sessionDescription = k_download_session_wwan;
  122. }
  123. return sessionWWanDownload;
  124. }
  125. - (NSURLSession *)sessionUpload
  126. {
  127. static NSURLSession *sessionUpload = nil;
  128. if (sessionUpload == nil) {
  129. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_upload_session];
  130. configuration.allowsCellularAccess = YES;
  131. configuration.sessionSendsLaunchEvents = YES;
  132. configuration.discretionary = NO;
  133. configuration.HTTPMaximumConnectionsPerHost = 1;
  134. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  135. sessionUpload = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  136. sessionUpload.sessionDescription = k_upload_session;
  137. }
  138. return sessionUpload;
  139. }
  140. - (NSURLSession *)sessionUploadForeground
  141. {
  142. static NSURLSession *sessionUploadForeground;
  143. if (sessionUploadForeground == nil) {
  144. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  145. configuration.allowsCellularAccess = YES;
  146. configuration.discretionary = NO;
  147. configuration.HTTPMaximumConnectionsPerHost = 1;
  148. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  149. sessionUploadForeground = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  150. sessionUploadForeground.sessionDescription = k_upload_session_foreground;
  151. }
  152. return sessionUploadForeground;
  153. }
  154. - (NSURLSession *)sessionWWanUpload
  155. {
  156. static NSURLSession *sessionWWanUpload = nil;
  157. if (sessionWWanUpload == nil) {
  158. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_upload_session_wwan];
  159. configuration.allowsCellularAccess = NO;
  160. configuration.sessionSendsLaunchEvents = YES;
  161. configuration.discretionary = NO;
  162. configuration.HTTPMaximumConnectionsPerHost = 1;
  163. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  164. sessionWWanUpload = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  165. sessionWWanUpload.sessionDescription = k_upload_session_wwan;
  166. }
  167. return sessionWWanUpload;
  168. }
  169. - (OCCommunication *)sharedOCCommunication
  170. {
  171. static OCCommunication* sharedOCCommunication = nil;
  172. if (sharedOCCommunication == nil)
  173. {
  174. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  175. configuration.allowsCellularAccess = YES;
  176. configuration.discretionary = NO;
  177. configuration.HTTPMaximumConnectionsPerHost = k_maxConcurrentOperation;
  178. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  179. OCURLSessionManager *networkSessionManager = [[OCURLSessionManager alloc] initWithSessionConfiguration:configuration];
  180. [networkSessionManager.operationQueue setMaxConcurrentOperationCount: k_maxConcurrentOperation];
  181. networkSessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
  182. sharedOCCommunication = [[OCCommunication alloc] initWithUploadSessionManager:nil andDownloadSessionManager:nil andNetworkSessionManager:networkSessionManager];
  183. }
  184. return sharedOCCommunication;
  185. }
  186. - (NSURLSession *)getSessionfromSessionDescription:(NSString *)sessionDescription
  187. {
  188. if ([sessionDescription isEqualToString:k_download_session]) return [self sessionDownload];
  189. if ([sessionDescription isEqualToString:k_download_session_foreground]) return [self sessionDownloadForeground];
  190. if ([sessionDescription isEqualToString:k_download_session_wwan]) return [self sessionWWanDownload];
  191. if ([sessionDescription isEqualToString:k_upload_session]) return [self sessionUpload];
  192. if ([sessionDescription isEqualToString:k_upload_session_foreground]) return [self sessionUploadForeground];
  193. if ([sessionDescription isEqualToString:k_upload_session_wwan]) return [self sessionWWanUpload];
  194. return nil;
  195. }
  196. - (void)invalidateAndCancelAllSession
  197. {
  198. [[self sessionDownload] invalidateAndCancel];
  199. [[self sessionDownloadForeground] invalidateAndCancel];
  200. [[self sessionWWanDownload] invalidateAndCancel];
  201. [[self sessionUpload] invalidateAndCancel];
  202. [[self sessionUploadForeground] invalidateAndCancel];
  203. [[self sessionWWanUpload] invalidateAndCancel];
  204. }
  205. - (void)settingSessionsDownload:(BOOL)download upload:(BOOL)upload taskStatus:(NSInteger)taskStatus activeAccount:(NSString *)activeAccount activeUser:(NSString *)activeUser activeUrl:(NSString *)activeUrl
  206. {
  207. if (download) {
  208. [[self sessionDownload] getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  209. for (NSURLSessionTask *task in downloadTasks)
  210. if (taskStatus == k_taskStatusCancel) [task cancel];
  211. else if (taskStatus == k_taskStatusSuspend) [task suspend];
  212. else if (taskStatus == k_taskStatusResume) [task resume];
  213. }];
  214. [[self sessionDownloadForeground] getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  215. for (NSURLSessionTask *task in downloadTasks)
  216. if (taskStatus == k_taskStatusCancel) [task cancel];
  217. else if (taskStatus == k_taskStatusSuspend) [task suspend];
  218. else if (taskStatus == k_taskStatusResume) [task resume];
  219. }];
  220. [[self sessionWWanDownload] getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  221. for (NSURLSessionTask *task in downloadTasks)
  222. if (taskStatus == k_taskStatusCancel) [task cancel];
  223. else if (taskStatus == k_taskStatusSuspend) [task suspend];
  224. else if (taskStatus == k_taskStatusResume) [task resume];
  225. }];
  226. }
  227. if (upload) {
  228. [[self sessionUpload] getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  229. for (NSURLSessionTask *task in uploadTasks)
  230. if (taskStatus == k_taskStatusCancel)[task cancel];
  231. else if (taskStatus == k_taskStatusSuspend) [task suspend];
  232. else if (taskStatus == k_taskStatusResume) [task resume];
  233. }];
  234. [[self sessionUploadForeground] getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  235. for (NSURLSessionTask *task in uploadTasks)
  236. if (taskStatus == k_taskStatusCancel) [task cancel];
  237. else if (taskStatus == k_taskStatusSuspend) [task suspend];
  238. else if (taskStatus == k_taskStatusResume) [task resume];
  239. }];
  240. [[self sessionWWanUpload] getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  241. for (NSURLSessionTask *task in uploadTasks)
  242. if (taskStatus == k_taskStatusCancel) [task cancel];
  243. else if (taskStatus == k_taskStatusSuspend) [task suspend];
  244. else if (taskStatus == k_taskStatusResume) [task resume];
  245. }];
  246. }
  247. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 4 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  248. if (download && taskStatus == k_taskStatusCancel) {
  249. [[NCManageDatabase sharedInstance] setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionSelectorPost:@"" sessionTaskIdentifier:k_taskIdentifierDone predicate:[NSPredicate predicateWithFormat:@"account = %@ AND session CONTAINS 'download'", _activeAccount]];
  250. }
  251. if (upload && taskStatus == k_taskStatusCancel) {
  252. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"session CONTAINS 'upload'"] clearDateReadDirectoryID:nil];
  253. // File System
  254. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  255. [CCUtility removeAllFileID_UPLOAD_ActiveUser:activeUser activeUrl:activeUrl];
  256. });
  257. }
  258. });
  259. }
  260. - (void)settingSession:(NSString *)sessionDescription sessionTaskIdentifier:(NSUInteger)sessionTaskIdentifier taskStatus:(NSInteger)taskStatus
  261. {
  262. NSURLSession *session = [self getSessionfromSessionDescription:sessionDescription];
  263. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  264. if ([sessionDescription containsString:@"download"])
  265. for (NSURLSessionTask *task in downloadTasks)
  266. if (task.taskIdentifier == sessionTaskIdentifier) {
  267. if (taskStatus == k_taskStatusCancel) [task cancel];
  268. else if (taskStatus == k_taskStatusSuspend) [task suspend];
  269. else if (taskStatus == k_taskStatusResume) [task resume];
  270. }
  271. if ([sessionDescription containsString:@"upload"])
  272. for (NSURLSessionTask *task in uploadTasks)
  273. if (task.taskIdentifier == sessionTaskIdentifier) {
  274. if (taskStatus == k_taskStatusCancel) [task cancel];
  275. else if (taskStatus == k_taskStatusSuspend) [task suspend];
  276. else if (taskStatus == k_taskStatusResume) [task resume];
  277. }
  278. }];
  279. }
  280. #pragma --------------------------------------------------------------------------------------------
  281. #pragma mark ===== URLSession download/upload =====
  282. #pragma --------------------------------------------------------------------------------------------
  283. - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
  284. {
  285. // The pinnning check
  286. if ([[CCCertificate sharedManager] checkTrustedChallenge:challenge]) {
  287. completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  288. } else {
  289. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  290. }
  291. }
  292. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
  293. {
  294. NSString *url = [[[task currentRequest].URL absoluteString] stringByRemovingPercentEncoding];
  295. if (!url)
  296. return;
  297. NSString *fileName = [url lastPathComponent];
  298. NSString *serverUrl = [self getServerUrlFromUrl:url];
  299. if (!serverUrl) return;
  300. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  301. if (!directoryID) return;
  302. tableMetadata *metadata;
  303. NSInteger errorCode;
  304. NSDate *date = [NSDate date];
  305. NSDateFormatter *dateFormatter = [NSDateFormatter new];
  306. NSLocale *enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
  307. [dateFormatter setLocale:enUSPOSIXLocale];
  308. [dateFormatter setDateFormat:@"EEE, dd MMM y HH:mm:ss zzz"];
  309. NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)task.response;
  310. if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {
  311. errorCode = error.code;
  312. } else {
  313. if (httpResponse.statusCode > 0)
  314. errorCode = httpResponse.statusCode;
  315. else
  316. errorCode = error.code;
  317. }
  318. // ----------------------- DOWNLOAD -----------------------
  319. if ([task isKindOfClass:[NSURLSessionDownloadTask class]]) {
  320. metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"session = %@ AND sessionTaskIdentifier = %i",session.sessionDescription, task.taskIdentifier]];
  321. if (!metadata)
  322. metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"directoryID = %@ AND fileName = %@", directoryID, fileName, fileName]];
  323. if (metadata) {
  324. NSString *etag = metadata.etag;
  325. NSString *fileID = metadata.fileID;
  326. NSDictionary *fields = [httpResponse allHeaderFields];
  327. if (errorCode == 0) {
  328. etag = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-ETag"]];
  329. NSString *dateString = [fields objectForKey:@"Date"];
  330. if (![dateFormatter getObjectValue:&date forString:dateString range:nil error:&error]) {
  331. NSLog(@"[LOG] Date '%@' could not be parsed: %@", dateString, error);
  332. date = [NSDate date];
  333. }
  334. }
  335. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, task, nil];
  336. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  337. if (fileName.length > 0 && serverUrl.length > 0)
  338. [self downloadFileSuccessFailure:fileName fileID:metadata.fileID etag:etag date:date serverUrl:serverUrl selector:metadata.sessionSelector selectorPost:metadata.sessionSelectorPost errorCode:errorCode];
  339. } else {
  340. NSLog(@"[LOG] Remove record ? : metadata not found %@", url);
  341. dispatch_async(dispatch_get_main_queue(), ^{
  342. if ([self.delegate respondsToSelector:@selector(downloadFileFailure:serverUrl:selector:message:errorCode:)])
  343. [self.delegate downloadFileFailure:@"" serverUrl:serverUrl selector:@"" message:@"" errorCode:k_CCErrorInternalError];
  344. });
  345. }
  346. }
  347. // ------------------------ UPLOAD -----------------------
  348. if ([task isKindOfClass:[NSURLSessionUploadTask class]]) {
  349. metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"session = %@ AND sessionTaskIdentifier = %i",session.sessionDescription, task.taskIdentifier]];
  350. if (!metadata)
  351. metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"directoryID = %@ AND fileName = %@", directoryID, fileName]];
  352. if (metadata) {
  353. NSDictionary *fields = [httpResponse allHeaderFields];
  354. NSString *fileID = metadata.fileID;
  355. NSString *etag = metadata.etag;
  356. if (errorCode == 0) {
  357. fileID = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-FileId"]];
  358. etag = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-ETag"]];
  359. NSString *dateString = [fields objectForKey:@"Date"];
  360. if (dateString) {
  361. if (![dateFormatter getObjectValue:&date forString:dateString range:nil error:&error]) {
  362. NSLog(@"[LOG] Date '%@' could not be parsed: %@", dateString, error);
  363. date = [NSDate date];
  364. }
  365. } else {
  366. date = [NSDate date];
  367. }
  368. }
  369. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, task, nil];
  370. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  371. if (fileName.length > 0 && fileID.length > 0 && serverUrl.length > 0)
  372. [self uploadFileSuccessFailure:metadata fileName:fileName fileID:fileID etag:etag date:date serverUrl:serverUrl errorCode:errorCode];
  373. } else {
  374. NSLog(@"[LOG] Remove record ? : metadata not found %@", url);
  375. dispatch_async(dispatch_get_main_queue(), ^{
  376. if ([self.delegate respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  377. [self.delegate uploadFileFailure:nil fileID:@"" serverUrl:serverUrl selector:@"" message:@"" errorCode:k_CCErrorInternalError];
  378. });
  379. }
  380. }
  381. }
  382. #pragma --------------------------------------------------------------------------------------------
  383. #pragma mark ===== Download =====
  384. #pragma --------------------------------------------------------------------------------------------
  385. - (void)downloadFile:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost session:(NSString *)session taskStatus:(NSInteger)taskStatus delegate:(id)delegate
  386. {
  387. // add delegate
  388. [_delegates setObject:delegate forKey:fileID];
  389. if (fileID.length == 0) {
  390. dispatch_async(dispatch_get_main_queue(), ^{
  391. if ([[self getDelegate:fileID] respondsToSelector:@selector(downloadFileFailure:serverUrl:selector:message:errorCode:)])
  392. [[self getDelegate:fileID] downloadFileFailure:fileID serverUrl:serverUrl selector:selector message:NSLocalizedStringFromTable(@"_file_folder_not_exists_", @"Error", nil) errorCode:kOCErrorServerPathNotFound];
  393. });
  394. return;
  395. }
  396. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  397. if (!metadata) {
  398. dispatch_async(dispatch_get_main_queue(), ^{
  399. if ([[self getDelegate:fileID] respondsToSelector:@selector(downloadFileFailure:serverUrl:selector:message:errorCode:)])
  400. [[self getDelegate:fileID] downloadFileFailure:fileID serverUrl:serverUrl selector:selector message:NSLocalizedStringFromTable(@"_file_folder_not_exists_", @"Error", nil) errorCode:kOCErrorServerPathNotFound];
  401. });
  402. return;
  403. }
  404. // it's in download
  405. tableMetadata *result = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@ AND session CONTAINS 'download' AND sessionTaskIdentifier >= 0", _activeAccount, metadata.fileID]];
  406. if (result) {
  407. dispatch_async(dispatch_get_main_queue(), ^{
  408. if ([[self getDelegate:fileID] respondsToSelector:@selector(downloadFileFailure:serverUrl:selector:message:errorCode:)])
  409. [[self getDelegate:fileID] downloadFileFailure:fileID serverUrl:serverUrl selector:selector message:@"File already in download" errorCode:k_CCErrorFileAlreadyInDownload];
  410. });
  411. return;
  412. }
  413. // File exists ?
  414. tableLocalFile *localfile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  415. if (localfile != nil && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.fileID]]) {
  416. [[NCManageDatabase sharedInstance] setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionSelectorPost:@"" sessionTaskIdentifier:k_taskIdentifierDone predicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  417. dispatch_async(dispatch_get_main_queue(), ^{
  418. if ([[self getDelegate:metadata.fileID] respondsToSelector:@selector(downloadFileSuccess:serverUrl:selector:selectorPost:)])
  419. [[self getDelegate:metadata.fileID] downloadFileSuccess:metadata.fileID serverUrl:serverUrl selector:selector selectorPost:selectorPost];
  420. });
  421. return;
  422. }
  423. [[NCManageDatabase sharedInstance] setMetadataSession:session sessionError:@"" sessionSelector:selector sessionSelectorPost:selectorPost sessionTaskIdentifier:k_taskIdentifierNULL predicate:[NSPredicate predicateWithFormat:@"fileID = %@",metadata.fileID]];
  424. [self downloaURLSession:metadata.fileName serverUrl:serverUrl fileID:metadata.fileID session:session taskStatus:taskStatus selector:selector];
  425. }
  426. - (void)downloaURLSession:(NSString *)fileName serverUrl:(NSString *)serverUrl fileID:(NSString *)fileID session:(NSString *)session taskStatus:(NSInteger)taskStatus selector:(NSString *)selector
  427. {
  428. NSURLSession *sessionDownload;
  429. NSURL *url;
  430. NSMutableURLRequest *request;
  431. NSString *serverFileUrl = [[NSString stringWithFormat:@"%@/%@", serverUrl, fileName] encodeString:NSUTF8StringEncoding];
  432. url = [NSURL URLWithString:serverFileUrl];
  433. request = [NSMutableURLRequest requestWithURL:url];
  434. NSData *authData = [[NSString stringWithFormat:@"%@:%@", _activeUser, _activePassword] dataUsingEncoding:NSUTF8StringEncoding];
  435. NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];
  436. [request setValue:authValue forHTTPHeaderField:@"Authorization"];
  437. if ([session isEqualToString:k_download_session]) sessionDownload = [self sessionDownload];
  438. else if ([session isEqualToString:k_download_session_foreground]) sessionDownload = [self sessionDownloadForeground];
  439. else if ([session isEqualToString:k_download_session_wwan]) sessionDownload = [self sessionWWanDownload];
  440. NSURLSessionDownloadTask *downloadTask = [sessionDownload downloadTaskWithRequest:request];
  441. if (downloadTask == nil) {
  442. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:[NSString stringWithFormat:@"%@", @k_CCErrorTaskNil] sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:k_taskIdentifierError predicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  443. NSLog(@"[LOG] downloadFileSession TaskIdentifier [error CCErrorTaskNil] - %@", fileName);
  444. } else {
  445. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:nil sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:downloadTask.taskIdentifier predicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  446. // Manage uploadTask cancel,suspend,resume
  447. if (taskStatus == k_taskStatusCancel) [downloadTask cancel];
  448. else if (taskStatus == k_taskStatusSuspend) [downloadTask suspend];
  449. else if (taskStatus == k_taskStatusResume) [downloadTask resume];
  450. NSLog(@"[LOG] downloadFileSession %@ Task [%lu]", fileID, (unsigned long)downloadTask.taskIdentifier);
  451. }
  452. dispatch_async(dispatch_get_main_queue(), ^{
  453. // Refresh datasource if is not a Plist
  454. if ([_delegate respondsToSelector:@selector(reloadDatasource:)])
  455. [_delegate reloadDatasource:serverUrl];
  456. #ifndef EXTENSION
  457. [app updateApplicationIconBadgeNumber];
  458. #endif
  459. });
  460. }
  461. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
  462. {
  463. NSString *url = [[[downloadTask currentRequest].URL absoluteString] stringByRemovingPercentEncoding];
  464. NSString *fileName = [url lastPathComponent];
  465. NSString *serverUrl = [self getServerUrlFromUrl:url];
  466. if (!serverUrl) return;
  467. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  468. if (!directoryID) return;
  469. float progress = (float) totalBytesWritten / (float)totalBytesExpectedToWrite;
  470. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataFromFileName:fileName directoryID:directoryID];
  471. if (metadata) {
  472. NSDictionary* userInfo = @{@"fileID": (metadata.fileID), @"serverUrl": (serverUrl), @"progress": ([NSNumber numberWithFloat:progress])};
  473. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  474. } else {
  475. NSLog(@"[LOG] metadata not found");
  476. }
  477. }
  478. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
  479. {
  480. NSURLRequest *url = [downloadTask currentRequest];
  481. NSString *fileName = [[url.URL absoluteString] lastPathComponent];
  482. NSString *serverUrl = [self getServerUrlFromUrl:[url.URL absoluteString]];
  483. if (!serverUrl) return;
  484. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"session = %@ AND sessionTaskIdentifier = %i",session.sessionDescription, downloadTask.taskIdentifier]];
  485. // If the record metadata do not exists, exit
  486. if (!metadata) {
  487. [[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];
  488. NSLog(@"[LOG] Serious error internal download : metadata not found %@ ", url);
  489. dispatch_async(dispatch_get_main_queue(), ^{
  490. if ([self.delegate respondsToSelector:@selector(downloadFileFailure:serverUrl:selector:message:errorCode:)])
  491. [self.delegate downloadFileFailure:@"" serverUrl:serverUrl selector:@"" message:@"" errorCode:k_CCErrorInternalError];
  492. });
  493. return;
  494. }
  495. NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)downloadTask.response;
  496. if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {
  497. NSString *destinationFilePath = [NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryActiveUser:_activeUser activeUrl:_activeUrl], metadata.fileID];
  498. NSURL *destinationURL = [NSURL fileURLWithPath:destinationFilePath];
  499. [[NSFileManager defaultManager] removeItemAtURL:destinationURL error:NULL];
  500. [[NSFileManager defaultManager] copyItemAtURL:location toURL:destinationURL error:nil];
  501. }
  502. }
  503. - (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
  504. {
  505. #ifndef EXTENSION
  506. [app.listProgressMetadata removeObjectForKey:fileID];
  507. #endif
  508. // Progress Task
  509. NSDictionary* userInfo = @{@"fileID": (fileID), @"serverUrl": (serverUrl), @"progress": ([NSNumber numberWithFloat:0.0])};
  510. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  511. if (errorCode != 0) {
  512. if (errorCode != kCFURLErrorCancelled) {
  513. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:[NSString stringWithFormat:@"%@", @(errorCode)] sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:k_taskIdentifierError predicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  514. }
  515. dispatch_async(dispatch_get_main_queue(), ^{
  516. if ([[self getDelegate:fileID] respondsToSelector:@selector(downloadFileFailure:serverUrl:selector:message:errorCode:)])
  517. [[self getDelegate:fileID] downloadFileFailure:fileID serverUrl:serverUrl selector:selector message:[CCError manageErrorKCF:errorCode withNumberError:YES] errorCode:errorCode];
  518. });
  519. } else {
  520. __block tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  521. if (!metadata) {
  522. [[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];
  523. NSLog(@"[LOG] Serious error internal download : metadata not found %@ ", fileName);
  524. dispatch_async(dispatch_get_main_queue(), ^{
  525. if ([self.delegate respondsToSelector:@selector(downloadFileFailure:serverUrl:selector:message:errorCode:)])
  526. [self.delegate downloadFileFailure:fileID serverUrl:serverUrl selector:selector message:[NSString stringWithFormat:@"Serious error internal download : metadata not found %@", fileName] errorCode:k_CCErrorInternalError];
  527. });
  528. return;
  529. }
  530. metadata.session = @"";
  531. metadata.sessionError = @"";
  532. metadata.sessionSelector = @"";
  533. metadata.sessionSelectorPost = @"";
  534. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  535. metadata = [[NCManageDatabase sharedInstance] updateMetadata:metadata];
  536. [[NCManageDatabase sharedInstance] addLocalFileWithMetadata:metadata];
  537. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  538. [[CCExifGeo sharedInstance] setExifLocalTableEtag:metadata directoryUser:_directoryUser activeAccount:_activeAccount];
  539. // Icon
  540. [CCGraphics createNewImageFrom:metadata.fileID directoryUser:_directoryUser fileNameTo:metadata.fileID extension:[metadata.fileName pathExtension] size:@"m" imageForUpload:NO typeFile:metadata.typeFile writePreview:YES optimizedFileName:[CCUtility getOptimizedPhoto]];
  541. // Activity
  542. [[NCManageDatabase sharedInstance] addActivityClient:fileName fileID:metadata.fileID action:k_activityDebugActionDownload selector:metadata.sessionSelector note:serverUrl type:k_activityTypeSuccess verbose:k_activityVerboseDefault activeUrl:_activeUrl];
  543. dispatch_async(dispatch_get_main_queue(), ^{
  544. if ([[self getDelegate:fileID] respondsToSelector:@selector(downloadFileSuccess:serverUrl:selector:selectorPost:)])
  545. [[self getDelegate:fileID] downloadFileSuccess:fileID serverUrl:serverUrl selector:selector selectorPost:selectorPost];
  546. });
  547. }
  548. }
  549. #pragma --------------------------------------------------------------------------------------------
  550. #pragma mark ===== Upload =====
  551. #pragma --------------------------------------------------------------------------------------------
  552. - (void)uploadFileFromAssetLocalIdentifier:(CCMetadataNet *)metadataNet delegate:(id)delegate
  553. {
  554. //delegate
  555. if (delegate == nil)
  556. delegate = self.delegate;
  557. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadataNet.assetLocalIdentifier] options:nil];
  558. if (!result.count) {
  559. // Delete record on Table Auto Upload
  560. [[NCManageDatabase sharedInstance] deleteQueueUploadWithAssetLocalIdentifier:metadataNet.assetLocalIdentifier selector:metadataNet.selector];
  561. [[NCManageDatabase sharedInstance] addActivityClient:metadataNet.fileName fileID:metadataNet.assetLocalIdentifier action:k_activityDebugActionUpload selector:metadataNet.selector note:@"Error photo/video not found, remove from upload" type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:_activeUrl];
  562. if ([delegate respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  563. [delegate uploadFileFailure:metadataNet fileID:nil serverUrl:metadataNet.serverUrl selector:metadataNet.selector message:@"Error photo/video not found, remove from upload" errorCode: k_CCErrorInternalError];
  564. return;
  565. }
  566. @synchronized (self) {
  567. PHAsset *assetResult = result[0];
  568. PHAssetMediaType assetMediaType = assetResult.mediaType;
  569. // IMAGE
  570. if (assetMediaType == PHAssetMediaTypeImage) {
  571. __block PHAsset *asset = result[0];
  572. PHImageRequestOptions *options = [PHImageRequestOptions new];
  573. options.networkAccessAllowed = YES; // iCloud
  574. [[PHImageManager defaultManager] requestImageDataForAsset:asset options:options resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) {
  575. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  576. BOOL result = YES;
  577. NSError *error = nil;
  578. if ([dataUTI isEqualToString:@"public.heic"] && tableAccount.autoUploadFormatCompatibility) {
  579. UIImage *image = [UIImage imageWithData:imageData];
  580. imageData = UIImageJPEGRepresentation(image, 1.0);
  581. NSString *fileNameJPEG = [[metadataNet.fileName lastPathComponent] stringByDeletingPathExtension];
  582. metadataNet.fileName = [fileNameJPEG stringByAppendingString:@".jpg"];
  583. if (!metadataNet.encrypted)
  584. [imageData writeToFile:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadataNet.fileName] options:NSDataWritingAtomic error:&error];
  585. } else {
  586. if (!metadataNet.encrypted)
  587. [imageData writeToFile:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadataNet.fileName] options:NSDataWritingAtomic error:&error];
  588. }
  589. if (error) {
  590. dispatch_async(dispatch_get_main_queue(), ^{
  591. if ([delegate respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  592. [delegate uploadFileFailure:metadataNet fileID:nil serverUrl:metadataNet.serverUrl selector:metadataNet.selector message:[NSString stringWithFormat:@"Image request failed [%@]", error.description] errorCode:error.code];
  593. });
  594. } else {
  595. // *** ENCRYPTED ***
  596. if (metadataNet.encrypted) {
  597. NSString *key;
  598. NSString *initializationVector;
  599. NSString *authenticationTag;
  600. result = [[NCEndToEndEncryption sharedManager] encryptFileName:metadataNet.fileName directoryUser: _directoryUser data:imageData key:&key initializationVector:&initializationVector authenticationTag:&authenticationTag];
  601. // Write to DB
  602. if (result) {
  603. tableE2eEncryption *addObject = [tableE2eEncryption new];
  604. addObject.account = metadataNet.account;
  605. addObject.authenticationTag = authenticationTag;
  606. addObject.fileName = [CCUtility returnFileNamePathFromFileName:metadataNet.fileName serverUrl:metadataNet.serverUrl activeUrl:_activeUrl];
  607. addObject.fileNameIdentifier = metadataNet.fileNameIdentifier;
  608. addObject.key = key;
  609. addObject.initializationVector = initializationVector;
  610. CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)[metadataNet.fileName pathExtension], NULL);
  611. CFStringRef mimeTypeRef = UTTypeCopyPreferredTagWithClass (UTI, kUTTagClassMIMEType);
  612. if (mimeTypeRef) {
  613. addObject.mimeType = (__bridge NSString *)mimeTypeRef;
  614. } else {
  615. addObject.mimeType = @"application/octet-stream";
  616. }
  617. addObject.version = [[NCManageDatabase sharedInstance] getEndToEndEncryptionVersion];
  618. result = [[NCManageDatabase sharedInstance] addE2eEncryption:addObject];
  619. }
  620. }
  621. dispatch_async(dispatch_get_main_queue(), ^{
  622. if (result) {
  623. // OOOOOK
  624. [self upload:metadataNet.fileName serverUrl:metadataNet.serverUrl assetLocalIdentifier:metadataNet.assetLocalIdentifier session:metadataNet.session taskStatus:metadataNet.taskStatus selector:metadataNet.selector selectorPost:metadataNet.selectorPost errorCode:metadataNet.errorCode delegate:delegate];
  625. } else {
  626. // ERROR
  627. if ([delegate respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  628. [delegate uploadFileFailure:metadataNet fileID:nil serverUrl:metadataNet.serverUrl selector:metadataNet.selector message:[NSString stringWithFormat:@"Image request encrypted failed [%@]", error.description] errorCode:error.code];
  629. }
  630. });
  631. }
  632. }];
  633. }
  634. // VIDEO
  635. if (assetMediaType == PHAssetMediaTypeVideo) {
  636. __block PHAsset *asset = result[0];
  637. PHVideoRequestOptions *options = [PHVideoRequestOptions new];
  638. options.networkAccessAllowed = YES; // iCloud
  639. [[PHImageManager defaultManager] requestPlayerItemForVideo:asset options:options resultHandler:^(AVPlayerItem * _Nullable playerItem, NSDictionary * _Nullable info) {
  640. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadataNet.fileName]])
  641. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadataNet.fileName] error:nil];
  642. AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:playerItem.asset presetName:AVAssetExportPresetHighestQuality];
  643. if (exportSession) {
  644. exportSession.outputURL = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadataNet.fileName]];
  645. exportSession.outputFileType = AVFileTypeQuickTimeMovie;
  646. [exportSession exportAsynchronouslyWithCompletionHandler:^{
  647. if (AVAssetExportSessionStatusCompleted == exportSession.status) {
  648. // *** ENCRYPTED ***
  649. // OOOOOOK
  650. dispatch_async(dispatch_get_main_queue(), ^{
  651. [self upload:metadataNet.fileName serverUrl:metadataNet.serverUrl assetLocalIdentifier:metadataNet.assetLocalIdentifier session:metadataNet.session taskStatus:metadataNet.taskStatus selector:metadataNet.selector selectorPost:metadataNet.selectorPost errorCode:metadataNet.errorCode delegate:delegate];
  652. });
  653. } else {
  654. dispatch_async(dispatch_get_main_queue(), ^{
  655. if ([delegate respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  656. [delegate uploadFileFailure:metadataNet fileID:nil serverUrl:metadataNet.serverUrl selector:metadataNet.selector message:[NSString stringWithFormat:@"Video export failed [%@]", exportSession.error.description] errorCode:exportSession.error.code];
  657. });
  658. }
  659. }];
  660. } else {
  661. dispatch_async(dispatch_get_main_queue(), ^{
  662. if ([delegate respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  663. [delegate uploadFileFailure:metadataNet fileID:nil serverUrl:metadataNet.serverUrl selector:metadataNet.selector message:@"Create Video session failed [Internal error]" errorCode:k_CCErrorInternalError];
  664. });
  665. }
  666. }];
  667. }
  668. }
  669. }
  670. - (void)uploadFile:(NSString *)fileName serverUrl:(NSString *)serverUrl session:(NSString *)session taskStatus:(NSInteger)taskStatus selector:(NSString *)selector selectorPost:(NSString *)selectorPost errorCode:(NSInteger)errorCode delegate:(id)delegate
  671. {
  672. [self upload:fileName serverUrl:serverUrl assetLocalIdentifier:nil session:session taskStatus:taskStatus selector:selector selectorPost:selectorPost errorCode:errorCode delegate:delegate];
  673. }
  674. - (void)upload:(NSString *)fileName serverUrl:(NSString *)serverUrl assetLocalIdentifier:(NSString *)assetLocalIdentifier session:(NSString *)session taskStatus:(NSInteger)taskStatus selector:(NSString *)selector selectorPost:(NSString *)selectorPost errorCode:(NSInteger)errorCode delegate:(id)delegate
  675. {
  676. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  677. if (!directoryID) return;
  678. // create Metadata
  679. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  680. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:_activeUrl];
  681. __block tableMetadata *metadata = [CCUtility insertFileSystemInMetadata:fileName directory:_directoryUser activeAccount:_activeAccount autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory];
  682. //fileID
  683. NSString *uploadID = [k_uploadSessionID stringByAppendingString:[CCUtility createRandomString:16]];
  684. //add delegate
  685. if (delegate)
  686. [_delegates setObject:delegate forKey:uploadID];
  687. metadata.date = [NSDate new];
  688. metadata.fileID = uploadID;
  689. metadata.directoryID = directoryID;
  690. metadata.fileName = fileName;
  691. metadata.assetLocalIdentifier = assetLocalIdentifier;
  692. metadata.session = session;
  693. metadata.sessionID = uploadID;
  694. metadata.sessionSelector = selector;
  695. metadata.sessionSelectorPost = selectorPost;
  696. // File exists ???
  697. if (errorCode == 403) {
  698. dispatch_async(dispatch_get_main_queue(), ^{
  699. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:fileName message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  700. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  701. // Activity
  702. [[NCManageDatabase sharedInstance] addActivityClient:fileName fileID:uploadID action:k_activityDebugActionUpload selector:selector note:NSLocalizedString(@"_file_already_exists_", nil) type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:_activeUrl];
  703. // Error for uploadFileFailure
  704. if ([[self getDelegate:uploadID] respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  705. [[self getDelegate:uploadID] uploadFileFailure:nil fileID:nil serverUrl:serverUrl selector:selector message:NSLocalizedString(@"_file_already_exists_", nil) errorCode:403];
  706. return;
  707. }];
  708. UIAlertAction *overwriteAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_overwrite_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  709. // -- remove record --
  710. tableMetadata *metadataDelete = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND fileName = %@ AND directoryID = %@", _activeAccount, fileName, directoryID]];
  711. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadataDelete.fileID] error:nil];
  712. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.ico", _directoryUser, metadataDelete.fileID] error:nil];
  713. if (metadataDelete.directory && serverUrl) {
  714. NSString *dirForDelete = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadataDelete.fileName];
  715. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:dirForDelete];
  716. }
  717. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataDelete.fileID] clearDateReadDirectoryID:nil];
  718. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataDelete.fileID]];
  719. // -- Go to Upload --
  720. [CCGraphics createNewImageFrom:metadata.fileName directoryUser:_directoryUser fileNameTo:metadata.fileID extension:[metadata.fileName pathExtension] size:@"m" imageForUpload:YES typeFile:metadata.typeFile writePreview:YES optimizedFileName:NO];
  721. metadata = [[NCManageDatabase sharedInstance] addMetadata:metadata];
  722. if (metadata) {
  723. [self uploadURLSession:fileName serverUrl:serverUrl sessionID:uploadID session:metadata.session taskStatus:taskStatus assetLocalIdentifier:assetLocalIdentifier selector:selector];
  724. }
  725. }];
  726. [alertController addAction:cancelAction];
  727. [alertController addAction:overwriteAction];
  728. UIWindow *alertWindow = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
  729. alertWindow.rootViewController = [[UIViewController alloc] init];
  730. alertWindow.windowLevel = UIWindowLevelAlert + 1;
  731. [alertWindow makeKeyAndVisible];
  732. [alertWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
  733. });
  734. } else {
  735. // -- Go to upload --
  736. #ifndef EXTENSION
  737. [CCGraphics createNewImageFrom:metadata.fileName directoryUser:_directoryUser fileNameTo:metadata.fileID extension:[metadata.fileName pathExtension] size:@"m" imageForUpload:YES typeFile:metadata.typeFile writePreview:YES optimizedFileName:NO];
  738. #endif
  739. metadata = [[NCManageDatabase sharedInstance] addMetadata:metadata];
  740. if (metadata) {
  741. [self uploadURLSession:fileName serverUrl:serverUrl sessionID:uploadID session:metadata.session taskStatus:taskStatus assetLocalIdentifier:assetLocalIdentifier selector:selector];
  742. }
  743. }
  744. }
  745. - (void)uploadFileMetadata:(tableMetadata *)metadata taskStatus:(NSInteger)taskStatus
  746. {
  747. BOOL reSend = NO;
  748. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  749. if (!serverUrl) return;
  750. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.sessionID]]) {
  751. reSend = YES;
  752. NSLog(@"[LOG] Re-upload File : %@ - fileID : %@", metadata.fileName, metadata.fileID);
  753. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:@"" sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:k_taskIdentifierNULL predicate:[NSPredicate predicateWithFormat:@"sessionID = %@ AND account = %@", metadata.sessionID, _activeAccount]];
  754. [self uploadURLSession:metadata.fileName serverUrl:serverUrl sessionID:metadata.sessionID session:metadata.session taskStatus:taskStatus assetLocalIdentifier:metadata.assetLocalIdentifier selector:metadata.sessionSelector];
  755. }
  756. if (!reSend) {
  757. NSLog(@"[LOG] Error reUploadBackground, file not found.");
  758. #ifndef EXTENSION
  759. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_no_reuploadfile_", nil) preferredStyle:UIAlertControllerStyleAlert];
  760. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  761. [alertController addAction:okAction];
  762. [[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:alertController animated:YES completion:nil];
  763. return;
  764. #endif
  765. }
  766. }
  767. - (void)uploadURLSession:(NSString *)fileName serverUrl:(NSString *)serverUrl sessionID:(NSString*)sessionID session:(NSString *)session taskStatus:(NSInteger)taskStatus assetLocalIdentifier:(NSString *)assetLocalIdentifier selector:(NSString *)selector
  768. {
  769. NSURLSession *sessionUpload;
  770. NSURL *url;
  771. NSMutableURLRequest *request;
  772. PHAsset *asset;
  773. NSString *fileNamePath = [[NSString stringWithFormat:@"%@/%@", serverUrl, fileName] encodeString:NSUTF8StringEncoding];
  774. url = [NSURL URLWithString:fileNamePath];
  775. request = [NSMutableURLRequest requestWithURL:url];
  776. NSData *authData = [[NSString stringWithFormat:@"%@:%@", _activeUser, _activePassword] dataUsingEncoding:NSUTF8StringEncoding];
  777. NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];
  778. [request setHTTPMethod:@"PUT"];
  779. [request setValue:authValue forHTTPHeaderField:@"Authorization"];
  780. // Change date file upload with header : X-OC-Mtime (ctime assetLocalIdentifier)
  781. if (assetLocalIdentifier) {
  782. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[assetLocalIdentifier] options:nil];
  783. if (result.count) {
  784. asset = result[0];
  785. long dateFileCreation = [asset.creationDate timeIntervalSince1970];
  786. [request setValue:[NSString stringWithFormat:@"%ld", dateFileCreation] forHTTPHeaderField:@"X-OC-Mtime"];
  787. }
  788. }
  789. // Rename with the SessionID
  790. NSString *fileNameForUpload = sessionID;
  791. [[NSFileManager defaultManager] moveItemAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileName] toPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileNameForUpload] error:nil];
  792. // file NOT exists
  793. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileNameForUpload]] == NO) {
  794. // Activity
  795. [[NCManageDatabase sharedInstance] addActivityClient:fileName fileID:sessionID action:k_activityDebugActionUpload selector:selector note:NSLocalizedString(@"_file_not_present_", nil) type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:_activeUrl];
  796. // Delete record : Metadata
  797. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"sessionID = %@ AND account = %@", sessionID, _activeAccount] clearDateReadDirectoryID:nil];
  798. // Delete record : Table Auto Upload
  799. [[NCManageDatabase sharedInstance] deleteQueueUploadWithAssetLocalIdentifier:assetLocalIdentifier selector:selector];
  800. dispatch_async(dispatch_get_main_queue(), ^{
  801. // Error for uploadFileFailure
  802. if ([[self getDelegate:sessionID] respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  803. [[self getDelegate:sessionID] uploadFileFailure:nil fileID:sessionID serverUrl:serverUrl selector:selector message:NSLocalizedString(@"_file_not_present_", nil) errorCode:404];
  804. });
  805. return;
  806. }
  807. if ([session isEqualToString:k_upload_session]) sessionUpload = [self sessionUpload];
  808. else if ([session isEqualToString:k_upload_session_foreground]) sessionUpload = [self sessionUploadForeground];
  809. else if ([session isEqualToString:k_upload_session_wwan]) sessionUpload = [self sessionWWanUpload];
  810. NSURLSessionUploadTask *uploadTask = [sessionUpload uploadTaskWithRequest:request fromFile:[NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileNameForUpload]]];
  811. // Error
  812. if (uploadTask == nil) {
  813. [[NCManageDatabase sharedInstance] addActivityClient:fileName fileID:assetLocalIdentifier action:k_activityDebugActionUpload selector:selector note:@"Upload task not available" type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:_activeUrl];
  814. [[NCManageDatabase sharedInstance] setMetadataSession:session sessionError:[NSString stringWithFormat:@"%@", @k_CCErrorTaskNil] sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:k_taskIdentifierError predicate:[NSPredicate predicateWithFormat:@"sessionID = %@ AND account = %@", sessionID, _activeAccount]];
  815. NSLog(@"[LOG] Upload file TaskIdentifier [error CCErrorTaskNil] - %@", fileName);
  816. } else {
  817. [[NCManageDatabase sharedInstance] setMetadataSession:session sessionError:@"" sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:uploadTask.taskIdentifier predicate:[NSPredicate predicateWithFormat:@"sessionID = %@ AND account = %@", sessionID, _activeAccount]];
  818. // OOOOOOKKKK remove record on Table Auto Upload
  819. [[NCManageDatabase sharedInstance] deleteQueueUploadWithAssetLocalIdentifier:assetLocalIdentifier selector:selector];
  820. // Manage uploadTask cancel,suspend,resume
  821. if (taskStatus == k_taskStatusCancel) [uploadTask cancel];
  822. else if (taskStatus == k_taskStatusSuspend) [uploadTask suspend];
  823. else if (taskStatus == k_taskStatusResume) [uploadTask resume];
  824. NSLog(@"[LOG] Upload file %@ TaskIdentifier %lu", fileName, (unsigned long)uploadTask.taskIdentifier);
  825. }
  826. dispatch_async(dispatch_get_main_queue(), ^{
  827. // refresh main
  828. if ([self.delegate respondsToSelector:@selector(reloadDatasource:)])
  829. [self.delegate reloadDatasource:serverUrl];
  830. #ifndef EXTENSION
  831. [app updateApplicationIconBadgeNumber];
  832. #endif
  833. });
  834. }
  835. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
  836. {
  837. NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)dataTask.response;
  838. if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {
  839. NSNumber *taskIdentifier = [NSNumber numberWithLong:dataTask.taskIdentifier];
  840. if (data)
  841. [_taskData setObject:[data copy] forKey:taskIdentifier];
  842. }
  843. }
  844. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
  845. {
  846. NSString *url = [[[task currentRequest].URL absoluteString] stringByRemovingPercentEncoding];
  847. NSString *fileName = [url lastPathComponent];
  848. NSString *serverUrl = [self getServerUrlFromUrl:url];
  849. if (!serverUrl) return;
  850. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  851. if (!directoryID) return;
  852. float progress = (float) totalBytesSent / (float)totalBytesExpectedToSend;
  853. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataFromFileName:fileName directoryID:directoryID];
  854. if (metadata) {
  855. NSDictionary* userInfo = @{@"fileID": (metadata.fileID), @"serverUrl": (serverUrl), @"progress": ([NSNumber numberWithFloat:progress])};
  856. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  857. }
  858. }
  859. - (void)uploadFileSuccessFailure:(tableMetadata *)metadata fileName:(NSString *)fileName fileID:(NSString *)fileID etag:(NSString *)etag date:(NSDate *)date serverUrl:(NSString *)serverUrl errorCode:(NSInteger)errorCode
  860. {
  861. NSString *sessionID = metadata.sessionID;
  862. // Progress Task
  863. NSDictionary* userInfo = @{@"fileID": (fileID), @"serverUrl": (serverUrl), @"progress": ([NSNumber numberWithFloat:0.0])};
  864. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  865. // ERRORE
  866. if (errorCode != 0) {
  867. #ifndef EXTENSION
  868. [app.listProgressMetadata removeObjectForKey:sessionID];
  869. #endif
  870. // Mark error only if not Cancelled Task
  871. if (errorCode != kCFURLErrorCancelled) {
  872. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:[NSString stringWithFormat:@"%@", @(errorCode)] sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:k_taskIdentifierError predicate:[NSPredicate predicateWithFormat:@"sessionID = %@ AND account = %@", metadata.sessionID, _activeAccount]];
  873. }
  874. dispatch_async(dispatch_get_main_queue(), ^{
  875. if ([[self getDelegate:sessionID] respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  876. [[self getDelegate:sessionID] uploadFileFailure:nil fileID:fileID serverUrl:serverUrl selector:metadata.sessionSelector message:[CCError manageErrorKCF:errorCode withNumberError:YES] errorCode:errorCode];
  877. });
  878. return;
  879. }
  880. // copy ico in new fileID
  881. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@.ico", _directoryUser, sessionID] toPath:[NSString stringWithFormat:@"%@/%@.ico", _directoryUser, fileID]];
  882. metadata.fileID = fileID;
  883. metadata.etag = etag;
  884. metadata.date = date;
  885. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  886. // Add new metadata
  887. if (metadata)
  888. metadata = [[NCManageDatabase sharedInstance] addMetadata:metadata];
  889. if (!metadata) {
  890. dispatch_async(dispatch_get_main_queue(), ^{
  891. if ([[self getDelegate:sessionID] respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  892. [[self getDelegate:sessionID] uploadFileFailure:nil fileID:fileID serverUrl:serverUrl selector:@"" message:[NSString stringWithFormat:@"Serious error internal upload : metadata not found %@", fileName] errorCode:k_CCErrorInternalError];
  893. });
  894. return;
  895. }
  896. // Delete old ID_UPLOAD_XXXXX metadata
  897. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", sessionID] clearDateReadDirectoryID:nil];
  898. #ifndef EXTENSION
  899. [app.listProgressMetadata removeObjectForKey:sessionID];
  900. #endif
  901. NSLog(@"[LOG] Insert new upload : %@ - fileID : %@", metadata.fileName, metadata.fileID);
  902. metadata.session = @"";
  903. metadata.sessionError = @"";
  904. metadata.sessionID = @"";
  905. metadata = [[NCManageDatabase sharedInstance] updateMetadata:metadata];
  906. // rename file sessionID -> fileID
  907. [CCUtility moveFileAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, sessionID] toPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.fileID]];
  908. // remove temp icon
  909. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.ico", _directoryUser, sessionID] error:nil];
  910. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.ico", _directoryUser, metadata.fileID] error:nil];
  911. // Local
  912. if (metadata.directory == NO)
  913. [[NCManageDatabase sharedInstance] addLocalFileWithMetadata:metadata];
  914. // EXIF
  915. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  916. [[CCExifGeo sharedInstance] setExifLocalTableEtag:metadata directoryUser:_directoryUser activeAccount:_activeAccount];
  917. // Create ICON
  918. if (metadata.directory == NO)
  919. [CCGraphics createNewImageFrom:metadata.fileID directoryUser:_directoryUser fileNameTo:metadata.fileID extension:[metadata.fileName pathExtension] size:@"m" imageForUpload:NO typeFile:metadata.typeFile writePreview:YES optimizedFileName:[CCUtility getOptimizedPhoto]];
  920. // Optimization
  921. if ([CCUtility getUploadAndRemovePhoto] || [metadata.sessionSelectorPost isEqualToString:selectorUploadRemovePhoto])
  922. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.fileID] error:nil];
  923. // Copy photo or video in the photo album for auto upload
  924. if ([metadata.assetLocalIdentifier length] > 0 && ([metadata.sessionSelector isEqualToString:selectorUploadAutoUpload] || [metadata.sessionSelector isEqualToString:selectorUploadFile])) {
  925. PHAsset *asset;
  926. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadata.assetLocalIdentifier] options:nil];
  927. if(result.count){
  928. asset = result[0];
  929. [asset saveToAlbum:[NCBrandOptions sharedInstance].brand completionBlock:^(BOOL success) {
  930. if (success) NSLog(@"[LOG] Insert file %@ in %@", metadata.fileName, [NCBrandOptions sharedInstance].brand);
  931. else NSLog(@"[LOG] File %@ do not insert in %@", metadata.fileName, [NCBrandOptions sharedInstance].brand);
  932. }];
  933. }
  934. }
  935. // Actvity
  936. [[NCManageDatabase sharedInstance] addActivityClient:fileName fileID:fileID action:k_activityDebugActionUpload selector:metadata.sessionSelector note:serverUrl type:k_activityTypeSuccess verbose:k_activityVerboseDefault activeUrl:_activeUrl];
  937. dispatch_async(dispatch_get_main_queue(), ^{
  938. if ([[self getDelegate:sessionID] respondsToSelector:@selector(uploadFileSuccess:fileID:serverUrl:selector:selectorPost:)])
  939. [[self getDelegate:sessionID] uploadFileSuccess:nil fileID:metadata.fileID serverUrl:serverUrl selector:metadata.sessionSelector selectorPost:metadata.sessionSelectorPost];
  940. });
  941. }
  942. #pragma --------------------------------------------------------------------------------------------
  943. #pragma mark ===== Download Verify =====
  944. #pragma --------------------------------------------------------------------------------------------
  945. - (void)verifyDownloadInProgress
  946. {
  947. NSArray *dataSourceDownload = [[NCManageDatabase sharedInstance] getTableMetadataDownload];
  948. NSArray *dataSourceDownloadWWan = [[NCManageDatabase sharedInstance] getTableMetadataDownloadWWan];
  949. NSMutableArray *dataSource = [NSMutableArray new];
  950. [dataSource addObjectsFromArray:dataSourceDownload];
  951. [dataSource addObjectsFromArray:dataSourceDownloadWWan];
  952. NSLog(@"[LOG] Verify download file in progress n. %lu", (unsigned long)[dataSource count]);
  953. for (tableMetadata *metadata in dataSource) {
  954. NSURLSession *session = [self getSessionfromSessionDescription:metadata.session];
  955. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  956. dispatch_async(dispatch_get_main_queue(), ^{
  957. BOOL findTask = NO;
  958. BOOL findTaskPlist = NO;
  959. for (NSURLSessionDownloadTask *downloadTask in downloadTasks) {
  960. NSLog(@"[LOG] Find metadata Tasks [%li] = [%lu] state : %lu", (long)metadata.sessionTaskIdentifier ,(unsigned long)downloadTask.taskIdentifier, (unsigned long)[downloadTask state]);
  961. if (metadata.sessionTaskIdentifier == downloadTask.taskIdentifier) findTask = YES;
  962. if (findTask == YES || findTaskPlist == YES) break; // trovati, download ancora in corso
  963. }
  964. // DATA
  965. if (findTask == NO && metadata.sessionTaskIdentifier >= 0) {
  966. NSLog(@"[LOG] NOT Find metadata Task [%li] fileID : %@ - filename : %@", (long)metadata.sessionTaskIdentifier, metadata.fileID, metadata.fileName);
  967. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:[NSString stringWithFormat:@"%@", @k_CCErrorTaskDownloadNotFound] sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:k_taskIdentifierError predicate:[NSPredicate predicateWithFormat:@"fileID = %@ ", metadata.fileID]];
  968. dispatch_async(dispatch_get_main_queue(), ^{
  969. if ([self.delegate respondsToSelector:@selector(reloadDatasource:)])
  970. [self.delegate reloadDatasource:[[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID]];
  971. });
  972. }
  973. });
  974. }];
  975. }
  976. }
  977. - (void)verifyDownloadInError:(id)delegate
  978. {
  979. NSMutableSet *serversUrl = [NSMutableSet new];
  980. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND session CONTAINS 'download' AND sessionTaskIdentifier = %i", _activeAccount, k_taskIdentifierError] sorted:nil ascending:NO];
  981. NSLog(@"[LOG] Verify re download in error n. %lu", (unsigned long)[metadatas count]);
  982. for (tableMetadata *metadata in metadatas) {
  983. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  984. if (!serverUrl) continue;
  985. if (metadata.sessionTaskIdentifier == k_taskIdentifierError)
  986. [self downloadFile:metadata.fileID serverUrl:serverUrl selector:metadata.sessionSelector selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:delegate];
  987. [serversUrl addObject:serverUrl];
  988. NSLog(@"[LOG] Re download file : %@ [%li]", metadata.fileName, (long)metadata.sessionTaskIdentifier);
  989. }
  990. dispatch_async(dispatch_get_main_queue(), ^{
  991. for (NSString *serverUrl in serversUrl)
  992. if ([self.delegate respondsToSelector:@selector(reloadDatasource:)])
  993. [self.delegate reloadDatasource:serverUrl];
  994. });
  995. }
  996. #pragma --------------------------------------------------------------------------------------------
  997. #pragma mark ===== Upload Verify =====
  998. #pragma --------------------------------------------------------------------------------------------
  999. - (void)verifyUploadInProgress
  1000. {
  1001. NSArray *dataSourceUpload = [[NCManageDatabase sharedInstance] getTableMetadataUpload];
  1002. NSArray *dataSourceUploadWWan = [[NCManageDatabase sharedInstance] getTableMetadataUploadWWan];
  1003. NSMutableArray *dataSource = [[NSMutableArray alloc] init];
  1004. [dataSource addObjectsFromArray:dataSourceUpload];
  1005. [dataSource addObjectsFromArray:dataSourceUploadWWan];
  1006. NSLog(@"[LOG] Verify upload file in progress n. %lu", (unsigned long)[dataSource count]);
  1007. for (tableMetadata *metadata in dataSource) {
  1008. __block NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1009. if (!serverUrl) continue;
  1010. NSURLSession *session = [self getSessionfromSessionDescription:metadata.session];
  1011. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1012. BOOL findTask = NO;
  1013. // cerchiamo la corrispondenza dei task
  1014. for (NSURLSessionUploadTask *uploadTask in uploadTasks) {
  1015. NSLog(@"[LOG] Find metadata Tasks [%li] = [%lu] state : %lu", (long)metadata.sessionTaskIdentifier, (unsigned long)uploadTask.taskIdentifier, (unsigned long)[uploadTask state]);
  1016. if (metadata.sessionTaskIdentifier == uploadTask.taskIdentifier) findTask = YES;
  1017. if (findTask == YES) break;
  1018. }
  1019. // se non c'è il relativo uploadTask.taskIdentifier allora chiediamolo
  1020. if (findTask == NO) {
  1021. NSLog(@"[LOG] Call ReadFileVerifyUpload because this file %@ is in progress but there is no task : [%li]", metadata.fileName, (long)metadata.sessionTaskIdentifier);
  1022. if (metadata.sessionTaskIdentifier >= 0) [self readFileVerifyUpload:metadata.fileName serverUrl:serverUrl];
  1023. }
  1024. }];
  1025. // Notification change session
  1026. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, nil];
  1027. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1028. }
  1029. }
  1030. - (void)verifyUploadInErrorOrWait
  1031. {
  1032. NSMutableSet *directoryIDs = [NSMutableSet new];
  1033. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND session CONTAINS 'upload' AND (sessionTaskIdentifier = %i OR sessionTaskIdentifier = %i)", _activeAccount, k_taskIdentifierError, k_taskIdentifierWaitStart] sorted:nil ascending:NO];
  1034. NSLog(@"[LOG] Verify re upload in error n. %lu", (unsigned long)[metadatas count]);
  1035. for (tableMetadata *metadata in metadatas) {
  1036. [self uploadFileMetadata:metadata taskStatus: k_taskStatusResume];
  1037. [directoryIDs addObject:metadata.directoryID];
  1038. NSLog(@"[LOG] Re upload file : %@", metadata.fileName);
  1039. }
  1040. dispatch_async(dispatch_get_main_queue(), ^{
  1041. for (NSString *directoryID in directoryIDs)
  1042. if ([self.delegate respondsToSelector:@selector(reloadDatasource:)])
  1043. [self.delegate reloadDatasource:[[NCManageDatabase sharedInstance] getServerUrl:directoryID]];
  1044. });
  1045. }
  1046. - (void)readFileVerifyUpload:(NSString *)fileName serverUrl:(NSString *)serverUrl
  1047. {
  1048. #ifndef EXTENSION
  1049. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:_activeAccount];
  1050. metadataNet.action = actionReadFile;
  1051. metadataNet.fileName = fileName;
  1052. metadataNet.serverUrl = serverUrl;
  1053. metadataNet.selector = selectorReadFileVerifyUpload;
  1054. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1055. #else
  1056. NSLog(@"[LOG] Function not available for extension.");
  1057. #endif
  1058. }
  1059. //
  1060. // File exists : selectorReadFileVerifyUpload
  1061. //
  1062. - (void)readFileSuccess:(CCMetadataNet *)metadataNet metadata:(tableMetadata *)metadata
  1063. {
  1064. NSString *fileName = metadataNet.fileName;
  1065. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:metadataNet.serverUrl];
  1066. if (!directoryID)
  1067. [self uploadFileSuccessFailure:metadata fileName:metadataNet.fileName fileID:metadata.fileID etag:metadata.etag date:metadata.date serverUrl:metadataNet.serverUrl errorCode:k_CCErrorFileUploadNotFound];
  1068. tableMetadata *metadataTemp = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileName = %@ AND directoryID = %@ AND account = %@", fileName , directoryID, _activeAccount]];
  1069. // is completed ?
  1070. if (metadataTemp.sessionTaskIdentifier == k_taskIdentifierDone) {
  1071. [CCGraphics createNewImageFrom:metadata.fileID directoryUser:_directoryUser fileNameTo:metadata.fileID extension:[metadata.fileName pathExtension] size:@"m" imageForUpload:NO typeFile:metadata.typeFile writePreview:YES optimizedFileName:[CCUtility getOptimizedPhoto]];
  1072. NSLog(@"[LOG] Verify read file success, but files already processed");
  1073. dispatch_async(dispatch_get_main_queue(), ^{
  1074. if ([self.delegate respondsToSelector:@selector(reloadDatasource:)])
  1075. [self.delegate reloadDatasource:[[NCManageDatabase sharedInstance] getServerUrl:directoryID]];
  1076. });
  1077. } else {
  1078. [self uploadFileSuccessFailure:metadataTemp fileName:metadataNet.fileName fileID:metadata.fileID etag:metadata.etag date:metadata.date serverUrl:metadataNet.serverUrl errorCode:0];
  1079. }
  1080. }
  1081. //
  1082. // File do not exists : selectorReadFileVerifyUpload
  1083. //
  1084. - (void)readFileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1085. {
  1086. NSString *fileName = metadataNet.fileName;
  1087. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:metadataNet.serverUrl];
  1088. if (!directoryID) return;
  1089. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileName = %@ AND directoryID = %@ AND account = %@",fileName , directoryID, _activeAccount]];
  1090. NSInteger error;
  1091. if (errorCode == kOCErrorServerPathNotFound)
  1092. error = k_CCErrorFileUploadNotFound;
  1093. else
  1094. error = errorCode;
  1095. // fix CCNetworking.m line 1340 2.17.2 (00005)
  1096. if (metadata)
  1097. [self uploadFileSuccessFailure:metadata fileName:metadataNet.fileName fileID:metadata.fileID etag:metadata.etag date:metadata.date serverUrl:metadataNet.serverUrl errorCode:error];
  1098. }
  1099. #pragma --------------------------------------------------------------------------------------------
  1100. #pragma mark ===== Utility =====
  1101. #pragma --------------------------------------------------------------------------------------------
  1102. - (id)getDelegate:(NSString *)fileID
  1103. {
  1104. id delegate = [_delegates objectForKey:fileID];
  1105. if (delegate)
  1106. return delegate;
  1107. else
  1108. return self.delegate;
  1109. }
  1110. - (NSString *)getServerUrlFromUrl:(NSString *)url
  1111. {
  1112. NSString *fileName = [url lastPathComponent];
  1113. url = [url stringByReplacingOccurrencesOfString:[@"/" stringByAppendingString:fileName] withString:@""];
  1114. return url;
  1115. }
  1116. - (NSString *)getTitleFromPlistName:(NSString *)fileName
  1117. {
  1118. if ([[fileName lastPathComponent] isEqualToString:@"plist"] == NO)
  1119. fileName = [fileName stringByAppendingString:@".plist"];
  1120. if (![[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileName]]) return nil;
  1121. NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileName]];
  1122. return [data objectForKey:@"title"];
  1123. }
  1124. @end
  1125. #pragma --------------------------------------------------------------------------------------------
  1126. #pragma mark ===== CCMetadataNet =====
  1127. #pragma --------------------------------------------------------------------------------------------
  1128. @implementation CCMetadataNet
  1129. - (id)init
  1130. {
  1131. self = [super init];
  1132. self.priority = NSOperationQueuePriorityNormal;
  1133. return self;
  1134. }
  1135. - (id)initWithAccount:(NSString *)withAccount
  1136. {
  1137. self = [super init];
  1138. if (self) {
  1139. _account = withAccount;
  1140. _priority = NSOperationQueuePriorityNormal;
  1141. }
  1142. return self;
  1143. }
  1144. - (id)copyWithZone: (NSZone *) zone
  1145. {
  1146. CCMetadataNet *metadataNet = [[CCMetadataNet allocWithZone: zone] init];
  1147. [metadataNet setAccount: self.account];
  1148. [metadataNet setAction: self.action];
  1149. [metadataNet setAssetLocalIdentifier: self.assetLocalIdentifier];
  1150. [metadataNet setContentType: self.contentType];
  1151. [metadataNet setDate: self.date];
  1152. [metadataNet setDelegate: self.delegate];
  1153. [metadataNet setDepth: self.depth];
  1154. [metadataNet setDirectory: self.directory];
  1155. [metadataNet setDirectoryID: self.directoryID];
  1156. [metadataNet setDirectoryIDTo: self.directoryIDTo];
  1157. [metadataNet setEncrypted: self.encrypted];
  1158. [metadataNet setEncryptedMetadata: self.encryptedMetadata];
  1159. [metadataNet setErrorCode: self.errorCode];
  1160. [metadataNet setErrorRetry: self.errorRetry];
  1161. [metadataNet setEtag:self.etag];
  1162. [metadataNet setExpirationTime: self.expirationTime];
  1163. [metadataNet setFileID: self.fileID];
  1164. [metadataNet setFileName: self.fileName];
  1165. [metadataNet setFileNameIdentifier: self.fileNameIdentifier];
  1166. [metadataNet setFileNameTo: self.fileNameTo];
  1167. [metadataNet setKey: self.key];
  1168. [metadataNet setKeyCipher: self.keyCipher];
  1169. [metadataNet setOptions: self.options];
  1170. [metadataNet setPassword: self.password];
  1171. [metadataNet setPathFolder: self.pathFolder];
  1172. [metadataNet setPriority: self.priority];
  1173. [metadataNet setServerUrl: self.serverUrl];
  1174. [metadataNet setServerUrlTo: self.serverUrlTo];
  1175. [metadataNet setSelector: self.selector];
  1176. [metadataNet setSelectorPost: self.selectorPost];
  1177. [metadataNet setSession: self.session];
  1178. [metadataNet setSessionID: self.sessionID];
  1179. [metadataNet setShare: self.share];
  1180. [metadataNet setShareeType: self.shareeType];
  1181. [metadataNet setSharePermission: self.sharePermission];
  1182. [metadataNet setSize: self.size];
  1183. [metadataNet setTaskStatus: self.taskStatus];
  1184. [metadataNet setToken: self.token];
  1185. return metadataNet;
  1186. }
  1187. @end