CCNetworking.m 93 KB

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