CCNetworking.m 95 KB

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