CCMain.m 96 KB

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