CCNetworking.m 101 KB

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