CCMain.m 94 KB

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