CCNetworking.m 76 KB

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