CCNetworking.m 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667
  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. // Forced session on Foreground
  681. metadata.session = k_upload_session_foreground;
  682. if ([metadata.session isEqualToString:k_upload_session_wwan])
  683. metadata.session = k_upload_session_wwanforeground;
  684. dispatch_async(dispatch_get_main_queue(), ^{
  685. [CCGraphics createNewImageFrom:metadata.fileNameView directoryUser:_directoryUser fileNameTo:metadata.fileID extension:[metadata.fileNameView pathExtension] size:@"m" imageForUpload:YES typeFile:metadata.typeFile writePreview:YES optimizedFileName:NO];
  686. [self uploadURLSessionMetadata:[[NCManageDatabase sharedInstance] addMetadata:metadata] serverUrl:serverUrl sessionID:uploadID taskStatus:taskStatus assetLocalIdentifier:assetLocalIdentifier selector:selector];
  687. });
  688. });
  689. } else {
  690. [CCGraphics createNewImageFrom:metadata.fileNameView directoryUser:_directoryUser fileNameTo:metadata.fileID extension:[metadata.fileNameView pathExtension] size:@"m" imageForUpload:YES typeFile:metadata.typeFile writePreview:YES optimizedFileName:NO];
  691. [self uploadURLSessionMetadata:[[NCManageDatabase sharedInstance] addMetadata:metadata] serverUrl:serverUrl sessionID:uploadID taskStatus:taskStatus assetLocalIdentifier:assetLocalIdentifier selector:selector];
  692. }
  693. }
  694. - (void)uploadFileMetadata:(tableMetadata *)metadata taskStatus:(NSInteger)taskStatus
  695. {
  696. BOOL reSend = NO;
  697. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  698. if (!serverUrl) return;
  699. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.sessionID]]) {
  700. reSend = YES;
  701. NSLog(@"[LOG] Re-upload File : %@ - fileID : %@", metadata.fileName, metadata.fileID);
  702. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:@"" sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:k_taskIdentifierNULL predicate:[NSPredicate predicateWithFormat:@"sessionID = %@ AND account = %@", metadata.sessionID, _activeAccount]];
  703. [self uploadURLSessionMetadata:metadata serverUrl:serverUrl sessionID:metadata.sessionID taskStatus:taskStatus assetLocalIdentifier:metadata.assetLocalIdentifier selector:metadata.sessionSelector];
  704. }
  705. if (!reSend) {
  706. NSLog(@"[LOG] Error reUploadBackground, file not found.");
  707. #ifndef EXTENSION
  708. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_no_reuploadfile_", nil) preferredStyle:UIAlertControllerStyleAlert];
  709. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  710. [alertController addAction:okAction];
  711. [[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:alertController animated:YES completion:nil];
  712. return;
  713. #endif
  714. }
  715. }
  716. - (void)uploadURLSessionMetadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl sessionID:(NSString*)sessionID taskStatus:(NSInteger)taskStatus assetLocalIdentifier:(NSString *)assetLocalIdentifier selector:(NSString *)selector
  717. {
  718. NSURL *url;
  719. NSMutableURLRequest *request;
  720. PHAsset *asset;
  721. NSString *fileNamePath = [[NSString stringWithFormat:@"%@/%@", serverUrl, metadata.fileName] encodeString:NSUTF8StringEncoding];
  722. url = [NSURL URLWithString:fileNamePath];
  723. request = [NSMutableURLRequest requestWithURL:url];
  724. NSData *authData = [[NSString stringWithFormat:@"%@:%@", _activeUser, _activePassword] dataUsingEncoding:NSUTF8StringEncoding];
  725. NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];
  726. [request setHTTPMethod:@"PUT"];
  727. [request setValue:authValue forHTTPHeaderField:@"Authorization"];
  728. [request setValue:[CCUtility getUserAgent] forHTTPHeaderField:@"User-Agent"];
  729. // Change date file upload with header : X-OC-Mtime (ctime assetLocalIdentifier)
  730. if (assetLocalIdentifier) {
  731. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[assetLocalIdentifier] options:nil];
  732. if (result.count) {
  733. asset = result[0];
  734. long dateFileCreation = [asset.creationDate timeIntervalSince1970];
  735. [request setValue:[NSString stringWithFormat:@"%ld", dateFileCreation] forHTTPHeaderField:@"X-OC-Mtime"];
  736. }
  737. }
  738. // Rename with the SessionID
  739. NSString *fileNameForUpload = sessionID;
  740. [[NSFileManager defaultManager] moveItemAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.fileName] toPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileNameForUpload] error:nil];
  741. // file NOT exists
  742. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileNameForUpload]] == NO) {
  743. // Delete record : Metadata
  744. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"sessionID = %@ AND account = %@", sessionID, _activeAccount] clearDateReadDirectoryID:nil];
  745. // Error for uploadFileFailure
  746. [[self getDelegate:sessionID] uploadFileSuccessFailure:metadata.fileName fileID:@"" assetLocalIdentifier:assetLocalIdentifier serverUrl:serverUrl selector:selector selectorPost:@"" errorMessage:NSLocalizedString(@"_file_not_present_", nil) errorCode:404];
  747. return;
  748. }
  749. NSURLSession *sessionUpload;
  750. // NSURLSession
  751. if ([metadata.session isEqualToString:k_upload_session]) sessionUpload = [self sessionUpload];
  752. else if ([metadata.session isEqualToString:k_upload_session_wwan]) sessionUpload = [self sessionWWanUpload];
  753. else if ([metadata.session isEqualToString:k_upload_session_foreground]) sessionUpload = [self sessionUploadForeground];
  754. else if ([metadata.session isEqualToString:k_upload_session_wwanforeground]) sessionUpload = [self sessionWWanUploadForeground];
  755. NSURLSessionUploadTask *uploadTask = [sessionUpload uploadTaskWithRequest:request fromFile:[NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileNameForUpload]]];
  756. // Error
  757. if (uploadTask == nil) {
  758. [[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];
  759. [[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]];
  760. [[NCManageDatabase sharedInstance] deleteQueueUploadWithAssetLocalIdentifier:assetLocalIdentifier selector:selector];
  761. [[self getDelegate:sessionID] uploadFileSuccessFailure:metadata.fileNameView fileID:@"" assetLocalIdentifier:assetLocalIdentifier serverUrl:serverUrl selector:selector selectorPost:@"" errorMessage:@"Serious internal error uploadTask not available" errorCode:k_CCErrorInternalError];
  762. } else {
  763. // E2EE : CREATE AND SEND METADATA
  764. if ([CCUtility isFolderEncrypted:serverUrl account:_activeAccount] && [CCUtility isEndToEndEnabled:_activeAccount]) {
  765. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  766. // Send Metadata
  767. NSString *token;
  768. NSError *error = [[NCNetworkingSync sharedManager] sendEndToEndMetadataOnServerUrl:serverUrl account:_activeAccount user:_activeUser userID:_activeUserID password:_activePassword url:_activeUrl fileNameRename:nil fileNameNewRename:nil token:&token];
  769. if (error == nil) {
  770. [[NCManageDatabase sharedInstance] setMetadataSession:metadata.session sessionError:@"" sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:uploadTask.taskIdentifier predicate:[NSPredicate predicateWithFormat:@"sessionID = %@ AND account = %@", sessionID, _activeAccount]];
  771. // Manage uploadTask cancel,suspend,resume
  772. if (taskStatus == k_taskStatusCancel) [uploadTask cancel];
  773. else if (taskStatus == k_taskStatusSuspend) [uploadTask suspend];
  774. else if (taskStatus == k_taskStatusResume) [uploadTask resume];
  775. NSLog(@"[LOG] Upload file %@ TaskIdentifier %lu", metadata.fileName, (unsigned long)uploadTask.taskIdentifier);
  776. } else {
  777. NSString *message = [NSString stringWithFormat:@"%@ %d", error.localizedDescription, (int)error.code];
  778. [[NCManageDatabase sharedInstance] addActivityClient:metadata.fileNameView fileID:assetLocalIdentifier action:k_activityDebugActionUpload selector:selector note:message type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:_activeUrl];
  779. [[NCManageDatabase sharedInstance] setMetadataSession:metadata.session sessionError:message sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:k_taskIdentifierError predicate:[NSPredicate predicateWithFormat:@"sessionID = %@ AND account = %@", sessionID, _activeAccount]];
  780. [uploadTask cancel];
  781. }
  782. });
  783. } else {
  784. // *** PLAIN ***
  785. [[NCManageDatabase sharedInstance] setMetadataSession:metadata.session sessionError:@"" sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:uploadTask.taskIdentifier predicate:[NSPredicate predicateWithFormat:@"sessionID = %@ AND account = %@", sessionID, _activeAccount]];
  786. // OK remove record on tableQueueUpload
  787. [[NCManageDatabase sharedInstance] deleteQueueUploadWithAssetLocalIdentifier:assetLocalIdentifier selector:selector];
  788. #ifndef EXTENSION
  789. // Next tableQueueUpload
  790. [(AppDelegate *)[[UIApplication sharedApplication] delegate] performSelectorOnMainThread:@selector(loadAutoDownloadUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUpload] waitUntilDone:NO];
  791. #endif
  792. // Manage uploadTask cancel,suspend,resume
  793. if (taskStatus == k_taskStatusCancel) [uploadTask cancel];
  794. else if (taskStatus == k_taskStatusSuspend) [uploadTask suspend];
  795. else if (taskStatus == k_taskStatusResume) [uploadTask resume];
  796. NSLog(@"[LOG] Upload file %@ TaskIdentifier %lu", metadata.fileName, (unsigned long)uploadTask.taskIdentifier);
  797. }
  798. }
  799. // refresh main
  800. if ([self.delegate respondsToSelector:@selector(reloadDatasource:)])
  801. [self.delegate reloadDatasource:serverUrl];
  802. #ifndef EXTENSION
  803. [(AppDelegate *)[[UIApplication sharedApplication] delegate] updateApplicationIconBadgeNumber];
  804. #endif
  805. }
  806. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
  807. {
  808. NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)dataTask.response;
  809. if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {
  810. NSNumber *taskIdentifier = [NSNumber numberWithLong:dataTask.taskIdentifier];
  811. if (data)
  812. [_taskData setObject:[data copy] forKey:taskIdentifier];
  813. }
  814. }
  815. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
  816. {
  817. NSString *url = [[[task currentRequest].URL absoluteString] stringByRemovingPercentEncoding];
  818. NSString *fileName = [url lastPathComponent];
  819. NSString *serverUrl = [self getServerUrlFromUrl:url];
  820. if (!serverUrl) return;
  821. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  822. if (!directoryID) return;
  823. float progress = (float) totalBytesSent / (float)totalBytesExpectedToSend;
  824. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataFromFileName:fileName directoryID:directoryID];
  825. if (metadata) {
  826. NSDictionary* userInfo = @{@"fileID": (metadata.fileID), @"serverUrl": (serverUrl), @"progress": ([NSNumber numberWithFloat:progress])};
  827. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  828. }
  829. }
  830. - (void)uploadFileSuccessFailure:(tableMetadata *)metadata fileName:(NSString *)fileName fileID:(NSString *)fileID etag:(NSString *)etag date:(NSDate *)date serverUrl:(NSString *)serverUrl errorCode:(NSInteger)errorCode
  831. {
  832. NSString *sessionID = metadata.sessionID;
  833. NSString *errorMessage = @"";
  834. // Progress Task
  835. NSDictionary* userInfo = @{@"fileID": (fileID), @"serverUrl": (serverUrl), @"progress": ([NSNumber numberWithFloat:0.0])};
  836. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  837. // ERRORE
  838. if (errorCode != 0) {
  839. #ifndef EXTENSION
  840. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  841. [appDelegate.listProgressMetadata removeObjectForKey:sessionID];
  842. #endif
  843. // Mark error only if not Cancelled Task
  844. if (errorCode != kCFURLErrorCancelled) {
  845. [[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]];
  846. }
  847. errorMessage = [CCError manageErrorKCF:errorCode withNumberError:YES];
  848. } else {
  849. // copy ico in new fileID
  850. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@.ico", _directoryUser, sessionID] toPath:[NSString stringWithFormat:@"%@/%@.ico", _directoryUser, fileID]];
  851. // Add new metadata
  852. metadata.fileID = fileID;
  853. metadata.etag = etag;
  854. metadata.date = date;
  855. metadata.e2eEncrypted = false;
  856. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  857. metadata = [[NCManageDatabase sharedInstance] addMetadata:metadata];
  858. // Delete old ID_UPLOAD_XXXXX metadata
  859. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", sessionID] clearDateReadDirectoryID:nil];
  860. #ifndef EXTENSION
  861. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  862. [appDelegate.listProgressMetadata removeObjectForKey:sessionID];
  863. #endif
  864. metadata.session = @"";
  865. metadata.sessionError = @"";
  866. metadata.sessionID = @"";
  867. metadata = [[NCManageDatabase sharedInstance] updateMetadata:metadata];
  868. NSLog(@"[LOG] Insert new upload : %@ - fileID : %@", metadata.fileName, metadata.fileID);
  869. if ([CCUtility isFolderEncrypted:serverUrl account:_activeAccount]) {
  870. // rename file fileNameView (original file) -> fileID
  871. [CCUtility moveFileAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.fileNameView] toPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.fileID]];
  872. // remove encrypted file
  873. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, sessionID] error:nil];
  874. } else {
  875. // rename file sessionID -> fileID
  876. [CCUtility moveFileAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, sessionID] toPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.fileID]];
  877. }
  878. // Local
  879. if (metadata.directory == NO)
  880. [[NCManageDatabase sharedInstance] addLocalFileWithMetadata:metadata];
  881. // EXIF
  882. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  883. [[CCExifGeo sharedInstance] setExifLocalTableEtag:metadata directoryUser:_directoryUser activeAccount:_activeAccount];
  884. // Create ICON
  885. if (metadata.directory == NO)
  886. [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]];
  887. // Optimization
  888. if (([CCUtility getUploadAndRemovePhoto] || [metadata.sessionSelectorPost isEqualToString:selectorUploadRemovePhoto]) && [metadata.typeFile isEqualToString:k_metadataTypeFile_document] == NO)
  889. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.fileID] error:nil];
  890. // Copy photo or video in the photo album for auto upload
  891. if ([metadata.assetLocalIdentifier length] > 0 && ([metadata.sessionSelector isEqualToString:selectorUploadAutoUpload] || [metadata.sessionSelector isEqualToString:selectorUploadFile])) {
  892. PHAsset *asset;
  893. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadata.assetLocalIdentifier] options:nil];
  894. if(result.count){
  895. asset = result[0];
  896. [asset saveToAlbum:[NCBrandOptions sharedInstance].brand completionBlock:^(BOOL success) {
  897. if (success) NSLog(@"[LOG] Insert file %@ in %@", metadata.fileName, [NCBrandOptions sharedInstance].brand);
  898. else NSLog(@"[LOG] File %@ do not insert in %@", metadata.fileName, [NCBrandOptions sharedInstance].brand);
  899. }];
  900. }
  901. }
  902. // Actvity
  903. [[NCManageDatabase sharedInstance] addActivityClient:metadata.fileNameView fileID:fileID action:k_activityDebugActionUpload selector:metadata.sessionSelector note:serverUrl type:k_activityTypeSuccess verbose:k_activityVerboseDefault activeUrl:_activeUrl];
  904. }
  905. // E2EE : UNLOCK
  906. if ([CCUtility isFolderEncrypted:serverUrl account:_activeAccount] && [CCUtility isEndToEndEnabled:_activeAccount]) {
  907. // OK remove record on tableQueueUpload [NEXT UPLOAD]
  908. [[NCManageDatabase sharedInstance] deleteQueueUploadWithAssetLocalIdentifier:metadata.assetLocalIdentifier selector:metadata.sessionSelector];
  909. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  910. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", _activeAccount, serverUrl]];
  911. if (directory) {
  912. NSError *error = [[NCNetworkingSync sharedManager] unlockEndToEndFolderEncrypted:_activeUser userID:_activeUserID password:_activePassword url:_activeUrl fileID:directory.fileID token:directory.e2eTokenLock];
  913. if (error) {
  914. #ifndef EXTENSION
  915. dispatch_async(dispatch_get_main_queue(), ^{
  916. [(AppDelegate *)[[UIApplication sharedApplication] delegate] messageNotification:@"_error_" description:[NSString stringWithFormat:@"%@ %d", error.localizedDescription, (int)error.code] visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  917. });
  918. #endif
  919. }
  920. }
  921. });
  922. }
  923. [[self getDelegate:sessionID] uploadFileSuccessFailure:metadata.fileName fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:serverUrl selector:metadata.sessionSelector selectorPost:metadata.sessionSelectorPost errorMessage:errorMessage errorCode:errorCode];
  924. }
  925. #pragma --------------------------------------------------------------------------------------------
  926. #pragma mark ===== Download Verify =====
  927. #pragma --------------------------------------------------------------------------------------------
  928. - (void)verifyDownloadInProgress
  929. {
  930. NSArray *dataSourceDownload = [[NCManageDatabase sharedInstance] getTableMetadataDownload];
  931. NSArray *dataSourceDownloadWWan = [[NCManageDatabase sharedInstance] getTableMetadataDownloadWWan];
  932. NSMutableArray *dataSource = [NSMutableArray new];
  933. [dataSource addObjectsFromArray:dataSourceDownload];
  934. [dataSource addObjectsFromArray:dataSourceDownloadWWan];
  935. NSLog(@"[LOG] Verify download file in progress n. %lu", (unsigned long)[dataSource count]);
  936. for (tableMetadata *metadata in dataSource) {
  937. NSURLSession *session = [self getSessionfromSessionDescription:metadata.session];
  938. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  939. dispatch_async(dispatch_get_main_queue(), ^{
  940. BOOL findTask = NO;
  941. BOOL findTaskPlist = NO;
  942. for (NSURLSessionDownloadTask *downloadTask in downloadTasks) {
  943. NSLog(@"[LOG] Find metadata Tasks [%li] = [%lu] state : %lu", (long)metadata.sessionTaskIdentifier ,(unsigned long)downloadTask.taskIdentifier, (unsigned long)[downloadTask state]);
  944. if (metadata.sessionTaskIdentifier == downloadTask.taskIdentifier) findTask = YES;
  945. if (findTask == YES || findTaskPlist == YES) break; // trovati, download ancora in corso
  946. }
  947. // DATA
  948. if (findTask == NO && metadata.sessionTaskIdentifier >= 0) {
  949. NSLog(@"[LOG] NOT Find metadata Task [%li] fileID : %@ - filename : %@", (long)metadata.sessionTaskIdentifier, metadata.fileID, metadata.fileName);
  950. [[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]];
  951. if ([self.delegate respondsToSelector:@selector(reloadDatasource:)])
  952. [self.delegate reloadDatasource:[[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID]];
  953. }
  954. });
  955. }];
  956. }
  957. }
  958. - (void)verifyDownloadInError:(id)delegate
  959. {
  960. NSMutableSet *serversUrl = [NSMutableSet new];
  961. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND session CONTAINS 'download' AND sessionTaskIdentifier = %i", _activeAccount, k_taskIdentifierError] sorted:nil ascending:NO];
  962. NSLog(@"[LOG] Verify re download in error n. %lu", (unsigned long)[metadatas count]);
  963. for (tableMetadata *metadata in metadatas) {
  964. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  965. if (!serverUrl) continue;
  966. if (metadata.sessionTaskIdentifier == k_taskIdentifierError)
  967. [self downloadFile:metadata.fileName fileID:metadata.fileID serverUrl:serverUrl selector:metadata.sessionSelector selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:delegate];
  968. [serversUrl addObject:serverUrl];
  969. NSLog(@"[LOG] Re download file : %@ [%li]", metadata.fileName, (long)metadata.sessionTaskIdentifier);
  970. }
  971. for (NSString *serverUrl in serversUrl) {
  972. if ([self.delegate respondsToSelector:@selector(reloadDatasource:)])
  973. [self.delegate reloadDatasource:serverUrl];
  974. }
  975. }
  976. #pragma --------------------------------------------------------------------------------------------
  977. #pragma mark ===== Upload Verify =====
  978. #pragma --------------------------------------------------------------------------------------------
  979. - (void)verifyUploadInProgress
  980. {
  981. NSArray *dataSourceUpload = [[NCManageDatabase sharedInstance] getTableMetadataUpload];
  982. NSArray *dataSourceUploadWWan = [[NCManageDatabase sharedInstance] getTableMetadataUploadWWan];
  983. NSMutableArray *dataSource = [[NSMutableArray alloc] init];
  984. [dataSource addObjectsFromArray:dataSourceUpload];
  985. [dataSource addObjectsFromArray:dataSourceUploadWWan];
  986. NSLog(@"[LOG] Verify upload file in progress n. %lu", (unsigned long)[dataSource count]);
  987. for (tableMetadata *metadata in dataSource) {
  988. __block NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  989. if (!serverUrl) continue;
  990. NSURLSession *session = [self getSessionfromSessionDescription:metadata.session];
  991. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  992. BOOL findTask = NO;
  993. // cerchiamo la corrispondenza dei task
  994. for (NSURLSessionUploadTask *uploadTask in uploadTasks) {
  995. NSLog(@"[LOG] Find metadata Tasks [%li] = [%lu] state : %lu", (long)metadata.sessionTaskIdentifier, (unsigned long)uploadTask.taskIdentifier, (unsigned long)[uploadTask state]);
  996. if (metadata.sessionTaskIdentifier == uploadTask.taskIdentifier) findTask = YES;
  997. if (findTask == YES) break;
  998. }
  999. // se non c'è il relativo uploadTask.taskIdentifier allora chiediamolo
  1000. if (findTask == NO) {
  1001. NSLog(@"[LOG] Call ReadFileVerifyUpload because this file %@ is in progress but there is no task : [%li]", metadata.fileName, (long)metadata.sessionTaskIdentifier);
  1002. if (metadata.sessionTaskIdentifier >= 0) [self readFileVerifyUpload:metadata.fileName serverUrl:serverUrl];
  1003. }
  1004. }];
  1005. // Notification change session
  1006. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, nil];
  1007. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1008. }
  1009. }
  1010. - (void)verifyUploadInErrorOrWait
  1011. {
  1012. NSMutableSet *directoryIDs = [NSMutableSet new];
  1013. 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];
  1014. NSLog(@"[LOG] Verify re upload in error n. %lu", (unsigned long)[metadatas count]);
  1015. for (tableMetadata *metadata in metadatas) {
  1016. [self uploadFileMetadata:metadata taskStatus: k_taskStatusResume];
  1017. [directoryIDs addObject:metadata.directoryID];
  1018. NSLog(@"[LOG] Re upload file : %@", metadata.fileName);
  1019. }
  1020. dispatch_async(dispatch_get_main_queue(), ^{
  1021. for (NSString *directoryID in directoryIDs)
  1022. if ([self.delegate respondsToSelector:@selector(reloadDatasource:)])
  1023. [self.delegate reloadDatasource:[[NCManageDatabase sharedInstance] getServerUrl:directoryID]];
  1024. });
  1025. }
  1026. - (void)readFileVerifyUpload:(NSString *)fileName serverUrl:(NSString *)serverUrl
  1027. {
  1028. #ifndef EXTENSION
  1029. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  1030. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:_activeAccount];
  1031. metadataNet.action = actionReadFile;
  1032. metadataNet.fileName = fileName;
  1033. metadataNet.serverUrl = serverUrl;
  1034. metadataNet.selector = selectorReadFileVerifyUpload;
  1035. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1036. #else
  1037. NSLog(@"[LOG] Function not available for extension.");
  1038. #endif
  1039. }
  1040. //
  1041. // File exists : selectorReadFileVerifyUpload
  1042. //
  1043. - (void)readFileSuccess:(CCMetadataNet *)metadataNet metadata:(tableMetadata *)metadata
  1044. {
  1045. NSString *fileName = metadataNet.fileName;
  1046. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:metadataNet.serverUrl];
  1047. if (!directoryID)
  1048. [self uploadFileSuccessFailure:metadata fileName:metadataNet.fileName fileID:metadata.fileID etag:metadata.etag date:metadata.date serverUrl:metadataNet.serverUrl errorCode:k_CCErrorFileUploadNotFound];
  1049. tableMetadata *metadataTemp = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileName = %@ AND directoryID = %@ AND account = %@", fileName , directoryID, _activeAccount]];
  1050. // is completed ?
  1051. if (metadataTemp.sessionTaskIdentifier == k_taskIdentifierDone) {
  1052. [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]];
  1053. NSLog(@"[LOG] Verify read file success, but files already processed");
  1054. dispatch_async(dispatch_get_main_queue(), ^{
  1055. if ([self.delegate respondsToSelector:@selector(reloadDatasource:)])
  1056. [self.delegate reloadDatasource:[[NCManageDatabase sharedInstance] getServerUrl:directoryID]];
  1057. });
  1058. } else {
  1059. [self uploadFileSuccessFailure:metadataTemp fileName:metadataNet.fileName fileID:metadata.fileID etag:metadata.etag date:metadata.date serverUrl:metadataNet.serverUrl errorCode:0];
  1060. }
  1061. }
  1062. //
  1063. // File do not exists : selectorReadFileVerifyUpload
  1064. //
  1065. - (void)readFileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1066. {
  1067. NSString *fileName = metadataNet.fileName;
  1068. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:metadataNet.serverUrl];
  1069. if (!directoryID) return;
  1070. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileName = %@ AND directoryID = %@ AND account = %@",fileName , directoryID, _activeAccount]];
  1071. NSInteger error;
  1072. if (errorCode == kOCErrorServerPathNotFound)
  1073. error = k_CCErrorFileUploadNotFound;
  1074. else
  1075. error = errorCode;
  1076. // fix CCNetworking.m line 1340 2.17.2 (00005)
  1077. if (metadata)
  1078. [self uploadFileSuccessFailure:metadata fileName:metadataNet.fileName fileID:metadata.fileID etag:metadata.etag date:metadata.date serverUrl:metadataNet.serverUrl errorCode:error];
  1079. }
  1080. #pragma --------------------------------------------------------------------------------------------
  1081. #pragma mark ===== Utility =====
  1082. #pragma --------------------------------------------------------------------------------------------
  1083. - (id)getDelegate:(NSString *)fileID
  1084. {
  1085. id delegate = [_delegates objectForKey:fileID];
  1086. if (delegate)
  1087. return delegate;
  1088. else
  1089. return self.delegate;
  1090. }
  1091. - (NSString *)getServerUrlFromUrl:(NSString *)url
  1092. {
  1093. NSString *fileName = [url lastPathComponent];
  1094. url = [url stringByReplacingOccurrencesOfString:[@"/" stringByAppendingString:fileName] withString:@""];
  1095. return url;
  1096. }
  1097. - (NSString *)getTitleFromPlistName:(NSString *)fileName
  1098. {
  1099. if ([[fileName lastPathComponent] isEqualToString:@"plist"] == NO)
  1100. fileName = [fileName stringByAppendingString:@".plist"];
  1101. if (![[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileName]]) return nil;
  1102. NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileName]];
  1103. return [data objectForKey:@"title"];
  1104. }
  1105. #pragma --------------------------------------------------------------------------------------------
  1106. #pragma mark ===== E2EE End To End Encryption =====
  1107. #pragma --------------------------------------------------------------------------------------------
  1108. // E2EE
  1109. - (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
  1110. {
  1111. __block NSError *error;
  1112. NSString *key;
  1113. NSString *initializationVector;
  1114. NSString *authenticationTag;
  1115. NSString *metadataKey;
  1116. NSInteger metadataKeyIndex;
  1117. // Verify File Size
  1118. NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileName] error:&error];
  1119. NSNumber *fileSizeNumber = [fileAttributes objectForKey:NSFileSize];
  1120. long long fileSize = [fileSizeNumber longLongValue];
  1121. if (fileSize > k_max_filesize_E2E) {
  1122. // Error for uploadFileFailure
  1123. *errorMessage = @"E2E Error file too big";
  1124. return;
  1125. }
  1126. // if exists overwrite file else create a new encrypted filename
  1127. tableMetadata *overwriteMetadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND fileNameView = %@", _activeAccount, directoryID, fileName]];
  1128. if (overwriteMetadata)
  1129. *fileNameIdentifier = overwriteMetadata.fileName;
  1130. else
  1131. *fileNameIdentifier = [CCUtility generateRandomIdentifier];
  1132. // Write to DB
  1133. if ([[NCEndToEndEncryption sharedManager] encryptFileName:fileName fileNameIdentifier:*fileNameIdentifier directoryUser: _directoryUser key:&key initializationVector:&initializationVector authenticationTag:&authenticationTag]) {
  1134. tableE2eEncryption *object = [[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", _activeAccount, serverUrl]];
  1135. if (object) {
  1136. metadataKey = object.metadataKey;
  1137. metadataKeyIndex = object.metadataKeyIndex;
  1138. } else {
  1139. metadataKey = [[[NCEndToEndEncryption sharedManager] generateKey:16] base64EncodedStringWithOptions:0]; // AES_KEY_128_LENGTH
  1140. metadataKeyIndex = 0;
  1141. }
  1142. tableE2eEncryption *addObject = [tableE2eEncryption new];
  1143. addObject.account = _activeAccount;
  1144. addObject.authenticationTag = authenticationTag;
  1145. addObject.fileName = fileName;
  1146. addObject.fileNameIdentifier = *fileNameIdentifier;
  1147. addObject.fileNamePath = [CCUtility returnFileNamePathFromFileName:fileName serverUrl:serverUrl activeUrl:_activeUrl];
  1148. addObject.key = key;
  1149. addObject.initializationVector = initializationVector;
  1150. addObject.metadataKey = metadataKey;
  1151. addObject.metadataKeyIndex = metadataKeyIndex;
  1152. CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)[fileName pathExtension], NULL);
  1153. CFStringRef mimeTypeRef = UTTypeCopyPreferredTagWithClass (UTI, kUTTagClassMIMEType);
  1154. if (mimeTypeRef) {
  1155. addObject.mimeType = (__bridge NSString *)mimeTypeRef;
  1156. } else {
  1157. addObject.mimeType = @"application/octet-stream";
  1158. }
  1159. addObject.serverUrl = serverUrl;
  1160. addObject.version = [[NCManageDatabase sharedInstance] getEndToEndEncryptionVersion];
  1161. // Get the last metadata
  1162. NSString *metadata;
  1163. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", account, serverUrl]];
  1164. error = [[NCNetworkingSync sharedManager] getEndToEndMetadata:user userID:userID password:password url:url fileID:directory.fileID metadata:&metadata];
  1165. if (error == nil) {
  1166. if ([[NCEndToEndMetadata sharedInstance] decoderMetadata:metadata privateKey:[CCUtility getEndToEndPrivateKey:account] serverUrl:serverUrl account:account url:url] == false) {
  1167. *errorMessage = @"Serious internal error in decoding metadata";
  1168. return;
  1169. }
  1170. }
  1171. *e2eMetadata = metadata;
  1172. // write new record e2ee
  1173. if([[NCManageDatabase sharedInstance] addE2eEncryption:addObject] == NO)
  1174. *errorMessage = @"E2E Error to create encrypted file";
  1175. } else {
  1176. *errorMessage = @"E2E Error to create encrypted file";
  1177. }
  1178. }
  1179. @end
  1180. #pragma --------------------------------------------------------------------------------------------
  1181. #pragma mark ===== CCMetadataNet =====
  1182. #pragma --------------------------------------------------------------------------------------------
  1183. @implementation CCMetadataNet
  1184. - (id)init
  1185. {
  1186. self = [super init];
  1187. self.priority = NSOperationQueuePriorityNormal;
  1188. return self;
  1189. }
  1190. - (id)initWithAccount:(NSString *)withAccount
  1191. {
  1192. self = [self init];
  1193. if (self) {
  1194. _account = withAccount;
  1195. }
  1196. return self;
  1197. }
  1198. - (id)copyWithZone: (NSZone *) zone
  1199. {
  1200. CCMetadataNet *metadataNet = [[CCMetadataNet allocWithZone: zone] init];
  1201. [metadataNet setAccount: self.account];
  1202. [metadataNet setAction: self.action];
  1203. [metadataNet setAssetLocalIdentifier: self.assetLocalIdentifier];
  1204. [metadataNet setContentType: self.contentType];
  1205. [metadataNet setDate: self.date];
  1206. [metadataNet setDelegate: self.delegate];
  1207. [metadataNet setDepth: self.depth];
  1208. [metadataNet setDirectory: self.directory];
  1209. [metadataNet setDirectoryID: self.directoryID];
  1210. [metadataNet setDirectoryIDTo: self.directoryIDTo];
  1211. [metadataNet setEncryptedMetadata: self.encryptedMetadata];
  1212. [metadataNet setErrorCode: self.errorCode];
  1213. [metadataNet setErrorRetry: self.errorRetry];
  1214. [metadataNet setEtag:self.etag];
  1215. [metadataNet setExpirationTime: self.expirationTime];
  1216. [metadataNet setFileID: self.fileID];
  1217. [metadataNet setFileName: self.fileName];
  1218. [metadataNet setFileNameTo: self.fileNameTo];
  1219. [metadataNet setFileNameView: self.fileNameView];
  1220. [metadataNet setKey: self.key];
  1221. [metadataNet setKeyCipher: self.keyCipher];
  1222. [metadataNet setOptions: self.options];
  1223. [metadataNet setPassword: self.password];
  1224. [metadataNet setPathFolder: self.pathFolder];
  1225. [metadataNet setPriority: self.priority];
  1226. [metadataNet setServerUrl: self.serverUrl];
  1227. [metadataNet setServerUrlTo: self.serverUrlTo];
  1228. [metadataNet setSelector: self.selector];
  1229. [metadataNet setSelectorPost: self.selectorPost];
  1230. [metadataNet setSession: self.session];
  1231. [metadataNet setSessionID: self.sessionID];
  1232. [metadataNet setShare: self.share];
  1233. [metadataNet setShareeType: self.shareeType];
  1234. [metadataNet setSharePermission: self.sharePermission];
  1235. [metadataNet setSize: self.size];
  1236. [metadataNet setTaskStatus: self.taskStatus];
  1237. return metadataNet;
  1238. }
  1239. @end