CCMain.m 92 KB

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