CCFavorites.m 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844
  1. //
  2. // CCFavorites.m
  3. // Nextcloud iOS
  4. //
  5. // Created by Marino Faggiana on 16/01/17.
  6. // Copyright (c) 2017 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "CCFavorites.h"
  24. #import "AppDelegate.h"
  25. #import "CCSynchronize.h"
  26. #import "NCBridgeSwift.h"
  27. @interface CCFavorites ()
  28. {
  29. AppDelegate *appDelegate;
  30. NSArray *_dataSource;
  31. BOOL _reloadDataSource;
  32. // Automatic Upload Folder
  33. NSString *_autoUploadFileName;
  34. NSString *_autoUploadDirectory;
  35. // Datasource
  36. CCSectionDataSourceMetadata *sectionDataSource;
  37. }
  38. @end
  39. @implementation CCFavorites
  40. #pragma --------------------------------------------------------------------------------------------
  41. #pragma mark ===== Init =====
  42. #pragma --------------------------------------------------------------------------------------------
  43. - (id)initWithCoder:(NSCoder *)aDecoder
  44. {
  45. if (self = [super initWithCoder:aDecoder]) {
  46. appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  47. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerProgressTask:) name:@"NotificationProgressTask" object:nil];
  48. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheming) name:@"changeTheming" object:nil];
  49. appDelegate.activeFavorites = self;
  50. }
  51. return self;
  52. }
  53. - (void)viewDidLoad
  54. {
  55. [super viewDidLoad];
  56. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMain" bundle:nil] forCellReuseIdentifier:@"CellMain"];
  57. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMainTransfer" bundle:nil] forCellReuseIdentifier:@"CellMainTransfer"];
  58. // dataSource
  59. _dataSource = [NSMutableArray new];
  60. // Metadata
  61. _metadata = [tableMetadata new];
  62. self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 1)];
  63. self.tableView.separatorColor = [NCBrandColor sharedInstance].seperator;
  64. self.tableView.emptyDataSetDelegate = self;
  65. self.tableView.emptyDataSetSource = self;
  66. self.tableView.delegate = self;
  67. // calculate _serverUrl
  68. if (!_serverUrl)
  69. _serverUrl = nil;
  70. // Title
  71. if (_titleViewControl)
  72. self.title = _titleViewControl;
  73. else
  74. self.title = NSLocalizedString(@"_favorites_", nil);
  75. }
  76. // Apparirà
  77. - (void)viewWillAppear:(BOOL)animated
  78. {
  79. [super viewWillAppear:animated];
  80. // Color
  81. [appDelegate aspectNavigationControllerBar:self.navigationController.navigationBar online:[appDelegate.reachability isReachable] hidden:NO];
  82. [appDelegate aspectTabBar:self.tabBarController.tabBar hidden:NO];
  83. // Plus Button
  84. [appDelegate plusButtonVisibile:true];
  85. [self reloadDatasource];
  86. }
  87. // E' arrivato
  88. - (void)viewDidAppear:(BOOL)animated
  89. {
  90. [super viewDidAppear:animated];
  91. // Active Main
  92. appDelegate.activeFavorites = self;
  93. }
  94. - (void)changeTheming
  95. {
  96. if (self.isViewLoaded && self.view.window)
  97. [appDelegate changeTheming:self];
  98. // Reload Table View
  99. [self.tableView reloadData];
  100. }
  101. #pragma --------------------------------------------------------------------------------------------
  102. #pragma mark ==== DZNEmptyDataSetSource ====
  103. #pragma --------------------------------------------------------------------------------------------
  104. - (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView
  105. {
  106. return [NCBrandColor sharedInstance].backgroundView;
  107. }
  108. - (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
  109. {
  110. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"favoriteNoFiles"] multiplier:2 color:[NCBrandColor sharedInstance].yellowFavorite];
  111. }
  112. - (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
  113. {
  114. NSString *text = [NSString stringWithFormat:@"%@", NSLocalizedString(@"_favorite_no_files_", nil)];
  115. NSDictionary *attributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20.0f], NSForegroundColorAttributeName:[UIColor lightGrayColor]};
  116. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  117. }
  118. - (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
  119. {
  120. NSString *text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_tutorial_favorite_view_", nil)];
  121. NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
  122. paragraph.lineBreakMode = NSLineBreakByWordWrapping;
  123. paragraph.alignment = NSTextAlignmentCenter;
  124. NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0], NSForegroundColorAttributeName: [UIColor lightGrayColor], NSParagraphStyleAttributeName: paragraph};
  125. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  126. }
  127. #pragma --------------------------------------------------------------------------------------------
  128. #pragma mark ===== Delete =====
  129. #pragma--------------------------------------------------------------------------------------------
  130. - (void)deleteFile:(NSArray *)metadatas e2ee:(BOOL)e2ee
  131. {
  132. NSInteger numDelete = metadatas.count;
  133. __block NSInteger cont = 0;
  134. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:appDelegate.activeUser withUserID:appDelegate.activeUserID withPassword:appDelegate.activePassword withUrl:appDelegate.activeUrl];
  135. for (tableMetadata *metadata in metadatas) {
  136. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  137. if (!serverUrl)
  138. continue;
  139. [ocNetworking deleteFileOrFolder:metadata.fileName serverUrl:serverUrl completion:^(NSString *message, NSInteger errorCode) {
  140. if (errorCode == 0 || errorCode == 404) {
  141. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID] error:nil];
  142. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID] clearDateReadDirectoryID:metadata.directoryID];
  143. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  144. [[NCManageDatabase sharedInstance] deletePhotosWithFileID:metadata.fileID];
  145. [[appDelegate activePhotos].fileIDHide addObject:metadata.fileID];
  146. // Directory ?
  147. if (metadata.directory) {
  148. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:[CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileName]];
  149. }
  150. // E2EE (if exists the record)
  151. if (e2ee) {
  152. [[NCManageDatabase sharedInstance] deleteE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileNameIdentifier == %@", metadata.account, serverUrl, metadata.fileName]];
  153. }
  154. }
  155. if (++cont == numDelete) {
  156. if (e2ee) {
  157. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  158. [[NCNetworkingEndToEnd sharedManager] rebuildAndSendEndToEndMetadataOnServerUrl:serverUrl account:appDelegate.activeAccount user:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl];
  159. dispatch_async(dispatch_get_main_queue(), ^{
  160. // ONLY for this View
  161. [self reloadDatasource];
  162. });
  163. });
  164. } else {
  165. // ONLY for this View
  166. [self reloadDatasource];;
  167. }
  168. }
  169. }];
  170. }
  171. }
  172. #pragma --------------------------------------------------------------------------------------------
  173. #pragma mark ===== Favorite =====
  174. #pragma--------------------------------------------------------------------------------------------
  175. - (void)addFavoriteFolder:(NSString *)serverUrl
  176. {
  177. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  178. if (!directoryID) return;
  179. NSString *selector;
  180. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  181. metadataNet.action = actionReadFolder;
  182. metadataNet.depth = @"1";
  183. metadataNet.directoryID = directoryID;
  184. if ([CCUtility getFavoriteOffline])
  185. selector = selectorReadFolderWithDownload;
  186. else
  187. selector = selectorReadFolder;
  188. metadataNet.selector = selector;
  189. metadataNet.serverUrl = serverUrl;
  190. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:[CCSynchronize sharedSynchronize] metadataNet:metadataNet];
  191. }
  192. - (void)settingFavorite:(tableMetadata *)metadata favorite:(BOOL)favorite
  193. {
  194. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  195. if(!serverUrl)
  196. return;
  197. NSString *fileNameServerUrl = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:appDelegate.activeUrl];
  198. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:appDelegate.activeUser withUserID:appDelegate.activeUserID withPassword:appDelegate.activePassword withUrl:appDelegate.activeUrl];
  199. [ocNetworking settingFavorite:fileNameServerUrl favorite:favorite completion:^(NSString *message, NSInteger errorCode) {
  200. if (errorCode == 0) {
  201. [[NCManageDatabase sharedInstance] setMetadataFavoriteWithFileID:metadata.fileID favorite:favorite];
  202. [self reloadDatasource];
  203. } else {
  204. if (errorCode == kOCErrorServerUnauthorized)
  205. [appDelegate openLoginView:self loginType:k_login_Modify_Password selector:k_intro_login];
  206. }
  207. }];
  208. }
  209. #pragma --------------------------------------------------------------------------------------------
  210. #pragma mark ===== listingFavorites =====
  211. #pragma--------------------------------------------------------------------------------------------
  212. - (void)listingFavorites
  213. {
  214. // test
  215. if (appDelegate.activeAccount.length == 0)
  216. return;
  217. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:appDelegate.activeUser withUserID:appDelegate.activeUserID withPassword:appDelegate.activePassword withUrl:appDelegate.activeUrl];
  218. [ocNetworking listingFavorites:@"" account:appDelegate.activeAccount success:^(NSArray *metadatas) {
  219. NSString *father = @"";
  220. NSMutableArray *filesEtag = [NSMutableArray new];
  221. for (tableMetadata *metadata in metadatas) {
  222. // insert for test NOT favorite
  223. [filesEtag addObject:metadata.fileID];
  224. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  225. if (!serverUrl)
  226. continue;
  227. NSString *serverUrlSon = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileName];
  228. if (![serverUrlSon containsString:father]) {
  229. if (metadata.directory) {
  230. if ([CCUtility getFavoriteOffline])
  231. [[CCSynchronize sharedSynchronize] readFileForFolder:metadata.fileName serverUrl:serverUrl selector:selectorReadFileFolderWithDownload];
  232. else
  233. [[CCSynchronize sharedSynchronize] readFileForFolder:metadata.fileName serverUrl:serverUrl selector:selectorReadFileFolder];
  234. } else {
  235. if ([CCUtility getFavoriteOffline])
  236. [[CCSynchronize sharedSynchronize] readFile:metadata selector:selectorReadFileWithDownload];
  237. else
  238. [[CCSynchronize sharedSynchronize] readFile:metadata selector:selectorReadFile];
  239. }
  240. father = serverUrlSon;
  241. }
  242. }
  243. // Verify remove favorite
  244. NSArray *allRecordFavorite = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND favorite == true", appDelegate.activeAccount] sorted:nil ascending:NO];
  245. for (tableMetadata *metadata in allRecordFavorite)
  246. if (![filesEtag containsObject:metadata.fileID])
  247. [[NCManageDatabase sharedInstance] setMetadataFavoriteWithFileID:metadata.fileID favorite:NO];
  248. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  249. } failure:^(NSString *message, NSInteger errorCode) {
  250. NSLog(@"[LOG] Listing Favorites failure error %d, %@", (int)errorCode, message);
  251. }];
  252. }
  253. #pragma --------------------------------------------------------------------------------------------
  254. #pragma mark ==== Download Thumbnail ====
  255. #pragma --------------------------------------------------------------------------------------------
  256. - (void)downloadThumbnail:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl indexPath:(NSIndexPath *)indexPath
  257. {
  258. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:appDelegate.activeUser withUserID:appDelegate.activeUserID withPassword:appDelegate.activePassword withUrl:appDelegate.activeUrl];
  259. [ocNetworking downloadThumbnailWithDimOfThumbnail:@"m" fileID:metadata.fileID fileNamePath:[CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:appDelegate.activeUrl] fileNameView:metadata.fileNameView completion:^(NSString *message, NSInteger errorCode) {
  260. if(errorCode == 0 && [[NSFileManager defaultManager] fileExistsAtPath:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView]] && [[NCMainCommon sharedInstance] isValidIndexPath:indexPath tableView:self.tableView]) {
  261. [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
  262. }
  263. }];
  264. }
  265. #pragma --------------------------------------------------------------------------------------------
  266. #pragma mark ==== Download <Delegate> ====
  267. #pragma --------------------------------------------------------------------------------------------
  268. - (void)downloadStart:(NSString *)fileID account:(NSString *)account task:(NSURLSessionDownloadTask *)task serverUrl:(NSString *)serverUrl
  269. {
  270. [self reloadDatasource];
  271. [appDelegate updateApplicationIconBadgeNumber];
  272. }
  273. - (void)downloadFileSuccessFailure:(NSString *)fileName fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector errorMessage:(NSString *)errorMessage errorCode:(NSInteger)errorCode
  274. {
  275. if (errorCode == 0) {
  276. _metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  277. if ([_metadata.typeFile isEqualToString: k_metadataTypeFile_compress]) {
  278. [self openWith:_metadata];
  279. } else if ([_metadata.typeFile isEqualToString: k_metadataTypeFile_unknown]) {
  280. [self openWith:_metadata];
  281. } else {
  282. if ([self shouldPerformSegue])
  283. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  284. }
  285. } else {
  286. // File do not exists on server, remove in local
  287. if (errorCode == kOCErrorServerPathNotFound || errorCode == kCFURLErrorBadServerResponse) {
  288. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageFileID:fileID] error:nil];
  289. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID] clearDateReadDirectoryID:nil];
  290. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  291. [[NCManageDatabase sharedInstance] deletePhotosWithFileID:fileID];
  292. [appDelegate.activePhotos.fileIDHide addObject:fileID];
  293. }
  294. [self reloadDatasource];
  295. [appDelegate.activeTransfers reloadDatasource];
  296. }
  297. }
  298. - (void)openWith:(tableMetadata *)metadata
  299. {
  300. if ([CCUtility fileProviderStorageExists:metadata.fileID fileName:metadata.fileNameView]) {
  301. NSURL *url = [NSURL fileURLWithPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileName:metadata.fileNameView]];
  302. _docController = [UIDocumentInteractionController interactionControllerWithURL:url];
  303. _docController.delegate = self;
  304. [_docController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
  305. }
  306. }
  307. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  308. {
  309. CGPoint location = [tapGesture locationInView:self.tableView];
  310. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  311. tableMetadata *metadata = [_dataSource objectAtIndex:indexPath.row];
  312. if (metadata)
  313. [appDelegate.activeMain openWindowShare:metadata];
  314. }
  315. #pragma --------------------------------------------------------------------------------------------
  316. #pragma mark ===== Progress & Task Button =====
  317. #pragma --------------------------------------------------------------------------------------------
  318. - (void)triggerProgressTask:(NSNotification *)notification
  319. {
  320. [[NCMainCommon sharedInstance] triggerProgressTask:notification sectionDataSourceFileIDIndexPath:sectionDataSource.fileIDIndexPath tableView:self.tableView];
  321. }
  322. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  323. {
  324. UITouch *touch = [[event allTouches] anyObject];
  325. CGPoint location = [touch locationInView:self.tableView];
  326. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  327. if ([[NCMainCommon sharedInstance] isValidIndexPath:indexPath tableView:self.tableView]) {
  328. tableMetadata *metadataSection = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  329. if (metadataSection) {
  330. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadataSection.fileID]];
  331. if (metadata)
  332. [[NCMainCommon sharedInstance] cancelTransferMetadata:metadata reloadDatasource:true];
  333. }
  334. }
  335. }
  336. - (void)cancelAllTask:(id)sender
  337. {
  338. CGPoint location = [sender locationInView:self.tableView];
  339. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  340. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  341. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_all_task_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  342. [[NCMainCommon sharedInstance] cancelAllTransfer];
  343. }]];
  344. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) { }]];
  345. alertController.popoverPresentationController.sourceView = self.view;
  346. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  347. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  348. [alertController.view layoutIfNeeded];
  349. [self presentViewController:alertController animated:YES completion:nil];
  350. }
  351. #pragma mark -
  352. #pragma --------------------------------------------------------------------------------------------
  353. #pragma mark ===== menu action : Favorite, More, Delete [swipe] =====
  354. #pragma --------------------------------------------------------------------------------------------
  355. - (BOOL)canOpenMenuAction:(tableMetadata *)metadata
  356. {
  357. return YES;
  358. }
  359. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell canSwipe:(MGSwipeDirection)direction
  360. {
  361. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  362. tableMetadata *metadata = [_dataSource objectAtIndex:indexPath.row];
  363. return [self canOpenMenuAction:metadata];
  364. }
  365. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell tappedButtonAtIndex:(NSInteger)index direction:(MGSwipeDirection)direction fromExpansion:(BOOL)fromExpansion
  366. {
  367. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  368. if (direction == MGSwipeDirectionRightToLeft) {
  369. [self actionDelete:indexPath];
  370. }
  371. if (direction == MGSwipeDirectionLeftToRight) {
  372. [self settingFavorite:[_dataSource objectAtIndex:indexPath.row] favorite:NO];
  373. }
  374. return YES;
  375. }
  376. - (void)actionDelete:(NSIndexPath *)indexPath
  377. {
  378. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", _metadata.fileID]];
  379. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  380. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  381. [self deleteFile:[[NSArray alloc] initWithObjects:[_dataSource objectAtIndex:indexPath.row], nil] e2ee:false];
  382. }]];
  383. if (localFile) {
  384. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_remove_local_file_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  385. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", _metadata.fileID]];
  386. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageFileID:_metadata.fileID] error:nil];
  387. [self reloadDatasource];
  388. }]];
  389. }
  390. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  391. }]];
  392. alertController.popoverPresentationController.sourceView = self.view;
  393. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  394. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  395. [alertController.view layoutIfNeeded];
  396. [self presentViewController:alertController animated:YES completion:nil];
  397. }
  398. - (void)actionMore:(UITapGestureRecognizer *)gestureRecognizer
  399. {
  400. CGPoint touch = [gestureRecognizer locationInView:self.tableView];
  401. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:touch];
  402. UIImage *iconHeader;
  403. tableMetadata *metadata = [_dataSource objectAtIndex:indexPath.row];
  404. AHKActionSheet *actionSheet = [[AHKActionSheet alloc] initWithView:self.tabBarController.view title:nil];
  405. actionSheet.animationDuration = 0.2;
  406. actionSheet.buttonHeight = 50.0;
  407. actionSheet.cancelButtonHeight = 50.0f;
  408. actionSheet.separatorHeight = 5.0f;
  409. actionSheet.automaticallyTintButtonImages = @(NO);
  410. actionSheet.encryptedButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].encrypted };
  411. actionSheet.buttonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  412. actionSheet.cancelButtonTextAttributes = @{ NSFontAttributeName:[UIFont boldSystemFontOfSize:17], NSForegroundColorAttributeName:[UIColor blackColor] };
  413. actionSheet.disableButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor darkGrayColor] };
  414. actionSheet.separatorColor = [NCBrandColor sharedInstance].seperator;
  415. actionSheet.cancelButtonTitle = NSLocalizedString(@"_cancel_",nil);
  416. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  417. if ([[NSFileManager defaultManager] fileExistsAtPath:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView]]) {
  418. iconHeader = [UIImage imageWithContentsOfFile:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView]];
  419. } else {
  420. if (metadata.directory)
  421. iconHeader = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  422. else
  423. iconHeader = [UIImage imageNamed:metadata.iconName];
  424. }
  425. [actionSheet addButtonWithTitle: metadata.fileNameView image: iconHeader backgroundColor: [NCBrandColor sharedInstance].tabBar height: 50.0 type: AHKActionSheetButtonTypeDisabled handler: nil
  426. ];
  427. // Share
  428. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil) image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"share"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement] backgroundColor:[NCBrandColor sharedInstance].backgroundView height: 50.0 type:AHKActionSheetButtonTypeDefault handler:^(AHKActionSheet *as) {
  429. [appDelegate.activeMain openWindowShare:metadata];
  430. }];
  431. // NO Directory
  432. if (metadata.directory == NO) {
  433. [actionSheet addButtonWithTitle:NSLocalizedString(@"_open_in_", nil) image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"openFile"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement] backgroundColor:[NCBrandColor sharedInstance].backgroundView height: 50.0 type:AHKActionSheetButtonTypeDefault handler:^(AHKActionSheet *as) {
  434. [self.tableView setEditing:NO animated:YES];
  435. [self openWith:metadata];
  436. }];
  437. }
  438. [actionSheet show];
  439. }
  440. #pragma --------------------------------------------------------------------------------------------
  441. #pragma mark ==== Table ====
  442. #pragma --------------------------------------------------------------------------------------------
  443. - (tableMetadata *)setSelfMetadataFromIndexPath:(NSIndexPath *)indexPath
  444. {
  445. tableMetadata *metadata = [_dataSource objectAtIndex:indexPath.row];
  446. return metadata;
  447. }
  448. - (void)readFolder:(NSString *)serverUrl
  449. {
  450. [self reloadDatasource];
  451. }
  452. - (void)reloadDatasource
  453. {
  454. NSMutableArray *metadatas = [NSMutableArray new];
  455. NSArray *recordsTableMetadata ;
  456. NSString *sorted = [CCUtility getOrderSettings];
  457. if ([sorted isEqualToString:@"fileName"])
  458. sorted = @"fileName";
  459. if (!_serverUrl) {
  460. recordsTableMetadata = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND favorite == true", appDelegate.activeAccount] sorted:sorted ascending:[CCUtility getAscendingSettings]];
  461. } else {
  462. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  463. if (directoryID)
  464. recordsTableMetadata = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"directoryID == %@", directoryID] sorted:sorted ascending:[CCUtility getAscendingSettings]];
  465. }
  466. sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil groupByField:nil fileIDHide:nil activeAccount:appDelegate.activeAccount];
  467. NSArray *fileIDs = [sectionDataSource.sectionArrayRow objectForKey:@"_none_"];
  468. for (NSString *fileID in fileIDs)
  469. [metadatas addObject:[sectionDataSource.allRecordsDataSource objectForKey:fileID]];
  470. _dataSource = [NSArray arrayWithArray:metadatas];
  471. // get auto upload folder
  472. _autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  473. _autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:appDelegate.activeUrl];
  474. [self.tableView reloadData];
  475. }
  476. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  477. {
  478. return 60;
  479. }
  480. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  481. {
  482. return 1;
  483. }
  484. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  485. {
  486. return [_dataSource count];
  487. }
  488. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  489. {
  490. tableMetadata *metadata = [_dataSource objectAtIndex:indexPath.row];
  491. if (metadata == nil || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata]) {
  492. return [CCCellMain new];
  493. }
  494. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  495. if (serverUrl == nil) {
  496. return [CCCellMain new];
  497. }
  498. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, serverUrl]];
  499. if (directory == nil) {
  500. return [CCCellMain new];
  501. }
  502. tableMetadata *metadataFolder = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", directory.fileID]];
  503. // Download thumbnail
  504. if (metadata.thumbnailExists && ![[NSFileManager defaultManager] fileExistsAtPath:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView]]) { // && !_metadataFolder.e2eEncrypted) {
  505. [self downloadThumbnail:metadata serverUrl:serverUrl indexPath:indexPath];
  506. }
  507. UITableViewCell *cell = [[NCMainCommon sharedInstance] cellForRowAtIndexPath:indexPath tableView:tableView metadata:metadata metadataFolder:metadataFolder serverUrl:self.serverUrl autoUploadFileName:_autoUploadFileName autoUploadDirectory:_autoUploadDirectory];
  508. // NORMAL - > MAIN
  509. if ([cell isKindOfClass:[CCCellMain class]]) {
  510. // More
  511. if ([self canOpenMenuAction:metadata]) {
  512. UITapGestureRecognizer *tapMore = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(actionMore:)];
  513. [tapMore setNumberOfTapsRequired:1];
  514. ((CCCellMain *)cell).more.userInteractionEnabled = YES;
  515. [((CCCellMain *)cell).more addGestureRecognizer:tapMore];
  516. }
  517. // MGSwipeButton
  518. ((CCCellMain *)cell).delegate = self;
  519. // LEFT : configure ONLY Root Favorites : Remove file/folder Favorites
  520. if (_serverUrl == nil) {
  521. ((CCCellMain *)cell).leftButtons = @[[MGSwipeButton buttonWithTitle:@"" icon:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"favorite"] multiplier:2 color:[UIColor whiteColor]] backgroundColor:[NCBrandColor sharedInstance].yellowFavorite padding:25]];
  522. ((CCCellMain *)cell).leftExpansion.buttonIndex = 0;
  523. ((CCCellMain *)cell).leftExpansion.fillOnTrigger = NO;
  524. //centerIconOverText
  525. MGSwipeButton *favoriteButton = (MGSwipeButton *)[((CCCellMain *)cell).leftButtons objectAtIndex:0];
  526. [favoriteButton centerIconOverText];
  527. }
  528. // RIGHT
  529. ((CCCellMain *)cell).rightButtons = @[[MGSwipeButton buttonWithTitle:@"" icon:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"delete"] multiplier:2 color:[UIColor whiteColor]] backgroundColor:[UIColor redColor] padding:25]];
  530. ((CCCellMain *)cell).rightExpansion.buttonIndex = 0;
  531. ((CCCellMain *)cell).rightExpansion.fillOnTrigger = NO;
  532. //centerIconOverText
  533. MGSwipeButton *deleteButton = (MGSwipeButton *)[((CCCellMain *)cell).rightButtons objectAtIndex:0];
  534. [deleteButton centerIconOverText];
  535. }
  536. // TRANSFER
  537. if ([cell isKindOfClass:[CCCellMainTransfer class]]) {
  538. // gesture Transfer
  539. [((CCCellMainTransfer *)cell).transferButton.stopButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  540. UILongPressGestureRecognizer *stopLongGesture = [UILongPressGestureRecognizer new];
  541. [stopLongGesture addTarget:self action:@selector(cancelAllTask:)];
  542. [((CCCellMainTransfer *)cell).transferButton.stopButton addGestureRecognizer:stopLongGesture];
  543. }
  544. return cell;
  545. }
  546. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  547. {
  548. // deselect row
  549. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  550. _metadata = [self setSelfMetadataFromIndexPath:indexPath];
  551. // if is in download [do not touch]
  552. if (_metadata.status == k_metadataStatusWaitDownload || _metadata.status == k_metadataStatusInDownload || _metadata.status == k_metadataStatusDownloading)
  553. return;
  554. // File
  555. if (_metadata.directory == NO) {
  556. // File do not exists
  557. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  558. if (serverUrl) {
  559. if ([CCUtility fileProviderStorageExists:_metadata.fileID fileName:_metadata.fileNameView]) {
  560. [self downloadFileSuccessFailure:_metadata.fileName fileID:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView errorMessage:@"" errorCode:0];
  561. } else {
  562. _metadata.session = k_download_session;
  563. _metadata.sessionError = @"";
  564. _metadata.sessionSelector = selectorLoadFileView;
  565. _metadata.status = k_metadataStatusWaitDownload;
  566. // Add Metadata for Download
  567. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:_metadata];
  568. [[CCNetworking sharedNetworking] downloadFile:metadata taskStatus:k_taskStatusResume delegate:self];
  569. }
  570. }
  571. }
  572. // Directory
  573. if (_metadata.directory)
  574. [self performSegueDirectoryWithControlPasscode];
  575. }
  576. -(void)performSegueDirectoryWithControlPasscode
  577. {
  578. CCFavorites *vc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCFavorites"];
  579. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  580. if (serverUrl) {
  581. vc.serverUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  582. vc.titleViewControl = _metadata.fileNameView;
  583. [self.navigationController pushViewController:vc animated:YES];
  584. }
  585. }
  586. #pragma --------------------------------------------------------------------------------------------
  587. #pragma mark ===== Navigation ====
  588. #pragma --------------------------------------------------------------------------------------------
  589. - (BOOL)shouldPerformSegue
  590. {
  591. // if i am in background -> exit
  592. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return NO;
  593. // if i am not window -> exit
  594. if (self.view.window == NO)
  595. return NO;
  596. // Collapsed but i am in detail -> exit
  597. if (self.splitViewController.isCollapsed)
  598. if (self.detailViewController.isViewLoaded && self.detailViewController.view.window) return NO;
  599. return YES;
  600. }
  601. -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  602. {
  603. id viewController = segue.destinationViewController;
  604. if ([viewController isKindOfClass:[UINavigationController class]]) {
  605. UINavigationController *nav = viewController;
  606. _detailViewController = (CCDetail *)nav.topViewController;
  607. } else {
  608. _detailViewController = segue.destinationViewController;
  609. }
  610. NSMutableArray *allRecordsDataSourceImagesVideos = [NSMutableArray new];
  611. for (tableMetadata *metadata in _dataSource) {
  612. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])
  613. [allRecordsDataSourceImagesVideos addObject:metadata];
  614. }
  615. _detailViewController.metadataDetail = _metadata;
  616. _detailViewController.dateFilterQuery = nil;
  617. _detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  618. [_detailViewController setTitle:_metadata.fileNameView];
  619. }
  620. @end