CCMain.m 114 KB

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