CCNetworking.m 102 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919
  1. //
  2. // CCNetworking.m
  3. // Crypto Cloud Technology Nextcloud
  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 "AppDelegate.h"
  25. #import "CCCertificate.h"
  26. #import "NSDate+ISO8601.h"
  27. #import "NSString+Encode.h"
  28. #import "NCRequestAsset.h"
  29. #import "NCBridgeSwift.h"
  30. @interface CCNetworking () <NCRequestAssetDelegate>
  31. {
  32. NSMutableDictionary *_taskData;
  33. NSString *_activeAccount;
  34. NSString *_activePassword;
  35. NSString *_activeUser;
  36. NSString *_activeUrl;
  37. NSString *_directoryUser;
  38. }
  39. @end
  40. @implementation CCNetworking
  41. + (CCNetworking *)sharedNetworking {
  42. static CCNetworking *sharedNetworking;
  43. @synchronized(self)
  44. {
  45. if (!sharedNetworking) {
  46. sharedNetworking = [[CCNetworking alloc] init];
  47. }
  48. return sharedNetworking;
  49. }
  50. }
  51. - (id)init
  52. {
  53. self = [super init];
  54. _taskData = [[NSMutableDictionary alloc] init];
  55. _delegates = [[NSMutableDictionary alloc] init];
  56. // Initialization Sessions
  57. [self sessionDownload];
  58. [self sessionDownloadForeground];
  59. [self sessionWWanDownload];
  60. [self sessionUpload];
  61. [self sessionUploadForeground];
  62. [self sessionWWanUpload];
  63. [self sharedOCCommunication];
  64. [self settingAccount];
  65. return self;
  66. }
  67. - (void)settingDelegate:(id <CCNetworkingDelegate>)delegate
  68. {
  69. _delegate = delegate;
  70. }
  71. - (void)settingAccount
  72. {
  73. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  74. _activeAccount = tableAccount.account;
  75. _activePassword = tableAccount.password;
  76. _activeUser = tableAccount.user;
  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 *)sessionUploadForeground
  143. {
  144. static NSURLSession *sessionUploadForeground;
  145. if (sessionUploadForeground == nil) {
  146. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  147. configuration.allowsCellularAccess = YES;
  148. configuration.discretionary = NO;
  149. configuration.HTTPMaximumConnectionsPerHost = 1;
  150. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  151. sessionUploadForeground = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  152. sessionUploadForeground.sessionDescription = k_upload_session_foreground;
  153. }
  154. return sessionUploadForeground;
  155. }
  156. - (NSURLSession *)sessionWWanUpload
  157. {
  158. static NSURLSession *sessionWWanUpload = nil;
  159. if (sessionWWanUpload == nil) {
  160. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_upload_session_wwan];
  161. configuration.allowsCellularAccess = NO;
  162. configuration.sessionSendsLaunchEvents = YES;
  163. configuration.discretionary = NO;
  164. configuration.HTTPMaximumConnectionsPerHost = 1;
  165. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  166. sessionWWanUpload = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  167. sessionWWanUpload.sessionDescription = k_upload_session_wwan;
  168. }
  169. return sessionWWanUpload;
  170. }
  171. - (OCCommunication *)sharedOCCommunication
  172. {
  173. static OCCommunication* sharedOCCommunication = nil;
  174. if (sharedOCCommunication == nil)
  175. {
  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. sharedOCCommunication = [[OCCommunication alloc] initWithUploadSessionManager:nil andDownloadSessionManager:nil andNetworkSessionManager:networkSessionManager];
  185. }
  186. return sharedOCCommunication;
  187. }
  188. - (NSURLSession *)getSessionfromSessionDescription:(NSString *)sessionDescription
  189. {
  190. if ([sessionDescription isEqualToString:k_download_session]) return [self sessionDownload];
  191. if ([sessionDescription isEqualToString:k_download_session_foreground]) return [self sessionDownloadForeground];
  192. if ([sessionDescription isEqualToString:k_download_session_wwan]) return [self sessionWWanDownload];
  193. if ([sessionDescription isEqualToString:k_upload_session]) return [self sessionUpload];
  194. if ([sessionDescription isEqualToString:k_upload_session_foreground]) return [self sessionUploadForeground];
  195. if ([sessionDescription isEqualToString:k_upload_session_wwan]) return [self sessionWWanUpload];
  196. return nil;
  197. }
  198. - (void)invalidateAndCancelAllSession
  199. {
  200. [[self sessionDownload] invalidateAndCancel];
  201. [[self sessionDownloadForeground] invalidateAndCancel];
  202. [[self sessionWWanDownload] invalidateAndCancel];
  203. [[self sessionUpload] invalidateAndCancel];
  204. [[self sessionUploadForeground] invalidateAndCancel];
  205. [[self sessionWWanUpload] invalidateAndCancel];
  206. }
  207. - (void)settingSessionsDownload:(BOOL)download upload:(BOOL)upload taskStatus:(NSInteger)taskStatus activeAccount:(NSString *)activeAccount activeUser:(NSString *)activeUser activeUrl:(NSString *)activeUrl
  208. {
  209. if (download) {
  210. [[self sessionDownload] getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  211. for (NSURLSessionTask *task in downloadTasks)
  212. if (taskStatus == k_taskStatusCancel) [task cancel];
  213. else if (taskStatus == k_taskStatusSuspend) [task suspend];
  214. else if (taskStatus == k_taskStatusResume) [task resume];
  215. }];
  216. [[self sessionDownloadForeground] getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  217. for (NSURLSessionTask *task in downloadTasks)
  218. if (taskStatus == k_taskStatusCancel) [task cancel];
  219. else if (taskStatus == k_taskStatusSuspend) [task suspend];
  220. else if (taskStatus == k_taskStatusResume) [task resume];
  221. }];
  222. [[self sessionWWanDownload] getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  223. for (NSURLSessionTask *task in downloadTasks)
  224. if (taskStatus == k_taskStatusCancel) [task cancel];
  225. else if (taskStatus == k_taskStatusSuspend) [task suspend];
  226. else if (taskStatus == k_taskStatusResume) [task resume];
  227. }];
  228. }
  229. if (upload) {
  230. [[self sessionUpload] getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  231. for (NSURLSessionTask *task in uploadTasks)
  232. if (taskStatus == k_taskStatusCancel)[task cancel];
  233. else if (taskStatus == k_taskStatusSuspend) [task suspend];
  234. else if (taskStatus == k_taskStatusResume) [task resume];
  235. }];
  236. [[self sessionUploadForeground] getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  237. for (NSURLSessionTask *task in uploadTasks)
  238. if (taskStatus == k_taskStatusCancel) [task cancel];
  239. else if (taskStatus == k_taskStatusSuspend) [task suspend];
  240. else if (taskStatus == k_taskStatusResume) [task resume];
  241. }];
  242. [[self sessionWWanUpload] getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  243. for (NSURLSessionTask *task in uploadTasks)
  244. if (taskStatus == k_taskStatusCancel) [task cancel];
  245. else if (taskStatus == k_taskStatusSuspend) [task suspend];
  246. else if (taskStatus == k_taskStatusResume) [task resume];
  247. }];
  248. }
  249. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  250. if (download && taskStatus == k_taskStatusCancel) {
  251. [[NCManageDatabase sharedInstance] setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionSelectorPost:@"" sessionTaskIdentifier:k_taskIdentifierDone sessionTaskIdentifierPlist:k_taskIdentifierDone predicate:[NSPredicate predicateWithFormat:@"account = %@ AND session CONTAINS 'download'", _activeAccount]];
  252. }
  253. if (upload && taskStatus == k_taskStatusCancel) {
  254. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"session CONTAINS 'upload'"] clearDateReadDirectoryID:nil];
  255. // File System
  256. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  257. [CCUtility removeAllFileID_UPLOAD_ActiveUser:activeUser activeUrl:activeUrl];
  258. });
  259. }
  260. });
  261. }
  262. - (void)settingSession:(NSString *)sessionDescription sessionTaskIdentifier:(NSUInteger)sessionTaskIdentifier taskStatus:(NSInteger)taskStatus
  263. {
  264. NSURLSession *session = [self getSessionfromSessionDescription:sessionDescription];
  265. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  266. if ([sessionDescription containsString:@"download"])
  267. for (NSURLSessionTask *task in downloadTasks)
  268. if (task.taskIdentifier == sessionTaskIdentifier) {
  269. if (taskStatus == k_taskStatusCancel) [task cancel];
  270. else if (taskStatus == k_taskStatusSuspend) [task suspend];
  271. else if (taskStatus == k_taskStatusResume) [task resume];
  272. }
  273. if ([sessionDescription containsString:@"upload"])
  274. for (NSURLSessionTask *task in uploadTasks)
  275. if (task.taskIdentifier == sessionTaskIdentifier) {
  276. if (taskStatus == k_taskStatusCancel) [task cancel];
  277. else if (taskStatus == k_taskStatusSuspend) [task suspend];
  278. else if (taskStatus == k_taskStatusResume) [task resume];
  279. }
  280. }];
  281. }
  282. #pragma --------------------------------------------------------------------------------------------
  283. #pragma mark ===== URLSession download/upload =====
  284. #pragma --------------------------------------------------------------------------------------------
  285. - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
  286. {
  287. // The pinnning check
  288. if ([[CCCertificate sharedManager] checkTrustedChallenge:challenge]) {
  289. completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  290. } else {
  291. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  292. }
  293. }
  294. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
  295. {
  296. NSString *url = [[[task currentRequest].URL absoluteString] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  297. NSString *fileName = [url lastPathComponent];
  298. NSString *serverUrl = [self getServerUrlFromUrl:url];
  299. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  300. tableMetadata *metadata;
  301. NSInteger errorCode;
  302. NSDate *date = [NSDate date];
  303. NSDateFormatter *dateFormatter = [NSDateFormatter new];
  304. NSLocale *enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
  305. [dateFormatter setLocale:enUSPOSIXLocale];
  306. [dateFormatter setDateFormat:@"EEE, dd MMM y HH:mm:ss zzz"];
  307. NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)task.response;
  308. if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {
  309. errorCode = error.code;
  310. } else {
  311. if (httpResponse.statusCode > 0)
  312. errorCode = httpResponse.statusCode;
  313. else
  314. errorCode = error.code;
  315. // Request trusted certificated
  316. if (errorCode == NSURLErrorServerCertificateUntrusted)
  317. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  318. }
  319. // ----------------------- DOWNLOAD -----------------------
  320. if ([task isKindOfClass:[NSURLSessionDownloadTask class]]) {
  321. metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"session = %@ AND (sessionTaskIdentifier = %i OR sessionTaskIdentifierPlist = %i)",session.sessionDescription, task.taskIdentifier, task.taskIdentifier]];
  322. if (!metadata)
  323. metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"directoryID = %@ AND (fileName = %@ OR fileNameData = %@)", directoryID, fileName, fileName]];
  324. if (metadata) {
  325. NSString *etag = metadata.etag;
  326. NSString *fileID = metadata.fileID;
  327. NSDictionary *fields = [httpResponse allHeaderFields];
  328. if (errorCode == 0) {
  329. etag = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-ETag"]];
  330. NSString *dateString = [fields objectForKey:@"Date"];
  331. if (![dateFormatter getObjectValue:&date forString:dateString range:nil error:&error]) {
  332. NSLog(@"Date '%@' could not be parsed: %@", dateString, error);
  333. date = [NSDate date];
  334. }
  335. }
  336. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, task, nil];
  337. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  338. if (fileName.length > 0 && serverUrl.length > 0)
  339. [self downloadFileSuccessFailure:fileName fileID:metadata.fileID etag:etag date:date serverUrl:serverUrl selector:metadata.sessionSelector selectorPost:metadata.sessionSelectorPost errorCode:errorCode];
  340. } else {
  341. NSLog(@"[LOG] Remove record ? : metadata not found %@", url);
  342. dispatch_async(dispatch_get_main_queue(), ^{
  343. if ([self.delegate respondsToSelector:@selector(downloadFileFailure:serverUrl:selector:message:errorCode:)])
  344. [self.delegate downloadFileFailure:@"" serverUrl:serverUrl selector:@"" message:@"" errorCode:k_CCErrorInternalError];
  345. });
  346. }
  347. }
  348. // ------------------------ UPLOAD -----------------------
  349. if ([task isKindOfClass:[NSURLSessionUploadTask class]]) {
  350. metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"session = %@ AND (sessionTaskIdentifier = %i OR sessionTaskIdentifierPlist = %i)",session.sessionDescription, task.taskIdentifier, task.taskIdentifier]];
  351. if (!metadata)
  352. metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"directoryID = %@ AND (fileName = %@ OR fileNameData = %@)", directoryID, fileName, fileName]];
  353. if (metadata) {
  354. NSDictionary *fields = [httpResponse allHeaderFields];
  355. NSString *fileID = metadata.fileID;
  356. NSString *etag = metadata.etag;
  357. if (errorCode == 0) {
  358. fileID = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-FileId"]];
  359. etag = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-ETag"]];
  360. NSString *dateString = [fields objectForKey:@"Date"];
  361. if (![dateFormatter getObjectValue:&date forString:dateString range:nil error:&error]) {
  362. NSLog(@"Date '%@' could not be parsed: %@", dateString, error);
  363. date = [NSDate date];
  364. }
  365. }
  366. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, task, nil];
  367. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  368. if (fileName.length > 0 && fileID.length > 0 && serverUrl.length > 0)
  369. [self uploadFileSuccessFailure:metadata fileName:fileName fileID:fileID etag:etag date:date serverUrl:serverUrl errorCode:errorCode];
  370. } else {
  371. NSLog(@"[LOG] Remove record ? : metadata not found %@", url);
  372. dispatch_async(dispatch_get_main_queue(), ^{
  373. if ([self.delegate respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  374. [self.delegate uploadFileFailure:nil fileID:@"" serverUrl:serverUrl selector:@"" message:@"" errorCode:k_CCErrorInternalError];
  375. });
  376. }
  377. }
  378. }
  379. #pragma --------------------------------------------------------------------------------------------
  380. #pragma mark ===== Download =====
  381. #pragma --------------------------------------------------------------------------------------------
  382. - (void)downloadFile:(NSString *)fileID serverUrl:(NSString *)serverUrl downloadData:(BOOL)downloadData downloadPlist:(BOOL)downloadPlist selector:(NSString *)selector selectorPost:(NSString *)selectorPost session:(NSString *)session taskStatus:(NSInteger)taskStatus delegate:(id)delegate
  383. {
  384. // add delegate
  385. if (delegate)
  386. [_delegates setObject:delegate forKey:fileID];
  387. if (fileID.length == 0) {
  388. dispatch_async(dispatch_get_main_queue(), ^{
  389. if ([[self getDelegate:fileID] respondsToSelector:@selector(downloadFileFailure:serverUrl:selector:message:errorCode:)])
  390. [[self getDelegate:fileID] downloadFileFailure:fileID serverUrl:serverUrl selector:selector message:NSLocalizedStringFromTable(@"_file_folder_not_exists_", @"Error", nil) errorCode:kOCErrorServerPathNotFound];
  391. });
  392. return;
  393. }
  394. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  395. if (!metadata) {
  396. dispatch_async(dispatch_get_main_queue(), ^{
  397. if ([[self getDelegate:fileID] respondsToSelector:@selector(downloadFileFailure:serverUrl:selector:message:errorCode:)])
  398. [[self getDelegate:fileID] downloadFileFailure:fileID serverUrl:serverUrl selector:selector message:NSLocalizedStringFromTable(@"_file_folder_not_exists_", @"Error", nil) errorCode:kOCErrorServerPathNotFound];
  399. });
  400. return;
  401. }
  402. if (downloadData) {
  403. // it's in download
  404. tableMetadata *result = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@ AND session CONTAINS 'download' AND sessionTaskIdentifier >= 0", _activeAccount, metadata.fileID]];
  405. if (result) {
  406. dispatch_async(dispatch_get_main_queue(), ^{
  407. if ([[self getDelegate:fileID] respondsToSelector:@selector(downloadFileFailure:serverUrl:selector:message:errorCode:)])
  408. [[self getDelegate:fileID] downloadFileFailure:fileID serverUrl:serverUrl selector:selector message:@"File already in download" errorCode:k_CCErrorFileAlreadyInDownload];
  409. });
  410. return;
  411. }
  412. // File exists ?
  413. tableLocalFile *localfile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  414. if (localfile != nil && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.fileID]]) {
  415. [[NCManageDatabase sharedInstance] setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionSelectorPost:@"" sessionTaskIdentifier:k_taskIdentifierDone sessionTaskIdentifierPlist:k_taskIdentifierDone predicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  416. dispatch_async(dispatch_get_main_queue(), ^{
  417. if ([[self getDelegate:metadata.fileID] respondsToSelector:@selector(downloadFileSuccess:serverUrl:selector:selectorPost:)])
  418. [[self getDelegate:metadata.fileID] downloadFileSuccess:metadata.fileID serverUrl:serverUrl selector:selector selectorPost:selectorPost];
  419. });
  420. return;
  421. }
  422. [[NCManageDatabase sharedInstance] setMetadataSession:session sessionError:@"" sessionSelector:selector sessionSelectorPost:selectorPost sessionTaskIdentifier:k_taskIdentifierNULL sessionTaskIdentifierPlist:k_taskIdentifierNULL predicate:[NSPredicate predicateWithFormat:@"fileID = %@",metadata.fileID]];
  423. [self downloaURLSession:metadata.fileNameData fileNamePrint:metadata.fileNamePrint serverUrl:serverUrl fileID:metadata.fileID session:session taskStatus:taskStatus selector:selector];
  424. }
  425. if (downloadPlist) {
  426. tableMetadata *result = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@ AND session CONTAINS 'download' AND sessionTaskIdentifierPlist >= 0", metadata.fileID]];
  427. // it's in download
  428. if (result) {
  429. dispatch_async(dispatch_get_main_queue(), ^{
  430. if ([[self getDelegate:fileID] respondsToSelector:@selector(downloadFileFailure:serverUrl:selector:message:errorCode:)])
  431. [[self getDelegate:fileID] downloadFileFailure:fileID serverUrl:serverUrl selector:selector message:@"File already in download" errorCode:k_CCErrorFileAlreadyInDownload];
  432. });
  433. return;
  434. }
  435. [[NCManageDatabase sharedInstance] setMetadataSession:session sessionError:@"" sessionSelector:selector sessionSelectorPost:selectorPost sessionTaskIdentifier:k_taskIdentifierNULL sessionTaskIdentifierPlist:k_taskIdentifierNULL predicate:[NSPredicate predicateWithFormat:@"fileID = %@",metadata.fileID]];
  436. [self downloaURLSession:metadata.fileName fileNamePrint:metadata.fileNamePrint serverUrl:serverUrl fileID:metadata.fileID session:session taskStatus:taskStatus selector:selector];
  437. }
  438. }
  439. - (void)downloaURLSession:(NSString *)fileName fileNamePrint:(NSString *)fileNamePrint serverUrl:(NSString *)serverUrl fileID:(NSString *)fileID session:(NSString *)session taskStatus:(NSInteger)taskStatus selector:(NSString *)selector
  440. {
  441. NSURLSession *sessionDownload;
  442. NSURL *url;
  443. NSMutableURLRequest *request;
  444. NSString *serverFileUrl = [[NSString stringWithFormat:@"%@/%@", serverUrl, fileName] encodeString:NSUTF8StringEncoding];
  445. url = [NSURL URLWithString:serverFileUrl];
  446. request = [NSMutableURLRequest requestWithURL:url];
  447. NSData *authData = [[NSString stringWithFormat:@"%@:%@", _activeUser, _activePassword] dataUsingEncoding:NSUTF8StringEncoding];
  448. NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];
  449. [request setValue:authValue forHTTPHeaderField:@"Authorization"];
  450. if ([session isEqualToString:k_download_session]) sessionDownload = [self sessionDownload];
  451. else if ([session isEqualToString:k_download_session_foreground]) sessionDownload = [self sessionDownloadForeground];
  452. else if ([session isEqualToString:k_download_session_wwan]) sessionDownload = [self sessionWWanDownload];
  453. NSURLSessionDownloadTask *downloadTask = [sessionDownload downloadTaskWithRequest:request];
  454. if (downloadTask == nil) {
  455. NSUInteger sessionTaskIdentifier = k_taskIdentifierNULL;
  456. NSUInteger sessionTaskIdentifierPlist = k_taskIdentifierNULL;
  457. if ([CCUtility isFileNotCryptated:fileName] || [CCUtility isCryptoString:fileName]) sessionTaskIdentifier = k_taskIdentifierError;
  458. if ([CCUtility isCryptoPlistString:fileName]) sessionTaskIdentifierPlist = k_taskIdentifierError;
  459. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:[NSString stringWithFormat:@"%@", @k_CCErrorTaskNil] sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:sessionTaskIdentifier sessionTaskIdentifierPlist:sessionTaskIdentifierPlist predicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  460. NSLog(@"[LOG] downloadFileSession TaskIdentifier [error CCErrorTaskNil] - %@ - %@", fileName, fileNamePrint);
  461. } else {
  462. NSUInteger sessionTaskIdentifier = k_taskIdentifierNULL;
  463. NSUInteger sessionTaskIdentifierPlist = k_taskIdentifierNULL;
  464. if ([CCUtility isCryptoString:fileName] || [CCUtility isFileNotCryptated:fileName]) sessionTaskIdentifier = downloadTask.taskIdentifier;
  465. if ([CCUtility isCryptoPlistString:fileName]) sessionTaskIdentifierPlist = downloadTask.taskIdentifier;
  466. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:nil sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:sessionTaskIdentifier sessionTaskIdentifierPlist:sessionTaskIdentifierPlist predicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  467. // Manage uploadTask cancel,suspend,resume
  468. if (taskStatus == k_taskStatusCancel) [downloadTask cancel];
  469. else if (taskStatus == k_taskStatusSuspend) [downloadTask suspend];
  470. else if (taskStatus == k_taskStatusResume) [downloadTask resume];
  471. NSLog(@"[LOG] downloadFileSession %@ - %@ Task [%lu %lu]", fileID, fileNamePrint, (unsigned long)sessionTaskIdentifier, (unsigned long)sessionTaskIdentifierPlist);
  472. }
  473. dispatch_async(dispatch_get_main_queue(), ^{
  474. // Refresh datasource if is not a Plist
  475. if ([_delegate respondsToSelector:@selector(reloadDatasource:)] && [CCUtility isCryptoPlistString:fileName] == NO)
  476. [_delegate reloadDatasource:serverUrl];
  477. #ifndef EXTENSION
  478. [app updateApplicationIconBadgeNumber];
  479. #endif
  480. });
  481. }
  482. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
  483. {
  484. NSString *url = [[[downloadTask currentRequest].URL absoluteString] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  485. NSString *fileName = [url lastPathComponent];
  486. NSString *serverUrl = [self getServerUrlFromUrl:url];
  487. // if plist return
  488. if ([CCUtility getTypeFileName:fileName] == k_metadataTypeFilenamePlist)
  489. return;
  490. float progress = (float) totalBytesWritten / (float)totalBytesExpectedToWrite;
  491. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataFromFileName:fileName directoryID:[[NCManageDatabase sharedInstance] getDirectoryID:serverUrl]];
  492. if (metadata) {
  493. NSDictionary* userInfo = @{@"fileID": (metadata.fileID), @"serverUrl": (serverUrl), @"cryptated": ([NSNumber numberWithBool:metadata.cryptated]), @"progress": ([NSNumber numberWithFloat:progress])};
  494. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  495. } else {
  496. NSLog(@"metadata not found");
  497. }
  498. }
  499. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
  500. {
  501. NSURLRequest *url = [downloadTask currentRequest];
  502. NSString *fileName = [[url.URL absoluteString] lastPathComponent];
  503. NSString *serverUrl = [self getServerUrlFromUrl:[url.URL absoluteString]];
  504. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"session = %@ AND (sessionTaskIdentifier = %i OR sessionTaskIdentifierPlist = %i)",session.sessionDescription, downloadTask.taskIdentifier, downloadTask.taskIdentifier]];
  505. // If the record metadata do not exists, exit
  506. if (!metadata) {
  507. [[NCManageDatabase sharedInstance] addActivityClient:fileName fileID:@"" action:k_activityDebugActionUpload selector:@"" note:[NSString stringWithFormat:@"Serius error internal download : metadata not found %@", url] type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:_activeUrl];
  508. NSLog(@"[LOG] Serius error internal download : metadata not found %@ ", url);
  509. dispatch_async(dispatch_get_main_queue(), ^{
  510. if ([self.delegate respondsToSelector:@selector(downloadFileFailure:serverUrl:selector:message:errorCode:)])
  511. [self.delegate downloadFileFailure:@"" serverUrl:serverUrl selector:@"" message:@"" errorCode:k_CCErrorInternalError];
  512. });
  513. return;
  514. }
  515. NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)downloadTask.response;
  516. if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {
  517. NSString *destinationFilePath;
  518. if ([CCUtility isCryptoPlistString:fileName]) {
  519. destinationFilePath = [NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryActiveUser:_activeUser activeUrl:_activeUrl], fileName];
  520. } else {
  521. if (metadata.cryptated) destinationFilePath = [NSString stringWithFormat:@"%@/%@.crypt", [CCUtility getDirectoryActiveUser:_activeUser activeUrl:_activeUrl], metadata.fileID];
  522. else destinationFilePath = [NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryActiveUser:_activeUser activeUrl:_activeUrl], metadata.fileID];
  523. }
  524. NSURL *destinationURL = [NSURL fileURLWithPath:destinationFilePath];
  525. [[NSFileManager defaultManager] removeItemAtURL:destinationURL error:NULL];
  526. [[NSFileManager defaultManager] copyItemAtURL:location toURL:destinationURL error:nil];
  527. }
  528. }
  529. - (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
  530. {
  531. #ifndef EXTENSION
  532. [app.listProgressMetadata removeObjectForKey:fileID];
  533. #endif
  534. // Progress Task
  535. NSDictionary* userInfo = @{@"fileID": (fileID), @"serverUrl": (serverUrl), @"cryptated": ([NSNumber numberWithBool:NO]), @"progress": ([NSNumber numberWithFloat:0.0])};
  536. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  537. if (errorCode != 0) {
  538. if (errorCode != kCFURLErrorCancelled) {
  539. if ([CCUtility isCryptoPlistString:fileName]) {
  540. [[NCManageDatabase sharedInstance] setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionSelectorPost:@"" sessionTaskIdentifier:k_taskIdentifierDone sessionTaskIdentifierPlist:k_taskIdentifierDone predicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  541. } else {
  542. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:[NSString stringWithFormat:@"%@", @(errorCode)] sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:k_taskIdentifierError sessionTaskIdentifierPlist:k_taskIdentifierNULL predicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  543. }
  544. }
  545. dispatch_async(dispatch_get_main_queue(), ^{
  546. if ([[self getDelegate:fileID] respondsToSelector:@selector(downloadFileFailure:serverUrl:selector:message:errorCode:)])
  547. [[self getDelegate:fileID] downloadFileFailure:fileID serverUrl:serverUrl selector:selector message:[CCError manageErrorKCF:errorCode withNumberError:YES] errorCode:errorCode];
  548. });
  549. } else {
  550. __block tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  551. if (!metadata) {
  552. [[NCManageDatabase sharedInstance] addActivityClient:fileName fileID:fileID action:k_activityDebugActionUpload selector:@"" note:[NSString stringWithFormat:@"Serius error internal download : metadata not found %@", fileName] type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:_activeUrl];
  553. NSLog(@"[LOG] Serius error internal download : metadata not found %@ ", fileName);
  554. dispatch_async(dispatch_get_main_queue(), ^{
  555. if ([self.delegate respondsToSelector:@selector(downloadFileFailure:serverUrl:selector:message:errorCode:)])
  556. [self.delegate downloadFileFailure:fileID serverUrl:serverUrl selector:selector message:[NSString stringWithFormat:@"Serius error internal download : metadata not found %@", fileName] errorCode:k_CCErrorInternalError];
  557. });
  558. return;
  559. }
  560. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  561. NSInteger sessionTaskIdentifierPlist = metadata.sessionTaskIdentifierPlist;
  562. if ([CCUtility isCryptoString:fileName] || [CCUtility isFileNotCryptated:fileName]) sessionTaskIdentifier = k_taskIdentifierDone;
  563. if ([CCUtility isCryptoPlistString:fileName]) sessionTaskIdentifierPlist = k_taskIdentifierDone;
  564. if (sessionTaskIdentifier == k_taskIdentifierDone && sessionTaskIdentifierPlist == k_taskIdentifierDone) {
  565. metadata.session = @"";
  566. metadata.sessionError = @"";
  567. metadata.sessionSelector = @"";
  568. metadata.sessionSelectorPost = @"";
  569. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  570. metadata.sessionTaskIdentifierPlist = k_taskIdentifierDone;
  571. // Fix Main Thread for insertInformationPlist
  572. if([selector isEqualToString:selectorLoadPlist] || [selector isEqualToString:selectorLoadModelView]) {
  573. dispatch_async(dispatch_get_main_queue(), ^{
  574. if([selector isEqualToString:selectorLoadPlist] || [selector isEqualToString:selectorLoadModelView])
  575. metadata = [CCUtility insertInformationPlist:metadata directoryUser:_directoryUser];
  576. metadata = [[NCManageDatabase sharedInstance] updateMetadata:metadata activeUrl:_activeUrl];
  577. });
  578. } else {
  579. metadata = [[NCManageDatabase sharedInstance] updateMetadata:metadata activeUrl:_activeUrl];
  580. }
  581. } else {
  582. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:nil sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:sessionTaskIdentifier sessionTaskIdentifierPlist:sessionTaskIdentifierPlist predicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  583. }
  584. // DATA
  585. if ([CCUtility isCryptoString:fileName] || [CCUtility isFileNotCryptated:fileName]) {
  586. BOOL error = false;
  587. // if encrypted, rewrite
  588. if (metadata.cryptated == YES)
  589. if ([[CCCrypto sharedManager] decrypt:metadata.fileID fileNameDecrypted:metadata.fileID fileNamePrint:metadata.fileNamePrint password:[[CCCrypto sharedManager] getKeyPasscode:metadata.uuid] directoryUser:_directoryUser] == 0)
  590. error = true;
  591. if (!error) {
  592. [[NCManageDatabase sharedInstance] addLocalFileWithMetadata:metadata];
  593. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  594. [[CCExifGeo sharedInstance] setExifLocalTableEtag:metadata directoryUser:_directoryUser activeAccount:_activeAccount];
  595. // Icon
  596. [CCGraphics createNewImageFrom:metadata.fileID directoryUser:_directoryUser fileNameTo:metadata.fileID fileNamePrint:metadata.fileNamePrint size:@"m" imageForUpload:NO typeFile:metadata.typeFile writePreview:YES optimizedFileName:[CCUtility getOptimizedPhoto]];
  597. // Activity
  598. [[NCManageDatabase sharedInstance] addActivityClient:fileName fileID:metadata.fileID action:k_activityDebugActionDownload selector:metadata.sessionSelector note:serverUrl type:k_activityTypeSuccess verbose:k_activityVerboseDefault activeUrl:_activeUrl];
  599. }
  600. }
  601. dispatch_async(dispatch_get_main_queue(), ^{
  602. if ([[self getDelegate:fileID] respondsToSelector:@selector(downloadFileSuccess:serverUrl:selector:selectorPost:)])
  603. [[self getDelegate:fileID] downloadFileSuccess:fileID serverUrl:serverUrl selector:selector selectorPost:selectorPost];
  604. });
  605. }
  606. }
  607. #pragma --------------------------------------------------------------------------------------------
  608. #pragma mark ===== Upload =====
  609. #pragma --------------------------------------------------------------------------------------------
  610. - (void)uploadFileFromAssetLocalIdentifier:(NSString *)assetLocalIdentifier fileName:(NSString *)fileName serverUrl:(NSString *)serverUrl cryptated:(BOOL)cryptated session:(NSString *)session taskStatus:(NSInteger)taskStatus selector:(NSString *)selector selectorPost:(NSString *)selectorPost errorCode:(NSInteger)errorCode delegate:(id)delegate
  611. {
  612. //delegate
  613. if (delegate == nil)
  614. delegate = self.delegate;
  615. /* +++ OLD
  616. // *** Auto Upload ***
  617. if ([selector isEqualToString:selectorUploadAutoUpload]) {
  618. [self upload:fileName serverUrl:serverUrl cryptated:NO template:NO onlyPlist:NO fileNameTemplate:nil assetLocalIdentifier:assetLocalIdentifier session:session taskStatus:taskStatus selector:selector selectorPost:selectorPost errorCode:errorCode delegate:delegate];
  619. } else {
  620. // *** Auto Upload Full + Manual Upload ***
  621. NCRequestAsset *requestAsset = [NCRequestAsset new];
  622. requestAsset.delegate = self;
  623. [requestAsset writeAssetToSandboxFileName:fileName assetLocalIdentifier:assetLocalIdentifier selector:selector selectorPost:selectorPost errorCode:errorCode metadataNet:nil serverUrl:serverUrl activeUrl:_activeUrl directoryUser:_directoryUser cryptated:cryptated session:session taskStatus:taskStatus delegate:delegate];
  624. }
  625. */
  626. // +++ OLD
  627. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[assetLocalIdentifier] options:nil];
  628. if (!result.count) {
  629. [[NCManageDatabase sharedInstance] addActivityClient:fileName fileID:assetLocalIdentifier action:k_activityDebugActionUpload selector:selector note:@"Internal error image/video not found" type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:_activeUrl];
  630. if ([delegate respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  631. [delegate uploadFileFailure:nil fileID:nil serverUrl:serverUrl selector:selector message:@"Internal error image/video not found" errorCode: k_CCErrorInternalError];
  632. return;
  633. }
  634. PHAsset *assetResult = result[0];
  635. PHAssetMediaType assetMediaType = assetResult.mediaType;
  636. // IMAGE
  637. if (assetMediaType == PHAssetMediaTypeImage) {
  638. @autoreleasepool {
  639. __block PHAsset *asset = result[0];
  640. __block NSError *error = nil;
  641. PHImageRequestOptions *options = [PHImageRequestOptions new];
  642. options.networkAccessAllowed = YES; // iCloud
  643. [[PHImageManager defaultManager] requestImageDataForAsset:asset options:options resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) {
  644. [imageData writeToFile:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileName] options:NSDataWritingAtomic error:&error];
  645. if (error) {
  646. // Delete record on Table Auto Upload
  647. if ([selector isEqualToString:selectorUploadAutoUpload] || [selector isEqualToString:selectorUploadAutoUploadAll])
  648. [[NCManageDatabase sharedInstance] deleteAutoUploadWithAssetLocalIdentifier:assetLocalIdentifier];
  649. // Activity
  650. [[NCManageDatabase sharedInstance] addActivityClient:fileName fileID:assetLocalIdentifier action:k_activityDebugActionUpload selector:selector note:[NSString stringWithFormat:@"%@ [%@]",NSLocalizedString(@"_read_file_error_", nil), error.description] type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:_activeUrl];
  651. // Error for uploadFileFailure
  652. dispatch_async(dispatch_get_main_queue(), ^{
  653. if ([delegate respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  654. [delegate uploadFileFailure:nil fileID:nil serverUrl:serverUrl selector:selector message:[NSString stringWithFormat:@"%@ [%@]",NSLocalizedString(@"_read_file_error_", nil), error.description] errorCode:error.code];
  655. });
  656. } else {
  657. //OK
  658. dispatch_async(dispatch_get_main_queue(), ^{
  659. [self upload:fileName serverUrl:serverUrl cryptated:cryptated template:NO onlyPlist:NO fileNameTemplate:nil assetLocalIdentifier:assetLocalIdentifier session:session taskStatus:taskStatus selector:selector selectorPost:selectorPost errorCode:errorCode delegate:delegate];
  660. });
  661. }
  662. }];
  663. }
  664. }
  665. // VIDEO
  666. if (assetMediaType == PHAssetMediaTypeVideo) {
  667. @autoreleasepool {
  668. __block PHAsset *asset = result[0];
  669. __block NSError *error = nil;
  670. PHVideoRequestOptions *options = [PHVideoRequestOptions new];
  671. options.networkAccessAllowed = YES; // iCloud
  672. [[PHImageManager defaultManager] requestPlayerItemForVideo:asset options:options resultHandler:^(AVPlayerItem * _Nullable playerItem, NSDictionary * _Nullable info) {
  673. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileName]])
  674. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileName] error:nil];
  675. AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:playerItem.asset presetName:AVAssetExportPresetHighestQuality];
  676. if (exportSession) {
  677. exportSession.outputURL = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileName]];
  678. exportSession.outputFileType = AVFileTypeQuickTimeMovie;
  679. [exportSession exportAsynchronouslyWithCompletionHandler:^{
  680. if (AVAssetExportSessionStatusCompleted == exportSession.status) {
  681. // OK
  682. dispatch_async(dispatch_get_main_queue(), ^{
  683. [self upload:fileName serverUrl:serverUrl cryptated:cryptated template:NO onlyPlist:NO fileNameTemplate:nil assetLocalIdentifier:assetLocalIdentifier session:session taskStatus:taskStatus selector:selector selectorPost:selectorPost errorCode:errorCode delegate:delegate];
  684. });
  685. } else if (AVAssetExportSessionStatusFailed == exportSession.status) {
  686. // Delete record on Table Auto Upload
  687. if ([selector isEqualToString:selectorUploadAutoUpload] || [selector isEqualToString:selectorUploadAutoUploadAll])
  688. [[NCManageDatabase sharedInstance] deleteAutoUploadWithAssetLocalIdentifier:assetLocalIdentifier];
  689. // Activity
  690. [[NCManageDatabase sharedInstance] addActivityClient:fileName fileID:assetLocalIdentifier action:k_activityDebugActionUpload selector:selector note:[NSString stringWithFormat:@"%@ [%@]",NSLocalizedString(@"_read_file_error_", nil), error.description] type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:_activeUrl];
  691. // Error for uploadFileFailure
  692. dispatch_async(dispatch_get_main_queue(), ^{
  693. if ([delegate respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  694. [delegate uploadFileFailure:nil fileID:nil serverUrl:serverUrl selector:selector message:[NSString stringWithFormat:@"%@ [%@]",NSLocalizedString(@"_read_file_error_", nil), exportSession.error.description] errorCode:exportSession.error.code];
  695. });
  696. } else {
  697. NSLog(@"Export Session Status: %ld", (long)exportSession.status);
  698. }
  699. }];
  700. } else {
  701. // Delete record on Table Auto Upload
  702. if ([selector isEqualToString:selectorUploadAutoUpload] || [selector isEqualToString:selectorUploadAutoUploadAll])
  703. [[NCManageDatabase sharedInstance] deleteAutoUploadWithAssetLocalIdentifier:assetLocalIdentifier];
  704. // Activity
  705. [[NCManageDatabase sharedInstance] addActivityClient:fileName fileID:assetLocalIdentifier action:k_activityDebugActionUpload selector:selector note:[NSString stringWithFormat:@"%@ [%@]",NSLocalizedString(@"_read_file_error_", nil), error.description] type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:_activeUrl];
  706. // Error for uploadFileFailure
  707. dispatch_async(dispatch_get_main_queue(), ^{
  708. if ([delegate respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  709. [delegate uploadFileFailure:nil fileID:nil serverUrl:serverUrl selector:selector message:[NSString stringWithFormat:@"%@ [%@]",NSLocalizedString(@"_read_file_error_", nil), exportSession.error.description] errorCode:exportSession.error.code];
  710. });
  711. }
  712. }];
  713. }
  714. }
  715. }
  716. - (void)uploadFile:(NSString *)fileName serverUrl:(NSString *)serverUrl cryptated:(BOOL)cryptated onlyPlist:(BOOL)onlyPlist session:(NSString *)session taskStatus:(NSInteger)taskStatus selector:(NSString *)selector selectorPost:(NSString *)selectorPost errorCode:(NSInteger)errorCode delegate:(id)delegate
  717. {
  718. [self upload:fileName serverUrl:serverUrl cryptated:cryptated template:NO onlyPlist:onlyPlist fileNameTemplate:nil assetLocalIdentifier:nil session:session taskStatus:taskStatus selector:selector selectorPost:selectorPost errorCode:errorCode delegate:delegate];
  719. }
  720. - (void)uploadTemplate:(NSString *)fileNamePrint fileNameCrypto:(NSString *)fileNameCrypto serverUrl:(NSString *)serverUrl session:(NSString *)session taskStatus:(NSInteger)taskStatus selector:(NSString *)selector selectorPost:(NSString *)selectorPost errorCode:(NSInteger)errorCode delegate:(id)delegate
  721. {
  722. [self upload:fileNameCrypto serverUrl:serverUrl cryptated:YES template:YES onlyPlist:NO fileNameTemplate:fileNamePrint assetLocalIdentifier:nil session:session taskStatus:taskStatus selector:selector selectorPost:selectorPost errorCode:errorCode delegate:delegate];
  723. }
  724. - (void)upload:(NSString *)fileName serverUrl:(NSString *)serverUrl cryptated:(BOOL)cryptated template:(BOOL)template onlyPlist:(BOOL)onlyPlist fileNameTemplate:(NSString *)fileNameTemplate assetLocalIdentifier:(NSString *)assetLocalIdentifier session:(NSString *)session taskStatus:(NSInteger)taskStatus selector:(NSString *)selector selectorPost:(NSString *)selectorPost errorCode:(NSInteger)errorCode delegate:(id)delegate
  725. {
  726. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  727. NSString *fileNameCrypto;
  728. // create Metadata
  729. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  730. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:_activeUrl];
  731. __block tableMetadata *metadata = [CCUtility insertFileSystemInMetadata:fileName directory:_directoryUser activeAccount:_activeAccount autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory];
  732. //fileID
  733. NSString *uploadID = [k_uploadSessionID stringByAppendingString:[CCUtility createRandomString:16]];
  734. //add delegate
  735. if (delegate)
  736. [_delegates setObject:delegate forKey:uploadID];
  737. if (onlyPlist == YES) {
  738. [CCUtility moveFileAtPath:[NSTemporaryDirectory() stringByAppendingString:fileName] toPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileName]];
  739. metadata = [CCUtility insertInformationPlist:metadata directoryUser:_directoryUser];
  740. metadata.date = [NSDate new];
  741. metadata.fileID = uploadID;
  742. metadata.directoryID = directoryID;
  743. metadata.fileNameData = [CCUtility trasformedFileNamePlistInCrypto:fileName];
  744. metadata.assetLocalIdentifier = assetLocalIdentifier;
  745. metadata.session = session;
  746. metadata.sessionID = uploadID;
  747. metadata.sessionSelector = selector;
  748. metadata.sessionSelectorPost = selectorPost;
  749. metadata.typeFile = k_metadataTypeFile_unknown;
  750. metadata = [[NCManageDatabase sharedInstance] addMetadata:metadata activeUrl:_activeUrl serverUrl:serverUrl];
  751. if (metadata)
  752. [self uploadURLSession:fileName fileNamePrint:metadata.fileNamePrint serverUrl:serverUrl sessionID:uploadID session:metadata.session taskStatus:taskStatus assetLocalIdentifier:assetLocalIdentifier cryptated:cryptated onlyPlist:onlyPlist selector:selector];
  753. }
  754. else if (cryptated == YES) {
  755. if (template == YES) {
  756. // copy from temp to directory user
  757. [CCUtility moveFileAtPath:[NSTemporaryDirectory() stringByAppendingString:fileName] toPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileName]];
  758. [CCUtility moveFileAtPath:[NSTemporaryDirectory() stringByAppendingString:[fileName stringByAppendingString:@".plist"]] toPath:[NSString stringWithFormat:@"%@/%@.plist", _directoryUser, fileName]];
  759. fileNameCrypto = fileName; // file Name Crypto
  760. fileName = fileNameTemplate; // file Name Print
  761. metadata = [CCUtility insertInformationPlist:metadata directoryUser:_directoryUser];
  762. metadata.date = [NSDate new];
  763. metadata.fileID = uploadID;
  764. metadata.directoryID = directoryID;
  765. metadata.fileName = [fileNameCrypto stringByAppendingString:@".plist"];
  766. metadata.fileNameData = fileNameCrypto;
  767. metadata.assetLocalIdentifier = assetLocalIdentifier;
  768. metadata.session = session;
  769. metadata.sessionID = uploadID;
  770. metadata.sessionSelector = selector;
  771. metadata.sessionSelectorPost = selectorPost;
  772. metadata.typeFile = k_metadataTypeFile_template;
  773. metadata = [[NCManageDatabase sharedInstance] addMetadata:metadata activeUrl:_activeUrl serverUrl:serverUrl];
  774. if (metadata) {
  775. // DATA
  776. [self uploadURLSession:fileNameCrypto fileNamePrint:fileName serverUrl:serverUrl sessionID:uploadID session:metadata.session taskStatus:taskStatus assetLocalIdentifier:assetLocalIdentifier cryptated:cryptated onlyPlist:onlyPlist selector:selector];
  777. // PLIST
  778. [self uploadURLSession:[fileNameCrypto stringByAppendingString:@".plist"] fileNamePrint:fileName serverUrl:serverUrl sessionID:uploadID session:metadata.session taskStatus:taskStatus assetLocalIdentifier:assetLocalIdentifier cryptated:cryptated onlyPlist:onlyPlist selector:selector];
  779. }
  780. }
  781. if (template == NO) {
  782. NSString *passcode = [[CCCrypto sharedManager] getKeyPasscode:[CCUtility getUUID]];
  783. fileNameCrypto = [[CCCrypto sharedManager] encryptWithCreatePlist:fileName fileNameEncrypted:fileName passcode:passcode directoryUser:_directoryUser];
  784. // Encrypted file error
  785. if (fileNameCrypto == nil) {
  786. dispatch_async(dispatch_get_main_queue(), ^{
  787. NSString *msg = [NSString stringWithFormat:NSLocalizedString(@"_encrypt_error_", nil), fileName, @""];
  788. UIAlertController *alertController= [UIAlertController alertControllerWithTitle:nil message:msg preferredStyle:UIAlertControllerStyleAlert];
  789. UIAlertAction* ok = [UIAlertAction actionWithTitle: NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault
  790. handler:^(UIAlertAction * action) {
  791. [alertController dismissViewControllerAnimated:YES completion:nil];
  792. }];
  793. [alertController addAction:ok];
  794. UIWindow *alertWindow = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
  795. alertWindow.rootViewController = [[UIViewController alloc]init];
  796. alertWindow.windowLevel = UIWindowLevelAlert + 1;
  797. [alertWindow makeKeyAndVisible];
  798. [alertWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
  799. // Error for uploadFileFailure
  800. if ([[self getDelegate:uploadID] respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  801. [[self getDelegate:uploadID] uploadFileFailure:nil fileID:nil serverUrl:serverUrl selector:selector message:NSLocalizedString(@"_encrypt_error_", nil) errorCode:0];
  802. });
  803. return;
  804. }
  805. metadata.cryptated = YES;
  806. metadata.date = [NSDate new];
  807. metadata.fileID = uploadID;
  808. metadata.directoryID = directoryID;
  809. metadata.fileName = [fileNameCrypto stringByAppendingString:@".plist"];
  810. metadata.fileNameData = fileNameCrypto;
  811. metadata.fileNamePrint = fileName;
  812. metadata.assetLocalIdentifier = assetLocalIdentifier;
  813. metadata.session = session;
  814. metadata.sessionID = uploadID;
  815. metadata.sessionSelector = selector;
  816. metadata.sessionSelectorPost = selectorPost;
  817. metadata.title = [self getTitleFromPlistName:fileNameCrypto];
  818. metadata.type = k_metadataType_file;
  819. #ifndef EXTENSION
  820. [CCGraphics createNewImageFrom:fileName directoryUser:_directoryUser fileNameTo:uploadID fileNamePrint:fileName size:@"m" imageForUpload:YES typeFile:metadata.typeFile writePreview:YES optimizedFileName:NO];
  821. #endif
  822. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])
  823. [[CCCrypto sharedManager] addPlistImage:[NSString stringWithFormat:@"%@/%@", _directoryUser, [fileNameCrypto stringByAppendingString:@".plist"]] fileNamePathImage:[NSTemporaryDirectory() stringByAppendingString:uploadID]];
  824. metadata = [[NCManageDatabase sharedInstance] addMetadata:metadata activeUrl:_activeUrl serverUrl:serverUrl];
  825. if (metadata) {
  826. // DATA
  827. [self uploadURLSession:fileNameCrypto fileNamePrint:fileName serverUrl:serverUrl sessionID:uploadID session:metadata.session taskStatus:taskStatus assetLocalIdentifier:assetLocalIdentifier cryptated:cryptated onlyPlist:onlyPlist selector:selector];
  828. // PLIST
  829. [self uploadURLSession:[fileNameCrypto stringByAppendingString:@".plist"] fileNamePrint:fileName serverUrl:serverUrl sessionID:uploadID session:metadata.session taskStatus:taskStatus assetLocalIdentifier:assetLocalIdentifier cryptated:cryptated onlyPlist:onlyPlist selector:selector];
  830. }
  831. }
  832. }
  833. else if (cryptated == NO) {
  834. metadata.cryptated = NO;
  835. metadata.date = [NSDate new];
  836. metadata.fileID = uploadID;
  837. metadata.directoryID = directoryID;
  838. metadata.fileName = fileName;
  839. metadata.fileNameData = fileName;
  840. metadata.fileNamePrint = fileName;
  841. metadata.assetLocalIdentifier = assetLocalIdentifier;
  842. metadata.session = session;
  843. metadata.sessionID = uploadID;
  844. metadata.sessionSelector = selector;
  845. metadata.sessionSelectorPost = selectorPost;
  846. metadata.type = k_metadataType_file;
  847. // File exists ???
  848. if (errorCode == 403) {
  849. dispatch_async(dispatch_get_main_queue(), ^{
  850. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:fileName message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  851. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  852. // Activity
  853. [[NCManageDatabase sharedInstance] addActivityClient:fileName fileID:uploadID action:k_activityDebugActionUpload selector:selector note:NSLocalizedString(@"_file_already_exists_", nil) type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:_activeUrl];
  854. // Error for uploadFileFailure
  855. if ([[self getDelegate:uploadID] respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  856. [[self getDelegate:uploadID] uploadFileFailure:nil fileID:nil serverUrl:serverUrl selector:selector message:NSLocalizedString(@"_file_already_exists_", nil) errorCode:403];
  857. return;
  858. }];
  859. UIAlertAction *overwriteAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_overwrite_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  860. // -- remove record --
  861. tableMetadata *metadataDelete = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND fileName = %@ AND directoryID = %@", _activeAccount, fileName, directoryID]];
  862. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadataDelete.fileID] error:nil];
  863. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.ico", _directoryUser, metadataDelete.fileID] error:nil];
  864. if (metadataDelete.directory && serverUrl) {
  865. NSString *dirForDelete = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadataDelete.fileNameData];
  866. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:dirForDelete];
  867. }
  868. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataDelete.fileID] clearDateReadDirectoryID:nil];
  869. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataDelete.fileID]];
  870. // -- Go to Upload --
  871. [CCGraphics createNewImageFrom:metadata.fileNamePrint directoryUser:_directoryUser fileNameTo:metadata.fileID fileNamePrint:metadata.fileNamePrint size:@"m" imageForUpload:YES typeFile:metadata.typeFile writePreview:YES optimizedFileName:NO];
  872. metadata = [[NCManageDatabase sharedInstance] addMetadata:metadata activeUrl:_activeUrl serverUrl:serverUrl];
  873. if (metadata) {
  874. [self uploadURLSession:fileName fileNamePrint:fileName serverUrl:serverUrl sessionID:uploadID session:metadata.session taskStatus:taskStatus assetLocalIdentifier:assetLocalIdentifier cryptated:cryptated onlyPlist:onlyPlist selector:selector];
  875. }
  876. }];
  877. [alertController addAction:cancelAction];
  878. [alertController addAction:overwriteAction];
  879. UIWindow *alertWindow = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
  880. alertWindow.rootViewController = [[UIViewController alloc] init];
  881. alertWindow.windowLevel = UIWindowLevelAlert + 1;
  882. [alertWindow makeKeyAndVisible];
  883. [alertWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
  884. });
  885. } else {
  886. // -- Go to upload --
  887. #ifndef EXTENSION
  888. [CCGraphics createNewImageFrom:metadata.fileNamePrint directoryUser:_directoryUser fileNameTo:metadata.fileID fileNamePrint:metadata.fileNamePrint size:@"m" imageForUpload:YES typeFile:metadata.typeFile writePreview:YES optimizedFileName:NO];
  889. #endif
  890. metadata = [[NCManageDatabase sharedInstance] addMetadata:metadata activeUrl:_activeUrl serverUrl:serverUrl];
  891. if (metadata) {
  892. [self uploadURLSession:fileName fileNamePrint:fileName serverUrl:serverUrl sessionID:uploadID session:metadata.session taskStatus:taskStatus assetLocalIdentifier:assetLocalIdentifier cryptated:cryptated onlyPlist:onlyPlist selector:selector];
  893. }
  894. }
  895. }
  896. }
  897. - (void)uploadFileMetadata:(tableMetadata *)metadata taskStatus:(NSInteger)taskStatus
  898. {
  899. BOOL send = NO;
  900. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  901. if (metadata.cryptated) {
  902. // ENCRYPTED
  903. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.fileNameData]] && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.fileName]]) {
  904. send = YES;
  905. [self uploadURLSession:metadata.fileNameData fileNamePrint:metadata.fileNamePrint serverUrl:serverUrl sessionID:metadata.sessionID session:metadata.session taskStatus:taskStatus assetLocalIdentifier:nil cryptated:YES onlyPlist:NO selector:metadata.sessionSelector];
  906. [self uploadURLSession:metadata.fileName fileNamePrint:metadata.fileNamePrint serverUrl:serverUrl sessionID:metadata.sessionID session:metadata.session taskStatus:taskStatus assetLocalIdentifier:nil cryptated:YES onlyPlist:NO selector:metadata.sessionSelector];
  907. }
  908. } else {
  909. // PLAIN
  910. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.sessionID]]) {
  911. send = YES;
  912. [self uploadURLSession:metadata.fileName fileNamePrint:metadata.fileNamePrint serverUrl:serverUrl sessionID:metadata.sessionID session:metadata.session taskStatus:taskStatus assetLocalIdentifier:nil cryptated:NO onlyPlist:NO selector:metadata.sessionSelector];
  913. }
  914. }
  915. if (send) {
  916. NSLog(@"[LOG] Re-upload File : %@ - fileID : %@", metadata.fileNamePrint, metadata.fileID);
  917. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:@"" sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:k_taskIdentifierNULL sessionTaskIdentifierPlist:k_taskIdentifierNULL predicate:[NSPredicate predicateWithFormat:@"sessionID = %@ AND account = %@", metadata.sessionID, _activeAccount]];
  918. } else {
  919. NSLog(@"[LOG] Error reUploadBackground, file not found.");
  920. #ifndef EXTENSION
  921. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_no_reuploadfile_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  922. [alertView show];
  923. #endif
  924. }
  925. }
  926. - (void)uploadURLSession:(NSString *)fileName fileNamePrint:(NSString *)fileNamePrint serverUrl:(NSString *)serverUrl sessionID:(NSString*)sessionID session:(NSString *)session taskStatus:(NSInteger)taskStatus assetLocalIdentifier:(NSString *)assetLocalIdentifier cryptated:(BOOL)cryptated onlyPlist:(BOOL)onlyPlist selector:(NSString *)selector
  927. {
  928. NSURLSession *sessionUpload;
  929. NSURL *url;
  930. NSMutableURLRequest *request;
  931. NSString *fileNamePath = [[NSString stringWithFormat:@"%@/%@", serverUrl, fileName] encodeString:NSUTF8StringEncoding];
  932. url = [NSURL URLWithString:fileNamePath];
  933. request = [NSMutableURLRequest requestWithURL:url];
  934. NSData *authData = [[NSString stringWithFormat:@"%@:%@", _activeUser, _activePassword] dataUsingEncoding:NSUTF8StringEncoding];
  935. NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];
  936. [request setHTTPMethod:@"PUT"];
  937. [request setValue:authValue forHTTPHeaderField:@"Authorization"];
  938. // Rename with the SessionID
  939. NSString *fileNameForUpload;
  940. if ([CCUtility isFileNotCryptated:fileName]) fileNameForUpload = sessionID;
  941. else fileNameForUpload = fileName;
  942. if (!onlyPlist) {
  943. if ([CCUtility isFileNotCryptated:fileName])
  944. [[NSFileManager defaultManager] moveItemAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileName] toPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileNameForUpload] error:nil];
  945. if ([CCUtility isCryptoPlistString:fileName])
  946. [[NSFileManager defaultManager] moveItemAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileNamePrint] toPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, sessionID] error:nil];
  947. }
  948. // file NOT exists
  949. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileNameForUpload]] == NO) {
  950. // Activity
  951. [[NCManageDatabase sharedInstance] addActivityClient:fileName fileID:sessionID action:k_activityDebugActionUpload selector:selector note:NSLocalizedString(@"_file_not_present_", nil) type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:_activeUrl];
  952. // Delete record : Metadata
  953. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"sessionID = %@ AND account = %@", sessionID, _activeAccount] clearDateReadDirectoryID:nil];
  954. // Delete record : Table Auto Upload
  955. if ([selector isEqualToString:selectorUploadAutoUpload] || [selector isEqualToString:selectorUploadAutoUploadAll])
  956. [[NCManageDatabase sharedInstance] deleteAutoUploadWithAssetLocalIdentifier:assetLocalIdentifier];
  957. dispatch_async(dispatch_get_main_queue(), ^{
  958. // Error for uploadFileFailure
  959. if ([[self getDelegate:sessionID] respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  960. [[self getDelegate:sessionID] uploadFileFailure:nil fileID:sessionID serverUrl:serverUrl selector:selector message:NSLocalizedString(@"_file_not_present_", nil) errorCode:404];
  961. });
  962. return;
  963. }
  964. if ([session isEqualToString:k_upload_session]) sessionUpload = [self sessionUpload];
  965. else if ([session isEqualToString:k_upload_session_foreground]) sessionUpload = [self sessionUploadForeground];
  966. else if ([session isEqualToString:k_upload_session_wwan]) sessionUpload = [self sessionWWanUpload];
  967. NSURLSessionUploadTask *uploadTask = [sessionUpload uploadTaskWithRequest:request fromFile:[NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileNameForUpload]]];
  968. if (uploadTask == nil) {
  969. NSUInteger sessionTaskIdentifier = k_taskIdentifierNULL;
  970. NSUInteger sessionTaskIdentifierPlist = k_taskIdentifierNULL;
  971. if ([CCUtility isFileNotCryptated:fileName] || [CCUtility isCryptoString:fileName]) sessionTaskIdentifier = k_taskIdentifierError;
  972. if ([CCUtility isCryptoPlistString:fileName]) sessionTaskIdentifierPlist = k_taskIdentifierError;
  973. [[NCManageDatabase sharedInstance] setMetadataSession:session sessionError:[NSString stringWithFormat:@"%@", @k_CCErrorTaskNil] sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:sessionTaskIdentifier sessionTaskIdentifierPlist:sessionTaskIdentifierPlist predicate:[NSPredicate predicateWithFormat:@"sessionID = %@ AND account = %@", sessionID, _activeAccount]];
  974. NSLog(@"[LOG] Upload file TaskIdentifier [error CCErrorTaskNil] - %@ - %@", fileName, fileNamePrint);
  975. } else {
  976. NSUInteger sessionTaskIdentifier = k_taskIdentifierNULL;
  977. NSUInteger sessionTaskIdentifierPlist = k_taskIdentifierNULL;
  978. if ([CCUtility isCryptoString:fileName] || [CCUtility isFileNotCryptated:fileName]) sessionTaskIdentifier = uploadTask.taskIdentifier;
  979. if ([CCUtility isCryptoPlistString:fileName]) sessionTaskIdentifierPlist = uploadTask.taskIdentifier;
  980. [[NCManageDatabase sharedInstance] setMetadataSession:session sessionError:@"" sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:sessionTaskIdentifier sessionTaskIdentifierPlist:sessionTaskIdentifierPlist predicate:[NSPredicate predicateWithFormat:@"sessionID = %@ AND account = %@", sessionID, _activeAccount]];
  981. // Delete record on Table Auto Upload
  982. if ([selector isEqualToString:selectorUploadAutoUpload] || [selector isEqualToString:selectorUploadAutoUploadAll])
  983. [[NCManageDatabase sharedInstance] deleteAutoUploadWithAssetLocalIdentifier:assetLocalIdentifier];
  984. // Manage uploadTask cancel,suspend,resume
  985. if (taskStatus == k_taskStatusCancel) [uploadTask cancel];
  986. else if (taskStatus == k_taskStatusSuspend) [uploadTask suspend];
  987. else if (taskStatus == k_taskStatusResume) [uploadTask resume];
  988. NSLog(@"[LOG] Upload file %@ - %@ TaskIdentifier %lu", fileName,fileNamePrint, (unsigned long)uploadTask.taskIdentifier);
  989. }
  990. dispatch_async(dispatch_get_main_queue(), ^{
  991. // refresh main
  992. if ([self.delegate respondsToSelector:@selector(reloadDatasource:)])
  993. [self.delegate reloadDatasource:serverUrl];
  994. #ifndef EXTENSION
  995. [app updateApplicationIconBadgeNumber];
  996. #endif
  997. });
  998. }
  999. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
  1000. {
  1001. NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)dataTask.response;
  1002. if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {
  1003. NSNumber *taskIdentifier = [NSNumber numberWithLong:dataTask.taskIdentifier];
  1004. if (data)
  1005. [_taskData setObject:[data copy] forKey:taskIdentifier];
  1006. }
  1007. }
  1008. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
  1009. {
  1010. NSString *url = [[[task currentRequest].URL absoluteString] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  1011. NSString *fileName = [url lastPathComponent];
  1012. NSString *serverUrl = [self getServerUrlFromUrl:url];
  1013. // if plist return
  1014. if ([CCUtility getTypeFileName:fileName] == k_metadataTypeFilenamePlist)
  1015. return;
  1016. float progress = (float) totalBytesSent / (float)totalBytesExpectedToSend;
  1017. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataFromFileName:fileName directoryID:[[NCManageDatabase sharedInstance] getDirectoryID:serverUrl]];
  1018. if (metadata) {
  1019. NSDictionary* userInfo = @{@"fileID": (metadata.fileID), @"serverUrl": (serverUrl), @"cryptated": ([NSNumber numberWithBool:metadata.cryptated]), @"progress": ([NSNumber numberWithFloat:progress])};
  1020. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  1021. }
  1022. }
  1023. - (void)uploadFileSuccessFailure:(tableMetadata *)metadata fileName:(NSString *)fileName fileID:(NSString *)fileID etag:(NSString *)etag date:(NSDate *)date serverUrl:(NSString *)serverUrl errorCode:(NSInteger)errorCode
  1024. {
  1025. NSString *sessionID = metadata.sessionID;
  1026. // Progress Task
  1027. NSDictionary* userInfo = @{@"fileID": (fileID), @"serverUrl": (serverUrl), @"cryptated": ([NSNumber numberWithBool:NO]), @"progress": ([NSNumber numberWithFloat:0.0])};
  1028. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  1029. // ERRORE
  1030. if (errorCode != 0) {
  1031. #ifndef EXTENSION
  1032. [app.listProgressMetadata removeObjectForKey:sessionID];
  1033. #endif
  1034. // Mark error only if not Cancelled Task
  1035. if (errorCode != kCFURLErrorCancelled) {
  1036. NSUInteger sessionTaskIdentifier = k_taskIdentifierNULL;
  1037. NSUInteger sessionTaskIdentifierPlist = k_taskIdentifierNULL;
  1038. if ([CCUtility isFileNotCryptated:fileName] || [CCUtility isCryptoString:fileName]) sessionTaskIdentifier = k_taskIdentifierError;
  1039. if ([CCUtility isCryptoPlistString:fileName]) sessionTaskIdentifierPlist = k_taskIdentifierError;
  1040. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:[NSString stringWithFormat:@"%@", @(errorCode)] sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:sessionTaskIdentifier sessionTaskIdentifierPlist:sessionTaskIdentifierPlist predicate:[NSPredicate predicateWithFormat:@"sessionID = %@ AND account = %@", metadata.sessionID, _activeAccount]];
  1041. }
  1042. dispatch_async(dispatch_get_main_queue(), ^{
  1043. if ([[self getDelegate:sessionID] respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  1044. [[self getDelegate:sessionID] uploadFileFailure:nil fileID:fileID serverUrl:serverUrl selector:metadata.sessionSelector message:[CCError manageErrorKCF:errorCode withNumberError:YES] errorCode:errorCode];
  1045. });
  1046. return;
  1047. }
  1048. // PLAIN or PLIST
  1049. if ([CCUtility isFileNotCryptated:fileName] || [CCUtility isCryptoPlistString:fileName]) {
  1050. // copy ico in new fileID
  1051. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@.ico", _directoryUser, sessionID] toPath:[NSString stringWithFormat:@"%@/%@.ico", _directoryUser, fileID]];
  1052. metadata.fileID = fileID;
  1053. metadata.etag = etag;
  1054. metadata.date = date;
  1055. metadata.sessionTaskIdentifierPlist = k_taskIdentifierDone;
  1056. if ([CCUtility isFileNotCryptated:fileName])
  1057. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  1058. // Add new metadata
  1059. metadata = [[NCManageDatabase sharedInstance] addMetadata:metadata activeUrl:_activeUrl serverUrl:serverUrl];
  1060. if (!metadata) {
  1061. dispatch_async(dispatch_get_main_queue(), ^{
  1062. if ([[self getDelegate:sessionID] respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  1063. [[self getDelegate:sessionID] uploadFileFailure:nil fileID:fileID serverUrl:serverUrl selector:@"" message:[NSString stringWithFormat:@"Serius error internal download : metadata not found %@", fileName] errorCode:k_CCErrorInternalError];
  1064. });
  1065. return;
  1066. }
  1067. // Delete old ID_UPLOAD_XXXXX metadata
  1068. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", sessionID] clearDateReadDirectoryID:nil];
  1069. }
  1070. // CRYPTO
  1071. if ([CCUtility isCryptoString:fileName]) {
  1072. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  1073. metadata = [[NCManageDatabase sharedInstance] updateMetadata:metadata activeUrl:_activeUrl];
  1074. }
  1075. // ALL TASK DONE (PLAIN/CRYPTO)
  1076. if (metadata.sessionTaskIdentifier == k_taskIdentifierDone && metadata.sessionTaskIdentifierPlist == k_taskIdentifierDone) {
  1077. #ifndef EXTENSION
  1078. [app.listProgressMetadata removeObjectForKey:sessionID];
  1079. #endif
  1080. NSLog(@"[LOG] Insert new upload : %@ - FileNamePrint : %@ - fileID : %@", metadata.fileName, metadata.fileNamePrint, metadata.fileID);
  1081. metadata.session = @"";
  1082. metadata.sessionError = @"";
  1083. metadata.sessionID = @"";
  1084. metadata = [[NCManageDatabase sharedInstance] updateMetadata:metadata activeUrl:_activeUrl];
  1085. // rename file sessionID -> fileID
  1086. [CCUtility moveFileAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, sessionID] toPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.fileID]];
  1087. // remove temp icon
  1088. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.ico", _directoryUser, sessionID] error:nil];
  1089. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.ico", _directoryUser, metadata.fileID] error:nil];
  1090. // if crypto remove filename data
  1091. if (metadata.cryptated)
  1092. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.fileNameData] error:nil];
  1093. // Local
  1094. if (metadata.directory == NO)
  1095. [[NCManageDatabase sharedInstance] addLocalFileWithMetadata:metadata];
  1096. // EXIF
  1097. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  1098. [[CCExifGeo sharedInstance] setExifLocalTableEtag:metadata directoryUser:_directoryUser activeAccount:_activeAccount];
  1099. // Create ICON
  1100. if (metadata.directory == NO)
  1101. [CCGraphics createNewImageFrom:metadata.fileID directoryUser:_directoryUser fileNameTo:metadata.fileID fileNamePrint:metadata.fileNamePrint size:@"m" imageForUpload:NO typeFile:metadata.typeFile writePreview:YES optimizedFileName:[CCUtility getOptimizedPhoto]];
  1102. // Optimization
  1103. if ([CCUtility getUploadAndRemovePhoto] || [metadata.sessionSelectorPost isEqualToString:selectorUploadRemovePhoto])
  1104. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.fileID] error:nil];
  1105. // Copy photo or video in the photo album for auto upload
  1106. if ([metadata.assetLocalIdentifier length] > 0 && [metadata.sessionSelector isEqualToString:selectorUploadAutoUpload]) {
  1107. PHAsset *asset;
  1108. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadata.assetLocalIdentifier] options:nil];
  1109. if(result.count){
  1110. asset = result[0];
  1111. [asset saveToAlbum:[NCBrandOptions sharedInstance].brand completionBlock:^(BOOL success) {
  1112. if (success) NSLog(@"[LOG] Insert file %@ in %@", metadata.fileNamePrint, [NCBrandOptions sharedInstance].brand);
  1113. else NSLog(@"[LOG] File %@ do not insert in %@", metadata.fileNamePrint, [NCBrandOptions sharedInstance].brand);
  1114. }];
  1115. }
  1116. }
  1117. // Actvity
  1118. [[NCManageDatabase sharedInstance] addActivityClient:fileName fileID:fileID action:k_activityDebugActionUpload selector:metadata.sessionSelector note:serverUrl type:k_activityTypeSuccess verbose:k_activityVerboseDefault activeUrl:_activeUrl];
  1119. dispatch_async(dispatch_get_main_queue(), ^{
  1120. if ([[self getDelegate:sessionID] respondsToSelector:@selector(uploadFileSuccess:fileID:serverUrl:selector:selectorPost:)])
  1121. [[self getDelegate:sessionID] uploadFileSuccess:nil fileID:metadata.fileID serverUrl:serverUrl selector:metadata.sessionSelector selectorPost:metadata.sessionSelectorPost];
  1122. });
  1123. }
  1124. }
  1125. #pragma --------------------------------------------------------------------------------------------
  1126. #pragma mark ===== Download Verify =====
  1127. #pragma --------------------------------------------------------------------------------------------
  1128. - (void)verifyDownloadInProgress
  1129. {
  1130. NSArray *dataSourceDownload = [[NCManageDatabase sharedInstance] getTableMetadataDownload];
  1131. NSArray *dataSourceDownloadWWan = [[NCManageDatabase sharedInstance] getTableMetadataDownloadWWan];
  1132. NSMutableArray *dataSource = [[NSMutableArray alloc] init];
  1133. [dataSource addObjectsFromArray:dataSourceDownload];
  1134. [dataSource addObjectsFromArray:dataSourceDownloadWWan];
  1135. NSLog(@"[LOG] Verify download file in progress n. %lu", (unsigned long)[dataSource count]);
  1136. for (tableMetadata *metadata in dataSource) {
  1137. NSURLSession *session = [self getSessionfromSessionDescription:metadata.session];
  1138. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1139. dispatch_async(dispatch_get_main_queue(), ^{
  1140. BOOL findTask = NO;
  1141. BOOL findTaskPlist = NO;
  1142. for (NSURLSessionDownloadTask *downloadTask in downloadTasks) {
  1143. NSLog(@"[LOG] Find metadata Tasks [%li %li] = [%lu] state : %lu", (long)metadata.sessionTaskIdentifier, (long)metadata.sessionTaskIdentifierPlist ,(unsigned long)downloadTask.taskIdentifier, (unsigned long)[downloadTask state]);
  1144. if (metadata.sessionTaskIdentifier == downloadTask.taskIdentifier) findTask = YES;
  1145. if (metadata.sessionTaskIdentifierPlist == downloadTask.taskIdentifier) findTaskPlist = YES;
  1146. if (findTask == YES || findTaskPlist == YES) break; // trovati, download ancora in corso
  1147. }
  1148. // DATA
  1149. if (findTask == NO && metadata.sessionTaskIdentifier >= 0) {
  1150. NSLog(@"[LOG] NOT Find metadata Task [%li] fileID : %@ - filename : %@", (long)metadata.sessionTaskIdentifier, metadata.fileID, metadata.fileNameData);
  1151. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:[NSString stringWithFormat:@"%@", @k_CCErrorTaskDownloadNotFound] sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:k_taskIdentifierError sessionTaskIdentifierPlist:k_taskIdentifierNULL predicate:[NSPredicate predicateWithFormat:@"fileID = %@ ", metadata.fileID]];
  1152. dispatch_async(dispatch_get_main_queue(), ^{
  1153. if ([self.delegate respondsToSelector:@selector(reloadDatasource:)])
  1154. [self.delegate reloadDatasource:[[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID]];
  1155. });
  1156. }
  1157. // PLIST
  1158. if (findTaskPlist == NO && metadata.sessionTaskIdentifierPlist >= 0) {
  1159. NSLog(@"[LOG] NOT Find metadata TaskPlist [%li] fileID : %@ - filename : %@", (long)metadata.sessionTaskIdentifierPlist, metadata.fileID, metadata.fileName);
  1160. [[NCManageDatabase sharedInstance] setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionSelectorPost:@"" sessionTaskIdentifier:k_taskIdentifierNULL sessionTaskIdentifierPlist:k_taskIdentifierDone predicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  1161. dispatch_async(dispatch_get_main_queue(), ^{
  1162. if ([self.delegate respondsToSelector:@selector(reloadDatasource:)])
  1163. [self.delegate reloadDatasource:[[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID]];
  1164. });
  1165. }
  1166. });
  1167. }];
  1168. }
  1169. /* Verify Upload In Error */
  1170. NSMutableSet *serversUrl = [NSMutableSet new];
  1171. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND session CONTAINS 'download' AND (sessionTaskIdentifier = %i OR sessionTaskIdentifierPlist = %i)", _activeAccount, k_taskIdentifierError, k_taskIdentifierError] sorted:nil ascending:NO];
  1172. NSLog(@"[LOG] Verify re download n. %lu", (unsigned long)[metadatas count]);
  1173. for (tableMetadata *metadata in metadatas) {
  1174. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1175. if (metadata.sessionTaskIdentifier == k_taskIdentifierError)
  1176. [self downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:metadata.sessionSelector selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:nil];
  1177. if (metadata.sessionTaskIdentifierPlist == k_taskIdentifierError)
  1178. [self downloadFile:metadata.fileID serverUrl:serverUrl downloadData:NO downloadPlist:YES selector:metadata.sessionSelector selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:nil];
  1179. [serversUrl addObject:serverUrl];
  1180. NSLog(@"[LOG] Re download file : %@ - %@ [%li %li]", metadata.fileName, metadata.fileNamePrint, (long)metadata.sessionTaskIdentifier, (long)metadata.sessionTaskIdentifierPlist);
  1181. }
  1182. dispatch_async(dispatch_get_main_queue(), ^{
  1183. for (NSString *serverUrl in serversUrl)
  1184. if ([self.delegate respondsToSelector:@selector(reloadDatasource:)])
  1185. [self.delegate reloadDatasource:serverUrl];
  1186. });
  1187. }
  1188. #pragma --------------------------------------------------------------------------------------------
  1189. #pragma mark ===== Upload Verify =====
  1190. #pragma --------------------------------------------------------------------------------------------
  1191. - (void)verifyUploadInProgress
  1192. {
  1193. NSArray *dataSourceUpload = [[NCManageDatabase sharedInstance] getTableMetadataUpload];
  1194. NSArray *dataSourceUploadWWan = [[NCManageDatabase sharedInstance] getTableMetadataUploadWWan];
  1195. NSMutableArray *dataSource = [[NSMutableArray alloc] init];
  1196. [dataSource addObjectsFromArray:dataSourceUpload];
  1197. [dataSource addObjectsFromArray:dataSourceUploadWWan];
  1198. NSLog(@"[LOG] Verify upload file in progress n. %lu", (unsigned long)[dataSource count]);
  1199. for (tableMetadata *metadata in dataSource) {
  1200. __block NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1201. NSURLSession *session = [self getSessionfromSessionDescription:metadata.session];
  1202. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1203. BOOL findTask = NO;
  1204. BOOL findTaskPlist = NO;
  1205. // cerchiamo la corrispondenza dei task
  1206. for (NSURLSessionUploadTask *uploadTask in uploadTasks) {
  1207. NSLog(@"[LOG] Find metadata Tasks [%li %li] = [%lu] state : %lu", (long)metadata.sessionTaskIdentifier, (long)metadata.sessionTaskIdentifierPlist , (unsigned long)uploadTask.taskIdentifier, (unsigned long)[uploadTask state]);
  1208. if (metadata.sessionTaskIdentifier == uploadTask.taskIdentifier) findTask = YES;
  1209. if (metadata.sessionTaskIdentifierPlist == uploadTask.taskIdentifier) findTaskPlist = YES;
  1210. if (findTask == YES || findTaskPlist == YES) break;
  1211. }
  1212. // se non c'è (ci sono) il relativo uploadTask.taskIdentifier allora chiediamolo
  1213. if ((metadata.cryptated == YES && findTask == NO && findTaskPlist == NO) || (metadata.cryptated == NO && findTask == NO)) {
  1214. NSLog(@"[LOG] Call ReadFileVerifyUpload because this file %@ (criptated %i) is in progress but there is no task : [%li %li]", metadata.fileNamePrint, metadata.cryptated, (long)metadata.sessionTaskIdentifier, (long)metadata.sessionTaskIdentifierPlist);
  1215. if (metadata.sessionTaskIdentifier >= 0) [self readFileVerifyUpload:metadata.fileNameData fileNamePrint:metadata.fileNamePrint serverUrl:serverUrl];
  1216. if (metadata.sessionTaskIdentifierPlist >= 0) [self readFileVerifyUpload:metadata.fileName fileNamePrint:metadata.fileNamePrint serverUrl:serverUrl];
  1217. }
  1218. }];
  1219. // Notification change session
  1220. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, nil];
  1221. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1222. }
  1223. /* Verify Upload In Error */
  1224. NSMutableSet *directoryIDs = [NSMutableSet new];
  1225. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND session CONTAINS 'upload' AND (sessionTaskIdentifier = %i OR sessionTaskIdentifierPlist = %i)", _activeAccount, k_taskIdentifierError, k_taskIdentifierError] sorted:nil ascending:NO];
  1226. NSLog(@"[LOG] Verify re upload n. %lu", (unsigned long)[metadatas count]);
  1227. for (tableMetadata *metadata in metadatas) {
  1228. [self uploadFileMetadata:metadata taskStatus: k_taskStatusResume];
  1229. [directoryIDs addObject:metadata.directoryID];
  1230. NSLog(@"[LOG] Re upload file : %@", metadata.fileName);
  1231. }
  1232. dispatch_async(dispatch_get_main_queue(), ^{
  1233. for (NSString *directoryID in directoryIDs)
  1234. if ([self.delegate respondsToSelector:@selector(reloadDatasource:)])
  1235. [self.delegate reloadDatasource:[[NCManageDatabase sharedInstance] getServerUrl:directoryID]];
  1236. });
  1237. }
  1238. - (void)readFileVerifyUpload:(NSString *)fileName fileNamePrint:(NSString *)fileNamePrint serverUrl:(NSString *)serverUrl
  1239. {
  1240. #ifndef EXTENSION
  1241. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:_activeAccount];
  1242. metadataNet.action = actionReadFile;
  1243. metadataNet.fileName = fileName;
  1244. metadataNet.fileNamePrint = fileNamePrint;
  1245. metadataNet.serverUrl = serverUrl;
  1246. metadataNet.selector = selectorReadFileVerifyUpload;
  1247. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1248. #else
  1249. NSLog(@"[LOG] Function not available for extension.");
  1250. #endif
  1251. }
  1252. //
  1253. // File exists : selectorReadFileVerifyUpload
  1254. //
  1255. - (void)readFileSuccess:(CCMetadataNet *)metadataNet metadata:(tableMetadata *)metadata
  1256. {
  1257. NSString *fileName;
  1258. if ([CCUtility isCryptoString:metadata.fileName])
  1259. fileName = [metadata.fileName stringByAppendingString:@".plist"];
  1260. else
  1261. fileName = metadataNet.fileName;
  1262. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:metadataNet.serverUrl];
  1263. tableMetadata *metadataTemp = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileName = %@ AND directoryID = %@ AND account = %@", fileName , directoryID, _activeAccount]];
  1264. // is completed ?
  1265. if (metadataTemp.sessionTaskIdentifier == k_taskIdentifierDone && metadataTemp.sessionTaskIdentifierPlist == k_taskIdentifierDone) {
  1266. [CCGraphics createNewImageFrom:metadata.fileID directoryUser:_directoryUser fileNameTo:metadata.fileID fileNamePrint:metadata.fileNamePrint size:@"m" imageForUpload:NO typeFile:metadata.typeFile writePreview:YES optimizedFileName:[CCUtility getOptimizedPhoto]];
  1267. NSLog(@"[LOG] Verify read file success, but files already processed");
  1268. dispatch_async(dispatch_get_main_queue(), ^{
  1269. if ([self.delegate respondsToSelector:@selector(reloadDatasource:)])
  1270. [self.delegate reloadDatasource:[[NCManageDatabase sharedInstance] getServerUrl:directoryID]];
  1271. });
  1272. } else {
  1273. [self uploadFileSuccessFailure:metadataTemp fileName:metadataNet.fileName fileID:metadata.fileID etag:metadata.etag date:metadata.date serverUrl:metadataNet.serverUrl errorCode:0];
  1274. }
  1275. }
  1276. //
  1277. // File do not exists : selectorReadFileVerifyUpload
  1278. //
  1279. - (void)readFileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1280. {
  1281. NSString *fileName;
  1282. if ([CCUtility isCryptoString:metadataNet.fileName])
  1283. fileName = [metadataNet.fileName stringByAppendingString:@".plist"];
  1284. else
  1285. fileName = metadataNet.fileName;
  1286. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:metadataNet.serverUrl];
  1287. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileName = %@ AND directoryID = %@ AND account = %@",fileName , directoryID, _activeAccount]];
  1288. NSInteger error;
  1289. if (errorCode == kOCErrorServerPathNotFound)
  1290. error = k_CCErrorFileUploadNotFound;
  1291. else
  1292. error = errorCode;
  1293. // fix CCNetworking.m line 1340 2.17.2 (00005)
  1294. if (metadata)
  1295. [self uploadFileSuccessFailure:metadata fileName:metadataNet.fileName fileID:metadata.fileID etag:metadata.etag date:metadata.date serverUrl:metadataNet.serverUrl errorCode:error];
  1296. }
  1297. #pragma --------------------------------------------------------------------------------------------
  1298. #pragma mark ===== Utility =====
  1299. #pragma --------------------------------------------------------------------------------------------
  1300. - (id)getDelegate:(NSString *)fileID
  1301. {
  1302. id delegate = [_delegates objectForKey:fileID];
  1303. if (delegate)
  1304. return delegate;
  1305. else
  1306. return self.delegate;
  1307. }
  1308. - (NSString *)getServerUrlFromUrl:(NSString *)url
  1309. {
  1310. NSString *fileName = [url lastPathComponent];
  1311. url = [url stringByReplacingOccurrencesOfString:[@"/" stringByAppendingString:fileName] withString:@""];
  1312. return url;
  1313. }
  1314. - (NSString *)getTitleFromPlistName:(NSString *)fileName
  1315. {
  1316. if ([[fileName lastPathComponent] isEqualToString:@"plist"] == NO)
  1317. fileName = [fileName stringByAppendingString:@".plist"];
  1318. if (![[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileName]]) return nil;
  1319. NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileName]];
  1320. return [data objectForKey:@"title"];
  1321. }
  1322. @end
  1323. #pragma --------------------------------------------------------------------------------------------
  1324. #pragma mark ===== CCMetadataNet =====
  1325. #pragma --------------------------------------------------------------------------------------------
  1326. @implementation CCMetadataNet
  1327. - (id)init
  1328. {
  1329. self = [super init];
  1330. self.priority = NSOperationQueuePriorityNormal;
  1331. return self;
  1332. }
  1333. - (id)initWithAccount:(NSString *)withAccount
  1334. {
  1335. self = [super init];
  1336. if (self) {
  1337. _account = withAccount;
  1338. _priority = NSOperationQueuePriorityNormal;
  1339. }
  1340. return self;
  1341. }
  1342. - (id)copyWithZone: (NSZone *) zone
  1343. {
  1344. CCMetadataNet *metadataNet = [[CCMetadataNet allocWithZone: zone] init];
  1345. [metadataNet setAccount: self.account];
  1346. [metadataNet setAction: self.action];
  1347. [metadataNet setAssetLocalIdentifier: self.assetLocalIdentifier];
  1348. [metadataNet setCryptated: self.cryptated];
  1349. [metadataNet setDate: self.date];
  1350. [metadataNet setDelegate: self.delegate];
  1351. [metadataNet setDirectory: self.directory];
  1352. [metadataNet setDirectoryID: self.directoryID];
  1353. [metadataNet setDirectoryIDTo: self.directoryIDTo];
  1354. [metadataNet setDownloadData: self.downloadData];
  1355. [metadataNet setDownloadPlist: self.downloadPlist];
  1356. [metadataNet setErrorCode: self.errorCode];
  1357. [metadataNet setErrorRetry: self.errorRetry];
  1358. [metadataNet setEtag:self.etag];
  1359. [metadataNet setExpirationTime: self.expirationTime];
  1360. [metadataNet setFileID: self.fileID];
  1361. [metadataNet setFileName: self.fileName];
  1362. [metadataNet setFileNameTo: self.fileNameTo];
  1363. [metadataNet setFileNameLocal: self.fileNameLocal];
  1364. [metadataNet setFileNamePrint: self.fileNamePrint];
  1365. [metadataNet setOptions: self.options];
  1366. [metadataNet setPassword: self.password];
  1367. [metadataNet setPathFolder: self.pathFolder];
  1368. [metadataNet setPriority: self.priority];
  1369. [metadataNet setQueue: self.queue];
  1370. [metadataNet setServerUrl: self.serverUrl];
  1371. [metadataNet setServerUrlTo: self.serverUrlTo];
  1372. [metadataNet setSelector: self.selector];
  1373. [metadataNet setSelectorPost: self.selectorPost];
  1374. [metadataNet setSession: self.session];
  1375. [metadataNet setSessionID: self.sessionID];
  1376. [metadataNet setShare: self.share];
  1377. [metadataNet setShareeType: self.shareeType];
  1378. [metadataNet setSharePermission: self.sharePermission];
  1379. [metadataNet setSize: self.size];
  1380. [metadataNet setTaskStatus: self.taskStatus];
  1381. return metadataNet;
  1382. }
  1383. @end