CCMain.m 92 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236
  1. //
  2. // CCMain.m
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2014 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  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 "CCMain.h"
  24. #import "AppDelegate.h"
  25. #import "NCAutoUpload.h"
  26. #import "NCBridgeSwift.h"
  27. #import "PKDownloadButton.h"
  28. @interface CCMain () <UITextViewDelegate, MGSwipeTableCellDelegate, NCSelectDelegate, UITextFieldDelegate, UIAdaptivePresentationControllerDelegate>
  29. {
  30. AppDelegate *appDelegate;
  31. BOOL _isRoot;
  32. BOOL _isViewDidLoad;
  33. UIImageView *_imageTitleHome;
  34. NSUInteger _failedAttempts;
  35. NSDate *_lockUntilDate;
  36. UIRefreshControl *refreshControl;
  37. CCHud *_hud;
  38. // Datasource
  39. CCSectionDataSourceMetadata *sectionDataSource;
  40. // Search
  41. NSString *_searchFileName;
  42. NSMutableArray *_searchResultMetadatas;
  43. NSString *_noFilesSearchTitle;
  44. NSString *_noFilesSearchDescription;
  45. NSTimer *_timerWaitInput;
  46. // Automatic Upload Folder
  47. NSString *_autoUploadFileName;
  48. NSString *_autoUploadDirectory;
  49. // Folder
  50. BOOL _loadingFolder;
  51. tableMetadata *_metadataFolder;
  52. CGFloat heightRichWorkspace;
  53. CGFloat heightSearchBar;
  54. //
  55. NSMutableArray *selectOcId;
  56. BOOL livePhoto;
  57. }
  58. @end
  59. @implementation CCMain
  60. #pragma --------------------------------------------------------------------------------------------
  61. #pragma mark ===== Init =====
  62. #pragma --------------------------------------------------------------------------------------------
  63. - (id)initWithCoder:(NSCoder *)aDecoder
  64. {
  65. if (self = [super initWithCoder:aDecoder]) {
  66. appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  67. appDelegate.activeMain = self;
  68. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initializeMain:) name:k_notificationCenter_initializeMain object:nil];
  69. }
  70. return self;
  71. }
  72. #pragma --------------------------------------------------------------------------------------------
  73. #pragma mark ===== View =====
  74. #pragma --------------------------------------------------------------------------------------------
  75. - (void)viewDidLoad
  76. {
  77. [super viewDidLoad];
  78. // init object
  79. self.metadata = [tableMetadata new];
  80. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  81. _isViewDidLoad = YES;
  82. _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
  83. _searchResultMetadatas = [NSMutableArray new];
  84. _searchFileName = @"";
  85. _noFilesSearchTitle = @"";
  86. _noFilesSearchDescription = @"";
  87. _cellFavouriteImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"favorite"] width:50 height:50 color:[UIColor whiteColor]];
  88. _cellTrashImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"trash"] width:50 height:50 color:[UIColor whiteColor]];
  89. selectOcId = [NSMutableArray new];
  90. // delegate
  91. self.tableView.tableFooterView = [UIView new];
  92. self.tableView.emptyDataSetDelegate = self;
  93. self.tableView.emptyDataSetSource = self;
  94. self.searchController.delegate = self;
  95. self.searchController.searchBar.delegate = self;
  96. // Notification
  97. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadDatasource:) name:k_notificationCenter_reloadDataSource object:nil];
  98. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTitle) name:k_notificationCenter_setTitleMain object:nil];
  99. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheming) name:k_notificationCenter_changeTheming object:nil];
  100. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteFile:) name:k_notificationCenter_deleteFile object:nil];
  101. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(favoriteFile:) name:k_notificationCenter_favoriteFile object:nil];
  102. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moveFile:) name:k_notificationCenter_moveFile object:nil];
  103. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(copyFile:) name:k_notificationCenter_copyFile object:nil];
  104. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(createFolder:) name:k_notificationCenter_createFolder object:nil];
  105. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadDatasourceTransfer:) name:k_notificationCenter_renameFile object:nil];
  106. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadDatasourceTransfer:) name:k_notificationCenter_downloadStartFile object:nil];
  107. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadDatasourceTransfer:) name:k_notificationCenter_downloadedFile object:nil];
  108. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadDatasourceTransfer:) name:k_notificationCenter_downloadCancelFile object:nil];
  109. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadDatasourceTransfer:) name:k_notificationCenter_uploadStartFile object:nil];
  110. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadDatasourceTransfer:) name:k_notificationCenter_uploadedFile object:nil];
  111. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadDatasourceTransfer:) name:k_notificationCenter_uploadCancelFile object:nil];
  112. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerProgressTask:) name:k_notificationCenter_progressTask object:nil];
  113. // Search
  114. self.definesPresentationContext = YES;
  115. self.searchController.searchResultsUpdater = self;
  116. self.searchController.dimsBackgroundDuringPresentation = NO;
  117. UIButton *searchButton = self.searchController.searchBar.subviews.firstObject.subviews.lastObject;
  118. if (searchButton && [searchButton isKindOfClass:[UIButton class]]) {
  119. [searchButton setTitleColor:NCBrandColor.sharedInstance.brandElement forState:UIControlStateNormal];
  120. }
  121. UITextField *searchTextField = [self.searchController.searchBar valueForKey:@"searchField"];
  122. if (searchTextField && [searchTextField isKindOfClass:[UITextField class]]) {
  123. searchTextField.textColor = NCBrandColor.sharedInstance.textView;
  124. }
  125. // Load Rich Workspace
  126. self.viewRichWorkspace = [[[NSBundle mainBundle] loadNibNamed:@"NCRichWorkspace" owner:self options:nil] firstObject];
  127. UITapGestureRecognizer *viewRichWorkspaceTapped = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(viewRichWorkspaceTapAction:)];
  128. viewRichWorkspaceTapped.numberOfTapsRequired = 1;
  129. viewRichWorkspaceTapped.delegate = self;
  130. [self.viewRichWorkspace.richView addGestureRecognizer:viewRichWorkspaceTapped];
  131. self.sortButton = self.viewRichWorkspace.sortButton;
  132. heightSearchBar = self.viewRichWorkspace.topView.frame.size.height;
  133. [self.sortButton setTitleColor:NCBrandColor.sharedInstance.brandElement forState:UIControlStateNormal];
  134. [self.sortButton addTarget:self action:@selector(toggleSortMenu) forControlEvents:UIControlEventTouchUpInside];
  135. heightRichWorkspace = UIScreen.mainScreen.bounds.size.height / 4 + heightSearchBar;
  136. [self.viewRichWorkspace setFrame:CGRectMake(0, 0, self.tableView.frame.size.width, heightRichWorkspace)];
  137. self.navigationItem.searchController = self.searchController;
  138. self.searchController.hidesNavigationBarDuringPresentation = true;
  139. self.navigationController.navigationBar.prefersLargeTitles = true;
  140. self.navigationItem.largeTitleDisplayMode = UINavigationItemLargeTitleDisplayModeAlways;
  141. // Table Header View
  142. [self.tableView setTableHeaderView:self.viewRichWorkspace];
  143. // Register cell
  144. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMain" bundle:nil] forCellReuseIdentifier:@"CellMain"];
  145. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMainTransfer" bundle:nil] forCellReuseIdentifier:@"CellMainTransfer"];
  146. self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 35, 0);
  147. // long press recognizer TableView
  148. UILongPressGestureRecognizer* longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPressTableView:)];
  149. [self.tableView addGestureRecognizer:longPressRecognizer];
  150. // Pull-to-Refresh
  151. [self createRefreshControl];
  152. // Register for 3D Touch Previewing if available
  153. if ([self.traitCollection respondsToSelector:@selector(forceTouchCapability)] && (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable)) {
  154. [self registerForPreviewingWithDelegate:self sourceView:self.view];
  155. }
  156. // if this is not Main (the Main uses inizializeMain)
  157. if (_isRoot == NO && appDelegate.account.length > 0) {
  158. // Read (File) Folder
  159. [self readFileReloadFolder];
  160. }
  161. // Title
  162. [self setTitle];
  163. // changeTheming
  164. [self changeTheming];
  165. }
  166. - (void)willDismissSearchController:(UISearchController *)searchController
  167. {
  168. [self.tableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
  169. }
  170. - (void)willPresentSearchController:(UISearchController *)searchController
  171. {
  172. [self updateNavBarShadow:self.tableView force:true];
  173. }
  174. - (void)viewWillAppear:(BOOL)animated
  175. {
  176. [super viewWillAppear:animated];
  177. [self updateNavBarShadow:self.tableView force:false];
  178. if(_isViewDidLoad && _isRoot) {
  179. self.navigationItem.hidesSearchBarWhenScrolling = false;
  180. [self.navigationController.navigationBar sizeToFit];
  181. }
  182. // test
  183. if (appDelegate.account.length == 0)
  184. return;
  185. if (_isSelectedMode)
  186. [self setUINavigationBarSelected];
  187. else
  188. [self setUINavigationBarDefault];
  189. // If not editing mode remove _selectedocIds
  190. if (!self.tableView.editing)
  191. [selectOcId removeAllObjects];
  192. // Check server URL "/"
  193. if (self.navigationController.viewControllers.firstObject == self && self.serverUrl == nil) {
  194. self.serverUrl = [[NCUtility shared] getHomeServerWithUrlBase:appDelegate.urlBase account:appDelegate.account];
  195. }
  196. // RichWorkspace
  197. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.account, self.serverUrl]];
  198. if (![self.richWorkspaceText isEqualToString:directory.richWorkspace]) {
  199. self.richWorkspaceText = directory.richWorkspace;
  200. [self setTableViewHeader];
  201. }
  202. // Query data source
  203. if (self.searchController.isActive == false) {
  204. [self reloadDatasource:self.serverUrl ocId:nil];
  205. }
  206. appDelegate.activeServerUrl = self.serverUrl;
  207. appDelegate.activeViewController = self;
  208. }
  209. - (void)viewDidAppear:(BOOL)animated
  210. {
  211. [super viewDidAppear:animated];
  212. if(_isViewDidLoad && _isRoot) {
  213. self.navigationItem.hidesSearchBarWhenScrolling = true;
  214. }
  215. // Active Main
  216. appDelegate.activeMain = self;
  217. // Test viewDidLoad
  218. if (_isViewDidLoad) {
  219. _isViewDidLoad = NO;
  220. } else {
  221. if (appDelegate.account.length > 0 && [selectOcId count] == 0) {
  222. // Read (file) Folder
  223. [self readFileReloadFolder];
  224. }
  225. }
  226. // Title
  227. [self setTitle];
  228. }
  229. - (void)viewWillDisappear:(BOOL)animated
  230. {
  231. [super viewWillDisappear:animated];
  232. }
  233. - (void) viewDidLayoutSubviews
  234. {
  235. [super viewDidLayoutSubviews];
  236. [self setTableViewHeader];
  237. }
  238. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  239. {
  240. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  241. [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  242. [self.tableView beginUpdates];
  243. [self.tableView endUpdates];
  244. [self setTableViewHeader];
  245. } completion:^(id<UIViewControllerTransitionCoordinatorContext> context){
  246. [self updateNavBarShadow:self.tableView force:false];
  247. }];
  248. }
  249. - (void)presentationControllerWillDismiss:(UIPresentationController *)presentationController
  250. {
  251. [self viewDidAppear:true];
  252. }
  253. - (BOOL)prefersStatusBarHidden
  254. {
  255. return NO;
  256. }
  257. // detect scroll for remove keyboard in search mode
  258. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
  259. {
  260. if (self.searchController.isActive && scrollView == self.tableView) {
  261. [self.searchController.searchBar endEditing:YES];
  262. }
  263. }
  264. - (void)scrollViewDidScroll:(UIScrollView *)scrollView {
  265. [self updateNavBarShadow:self.tableView force:false];
  266. }
  267. - (void)changeTheming
  268. {
  269. [appDelegate changeTheming:self tableView:self.tableView collectionView:nil form:false];
  270. // Refresh control
  271. refreshControl.tintColor = UIColor.lightGrayColor;
  272. refreshControl.backgroundColor = NCBrandColor.sharedInstance.backgroundView;
  273. [self.sortButton setTitleColor:NCBrandColor.sharedInstance.brandElement forState:UIControlStateNormal];
  274. // color searchbar
  275. self.searchController.searchBar.tintColor = NCBrandColor.sharedInstance.brandElement;
  276. // color searchbbar button text (cancel)
  277. UIButton *searchButton = self.searchController.searchBar.subviews.firstObject.subviews.lastObject;
  278. if (searchButton && [searchButton isKindOfClass:[UIButton class]]) {
  279. [searchButton setTitleColor:NCBrandColor.sharedInstance.brandElement forState:UIControlStateNormal];
  280. }
  281. // color textview searchbbar
  282. UITextField *searchTextView = [self.searchController.searchBar valueForKey:@"searchField"];
  283. if (searchTextView && [searchTextView isKindOfClass:[UITextField class]]) {
  284. searchTextView.textColor = NCBrandColor.sharedInstance.textView;
  285. }
  286. // Rich Workspace
  287. [self.viewRichWorkspace loadWithRichWorkspaceText:self.richWorkspaceText];
  288. // Title
  289. [self setTitle];
  290. // Reload Table View
  291. [self tableViewReloadData];
  292. }
  293. #pragma --------------------------------------------------------------------------------------------
  294. #pragma mark ===== Initialization =====
  295. #pragma --------------------------------------------------------------------------------------------
  296. //
  297. // Callers :
  298. //
  299. // ChangeDefaultAccount (delegate)
  300. // Split : inizialize
  301. // Settings Advanced : removeAllFiles
  302. //
  303. - (void)initializeMain:(NSNotification *)notification
  304. {
  305. // test
  306. if (appDelegate.account.length == 0)
  307. return;
  308. if ([appDelegate.listMainVC count] == 0 || _isRoot) {
  309. // This is Root home main add list
  310. appDelegate.homeMain = self;
  311. _isRoot = YES;
  312. _serverUrl = [[NCUtility shared] getHomeServerWithUrlBase:appDelegate.urlBase account:appDelegate.account];
  313. [appDelegate.listMainVC setObject:self forKey:_serverUrl];
  314. // go Home
  315. [self.navigationController popToRootViewControllerAnimated:NO];
  316. // Remove search mode
  317. [self cancelSearchBar];
  318. // Read this folder
  319. [self readFileReloadFolder];
  320. } else {
  321. // reload datasource
  322. [self reloadDatasource:_serverUrl ocId:nil];
  323. }
  324. }
  325. #pragma --------------------------------------------------------------------------------------------
  326. #pragma mark ==== NotificationCenter ====
  327. #pragma --------------------------------------------------------------------------------------------
  328. - (void)createFolder:(NSNotification *)notification
  329. {
  330. if (self.view.window == nil) { return; }
  331. NSDictionary *userInfo = notification.userInfo;
  332. tableMetadata *metadata = userInfo[@"metadata"];
  333. if (metadata) {
  334. if (![metadata.serverUrl isEqualToString:self.serverUrl]) { return; }
  335. [self reloadDatasource:self.serverUrl ocId:nil];
  336. } else {
  337. [self readFolder:self.serverUrl];
  338. }
  339. }
  340. - (void)deleteFile:(NSNotification *)notification
  341. {
  342. if (self.view.window == nil) { return; }
  343. NSDictionary *userInfo = notification.userInfo;
  344. tableMetadata *metadata = userInfo[@"metadata"];
  345. if (![metadata.serverUrl isEqualToString:self.serverUrl]) { return; }
  346. [self reloadDatasource:self.serverUrl ocId:nil];
  347. }
  348. - (void)moveFile:(NSNotification *)notification
  349. {
  350. if (self.view.window == nil) { return; }
  351. NSDictionary *userInfo = notification.userInfo;
  352. tableMetadata *metadata = userInfo[@"metadata"];
  353. tableMetadata *metadataNew = userInfo[@"metadataNew"];
  354. if (![metadata.serverUrl isEqualToString:self.serverUrl] && ![metadataNew.serverUrl isEqualToString:self.serverUrl]) { return; }
  355. [self reloadDatasource:self.serverUrl ocId:nil];
  356. }
  357. - (void)copyFile:(NSNotification *)notification
  358. {
  359. if (self.view.window == nil) { return; }
  360. NSDictionary *userInfo = notification.userInfo;
  361. tableMetadata *metadata = userInfo[@"metadata"];
  362. NSString *serverUrlTo = userInfo[@"serverUrlTo"];
  363. if (![metadata.serverUrl isEqualToString:self.serverUrl] && ![serverUrlTo isEqualToString:self.serverUrl]) { return; }
  364. [self reloadDatasource:self.serverUrl ocId:nil];
  365. }
  366. - (void)favoriteFile:(NSNotification *)notification
  367. {
  368. if (self.view.window == nil) { return; }
  369. NSDictionary *userInfo = notification.userInfo;
  370. tableMetadata *metadata = userInfo[@"metadata"];
  371. if (![metadata.serverUrl isEqualToString:self.serverUrl]) { return; }
  372. if (self.searchController.isActive) {
  373. [self readFolder:self.serverUrl];
  374. } else {
  375. [self reloadDatasource:self.serverUrl ocId:nil];
  376. }
  377. }
  378. #pragma --------------------------------------------------------------------------------------------
  379. #pragma mark ==== DZNEmptyDataSetSource ====
  380. #pragma --------------------------------------------------------------------------------------------
  381. - (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
  382. {
  383. if (_loadingFolder)
  384. return NO;
  385. else
  386. return YES;
  387. }
  388. - (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView
  389. {
  390. CGFloat height = self.tabBarController.tabBar.frame.size.height;
  391. return -height;
  392. }
  393. - (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView
  394. {
  395. return NCBrandColor.sharedInstance.backgroundView;
  396. }
  397. - (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
  398. {
  399. if (self.searchController.isActive)
  400. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"search"] width:300 height:300 color:NCBrandColor.sharedInstance.brandElement];
  401. else
  402. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder"] width:300 height:300 color:NCBrandColor.sharedInstance.brandElement];
  403. }
  404. - (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView
  405. {
  406. if (_loadingFolder && refreshControl.isRefreshing == NO) {
  407. UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
  408. activityView.transform = CGAffineTransformMakeScale(1.5f, 1.5f);
  409. activityView.color = NCBrandColor.sharedInstance.brandElement;
  410. [activityView startAnimating];
  411. return activityView;
  412. }
  413. return nil;
  414. }
  415. - (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
  416. {
  417. NSString *text;
  418. if (self.searchController.isActive) {
  419. text = _noFilesSearchTitle;
  420. } else {
  421. text = [NSString stringWithFormat:@"%@", NSLocalizedString(@"_files_no_files_", nil)];
  422. }
  423. NSDictionary *attributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20.0f], NSForegroundColorAttributeName:[UIColor lightGrayColor]};
  424. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  425. }
  426. - (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
  427. {
  428. NSString *text;
  429. if (self.searchController.isActive) {
  430. text = _noFilesSearchDescription;
  431. } else {
  432. text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_no_file_pull_down_", nil)];
  433. }
  434. NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
  435. paragraph.lineBreakMode = NSLineBreakByWordWrapping;
  436. paragraph.alignment = NSTextAlignmentCenter;
  437. NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0], NSForegroundColorAttributeName: [UIColor lightGrayColor], NSParagraphStyleAttributeName: paragraph};
  438. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  439. }
  440. #pragma --------------------------------------------------------------------------------------------
  441. #pragma mark ===== Graphic Window =====
  442. #pragma --------------------------------------------------------------------------------------------
  443. - (void)createRefreshControl
  444. {
  445. refreshControl = [NCMainRefreshControl new];
  446. self.tableView.refreshControl = refreshControl;
  447. refreshControl.tintColor = UIColor.lightGrayColor;
  448. refreshControl.backgroundColor = NCBrandColor.sharedInstance.backgroundView;
  449. [refreshControl addTarget:self action:@selector(refreshControlTarget) forControlEvents:UIControlEventValueChanged];
  450. }
  451. - (void)deleteRefreshControl
  452. {
  453. [refreshControl endRefreshing];
  454. [refreshControl removeFromSuperview];
  455. refreshControl = nil;
  456. }
  457. - (void)refreshControlTarget
  458. {
  459. [self readFolder:_serverUrl];
  460. // Actuate `Peek` feedback (weak boom)
  461. AudioServicesPlaySystemSound(1519);
  462. }
  463. - (void)setTitle
  464. {
  465. if (_isSelectedMode) {
  466. NSUInteger totali = [sectionDataSource.allRecordsDataSource count];
  467. NSUInteger selezionati = [[self.tableView indexPathsForSelectedRows] count];
  468. self.navigationItem.titleView = nil;
  469. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)selezionati, (unsigned long)totali];
  470. } else {
  471. if (_isRoot) {
  472. self.navigationItem.title = NCBrandOptions.sharedInstance.brand;
  473. } else {
  474. self.navigationItem.title = _titleMain;
  475. }
  476. }
  477. NSString *titleButtonMenuSort = [[NCUtility shared] getTitleButtonForViewWithKey:k_layout_view_main];
  478. [self.sortButton setTitle:NSLocalizedString(titleButtonMenuSort, nil) forState:UIControlStateNormal];
  479. }
  480. - (void)setUINavigationBarDefault
  481. {
  482. UIBarButtonItem *buttonSelect = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_select_", @"") style:UIBarButtonItemStylePlain target:self action:@selector(tableViewToggle)];
  483. self.navigationController.navigationBar.hidden = NO;
  484. self.navigationItem.rightBarButtonItem = buttonSelect;
  485. self.navigationItem.leftBarButtonItem = nil;
  486. }
  487. - (void)setUINavigationBarSelected
  488. {
  489. UIBarButtonItem *buttonMore = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationMore"] style:UIBarButtonItemStylePlain target:self action:@selector(toggleSelectMenu)];
  490. UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(cancelSelect)];
  491. self.navigationItem.leftBarButtonItem = leftButton;
  492. self.navigationItem.rightBarButtonItem = buttonMore; //[[NSArray alloc] initWithObjects:buttonMore, nil];
  493. }
  494. - (void)cancelSelect
  495. {
  496. [self tableViewSelect:false];
  497. }
  498. #pragma --------------------------------------------------------------------------------------------
  499. #pragma mark ===== Save selected File =====
  500. #pragma --------------------------------------------------------------------------------------------
  501. - (void)saveToPhotoAlbum:(tableMetadata *)metadata
  502. {
  503. NSString *fileNamePath = [CCUtility getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileNameView];
  504. PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
  505. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] && status == PHAuthorizationStatusAuthorized) {
  506. UIImage *image = [UIImage imageWithContentsOfFile:fileNamePath];
  507. if (image)
  508. UIImageWriteToSavedPhotosAlbum(image, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  509. else
  510. [[NCContentPresenter shared] messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorFileNotSaved forced:false];
  511. }
  512. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video] && status == PHAuthorizationStatusAuthorized) {
  513. if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(fileNamePath)) {
  514. UISaveVideoAtPathToSavedPhotosAlbum(fileNamePath, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  515. } else {
  516. [[NCContentPresenter shared] messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorFileNotSaved forced:false];
  517. }
  518. }
  519. if (status != PHAuthorizationStatusAuthorized) {
  520. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil) message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil) preferredStyle:UIAlertControllerStyleAlert];
  521. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  522. [alertController addAction:okAction];
  523. [self presentViewController:alertController animated:YES completion:nil];
  524. }
  525. }
  526. - (void)saveSelectedFilesSelector:(NSString *)path didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
  527. {
  528. if (error) {
  529. [[NCContentPresenter shared] messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code forced:false];
  530. }
  531. }
  532. - (void)saveSelectedFiles
  533. {
  534. if (_isSelectedMode && [selectOcId count] == 0)
  535. return;
  536. [_hud visibleHudTitle:@"" mode:MBProgressHUDModeIndeterminate color:nil];
  537. NSArray *metadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  538. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  539. for (tableMetadata *metadata in metadatas) {
  540. if (metadata.directory == NO && ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])) {
  541. [[NCOperationQueue shared] downloadWithMetadata:metadata selector:selectorSaveAlbum setFavorite:false];
  542. }
  543. }
  544. [_hud hideHud];
  545. });
  546. [self tableViewSelect:false];
  547. }
  548. #pragma mark -
  549. #pragma --------------------------------------------------------------------------------------------
  550. #pragma mark ===== Peek & Pop =====
  551. #pragma --------------------------------------------------------------------------------------------
  552. - (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
  553. {
  554. CGPoint convertedLocation = [self.view convertPoint:location toView:self.tableView];
  555. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:convertedLocation];
  556. tableMetadata *metadata = [[NCMainCommon shared] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  557. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  558. if (cell) {
  559. previewingContext.sourceRect = cell.frame;
  560. CCPeekPop *viewController = [[UIStoryboard storyboardWithName:@"CCPeekPop" bundle:nil] instantiateViewControllerWithIdentifier:@"PeekPopImagePreview"];
  561. viewController.metadata = metadata;
  562. viewController.imageFile = cell.file.image;
  563. viewController.showOpenIn = true;
  564. viewController.showShare = true;
  565. viewController.showOpenQuickLook = [[NCUtility shared] isQuickLookDisplayableWithMetadata:metadata];
  566. return viewController;
  567. }
  568. return nil;
  569. }
  570. - (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit
  571. {
  572. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:previewingContext.sourceRect.origin];
  573. [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
  574. }
  575. #pragma --------------------------------------------------------------------------------------------
  576. #pragma mark ==== Read Folder ====
  577. #pragma --------------------------------------------------------------------------------------------
  578. - (void)readFolder:(NSString *)serverUrl
  579. {
  580. // init control
  581. if (!serverUrl || !appDelegate.account || appDelegate.maintenanceMode) {
  582. [refreshControl endRefreshing];
  583. return;
  584. }
  585. // Search Mode
  586. if (self.searchController.isActive) {
  587. _searchFileName = @""; // forced reload searchg
  588. [self updateSearchResultsForSearchController:self.searchController];
  589. return;
  590. }
  591. _loadingFolder = YES;
  592. [refreshControl endRefreshing];
  593. [self tableViewReloadData];
  594. [[NCNetworking shared] readFolderWithServerUrl:serverUrl account:appDelegate.account completion:^(NSString *account, tableMetadata *metadataFolder, NSArray *metadatas, NSArray *metadatasUpdate, NSArray *metadatasLocalUpdate, NSInteger errorCode, NSString *errorDescription) {
  595. if (errorCode == 0 ) {
  596. _metadataFolder = metadataFolder;
  597. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:serverUrl e2eEncrypted:_metadataFolder.e2eEncrypted account:appDelegate.account urlBase:_metadataFolder.urlBase];
  598. [self setTitle];
  599. for (tableMetadata *metadata in metadatasLocalUpdate) {
  600. if (!metadata.directory) {
  601. [[NCNetworking shared] downloadWithMetadata:metadata selector:selectorDownloadFile setFavorite:false completion:^(NSInteger errorCode) { }];
  602. }
  603. }
  604. // E2EE Is encrypted folder get metadata
  605. if (isFolderEncrypted) {
  606. if ([CCUtility isEndToEndEnabled:account]) {
  607. [[NCCommunication shared] getE2EEMetadataWithFileId:metadataFolder.fileId e2eToken:nil customUserAgent:nil addCustomHeaders:nil completionHandler:^(NSString *account, NSString *e2eMetadata, NSInteger errorCode, NSString *errorDescription) {
  608. if (errorCode == 0 && e2eMetadata != nil) {
  609. BOOL result = [[NCEndToEndMetadata sharedInstance] decoderMetadata:e2eMetadata privateKey:[CCUtility getEndToEndPrivateKey:account] serverUrl:self.serverUrl account:account urlBase:appDelegate.urlBase];
  610. if (result == false) {
  611. [[NCContentPresenter shared] messageNotification:@"_error_e2ee_" description:@"_e2e_error_decode_metadata_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorDecodeMetadata forced:true];
  612. }
  613. } else if (errorCode != 404) {
  614. [[NCContentPresenter shared] messageNotification:@"_e2e_error_get_metadata_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode forced:true];
  615. }
  616. [self reloadDatasource:_serverUrl ocId:nil];
  617. }];
  618. } else {
  619. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:k_CCErrorE2EENotEnabled forced:true];
  620. }
  621. }
  622. } else {
  623. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode forced:true];
  624. }
  625. _loadingFolder = NO;
  626. [self reloadDatasource:serverUrl ocId:nil];
  627. }];
  628. }
  629. - (void)readFileReloadFolder
  630. {
  631. if (!_serverUrl || !appDelegate.account || appDelegate.maintenanceMode)
  632. return;
  633. [[NCNetworking shared] readFileWithServerUrlFileName:self.serverUrl account:appDelegate.account completion:^(NSString *account, tableMetadata *metadata, NSInteger errorCode, NSString *errorDescription) {
  634. if (errorCode == 0 && [account isEqualToString:appDelegate.account]) {
  635. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", account, self.serverUrl]];
  636. // Rich Workspace
  637. if (![self.richWorkspaceText isEqualToString:directory.richWorkspace]) {
  638. self.richWorkspaceText = directory.richWorkspace;
  639. }
  640. [self setTableViewHeader];
  641. // Read folder: No record, Change etag or BLINK
  642. if ([sectionDataSource.allRecordsDataSource count] == 0 || [metadata.etag isEqualToString:directory.etag] == NO || self.blinkFileNamePath != nil) {
  643. [self readFolder:self.serverUrl];
  644. }
  645. } else if (errorCode != 0) {
  646. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode forced:false];
  647. }
  648. }];
  649. }
  650. #pragma mark -
  651. #pragma --------------------------------------------------------------------------------------------
  652. #pragma mark ===== Search =====
  653. #pragma --------------------------------------------------------------------------------------------
  654. - (void)searchStartTimer
  655. {
  656. if (self.searchController.isActive == false) {
  657. return;
  658. }
  659. [[NCCommunication shared] searchLiteralWithServerUrl:appDelegate.urlBase depth:@"infinity" literal:_searchFileName showHiddenFiles:[CCUtility getShowHiddenFiles] customUserAgent:nil addCustomHeaders:nil timeout:120 completionHandler:^(NSString *account, NSArray *files, NSInteger errorCode, NSString *errorDescription) {
  660. if (errorCode == 0 && [account isEqualToString:appDelegate.account] && files != nil) {
  661. [[NCManageDatabase sharedInstance] convertNCCommunicationFilesToMetadatas:files useMetadataFolder:false account:account completion:^(tableMetadata *metadataFolder, NSArray<tableMetadata *> *metadatasFolder, NSArray<tableMetadata *> *metadatas) {
  662. [[NCManageDatabase sharedInstance] addMetadatas:metadatas];
  663. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatas];
  664. _metadataFolder = nil;
  665. [self reloadDatasource:_serverUrl ocId:nil];
  666. [self tableViewReloadData];
  667. [self setTitle];
  668. }];
  669. } else {
  670. if (errorCode != 0) {
  671. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode forced:true];
  672. }
  673. _searchFileName = @"";
  674. [self cancelSearchBar];
  675. }
  676. }];
  677. _noFilesSearchTitle = @"";
  678. _noFilesSearchDescription = NSLocalizedString(@"_search_in_progress_", nil);
  679. [self.tableView reloadEmptyDataSet];
  680. }
  681. - (void)updateSearchResultsForSearchController:(UISearchController *)searchController
  682. {
  683. // Color text "Cancel"
  684. [[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setTintColor:NCBrandColor.sharedInstance.brandElement];
  685. if (searchController.isActive) {
  686. [self deleteRefreshControl];
  687. NSString *fileName = [CCUtility removeForbiddenCharactersServer:searchController.searchBar.text];
  688. if (fileName.length >= k_minCharsSearch && [fileName isEqualToString:_searchFileName] == NO) {
  689. _searchFileName = fileName;
  690. _metadataFolder = nil;
  691. // First : filter
  692. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileNameView CONTAINS[cd] %@", appDelegate.account, _serverUrl, fileName] page:0 limit:0 sorted:@"fileName" ascending:NO];
  693. [_searchResultMetadatas removeAllObjects];
  694. for (tableMetadata *record in records) {
  695. [_searchResultMetadatas addObject:record];
  696. }
  697. // Version >= 12
  698. NSInteger serverVersionMajor = [[NCManageDatabase sharedInstance] getCapabilitiesServerIntWithAccount:appDelegate.account elements:NCElementsJSON.shared.capabilitiesVersionMajor];
  699. if (serverVersionMajor >= 12) {
  700. [_timerWaitInput invalidate];
  701. _timerWaitInput = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(searchStartTimer) userInfo:nil repeats:NO];
  702. }
  703. [self setTitle];
  704. }
  705. if (_searchResultMetadatas.count == 0 && fileName.length == 0) {
  706. [self reloadDatasource:_serverUrl ocId:nil];
  707. }
  708. } else {
  709. [self createRefreshControl];
  710. [self reloadDatasource:_serverUrl ocId:nil];
  711. }
  712. }
  713. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  714. {
  715. [self cancelSearchBar];
  716. }
  717. - (void)cancelSearchBar
  718. {
  719. if (self.searchController.active) {
  720. [self.searchController setActive:NO];
  721. _searchFileName = @"";
  722. _searchResultMetadatas = [NSMutableArray new];
  723. [self reloadDatasource:_serverUrl ocId:nil];
  724. }
  725. }
  726. #pragma mark -
  727. #pragma --------------------------------------------------------------------------------------------
  728. #pragma mark ===== Delete File or Folder =====
  729. #pragma --------------------------------------------------------------------------------------------
  730. - (void)deleteMetadatas
  731. {
  732. if (_isSelectedMode) {
  733. for (NSString *ocId in selectOcId) {
  734. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataFromOcId:ocId];
  735. if (metadata) {
  736. [[NCOperationQueue shared] deleteWithMetadata:metadata onlyLocal:false];
  737. }
  738. }
  739. [selectOcId removeAllObjects];
  740. [self tableViewSelect:false];
  741. } else {
  742. [[NCOperationQueue shared] deleteWithMetadata:self.metadata onlyLocal:false];
  743. }
  744. }
  745. // DELEGATE : Select
  746. - (void)dismissSelectWithServerUrl:(NSString *)serverUrl metadata:(tableMetadata *)metadata type:(NSString *)type array:(NSArray *)array buttonType:(NSString *)buttonType overwrite:(BOOL)overwrite
  747. {
  748. if (serverUrl != nil) {
  749. // E2EE DENIED
  750. if ([CCUtility isFolderEncrypted:serverUrl e2eEncrypted:metadata.e2eEncrypted account:appDelegate.account urlBase:appDelegate.urlBase]) {
  751. [[NCContentPresenter shared] messageNotification:@"_move_" description:@"_e2e_error_not_move_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:k_CCErrorE2EENotMove forced:true];
  752. return;
  753. }
  754. BOOL move = true;
  755. if ([buttonType isEqualToString:@"done1"]) { move = false; }
  756. if (_isSelectedMode) {
  757. for (NSString *ocId in selectOcId) {
  758. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataFromOcId:ocId];
  759. if (metadata) {
  760. [[NCOperationQueue shared] copyMoveWithMetadata:metadata serverUrl:serverUrl overwrite:overwrite move:move];
  761. }
  762. }
  763. [selectOcId removeAllObjects];
  764. [self tableViewSelect:false];
  765. } else {
  766. [[NCOperationQueue shared] copyMoveWithMetadata:self.metadata serverUrl:serverUrl overwrite:overwrite move:move];
  767. }
  768. }
  769. }
  770. - (void)moveOpenWindow:(NSArray *)indexPaths
  771. {
  772. if (_isSelectedMode && [selectOcId count] == 0)
  773. return;
  774. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"NCSelect" bundle:nil] instantiateInitialViewController];
  775. NCSelect *viewController = (NCSelect *)navigationController.topViewController;
  776. viewController.delegate = self;
  777. viewController.hideButtonCreateFolder = false;
  778. viewController.selectFile = false;
  779. viewController.includeDirectoryE2EEncryption = false;
  780. viewController.includeImages = false;
  781. viewController.type = @"";
  782. viewController.titleButtonDone = NSLocalizedString(@"_move_", nil);
  783. viewController.titleButtonDone1 = NSLocalizedString(@"_copy_", nil);
  784. viewController.isButtonDone1Hide = false;
  785. viewController.isOverwriteHide = false;
  786. viewController.keyLayout = k_layout_view_move;
  787. viewController.array = selectOcId;
  788. [navigationController setModalPresentationStyle:UIModalPresentationFullScreen];
  789. [self presentViewController:navigationController animated:YES completion:nil];
  790. }
  791. #pragma --------------------------------------------------------------------------------------------
  792. #pragma mark ===== Progress & Task Button =====
  793. #pragma --------------------------------------------------------------------------------------------
  794. - (void)triggerProgressTask:(NSNotification *)notification
  795. {
  796. if (sectionDataSource.ocIdIndexPath != nil) {
  797. [[NCMainCommon shared] triggerProgressTask:notification sectionDataSourceocIdIndexPath:sectionDataSource.ocIdIndexPath tableView:self.tableView viewController:self serverUrlViewController:self.serverUrl];
  798. }
  799. }
  800. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  801. {
  802. UITouch *touch = [[event allTouches] anyObject];
  803. CGPoint location = [touch locationInView:self.tableView];
  804. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  805. if ([self indexPathIsValid:indexPath]) {
  806. tableMetadata *metadataSection = [[NCMainCommon shared] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  807. if (metadataSection) {
  808. [[NCNetworking shared] cancelTransferMetadata:metadataSection completion:^{ }];
  809. }
  810. }
  811. }
  812. - (void)cancelAllTask:(id)sender
  813. {
  814. CGPoint location = [sender locationInView:self.tableView];
  815. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  816. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  817. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_all_task_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  818. [NCUtility.shared startActivityIndicatorWithView:self.view bottom:0];
  819. [[NCNetworking shared] cancelAllTransferWithAccount:appDelegate.account completion:^{
  820. [self reloadDatasource:self.serverUrl ocId:nil];
  821. }];
  822. [NCUtility.shared stopActivityIndicator];
  823. }]];
  824. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) { }]];
  825. alertController.popoverPresentationController.sourceView = self.tableView;
  826. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  827. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  828. [alertController.view layoutIfNeeded];
  829. [self presentViewController:alertController animated:YES completion:nil];
  830. }
  831. #pragma --------------------------------------------------------------------------------------------
  832. #pragma mark ===== Tap =====
  833. #pragma --------------------------------------------------------------------------------------------
  834. - (void)tapActionComment:(UITapGestureRecognizer *)tapGesture
  835. {
  836. CGPoint location = [tapGesture locationInView:self.tableView];
  837. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  838. tableMetadata *metadata = [[NCMainCommon shared] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  839. if (metadata && ![CCUtility isFolderEncrypted:self.serverUrl e2eEncrypted:metadata.e2eEncrypted account:appDelegate.account urlBase: appDelegate.urlBase]) {
  840. [[NCMainCommon shared] openShareWithViewController:self metadata:metadata indexPage:1];
  841. }
  842. }
  843. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  844. {
  845. CGPoint location = [tapGesture locationInView:self.tableView];
  846. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  847. tableMetadata *metadata = [[NCMainCommon shared] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  848. if (metadata && ![CCUtility isFolderEncrypted:self.serverUrl e2eEncrypted:metadata.e2eEncrypted account:appDelegate.account urlBase:appDelegate.urlBase]) {
  849. [[NCMainCommon shared] openShareWithViewController:self metadata:metadata indexPage:2];
  850. }
  851. }
  852. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  853. {
  854. CGPoint location = [tapGesture locationInView:self.tableView];
  855. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  856. tableMetadata *metadata = [[NCMainCommon shared] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  857. if (metadata) {
  858. }
  859. }
  860. #pragma --------------------------------------------------------------------------------------------
  861. #pragma mark ===== Rich Workspace =====
  862. #pragma --------------------------------------------------------------------------------------------
  863. - (void)viewRichWorkspaceTapAction:(UITapGestureRecognizer *)tapGesture
  864. {
  865. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"NCViewerRichWorkspace" bundle:nil] instantiateInitialViewController];
  866. NCViewerRichWorkspace *viewerRichWorkspace = (NCViewerRichWorkspace *)[navigationController topViewController];
  867. viewerRichWorkspace.richWorkspaceText = self.richWorkspaceText;
  868. viewerRichWorkspace.serverUrl = self.serverUrl;
  869. navigationController.modalPresentationStyle = UIModalPresentationFullScreen;
  870. [self presentViewController:navigationController animated:NO completion:NULL];
  871. }
  872. - (void)toggleSortMenu
  873. {
  874. NCSortMenu *sortMenu = [NCSortMenu new];
  875. [sortMenu toggleMenuWithViewController:self key:k_layout_view_main sortButton:self.sortButton serverUrl:self.serverUrl hideDirectoryOnTop:false];
  876. }
  877. - (void)toggleSelectMenu
  878. {
  879. [self toggleSelectMenuWithViewController:self.navigationController];
  880. }
  881. #pragma --------------------------------------------------------------------------------------------
  882. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  883. #pragma --------------------------------------------------------------------------------------------
  884. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  885. {
  886. if (recognizer.state == UIGestureRecognizerStateBegan) {
  887. CGPoint touchPoint = [recognizer locationInView:self.tableView];
  888. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:touchPoint];
  889. NSMutableArray *items = [NSMutableArray new];
  890. if ([self indexPathIsValid:indexPath])
  891. self.metadata = [[NCMainCommon shared] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  892. [self becomeFirstResponder];
  893. UIMenuController *menuController = [UIMenuController sharedMenuController];
  894. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyTouchFile:)]];
  895. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyTouchFiles:)]];
  896. if ([NCBrandOptions sharedInstance].disable_openin_file == false) {
  897. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinTouchFile:)]];
  898. }
  899. if ([[NCUtility shared] isQuickLookDisplayableWithMetadata:self.metadata]) {
  900. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_quicklook_", nil) action:@selector(openQuickLookTouch:)]];
  901. }
  902. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteTouchFile:)]];
  903. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteTouchFiles:)]];
  904. [menuController setMenuItems:items];
  905. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:self.tableView];
  906. [menuController setMenuVisible:YES animated:YES];
  907. }
  908. }
  909. - (BOOL)canBecomeFirstResponder
  910. {
  911. return YES;
  912. }
  913. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  914. {
  915. // For copy file, copy files, Open in ... :
  916. //
  917. // NO Directory
  918. // NO Error Passcode
  919. // NO In Session mode (download/upload)
  920. // NO Template
  921. if (@selector(copyTouchFile:) == action || @selector(openinTouchFile:) == action || @selector(openQuickLookTouch:) == action) {
  922. if (_isSelectedMode == NO && self.metadata && !self.metadata.directory && self.metadata.status == k_metadataStatusNormal) return YES;
  923. else return NO;
  924. }
  925. if (@selector(copyTouchFiles:) == action) {
  926. if (_isSelectedMode) {
  927. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  928. for (tableMetadata *metadata in selectedMetadatas) {
  929. if (!metadata.directory && metadata.status == k_metadataStatusNormal)
  930. return YES;
  931. }
  932. }
  933. return NO;
  934. }
  935. if (@selector(pasteTouchFile:) == action) {
  936. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  937. NSArray *items = [pasteboard items];
  938. if ([items count] == 1) {
  939. // Value : (NSData) ocId
  940. NSDictionary *dic = [items objectAtIndex:0];
  941. NSData *dataocId = [dic objectForKey: k_metadataKeyedUnarchiver];
  942. NSString *ocId = [NSKeyedUnarchiver unarchiveObjectWithData:dataocId];
  943. if (ocId) {
  944. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocId]];
  945. if (metadata) {
  946. return [CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView];
  947. } else {
  948. return NO;
  949. }
  950. }
  951. }
  952. return NO;
  953. }
  954. if (@selector(pasteTouchFiles:) == action) {
  955. BOOL isValid = NO;
  956. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  957. NSArray *items = [pasteboard items];
  958. if ([items count] <= 1) return NO;
  959. for (NSDictionary *dic in items) {
  960. // Value : (NSData) ocId
  961. NSData *dataocId = [dic objectForKey: k_metadataKeyedUnarchiver];
  962. NSString *ocId = [NSKeyedUnarchiver unarchiveObjectWithData:dataocId];
  963. if (ocId) {
  964. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataFromOcId:ocId];
  965. if (metadata) {
  966. if ([CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView]) {
  967. isValid = YES;
  968. } else {
  969. isValid = NO;
  970. break;
  971. }
  972. } else {
  973. isValid = NO;
  974. break;
  975. }
  976. } else {
  977. isValid = NO;
  978. break;
  979. }
  980. }
  981. return isValid;
  982. }
  983. return NO;
  984. }
  985. /************************************ COPY ************************************/
  986. - (void)copyTouchFile:(id)sender
  987. {
  988. // Remove all item
  989. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  990. pasteboard.items = [[NSArray alloc] init];
  991. if ([CCUtility fileProviderStorageExists:self.metadata.ocId fileNameView:self.metadata.fileNameView]) {
  992. [self copyFileToPasteboard:self.metadata];
  993. } else {
  994. [[NCNetworking shared] downloadWithMetadata:self.metadata selector:selectorLoadCopy setFavorite:false completion:^(NSInteger errorCode) { }];
  995. }
  996. }
  997. - (void)copyTouchFiles:(id)sender
  998. {
  999. // Remove all item
  1000. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1001. pasteboard.items = [[NSArray alloc] init];
  1002. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1003. for (tableMetadata *metadata in selectedMetadatas) {
  1004. if ([CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView]) {
  1005. [self copyFileToPasteboard:metadata];
  1006. } else {
  1007. [[NCNetworking shared] downloadWithMetadata:metadata selector:selectorLoadCopy setFavorite:false completion:^(NSInteger errorCode) { }];
  1008. }
  1009. }
  1010. [self tableViewSelect:false];
  1011. }
  1012. - (void)copyFileToPasteboard:(tableMetadata *)metadata
  1013. {
  1014. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1015. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  1016. // Value : (NSData) ocId
  1017. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata.ocId], k_metadataKeyedUnarchiver,nil];
  1018. [items addObject:item];
  1019. [pasteboard setItems:items];
  1020. }
  1021. /************************************ OPEN IN ... ******************************/
  1022. - (void)openinTouchFile:(id)sender
  1023. {
  1024. [[NCMainCommon shared] downloadOpenWithMetadata:self.metadata selector:selectorOpenIn];
  1025. }
  1026. /************************************ OPEN QUICK LOOK ******************************/
  1027. - (void)openQuickLookTouch:(id)sender
  1028. {
  1029. [[NCMainCommon shared] downloadOpenWithMetadata:self.metadata selector:selectorLoadFileQuickLook];
  1030. }
  1031. /************************************ PASTE ************************************/
  1032. - (void)pasteTouchFile:(id)sender
  1033. {
  1034. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1035. [self uploadFilePasteArray:[pasteboard items]];
  1036. }
  1037. - (void)pasteTouchFiles:(id)sender
  1038. {
  1039. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1040. [self uploadFilePasteArray:[pasteboard items]];
  1041. }
  1042. - (void)uploadFilePasteArray:(NSArray *)items
  1043. {
  1044. for (NSDictionary *dic in items) {
  1045. // Value : (NSData) ocId
  1046. NSData *dataocId = [dic objectForKey: k_metadataKeyedUnarchiver];
  1047. NSString *ocId = [NSKeyedUnarchiver unarchiveObjectWithData:dataocId];
  1048. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataFromOcId:ocId];
  1049. if (metadata) {
  1050. if ([CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView]) {
  1051. NSString *fileName = [[NCUtility shared] createFileName:metadata.fileNameView serverUrl:self.serverUrl account:appDelegate.account];
  1052. NSString *ocId = [[NSUUID UUID] UUIDString];
  1053. [CCUtility copyFileAtPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileNameView] toPath:[CCUtility getDirectoryProviderStorageOcId:ocId fileNameView:fileName]];
  1054. // Prepare record metadata
  1055. tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] createMetadataWithAccount:appDelegate.account fileName:fileName ocId:ocId serverUrl:self.serverUrl urlBase:appDelegate.urlBase url:@"" contentType:@"" livePhoto:false];
  1056. metadataForUpload.session = NCNetworking.shared.sessionIdentifierBackground;
  1057. metadataForUpload.sessionSelector = selectorUploadFile;
  1058. metadataForUpload.size = metadata.size;
  1059. metadataForUpload.status = k_metadataStatusWaitUpload;
  1060. // Add Medtadata for upload
  1061. [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1062. }
  1063. }
  1064. }
  1065. [[appDelegate networkingAutoUpload] startProcess];
  1066. }
  1067. #pragma mark -
  1068. #pragma --------------------------------------------------------------------------------------------
  1069. #pragma mark ===== menu action : Favorite, More, Delete [swipe] =====
  1070. #pragma --------------------------------------------------------------------------------------------
  1071. - (BOOL)canOpenMenuAction:(tableMetadata *)metadata
  1072. {
  1073. if (metadata == nil)
  1074. return NO;
  1075. // E2EE
  1076. if (_metadataFolder.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.account] == NO)
  1077. return NO;
  1078. return YES;
  1079. }
  1080. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell canSwipe:(MGSwipeDirection)direction
  1081. {
  1082. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  1083. tableMetadata *metadata = [[NCMainCommon shared] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1084. return [self canOpenMenuAction:metadata];
  1085. }
  1086. -(void)swipeTableCell:(nonnull MGSwipeTableCell *)cell didChangeSwipeState:(MGSwipeState)state gestureIsActive:(BOOL)gestureIsActive
  1087. {
  1088. }
  1089. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell tappedButtonAtIndex:(NSInteger)index direction:(MGSwipeDirection)direction fromExpansion:(BOOL)fromExpansion
  1090. {
  1091. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  1092. self.metadata = [[NCMainCommon shared] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1093. if (direction == MGSwipeDirectionRightToLeft) {
  1094. [self actionDelete:indexPath];
  1095. }
  1096. if (direction == MGSwipeDirectionLeftToRight) {
  1097. [[NCNetworking shared] favoriteMetadata:self.metadata urlBase:appDelegate.urlBase completion:^(NSInteger errorCode, NSString *errorDescription) {
  1098. if (errorCode != 0) {
  1099. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode forced:false];
  1100. }
  1101. }];
  1102. }
  1103. return YES;
  1104. }
  1105. - (void)actionDelete:(NSIndexPath *)indexPath
  1106. {
  1107. tableMetadata *metadata = [[NCMainCommon shared] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1108. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  1109. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  1110. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  1111. [self performSelector:@selector(deleteMetadatas) withObject:nil];
  1112. }]];
  1113. if (localFile) {
  1114. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_remove_local_file_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  1115. tableMetadata *metadataLivePhoto = [[NCManageDatabase sharedInstance] isLivePhotoWithMetadata:metadata];
  1116. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  1117. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId] error:nil];
  1118. if (metadataLivePhoto) {
  1119. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadataLivePhoto.ocId]];
  1120. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageOcId:metadataLivePhoto.ocId] error:nil];
  1121. }
  1122. [self reloadDatasource:metadata.serverUrl ocId:metadata.ocId];
  1123. }]];
  1124. }
  1125. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  1126. }]];
  1127. alertController.popoverPresentationController.sourceView = self.tableView;
  1128. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  1129. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  1130. [alertController.view layoutIfNeeded];
  1131. [self presentViewController:alertController animated:YES completion:nil];
  1132. }
  1133. - (void)actionMore:(UITapGestureRecognizer *)gestureRecognizer
  1134. {
  1135. CGPoint touch = [gestureRecognizer locationInView:self.tableView];
  1136. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:touch];
  1137. self.metadata = [[NCMainCommon shared] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1138. [self toggleMoreMenuWithViewController:self.tabBarController indexPath:indexPath metadata:self.metadata metadataFolder:_metadataFolder];
  1139. }
  1140. #pragma --------------------------------------------------------------------------------------------
  1141. #pragma mark - ==== Datasource ====
  1142. #pragma --------------------------------------------------------------------------------------------
  1143. - (void)reloadDatasource:(NSNotification *)notification
  1144. {
  1145. NSDictionary *userInfo = notification.userInfo;
  1146. NSString *ocId = userInfo[@"ocId"];
  1147. NSString *serverUrl = userInfo[@"serverUrl"];
  1148. [self reloadDatasource:serverUrl ocId:ocId];
  1149. }
  1150. - (void)reloadDatasourceTransfer:(NSNotification *)notification
  1151. {
  1152. if (self.view.window == nil) { return; }
  1153. NSDictionary *userInfo = notification.userInfo;
  1154. tableMetadata *metadata = userInfo[@"metadata"];
  1155. NSInteger errorCode = [userInfo[@"errorCode"] integerValue];
  1156. NSString *errorDescription = userInfo[@"errorDescription"];
  1157. if (errorCode != 0 && self.view.window != nil) {
  1158. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode forced:false];
  1159. }
  1160. [self reloadDatasource:metadata.serverUrl ocId:metadata.ocId];
  1161. }
  1162. - (void)reloadDatasource:(NSString *)serverUrl ocId:(NSString *)ocId
  1163. {
  1164. // test
  1165. if (appDelegate.account.length == 0 || serverUrl.length == 0 || serverUrl == nil) // || self.view.window == nil)
  1166. return;
  1167. // Se non siamo nella dir appropriata esci
  1168. if ([serverUrl isEqualToString:self.serverUrl] == NO || self.serverUrl == nil)
  1169. return;
  1170. // live photo
  1171. livePhoto = [CCUtility getLivePhoto];
  1172. // load share
  1173. appDelegate.shares = [[NCManageDatabase sharedInstance] getTableSharesWithAccount:appDelegate.account];
  1174. // Search Mode
  1175. if (self.searchController.isActive) {
  1176. // Create metadatas
  1177. NSMutableArray *metadatas = [NSMutableArray new];
  1178. for (tableMetadata *resultMetadata in _searchResultMetadatas) {
  1179. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataFromOcId:resultMetadata.ocId];
  1180. if (metadata) {
  1181. [metadatas addObject:metadata];
  1182. }
  1183. }
  1184. // [CCUtility getGroupBySettings]
  1185. sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:metadatas listProgressMetadata:nil groupBy:nil filterTypeFileImage:NO filterTypeFileVideo:NO filterLivePhoto:YES sort:@"fileName" ascending:NO directoryOnTop:NO account:appDelegate.account];
  1186. [self tableViewReloadData];
  1187. if ([sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] >= k_minCharsSearch) {
  1188. _noFilesSearchTitle = NSLocalizedString(@"_search_no_record_found_", nil);
  1189. _noFilesSearchDescription = @"";
  1190. }
  1191. if ([sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] < k_minCharsSearch) {
  1192. _noFilesSearchTitle = @"";
  1193. _noFilesSearchDescription = NSLocalizedString(@"_search_instruction_", nil);
  1194. }
  1195. [self.tableView reloadEmptyDataSet];
  1196. return;
  1197. }
  1198. // Get MetadataFolder
  1199. if ([serverUrl isEqualToString:[[NCUtility shared] getHomeServerWithUrlBase:appDelegate.urlBase account:appDelegate.account]])
  1200. _metadataFolder = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.account, k_serverUrl_root]];
  1201. else
  1202. _metadataFolder = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.account, serverUrl]];
  1203. _autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  1204. _autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectoryWithUrlBase:appDelegate.urlBase account:appDelegate.account];
  1205. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1206. NSArray *recordsTableMetadata = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.account, serverUrl] page:0 limit:0 sorted:@"fileName" ascending:NO];
  1207. // [CCUtility getGroupBySettings]
  1208. NSString *sort = [[NCUtility shared] getSortedForViewWithKey:k_layout_view_main];
  1209. BOOL ascending = [[NCUtility shared] getAscendingForViewWithKey:k_layout_view_main];
  1210. BOOL directoryOnTop = [[NCUtility shared] getDirectoryOnTopForViewWithKey:k_layout_view_main];
  1211. CCSectionDataSourceMetadata *sectionDataSourceTemp = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil groupBy:nil filterTypeFileImage:NO filterTypeFileVideo:NO filterLivePhoto:YES sort:sort ascending:ascending directoryOnTop:directoryOnTop account:appDelegate.account];
  1212. dispatch_async(dispatch_get_main_queue(), ^{
  1213. sectionDataSource = sectionDataSourceTemp;
  1214. [self tableViewReloadData];
  1215. });
  1216. });
  1217. // BLINK
  1218. if (self.blinkFileNamePath != nil) {
  1219. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1220. for (NSString *key in sectionDataSource.allRecordsDataSource) {
  1221. tableMetadata *metadata = [sectionDataSource.allRecordsDataSource objectForKey:key];
  1222. NSString *metadataFileNamePath = [NSString stringWithFormat:@"%@/%@", metadata.serverUrl, metadata.fileName];
  1223. if ([metadataFileNamePath isEqualToString:self.blinkFileNamePath]) {
  1224. for (NSString *key in sectionDataSource.ocIdIndexPath) {
  1225. if ([key isEqualToString:metadata.ocId]) {
  1226. NSIndexPath *indexPath = [sectionDataSource.ocIdIndexPath objectForKey:key];
  1227. [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
  1228. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1229. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  1230. if (cell) {
  1231. self.blinkFileNamePath = nil;
  1232. [[NCUtility shared] blinkWithCell:cell];
  1233. }
  1234. });
  1235. }
  1236. }
  1237. }
  1238. }
  1239. });
  1240. }
  1241. }
  1242. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  1243. {
  1244. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1245. if (selectedRows.count > 0) {
  1246. for (NSIndexPath *selectionIndex in selectedRows) {
  1247. NSString *ocId = [[sectionDataSource.sectionArrayRow objectForKey:[sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  1248. tableMetadata *metadata = [sectionDataSource.allRecordsDataSource objectForKey:ocId];
  1249. [metadatas addObject:metadata];
  1250. }
  1251. }
  1252. return metadatas;
  1253. }
  1254. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  1255. {
  1256. NSInteger totSections =[sectionDataSource.sections count] ;
  1257. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  1258. return nil;
  1259. }
  1260. id valueSection = [sectionDataSource.sections objectAtIndex:section];
  1261. return [sectionDataSource.sectionArrayRow objectForKey:valueSection];
  1262. }
  1263. #pragma --------------------------------------------------------------------------------------------
  1264. #pragma mark - ==== Table ====
  1265. #pragma --------------------------------------------------------------------------------------------
  1266. - (void)tableViewToggle
  1267. {
  1268. [self tableViewSelect:!_isSelectedMode];
  1269. }
  1270. - (void)tableViewSelect:(BOOL)toggle
  1271. {
  1272. _isSelectedMode = toggle;
  1273. // chiudiamo eventuali swipe aperti
  1274. if (_isSelectedMode)
  1275. [self.tableView setEditing:NO animated:NO];
  1276. [self.tableView setAllowsMultipleSelectionDuringEditing:_isSelectedMode];
  1277. [self.tableView setEditing:_isSelectedMode animated:YES];
  1278. if (_isSelectedMode)
  1279. [self setUINavigationBarSelected];
  1280. else
  1281. [self setUINavigationBarDefault];
  1282. [selectOcId removeAllObjects];
  1283. [self setTitle];
  1284. }
  1285. - (void)tableViewReloadData
  1286. {
  1287. // store selected cells before relod
  1288. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  1289. // reload table view
  1290. [self.tableView reloadData];
  1291. // selected cells stored
  1292. for (NSIndexPath *path in indexPaths)
  1293. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  1294. [self setTableViewHeader];
  1295. [self setTableViewFooter];
  1296. if (self.tableView.editing)
  1297. [self setTitle];
  1298. [self.tableView reloadEmptyDataSet];
  1299. }
  1300. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  1301. {
  1302. if (tableView.editing == 1) {
  1303. tableMetadata *metadata = [[NCMainCommon shared] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1304. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  1305. return NO;
  1306. if (metadata == nil || metadata.status != k_metadataStatusNormal)
  1307. return NO;
  1308. else
  1309. return YES;
  1310. } else {
  1311. [selectOcId removeAllObjects];
  1312. }
  1313. return YES;
  1314. }
  1315. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  1316. {
  1317. return 60;
  1318. }
  1319. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  1320. {
  1321. return [[sectionDataSource.sectionArrayRow allKeys] count];
  1322. }
  1323. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  1324. {
  1325. return [[sectionDataSource.sectionArrayRow objectForKey:[sectionDataSource.sections objectAtIndex:section]] count];
  1326. }
  1327. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  1328. {
  1329. return 0.0f;
  1330. }
  1331. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  1332. {
  1333. float shift;
  1334. UIVisualEffectView *visualEffectView;
  1335. NSString *titleSection = @"";
  1336. if (![self indexPathIsValid:[NSIndexPath indexPathForRow:0 inSection:section]])
  1337. return nil;
  1338. if ([[sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]])
  1339. titleSection = [sectionDataSource.sections objectAtIndex:section];
  1340. if ([[sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]])
  1341. titleSection = [CCUtility getTitleSectionDate:[sectionDataSource.sections objectAtIndex:section]];
  1342. // Format title
  1343. UIVisualEffect *blurEffect;
  1344. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  1345. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  1346. visualEffectView.backgroundColor = [NCBrandColor.sharedInstance.brandElement colorWithAlphaComponent:0.2];
  1347. if ([[CCUtility getGroupBySettings] isEqualToString:@"alphabetic"]) {
  1348. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  1349. shift = - 35;
  1350. else
  1351. shift = - 20;
  1352. } else shift = - 10;
  1353. // Title
  1354. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  1355. titleLabel.backgroundColor = [UIColor clearColor];
  1356. titleLabel.textColor = NCBrandColor.sharedInstance.textView;
  1357. titleLabel.font = [UIFont systemFontOfSize:12];
  1358. titleLabel.textAlignment = NSTextAlignmentLeft;
  1359. titleLabel.text = titleSection;
  1360. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  1361. [visualEffectView.contentView addSubview:titleLabel];
  1362. // Elements
  1363. UILabel *elementLabel= [[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  1364. elementLabel.backgroundColor = [UIColor clearColor];
  1365. elementLabel.textColor = NCBrandColor.sharedInstance.textView;
  1366. elementLabel.font = [UIFont systemFontOfSize:12];
  1367. elementLabel.textAlignment = NSTextAlignmentRight;
  1368. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  1369. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  1370. NSUInteger rowsCount = [metadatas count];
  1371. if (rowsCount == 0) return nil;
  1372. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  1373. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  1374. [visualEffectView.contentView addSubview:elementLabel];
  1375. return visualEffectView;
  1376. }
  1377. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  1378. {
  1379. return [sectionDataSource.sections indexOfObject:title];
  1380. }
  1381. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  1382. {
  1383. if ([[CCUtility getGroupBySettings] isEqualToString:@"alphabetic"])
  1384. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  1385. else
  1386. return nil;
  1387. }
  1388. /*
  1389. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  1390. {
  1391. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  1392. }
  1393. }
  1394. */
  1395. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  1396. {
  1397. tableMetadata *metadata = [[NCMainCommon shared] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1398. tableShare *shareCell;
  1399. if (metadata == nil || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata] || (_metadataFolder != nil && [[NCManageDatabase sharedInstance] isTableInvalidated:_metadataFolder])) {
  1400. return [CCCellMain new];
  1401. }
  1402. for (tableShare *share in appDelegate.shares) {
  1403. if ([share.serverUrl isEqualToString:metadata.serverUrl] && [share.fileName isEqualToString:metadata.fileName]) {
  1404. shareCell = share;
  1405. break;
  1406. }
  1407. }
  1408. UITableViewCell *cell = [[NCMainCommon shared] cellForRowAtIndexPath:indexPath tableView:tableView metadata:metadata metadataFolder:_metadataFolder serverUrl:self.serverUrl autoUploadFileName:_autoUploadFileName autoUploadDirectory:_autoUploadDirectory tableShare:shareCell livePhoto:livePhoto];
  1409. // NORMAL - > MAIN
  1410. if ([cell isKindOfClass:[CCCellMain class]]) {
  1411. // Comment tap
  1412. if (metadata.commentsUnread) {
  1413. UITapGestureRecognizer *tapComment = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionComment:)];
  1414. [tapComment setNumberOfTapsRequired:1];
  1415. ((CCCellMain *)cell).comment.userInteractionEnabled = YES;
  1416. [((CCCellMain *)cell).comment addGestureRecognizer:tapComment];
  1417. }
  1418. // Share add Tap
  1419. UITapGestureRecognizer *tapShare = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  1420. [tapShare setNumberOfTapsRequired:1];
  1421. ((CCCellMain *)cell).viewShared.userInteractionEnabled = YES;
  1422. [((CCCellMain *)cell).viewShared addGestureRecognizer:tapShare];
  1423. // More
  1424. if ([self canOpenMenuAction:metadata]) {
  1425. UITapGestureRecognizer *tapMore = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(actionMore:)];
  1426. [tapMore setNumberOfTapsRequired:1];
  1427. ((CCCellMain *)cell).more.userInteractionEnabled = YES;
  1428. [((CCCellMain *)cell).more addGestureRecognizer:tapMore];
  1429. }
  1430. // MGSwipeButton
  1431. ((CCCellMain *)cell).delegate = self;
  1432. // LEFT
  1433. ((CCCellMain *)cell).leftButtons = @[[MGSwipeButton buttonWithTitle:@"" icon:self.cellFavouriteImage backgroundColor:NCBrandColor.sharedInstance.yellowFavorite padding:25]];
  1434. ((CCCellMain *)cell).leftExpansion.buttonIndex = 0;
  1435. ((CCCellMain *)cell).leftExpansion.fillOnTrigger = NO;
  1436. //centerIconOverText
  1437. MGSwipeButton *favoriteButton = (MGSwipeButton *)[((CCCellMain *)cell).leftButtons objectAtIndex:0];
  1438. [favoriteButton centerIconOverText];
  1439. // RIGHT
  1440. ((CCCellMain *)cell).rightButtons = @[[MGSwipeButton buttonWithTitle:@"" icon:self.cellTrashImage backgroundColor:[UIColor redColor] padding:25]];
  1441. ((CCCellMain *)cell).rightExpansion.buttonIndex = 0;
  1442. ((CCCellMain *)cell).rightExpansion.fillOnTrigger = NO;
  1443. //centerIconOverText
  1444. MGSwipeButton *deleteButton = (MGSwipeButton *)[((CCCellMain *)cell).rightButtons objectAtIndex:0];
  1445. [deleteButton centerIconOverText];
  1446. }
  1447. // TRANSFER
  1448. if ([cell isKindOfClass:[CCCellMainTransfer class]]) {
  1449. // gesture Transfer
  1450. [((CCCellMainTransfer *)cell).transferButton.stopButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  1451. UILongPressGestureRecognizer *stopLongGesture = [UILongPressGestureRecognizer new];
  1452. [stopLongGesture addTarget:self action:@selector(cancelAllTask:)];
  1453. [((CCCellMainTransfer *)cell).transferButton.stopButton addGestureRecognizer:stopLongGesture];
  1454. }
  1455. return cell;
  1456. }
  1457. - (void)setTableViewHeader
  1458. {
  1459. NSInteger serverVersionMajor = [[NCManageDatabase sharedInstance] getCapabilitiesServerIntWithAccount:appDelegate.account elements:NCElementsJSON.shared.capabilitiesVersionMajor];
  1460. NSString *trimmedRichWorkspaceText = [self.richWorkspaceText stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
  1461. if (serverVersionMajor < k_nextcloud_version_18_0 || trimmedRichWorkspaceText.length == 0 ) {
  1462. [self.tableView.tableHeaderView setFrame:CGRectMake(self.tableView.tableHeaderView.frame.origin.x, self.tableView.tableHeaderView.frame.origin.y, self.tableView.frame.size.width, heightSearchBar)];
  1463. } else {
  1464. [self.viewRichWorkspace setFrame:CGRectMake(self.tableView.tableHeaderView.frame.origin.x, self.tableView.tableHeaderView.frame.origin.y, self.tableView.frame.size.width, heightRichWorkspace)];
  1465. }
  1466. if (self.searchController.isActive == true) {
  1467. [self.tableView.tableHeaderView setFrame:CGRectMake(self.tableView.tableHeaderView.frame.origin.x, self.tableView.tableHeaderView.frame.origin.y, self.tableView.frame.size.width, 0)];
  1468. }
  1469. [self.viewRichWorkspace setNeedsLayout];
  1470. [self.viewRichWorkspace loadWithRichWorkspaceText:self.richWorkspaceText];
  1471. }
  1472. - (void)setTableViewFooter
  1473. {
  1474. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  1475. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  1476. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  1477. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  1478. UIFont *appFont = [UIFont systemFontOfSize:12];
  1479. footerLabel.font = appFont;
  1480. footerLabel.textColor = [UIColor grayColor];
  1481. footerLabel.backgroundColor = [UIColor clearColor];
  1482. footerLabel.textAlignment = NSTextAlignmentCenter;
  1483. NSString *folders;
  1484. NSString *files;
  1485. NSString *footerText;
  1486. if (sectionDataSource.directories > 1) {
  1487. folders = [NSString stringWithFormat:@"%ld %@", (long)sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  1488. } else if (sectionDataSource.directories == 1){
  1489. folders = [NSString stringWithFormat:@"%ld %@", (long)sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  1490. } else {
  1491. folders = @"";
  1492. }
  1493. if (sectionDataSource.files > 1) {
  1494. files = [NSString stringWithFormat:@"%ld %@ %@", (long)sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:sectionDataSource.totalSize]];
  1495. } else if (sectionDataSource.files == 1){
  1496. files = [NSString stringWithFormat:@"%ld %@ %@", (long)sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:sectionDataSource.totalSize]];
  1497. } else {
  1498. files = @"";
  1499. }
  1500. if ([folders isEqualToString:@""]) {
  1501. footerText = files;
  1502. } else if ([files isEqualToString:@""]) {
  1503. footerText = folders;
  1504. } else {
  1505. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  1506. }
  1507. footerLabel.text = footerText;
  1508. [footerView addSubview:footerLabel];
  1509. [self.tableView setTableFooterView:footerView];
  1510. }
  1511. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  1512. {
  1513. CCCellMain *cell = [tableView cellForRowAtIndexPath:indexPath];
  1514. // settiamo il record file.
  1515. self.metadata = [[NCMainCommon shared] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1516. if (!self.metadata)
  1517. return;
  1518. // se non può essere selezionata deseleziona
  1519. if ([cell isEditing] == NO)
  1520. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  1521. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  1522. if (self.tableView.editing) {
  1523. [selectOcId addObject:self.metadata.ocId];
  1524. [self setTitle];
  1525. return;
  1526. }
  1527. if (self.metadata.status != k_metadataStatusNormal && self.metadata.status != k_metadataStatusDownloadError) {
  1528. return;
  1529. }
  1530. // file
  1531. if (self.metadata.directory == NO) {
  1532. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  1533. if ([CCUtility fileProviderStorageExists:self.metadata.ocId fileNameView:self.metadata.fileNameView]) {
  1534. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_downloadedFile object:nil userInfo:@{@"metadata": self.metadata, @"selector": selectorLoadFileView, @"errorCode": @(0), @"errorDescription": @""}];
  1535. } else {
  1536. if (_metadataFolder.e2eEncrypted && ![CCUtility isEndToEndEnabled:appDelegate.account]) {
  1537. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:k_CCErrorE2EENotEnabled forced:true];
  1538. } else {
  1539. if (([self.metadata.typeFile isEqualToString: k_metadataTypeFile_video] || [self.metadata.typeFile isEqualToString: k_metadataTypeFile_audio]) && _metadataFolder.e2eEncrypted == NO) {
  1540. [self shouldPerformSegue:self.metadata selector:@""];
  1541. } else if ([self.metadata.typeFile isEqualToString: k_metadataTypeFile_document] && [[NCUtility shared] isDirectEditingWithAccount:self.metadata.account contentType:self.metadata.contentType] != nil) {
  1542. if (NCCommunication.shared.isNetworkReachable) {
  1543. [self shouldPerformSegue:self.metadata selector:@""];
  1544. } else {
  1545. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_go_online_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:k_CCErrorOffline forced:true];
  1546. }
  1547. } else if ([self.metadata.typeFile isEqualToString: k_metadataTypeFile_document] && [[NCUtility shared] isRichDocument:self.metadata]) {
  1548. if (NCCommunication.shared.isNetworkReachable) {
  1549. [self shouldPerformSegue:self.metadata selector:@""];
  1550. } else {
  1551. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_go_online_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:k_CCErrorOffline forced:true];
  1552. }
  1553. } else {
  1554. if ([self.metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  1555. [self shouldPerformSegue:self.metadata selector:selectorLoadFileView];
  1556. }
  1557. [[NCNetworking shared] downloadWithMetadata:self.metadata selector:selectorLoadFileView setFavorite:false completion:^(NSInteger errorCode) { }];
  1558. }
  1559. }
  1560. }
  1561. }
  1562. if (self.metadata.directory) {
  1563. [self performSegueDirectoryWithMetadata:self.metadata blinkFileNamePath:self.blinkFileNamePath];
  1564. }
  1565. }
  1566. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  1567. {
  1568. tableMetadata *metadata = [[NCMainCommon shared] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1569. [selectOcId removeObject:metadata.ocId];
  1570. [self setTitle];
  1571. }
  1572. - (void)didSelectAll
  1573. {
  1574. for (int i = 0; i < self.tableView.numberOfSections; i++) {
  1575. for (int j = 0; j < [self.tableView numberOfRowsInSection:i]; j++) {
  1576. NSIndexPath *indexPath = [NSIndexPath indexPathForRow:j inSection:i];
  1577. tableMetadata *metadata = [[NCMainCommon shared] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1578. [selectOcId addObject:metadata.ocId];
  1579. [self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
  1580. }
  1581. }
  1582. [self setTitle];
  1583. }
  1584. - (BOOL)indexPathIsValid:(NSIndexPath *)indexPath
  1585. {
  1586. if (!indexPath)
  1587. return NO;
  1588. NSInteger section = indexPath.section;
  1589. NSInteger row = indexPath.row;
  1590. NSInteger lastSectionIndex = [self numberOfSectionsInTableView:self.tableView] - 1;
  1591. if (section > lastSectionIndex || lastSectionIndex < 0)
  1592. return NO;
  1593. NSInteger rowCount = [self.tableView numberOfRowsInSection:indexPath.section] - 1;
  1594. if (rowCount < 0)
  1595. return NO;
  1596. return row <= rowCount;
  1597. }
  1598. #pragma --------------------------------------------------------------------------------------------
  1599. #pragma mark ===== Navigation ====
  1600. #pragma --------------------------------------------------------------------------------------------
  1601. - (void)shouldPerformSegue:(tableMetadata *)metadata selector:(NSString *)selector
  1602. {
  1603. // if background return
  1604. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return;
  1605. if (self.view.window == NO)
  1606. return;
  1607. // Collapsed ma siamo già in detail esci
  1608. if (self.splitViewController.isCollapsed) {
  1609. if (appDelegate.activeDetail.isViewLoaded && appDelegate.activeDetail.view.window) return;
  1610. }
  1611. // Metadata for push detail
  1612. self.metadataForPushDetail = metadata;
  1613. self.selectorForPushDetail = selector;
  1614. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  1615. }
  1616. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  1617. {
  1618. tableMetadata *metadata;
  1619. NSMutableArray *photoDataSource = [NSMutableArray new];
  1620. UINavigationController *navigationController = segue.destinationViewController;
  1621. NCDetailViewController *detailViewController = (NCDetailViewController *)navigationController.topViewController;
  1622. if ([sender isKindOfClass:[tableMetadata class]]) {
  1623. metadata = sender;
  1624. [photoDataSource addObject:sender];
  1625. } else {
  1626. metadata = self.metadataForPushDetail;
  1627. for (NSString *ocId in sectionDataSource.allOcId) {
  1628. tableMetadata *metadata = [sectionDataSource.allRecordsDataSource objectForKey:ocId];
  1629. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  1630. [photoDataSource addObject:metadata];
  1631. }
  1632. }
  1633. detailViewController.metadata = metadata;
  1634. detailViewController.selector = self.selectorForPushDetail;
  1635. [detailViewController setTitle:metadata.fileNameView];
  1636. }
  1637. // can i go to next viewcontroller
  1638. - (void)performSegueDirectoryWithMetadata:(tableMetadata *)metadata blinkFileNamePath:(NSString *)blinkFileNamePath
  1639. {
  1640. NSString *nomeDir;
  1641. if (self.tableView.editing == NO) {
  1642. // E2EE Check enable
  1643. if (metadata.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.account] == NO) {
  1644. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:k_CCErrorE2EENotEnabled forced:true];
  1645. return;
  1646. }
  1647. nomeDir = metadata.fileName;
  1648. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:metadata.serverUrl addFileName:nomeDir];
  1649. CCMain *viewController = [appDelegate.listMainVC objectForKey:serverUrlPush];
  1650. if (!viewController) {
  1651. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMain"];
  1652. viewController.serverUrl = serverUrlPush;
  1653. viewController.titleMain = metadata.fileNameView;
  1654. viewController.blinkFileNamePath = blinkFileNamePath;
  1655. // save self
  1656. [appDelegate.listMainVC setObject:viewController forKey:serverUrlPush];
  1657. [self.navigationController pushViewController:viewController animated:YES];
  1658. } else {
  1659. if (viewController.isViewLoaded) {
  1660. viewController.titleMain = metadata.fileNameView;
  1661. viewController.blinkFileNamePath = blinkFileNamePath;
  1662. // Fix : Application tried to present modally an active controller
  1663. if ([self.navigationController isBeingPresented]) {
  1664. // being presented
  1665. } else if ([self.navigationController isMovingToParentViewController]) {
  1666. // being pushed
  1667. } else {
  1668. [self.navigationController pushViewController:viewController animated:YES];
  1669. }
  1670. }
  1671. }
  1672. }
  1673. }
  1674. @end