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