CCNetworking.m 76 KB

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