CCMain.m 115 KB

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