CCNetworking.m 110 KB

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