CCNetworking.m 93 KB

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