CCNetworking.m 91 KB

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