CCNetworking.m 81 KB

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