CCNetworking.m 82 KB

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