CCNetworking.m 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539
  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. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_no_reuploadfile_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  712. [alertView show];
  713. #endif
  714. }
  715. }
  716. - (void)uploadURLSession:(NSString *)fileName serverUrl:(NSString *)serverUrl sessionID:(NSString*)sessionID session:(NSString *)session taskStatus:(NSInteger)taskStatus assetLocalIdentifier:(NSString *)assetLocalIdentifier selector:(NSString *)selector
  717. {
  718. NSURLSession *sessionUpload;
  719. NSURL *url;
  720. NSMutableURLRequest *request;
  721. NSString *fileNamePath = [[NSString stringWithFormat:@"%@/%@", serverUrl, fileName] encodeString:NSUTF8StringEncoding];
  722. url = [NSURL URLWithString:fileNamePath];
  723. request = [NSMutableURLRequest requestWithURL:url];
  724. NSData *authData = [[NSString stringWithFormat:@"%@:%@", _activeUser, _activePassword] dataUsingEncoding:NSUTF8StringEncoding];
  725. NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];
  726. [request setHTTPMethod:@"PUT"];
  727. [request setValue:authValue forHTTPHeaderField:@"Authorization"];
  728. // Rename with the SessionID
  729. NSString *fileNameForUpload = sessionID;
  730. [[NSFileManager defaultManager] moveItemAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileName] toPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileNameForUpload] error:nil];
  731. // file NOT exists
  732. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileNameForUpload]] == NO) {
  733. // Activity
  734. [[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];
  735. // Delete record : Metadata
  736. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"sessionID = %@ AND account = %@", sessionID, _activeAccount] clearDateReadDirectoryID:nil];
  737. // Delete record : Table Auto Upload
  738. [[NCManageDatabase sharedInstance] deleteQueueUploadWithAssetLocalIdentifier:assetLocalIdentifier selector:selector];
  739. dispatch_async(dispatch_get_main_queue(), ^{
  740. // Error for uploadFileFailure
  741. if ([[self getDelegate:sessionID] respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  742. [[self getDelegate:sessionID] uploadFileFailure:nil fileID:sessionID serverUrl:serverUrl selector:selector message:NSLocalizedString(@"_file_not_present_", nil) errorCode:404];
  743. });
  744. return;
  745. }
  746. if ([session isEqualToString:k_upload_session]) sessionUpload = [self sessionUpload];
  747. else if ([session isEqualToString:k_upload_session_foreground]) sessionUpload = [self sessionUploadForeground];
  748. else if ([session isEqualToString:k_upload_session_wwan]) sessionUpload = [self sessionWWanUpload];
  749. NSURLSessionUploadTask *uploadTask = [sessionUpload uploadTaskWithRequest:request fromFile:[NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileNameForUpload]]];
  750. // Error
  751. if (uploadTask == nil) {
  752. [[NCManageDatabase sharedInstance] addActivityClient:fileName fileID:assetLocalIdentifier action:k_activityDebugActionUpload selector:selector note:@"Upload task not available" type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:_activeUrl];
  753. [[NCManageDatabase sharedInstance] setMetadataSession:session sessionError:[NSString stringWithFormat:@"%@", @k_CCErrorTaskNil] sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:k_taskIdentifierError predicate:[NSPredicate predicateWithFormat:@"sessionID = %@ AND account = %@", sessionID, _activeAccount]];
  754. NSLog(@"[LOG] Upload file TaskIdentifier [error CCErrorTaskNil] - %@", fileName);
  755. } else {
  756. [[NCManageDatabase sharedInstance] setMetadataSession:session sessionError:@"" sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:uploadTask.taskIdentifier predicate:[NSPredicate predicateWithFormat:@"sessionID = %@ AND account = %@", sessionID, _activeAccount]];
  757. // OOOOOOKKKK remove record on Table Auto Upload
  758. [[NCManageDatabase sharedInstance] deleteQueueUploadWithAssetLocalIdentifier:assetLocalIdentifier selector:selector];
  759. // Manage uploadTask cancel,suspend,resume
  760. if (taskStatus == k_taskStatusCancel) [uploadTask cancel];
  761. else if (taskStatus == k_taskStatusSuspend) [uploadTask suspend];
  762. else if (taskStatus == k_taskStatusResume) [uploadTask resume];
  763. NSLog(@"[LOG] Upload file %@ TaskIdentifier %lu", fileName, (unsigned long)uploadTask.taskIdentifier);
  764. }
  765. dispatch_async(dispatch_get_main_queue(), ^{
  766. // refresh main
  767. if ([self.delegate respondsToSelector:@selector(reloadDatasource:)])
  768. [self.delegate reloadDatasource:serverUrl];
  769. #ifndef EXTENSION
  770. [app updateApplicationIconBadgeNumber];
  771. #endif
  772. });
  773. }
  774. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
  775. {
  776. NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)dataTask.response;
  777. if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {
  778. NSNumber *taskIdentifier = [NSNumber numberWithLong:dataTask.taskIdentifier];
  779. if (data)
  780. [_taskData setObject:[data copy] forKey:taskIdentifier];
  781. }
  782. }
  783. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
  784. {
  785. NSString *url = [[[task currentRequest].URL absoluteString] stringByRemovingPercentEncoding];
  786. NSString *fileName = [url lastPathComponent];
  787. NSString *serverUrl = [self getServerUrlFromUrl:url];
  788. if (!serverUrl) return;
  789. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  790. if (!directoryID) return;
  791. float progress = (float) totalBytesSent / (float)totalBytesExpectedToSend;
  792. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataFromFileName:fileName directoryID:directoryID];
  793. if (metadata) {
  794. NSDictionary* userInfo = @{@"fileID": (metadata.fileID), @"serverUrl": (serverUrl), @"progress": ([NSNumber numberWithFloat:progress])};
  795. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  796. }
  797. }
  798. - (void)uploadFileSuccessFailure:(tableMetadata *)metadata fileName:(NSString *)fileName fileID:(NSString *)fileID etag:(NSString *)etag date:(NSDate *)date serverUrl:(NSString *)serverUrl errorCode:(NSInteger)errorCode
  799. {
  800. NSString *sessionID = metadata.sessionID;
  801. // Progress Task
  802. NSDictionary* userInfo = @{@"fileID": (fileID), @"serverUrl": (serverUrl), @"progress": ([NSNumber numberWithFloat:0.0])};
  803. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  804. // ERRORE
  805. if (errorCode != 0) {
  806. #ifndef EXTENSION
  807. [app.listProgressMetadata removeObjectForKey:sessionID];
  808. #endif
  809. // Mark error only if not Cancelled Task
  810. if (errorCode != kCFURLErrorCancelled) {
  811. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:[NSString stringWithFormat:@"%@", @(errorCode)] sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:k_taskIdentifierError predicate:[NSPredicate predicateWithFormat:@"sessionID = %@ AND account = %@", metadata.sessionID, _activeAccount]];
  812. }
  813. dispatch_async(dispatch_get_main_queue(), ^{
  814. if ([[self getDelegate:sessionID] respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  815. [[self getDelegate:sessionID] uploadFileFailure:nil fileID:fileID serverUrl:serverUrl selector:metadata.sessionSelector message:[CCError manageErrorKCF:errorCode withNumberError:YES] errorCode:errorCode];
  816. });
  817. return;
  818. }
  819. // copy ico in new fileID
  820. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@.ico", _directoryUser, sessionID] toPath:[NSString stringWithFormat:@"%@/%@.ico", _directoryUser, fileID]];
  821. metadata.fileID = fileID;
  822. metadata.etag = etag;
  823. metadata.date = date;
  824. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  825. // Add new metadata
  826. if (metadata)
  827. metadata = [[NCManageDatabase sharedInstance] addMetadata:metadata];
  828. if (!metadata) {
  829. dispatch_async(dispatch_get_main_queue(), ^{
  830. if ([[self getDelegate:sessionID] respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  831. [[self getDelegate:sessionID] uploadFileFailure:nil fileID:fileID serverUrl:serverUrl selector:@"" message:[NSString stringWithFormat:@"Serius error internal upload : metadata not found %@", fileName] errorCode:k_CCErrorInternalError];
  832. });
  833. return;
  834. }
  835. // Delete old ID_UPLOAD_XXXXX metadata
  836. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", sessionID] clearDateReadDirectoryID:nil];
  837. #ifndef EXTENSION
  838. [app.listProgressMetadata removeObjectForKey:sessionID];
  839. #endif
  840. NSLog(@"[LOG] Insert new upload : %@ - fileID : %@", metadata.fileName, metadata.fileID);
  841. metadata.session = @"";
  842. metadata.sessionError = @"";
  843. metadata.sessionID = @"";
  844. metadata = [[NCManageDatabase sharedInstance] updateMetadata:metadata];
  845. // rename file sessionID -> fileID
  846. [CCUtility moveFileAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, sessionID] toPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.fileID]];
  847. // remove temp icon
  848. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.ico", _directoryUser, sessionID] error:nil];
  849. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.ico", _directoryUser, metadata.fileID] error:nil];
  850. // Local
  851. if (metadata.directory == NO)
  852. [[NCManageDatabase sharedInstance] addLocalFileWithMetadata:metadata];
  853. // EXIF
  854. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  855. [[CCExifGeo sharedInstance] setExifLocalTableEtag:metadata directoryUser:_directoryUser activeAccount:_activeAccount];
  856. // Create ICON
  857. if (metadata.directory == NO)
  858. [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]];
  859. // Optimization
  860. if ([CCUtility getUploadAndRemovePhoto] || [metadata.sessionSelectorPost isEqualToString:selectorUploadRemovePhoto])
  861. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.fileID] error:nil];
  862. // Copy photo or video in the photo album for auto upload
  863. if ([metadata.assetLocalIdentifier length] > 0 && ([metadata.sessionSelector isEqualToString:selectorUploadAutoUpload] || [metadata.sessionSelector isEqualToString:selectorUploadFile])) {
  864. PHAsset *asset;
  865. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadata.assetLocalIdentifier] options:nil];
  866. if(result.count){
  867. asset = result[0];
  868. [asset saveToAlbum:[NCBrandOptions sharedInstance].brand completionBlock:^(BOOL success) {
  869. if (success) NSLog(@"[LOG] Insert file %@ in %@", metadata.fileName, [NCBrandOptions sharedInstance].brand);
  870. else NSLog(@"[LOG] File %@ do not insert in %@", metadata.fileName, [NCBrandOptions sharedInstance].brand);
  871. }];
  872. }
  873. }
  874. // Actvity
  875. [[NCManageDatabase sharedInstance] addActivityClient:fileName fileID:fileID action:k_activityDebugActionUpload selector:metadata.sessionSelector note:serverUrl type:k_activityTypeSuccess verbose:k_activityVerboseDefault activeUrl:_activeUrl];
  876. dispatch_async(dispatch_get_main_queue(), ^{
  877. if ([[self getDelegate:sessionID] respondsToSelector:@selector(uploadFileSuccess:fileID:serverUrl:selector:selectorPost:)])
  878. [[self getDelegate:sessionID] uploadFileSuccess:nil fileID:metadata.fileID serverUrl:serverUrl selector:metadata.sessionSelector selectorPost:metadata.sessionSelectorPost];
  879. });
  880. }
  881. #pragma --------------------------------------------------------------------------------------------
  882. #pragma mark ===== Download Verify =====
  883. #pragma --------------------------------------------------------------------------------------------
  884. - (void)verifyDownloadInProgress
  885. {
  886. NSArray *dataSourceDownload = [[NCManageDatabase sharedInstance] getTableMetadataDownload];
  887. NSArray *dataSourceDownloadWWan = [[NCManageDatabase sharedInstance] getTableMetadataDownloadWWan];
  888. NSMutableArray *dataSource = [NSMutableArray new];
  889. [dataSource addObjectsFromArray:dataSourceDownload];
  890. [dataSource addObjectsFromArray:dataSourceDownloadWWan];
  891. NSLog(@"[LOG] Verify download file in progress n. %lu", (unsigned long)[dataSource count]);
  892. for (tableMetadata *metadata in dataSource) {
  893. NSURLSession *session = [self getSessionfromSessionDescription:metadata.session];
  894. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  895. dispatch_async(dispatch_get_main_queue(), ^{
  896. BOOL findTask = NO;
  897. BOOL findTaskPlist = NO;
  898. for (NSURLSessionDownloadTask *downloadTask in downloadTasks) {
  899. NSLog(@"[LOG] Find metadata Tasks [%li] = [%lu] state : %lu", (long)metadata.sessionTaskIdentifier ,(unsigned long)downloadTask.taskIdentifier, (unsigned long)[downloadTask state]);
  900. if (metadata.sessionTaskIdentifier == downloadTask.taskIdentifier) findTask = YES;
  901. if (findTask == YES || findTaskPlist == YES) break; // trovati, download ancora in corso
  902. }
  903. // DATA
  904. if (findTask == NO && metadata.sessionTaskIdentifier >= 0) {
  905. NSLog(@"[LOG] NOT Find metadata Task [%li] fileID : %@ - filename : %@", (long)metadata.sessionTaskIdentifier, metadata.fileID, metadata.fileName);
  906. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:[NSString stringWithFormat:@"%@", @k_CCErrorTaskDownloadNotFound] sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:k_taskIdentifierError predicate:[NSPredicate predicateWithFormat:@"fileID = %@ ", metadata.fileID]];
  907. dispatch_async(dispatch_get_main_queue(), ^{
  908. if ([self.delegate respondsToSelector:@selector(reloadDatasource:)])
  909. [self.delegate reloadDatasource:[[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID]];
  910. });
  911. }
  912. });
  913. }];
  914. }
  915. }
  916. - (void)verifyDownloadInError:(id)delegate
  917. {
  918. NSMutableSet *serversUrl = [NSMutableSet new];
  919. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND session CONTAINS 'download' AND sessionTaskIdentifier = %i", _activeAccount, k_taskIdentifierError] sorted:nil ascending:NO];
  920. NSLog(@"[LOG] Verify re download in error n. %lu", (unsigned long)[metadatas count]);
  921. for (tableMetadata *metadata in metadatas) {
  922. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  923. if (!serverUrl) continue;
  924. if (metadata.sessionTaskIdentifier == k_taskIdentifierError)
  925. [self downloadFile:metadata.fileID serverUrl:serverUrl selector:metadata.sessionSelector selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:delegate];
  926. [serversUrl addObject:serverUrl];
  927. NSLog(@"[LOG] Re download file : %@ [%li]", metadata.fileName, (long)metadata.sessionTaskIdentifier);
  928. }
  929. dispatch_async(dispatch_get_main_queue(), ^{
  930. for (NSString *serverUrl in serversUrl)
  931. if ([self.delegate respondsToSelector:@selector(reloadDatasource:)])
  932. [self.delegate reloadDatasource:serverUrl];
  933. });
  934. }
  935. #pragma --------------------------------------------------------------------------------------------
  936. #pragma mark ===== Upload Verify =====
  937. #pragma --------------------------------------------------------------------------------------------
  938. - (void)verifyUploadInProgress
  939. {
  940. NSArray *dataSourceUpload = [[NCManageDatabase sharedInstance] getTableMetadataUpload];
  941. NSArray *dataSourceUploadWWan = [[NCManageDatabase sharedInstance] getTableMetadataUploadWWan];
  942. NSMutableArray *dataSource = [[NSMutableArray alloc] init];
  943. [dataSource addObjectsFromArray:dataSourceUpload];
  944. [dataSource addObjectsFromArray:dataSourceUploadWWan];
  945. NSLog(@"[LOG] Verify upload file in progress n. %lu", (unsigned long)[dataSource count]);
  946. for (tableMetadata *metadata in dataSource) {
  947. __block NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  948. if (!serverUrl) continue;
  949. NSURLSession *session = [self getSessionfromSessionDescription:metadata.session];
  950. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  951. BOOL findTask = NO;
  952. // cerchiamo la corrispondenza dei task
  953. for (NSURLSessionUploadTask *uploadTask in uploadTasks) {
  954. NSLog(@"[LOG] Find metadata Tasks [%li] = [%lu] state : %lu", (long)metadata.sessionTaskIdentifier, (unsigned long)uploadTask.taskIdentifier, (unsigned long)[uploadTask state]);
  955. if (metadata.sessionTaskIdentifier == uploadTask.taskIdentifier) findTask = YES;
  956. if (findTask == YES) break;
  957. }
  958. // se non c'è il relativo uploadTask.taskIdentifier allora chiediamolo
  959. if (findTask == NO) {
  960. NSLog(@"[LOG] Call ReadFileVerifyUpload because this file %@ is in progress but there is no task : [%li]", metadata.fileName, (long)metadata.sessionTaskIdentifier);
  961. if (metadata.sessionTaskIdentifier >= 0) [self readFileVerifyUpload:metadata.fileName serverUrl:serverUrl];
  962. }
  963. }];
  964. // Notification change session
  965. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, nil];
  966. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  967. }
  968. }
  969. - (void)verifyUploadInErrorOrWait
  970. {
  971. NSMutableSet *directoryIDs = [NSMutableSet new];
  972. 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];
  973. NSLog(@"[LOG] Verify re upload in error n. %lu", (unsigned long)[metadatas count]);
  974. for (tableMetadata *metadata in metadatas) {
  975. [self uploadFileMetadata:metadata taskStatus: k_taskStatusResume];
  976. [directoryIDs addObject:metadata.directoryID];
  977. NSLog(@"[LOG] Re upload file : %@", metadata.fileName);
  978. }
  979. dispatch_async(dispatch_get_main_queue(), ^{
  980. for (NSString *directoryID in directoryIDs)
  981. if ([self.delegate respondsToSelector:@selector(reloadDatasource:)])
  982. [self.delegate reloadDatasource:[[NCManageDatabase sharedInstance] getServerUrl:directoryID]];
  983. });
  984. }
  985. - (void)readFileVerifyUpload:(NSString *)fileName serverUrl:(NSString *)serverUrl
  986. {
  987. #ifndef EXTENSION
  988. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:_activeAccount];
  989. metadataNet.action = actionReadFile;
  990. metadataNet.fileName = fileName;
  991. metadataNet.serverUrl = serverUrl;
  992. metadataNet.selector = selectorReadFileVerifyUpload;
  993. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  994. #else
  995. NSLog(@"[LOG] Function not available for extension.");
  996. #endif
  997. }
  998. //
  999. // File exists : selectorReadFileVerifyUpload
  1000. //
  1001. - (void)readFileSuccess:(CCMetadataNet *)metadataNet metadata:(tableMetadata *)metadata
  1002. {
  1003. NSString *fileName = metadataNet.fileName;
  1004. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:metadataNet.serverUrl];
  1005. if (!directoryID)
  1006. [self uploadFileSuccessFailure:metadata fileName:metadataNet.fileName fileID:metadata.fileID etag:metadata.etag date:metadata.date serverUrl:metadataNet.serverUrl errorCode:k_CCErrorFileUploadNotFound];
  1007. tableMetadata *metadataTemp = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileName = %@ AND directoryID = %@ AND account = %@", fileName , directoryID, _activeAccount]];
  1008. // is completed ?
  1009. if (metadataTemp.sessionTaskIdentifier == k_taskIdentifierDone) {
  1010. [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]];
  1011. NSLog(@"[LOG] Verify read file success, but files already processed");
  1012. dispatch_async(dispatch_get_main_queue(), ^{
  1013. if ([self.delegate respondsToSelector:@selector(reloadDatasource:)])
  1014. [self.delegate reloadDatasource:[[NCManageDatabase sharedInstance] getServerUrl:directoryID]];
  1015. });
  1016. } else {
  1017. [self uploadFileSuccessFailure:metadataTemp fileName:metadataNet.fileName fileID:metadata.fileID etag:metadata.etag date:metadata.date serverUrl:metadataNet.serverUrl errorCode:0];
  1018. }
  1019. }
  1020. //
  1021. // File do not exists : selectorReadFileVerifyUpload
  1022. //
  1023. - (void)readFileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1024. {
  1025. NSString *fileName = metadataNet.fileName;
  1026. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:metadataNet.serverUrl];
  1027. if (!directoryID) return;
  1028. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileName = %@ AND directoryID = %@ AND account = %@",fileName , directoryID, _activeAccount]];
  1029. NSInteger error;
  1030. if (errorCode == kOCErrorServerPathNotFound)
  1031. error = k_CCErrorFileUploadNotFound;
  1032. else
  1033. error = errorCode;
  1034. // fix CCNetworking.m line 1340 2.17.2 (00005)
  1035. if (metadata)
  1036. [self uploadFileSuccessFailure:metadata fileName:metadataNet.fileName fileID:metadata.fileID etag:metadata.etag date:metadata.date serverUrl:metadataNet.serverUrl errorCode:error];
  1037. }
  1038. #pragma --------------------------------------------------------------------------------------------
  1039. #pragma mark ===== Utility =====
  1040. #pragma --------------------------------------------------------------------------------------------
  1041. - (id)getDelegate:(NSString *)fileID
  1042. {
  1043. id delegate = [_delegates objectForKey:fileID];
  1044. if (delegate)
  1045. return delegate;
  1046. else
  1047. return self.delegate;
  1048. }
  1049. - (NSString *)getServerUrlFromUrl:(NSString *)url
  1050. {
  1051. NSString *fileName = [url lastPathComponent];
  1052. url = [url stringByReplacingOccurrencesOfString:[@"/" stringByAppendingString:fileName] withString:@""];
  1053. return url;
  1054. }
  1055. - (NSString *)getTitleFromPlistName:(NSString *)fileName
  1056. {
  1057. if ([[fileName lastPathComponent] isEqualToString:@"plist"] == NO)
  1058. fileName = [fileName stringByAppendingString:@".plist"];
  1059. if (![[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileName]]) return nil;
  1060. NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileName]];
  1061. return [data objectForKey:@"title"];
  1062. }
  1063. @end
  1064. #pragma --------------------------------------------------------------------------------------------
  1065. #pragma mark ===== CCMetadataNet =====
  1066. #pragma --------------------------------------------------------------------------------------------
  1067. @implementation CCMetadataNet
  1068. - (id)init
  1069. {
  1070. self = [super init];
  1071. self.priority = NSOperationQueuePriorityNormal;
  1072. return self;
  1073. }
  1074. - (id)initWithAccount:(NSString *)withAccount
  1075. {
  1076. self = [super init];
  1077. if (self) {
  1078. _account = withAccount;
  1079. _priority = NSOperationQueuePriorityNormal;
  1080. }
  1081. return self;
  1082. }
  1083. - (id)copyWithZone: (NSZone *) zone
  1084. {
  1085. CCMetadataNet *metadataNet = [[CCMetadataNet allocWithZone: zone] init];
  1086. [metadataNet setAccount: self.account];
  1087. [metadataNet setAction: self.action];
  1088. [metadataNet setAssetLocalIdentifier: self.assetLocalIdentifier];
  1089. [metadataNet setDate: self.date];
  1090. [metadataNet setDelegate: self.delegate];
  1091. [metadataNet setDepth: self.depth];
  1092. [metadataNet setDirectory: self.directory];
  1093. [metadataNet setDirectoryID: self.directoryID];
  1094. [metadataNet setDirectoryIDTo: self.directoryIDTo];
  1095. [metadataNet setErrorCode: self.errorCode];
  1096. [metadataNet setErrorRetry: self.errorRetry];
  1097. [metadataNet setEtag:self.etag];
  1098. [metadataNet setExpirationTime: self.expirationTime];
  1099. [metadataNet setFileID: self.fileID];
  1100. [metadataNet setFileName: self.fileName];
  1101. [metadataNet setFileNameTo: self.fileNameTo];
  1102. [metadataNet setOptions: self.options];
  1103. [metadataNet setPassword: self.password];
  1104. [metadataNet setPathFolder: self.pathFolder];
  1105. [metadataNet setPriority: self.priority];
  1106. [metadataNet setServerUrl: self.serverUrl];
  1107. [metadataNet setServerUrlTo: self.serverUrlTo];
  1108. [metadataNet setSelector: self.selector];
  1109. [metadataNet setSelectorPost: self.selectorPost];
  1110. [metadataNet setSession: self.session];
  1111. [metadataNet setSessionID: self.sessionID];
  1112. [metadataNet setShare: self.share];
  1113. [metadataNet setShareeType: self.shareeType];
  1114. [metadataNet setSharePermission: self.sharePermission];
  1115. [metadataNet setSize: self.size];
  1116. [metadataNet setTaskStatus: self.taskStatus];
  1117. return metadataNet;
  1118. }
  1119. @end