CCNetworking.m 81 KB

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