CCMain.m 114 KB

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