CCMain.m 113 KB

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