CCNetworking.m 78 KB

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