CCNetworking.m 95 KB

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