CCMain.m 94 KB

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