CCMain.m 114 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667
  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:@"[LOG] 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:selectorDownloadFile];
  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. [self SetSortButtonText];
  571. }
  572. - (void)setUINavigationBarDefault
  573. {
  574. UIBarButtonItem *buttonSelect = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_select_", @"") style:UIBarButtonItemStylePlain target:self action:@selector(tableViewToggle)];
  575. self.navigationController.navigationBar.hidden = NO;
  576. self.navigationItem.rightBarButtonItem = buttonSelect;
  577. self.navigationItem.leftBarButtonItem = nil;
  578. }
  579. - (void)setUINavigationBarSelected
  580. {
  581. UIBarButtonItem *buttonMore = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationMore"] style:UIBarButtonItemStylePlain target:self action:@selector(toggleSelectMenu)];
  582. UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(cancelSelect)];
  583. self.navigationItem.leftBarButtonItem = leftButton;
  584. self.navigationItem.rightBarButtonItem = buttonMore; //[[NSArray alloc] initWithObjects:buttonMore, nil];
  585. }
  586. - (void)cancelSelect
  587. {
  588. [self tableViewSelect:false];
  589. }
  590. #pragma --------------------------------------------------------------------------------------------
  591. #pragma mark ===== Document Picker =====
  592. #pragma --------------------------------------------------------------------------------------------
  593. - (void)documentMenuWasCancelled:(UIDocumentMenuViewController *)documentMenu
  594. {
  595. NSLog(@"[LOG] Cancelled");
  596. }
  597. - (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller
  598. {
  599. NSLog(@"[LOG] Cancelled");
  600. }
  601. - (void)documentMenu:(UIDocumentMenuViewController *)documentMenu didPickDocumentPicker:(UIDocumentPickerViewController *)documentPicker
  602. {
  603. documentPicker.delegate = self;
  604. [self presentViewController:documentPicker animated:YES completion:nil];
  605. }
  606. - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
  607. {
  608. if (controller.documentPickerMode == UIDocumentPickerModeImport) {
  609. NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
  610. __block NSError *error;
  611. [coordinator coordinateReadingItemAtURL:url options:NSFileCoordinatorReadingForUploading error:&error byAccessor:^(NSURL *newURL) {
  612. NSString *serverUrl = [appDelegate getTabBarControllerActiveServerUrl];
  613. NSString *fileName = [url lastPathComponent];
  614. NSString *ocId = [[NSUUID UUID] UUIDString];
  615. NSData *data = [NSData dataWithContentsOfURL:newURL];
  616. if (data && error == nil) {
  617. if ([data writeToFile:[CCUtility getDirectoryProviderStorageOcId:ocId fileNameView:fileName] options:NSDataWritingAtomic error:&error]) {
  618. tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] createMetadataWithAccount:appDelegate.account fileName:fileName ocId:ocId serverUrl:serverUrl urlBase:appDelegate.urlBase url:@"" contentType:@"" livePhoto:false];
  619. metadataForUpload.session = NCCommunicationCommon.shared.sessionIdentifierBackground;
  620. metadataForUpload.sessionSelector = selectorUploadFile;
  621. metadataForUpload.size = data.length;
  622. metadataForUpload.status = k_metadataStatusWaitUpload;
  623. if ([[NCUtility shared] getMetadataConflictWithAccount:appDelegate.account serverUrl:serverUrl fileName:fileName] != nil) {
  624. NCCreateFormUploadConflict *conflict = [[UIStoryboard storyboardWithName:@"NCCreateFormUploadConflict" bundle:nil] instantiateInitialViewController];
  625. conflict.serverUrl = self.serverUrl;
  626. conflict.metadatasUploadInConflict = @[metadataForUpload];
  627. [self presentViewController:conflict animated:YES completion:nil];
  628. } else {
  629. [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  630. [[appDelegate networkingAutoUpload] startProcess];
  631. }
  632. } else {
  633. [[NCContentPresenter shared] messageNotification:@"_error_" description:error.description delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code forced:false];
  634. }
  635. } else {
  636. [[NCContentPresenter shared] messageNotification:@"_error_" description:@"_read_file_error_" delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code forced:false];
  637. }
  638. }];
  639. }
  640. }
  641. - (void)openImportDocumentPicker
  642. {
  643. UIDocumentMenuViewController *documentProviderMenu = [[UIDocumentMenuViewController alloc] initWithDocumentTypes:@[@"public.data"] inMode:UIDocumentPickerModeImport];
  644. documentProviderMenu.modalPresentationStyle = UIModalPresentationFormSheet;
  645. documentProviderMenu.popoverPresentationController.sourceView = self.tabBarController.tabBar;
  646. documentProviderMenu.popoverPresentationController.sourceRect = self.tabBarController.tabBar.bounds;
  647. documentProviderMenu.delegate = self;
  648. [self presentViewController:documentProviderMenu animated:YES completion:nil];
  649. }
  650. #pragma --------------------------------------------------------------------------------------------
  651. #pragma mark ===== Assets Picker =====
  652. #pragma --------------------------------------------------------------------------------------------
  653. -(void)dismissFormUploadAssets
  654. {
  655. }
  656. - (void)openAssetsPickerController
  657. {
  658. NCPhotosPickerViewController *viewController = [[NCPhotosPickerViewController alloc] init:self maxSelectedAssets:100 singleSelectedMode:false];
  659. [viewController openPhotosPickerViewControllerWithPhAssets:^(NSArray<PHAsset *> * _Nullable assets) {
  660. if (assets.count > 0) {
  661. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  662. NSString *serverUrl = [appDelegate getTabBarControllerActiveServerUrl];
  663. NCCreateFormUploadAssets *form = [[NCCreateFormUploadAssets alloc] initWithServerUrl:serverUrl assets:(NSMutableArray *)assets cryptated:NO session:NCCommunicationCommon.shared.sessionIdentifierBackground delegate:self];
  664. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:form];
  665. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  666. [self presentViewController:navigationController animated:YES completion:nil];
  667. });
  668. }
  669. }];
  670. }
  671. #pragma --------------------------------------------------------------------------------------------
  672. #pragma mark ===== Save selected File =====
  673. #pragma --------------------------------------------------------------------------------------------
  674. - (void)saveToPhotoAlbum:(tableMetadata *)metadata
  675. {
  676. NSString *fileNamePath = [CCUtility getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileNameView];
  677. PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
  678. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] && status == PHAuthorizationStatusAuthorized) {
  679. UIImage *image = [UIImage imageWithContentsOfFile:fileNamePath];
  680. if (image)
  681. UIImageWriteToSavedPhotosAlbum(image, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  682. else
  683. [[NCContentPresenter shared] messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorFileNotSaved forced:false];
  684. }
  685. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video] && status == PHAuthorizationStatusAuthorized) {
  686. if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(fileNamePath)) {
  687. UISaveVideoAtPathToSavedPhotosAlbum(fileNamePath, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  688. } else {
  689. [[NCContentPresenter shared] messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorFileNotSaved forced:false];
  690. }
  691. }
  692. if (status != PHAuthorizationStatusAuthorized) {
  693. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil) message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil) preferredStyle:UIAlertControllerStyleAlert];
  694. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  695. [alertController addAction:okAction];
  696. [self presentViewController:alertController animated:YES completion:nil];
  697. }
  698. }
  699. - (void)saveSelectedFilesSelector:(NSString *)path didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
  700. {
  701. if (error) {
  702. [[NCContentPresenter shared] messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code forced:false];
  703. }
  704. }
  705. - (void)saveSelectedFiles
  706. {
  707. if (_isSelectedMode && [_selectedocIdsMetadatas count] == 0)
  708. return;
  709. NSLog(@"[LOG] Start download selected files ...");
  710. [_hud visibleHudTitle:@"" mode:MBProgressHUDModeIndeterminate color:nil];
  711. NSArray *metadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  712. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  713. for (tableMetadata *metadata in metadatas) {
  714. if (metadata.directory == NO && ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])) {
  715. [[NCOperationQueue shared] downloadWithMetadata:metadata selector:selectorSaveAlbum setFavorite:false];
  716. }
  717. }
  718. [_hud hideHud];
  719. });
  720. [self tableViewSelect:false];
  721. }
  722. #pragma mark -
  723. #pragma --------------------------------------------------------------------------------------------
  724. #pragma mark ===== Peek & Pop =====
  725. #pragma --------------------------------------------------------------------------------------------
  726. - (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
  727. {
  728. CGPoint convertedLocation = [self.view convertPoint:location toView:self.tableView];
  729. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:convertedLocation];
  730. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  731. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  732. if (cell) {
  733. previewingContext.sourceRect = cell.frame;
  734. CCPeekPop *viewController = [[UIStoryboard storyboardWithName:@"CCPeekPop" bundle:nil] instantiateViewControllerWithIdentifier:@"PeekPopImagePreview"];
  735. viewController.metadata = metadata;
  736. viewController.imageFile = cell.file.image;
  737. viewController.showOpenIn = true;
  738. viewController.showShare = true;
  739. viewController.showOpenQuickLook = [[NCUtility shared] isQuickLookDisplayableWithMetadata:metadata];
  740. return viewController;
  741. }
  742. return nil;
  743. }
  744. - (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit
  745. {
  746. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:previewingContext.sourceRect.origin];
  747. [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
  748. }
  749. #pragma --------------------------------------------------------------------------------------------
  750. #pragma mark ==== Download ====
  751. #pragma --------------------------------------------------------------------------------------------
  752. - (void)downloadSelectedFilesFolders
  753. {
  754. if (_isSelectedMode && [_selectedocIdsMetadatas count] == 0)
  755. return;
  756. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  757. for (tableMetadata *metadata in selectedMetadatas) {
  758. [[NCOperationQueue shared] synchronizationMetadata:metadata selector:selectorDownloadFile];
  759. }
  760. [self tableViewSelect:false];
  761. }
  762. #pragma --------------------------------------------------------------------------------------------
  763. #pragma mark ===== Upload new Photos/Videos =====
  764. #pragma --------------------------------------------------------------------------------------------
  765. - (void)uploadFileAsset:(NSMutableArray *)assets serverUrl:(NSString *)serverUrl useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  766. {
  767. // if request create the folder for Auto Upload & the subfolders
  768. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  769. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPathWithUrlBase:appDelegate.urlBase account:appDelegate.account];
  770. if ([autoUploadPath isEqualToString:serverUrl]) {
  771. if ([[NCNetworking shared] createFoloderWithAssets:(PHFetchResult *)assets selector:selectorUploadFile useSubFolder:useSubFolder account:appDelegate.account urlBase:appDelegate.urlBase]) {
  772. [[NCContentPresenter shared] messageNotification:@"_error_" description:@"_error_createsubfolders_upload_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError forced:true];
  773. return;
  774. }
  775. }
  776. [self uploadFileAsset:assets serverUrl:serverUrl autoUploadPath:autoUploadPath useSubFolder:useSubFolder session:session];
  777. });
  778. }
  779. - (void)uploadFileAsset:(NSArray *)assets serverUrl:(NSString *)serverUrl autoUploadPath:(NSString *)autoUploadPath useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  780. {
  781. NSMutableArray *metadatasNOConflict = [NSMutableArray new];
  782. NSMutableArray *metadatasMOV = [NSMutableArray new];
  783. NSMutableArray *metadatasUploadInConflict = [NSMutableArray new];
  784. for (PHAsset *asset in assets) {
  785. BOOL livePhoto = false;
  786. NSString *fileName = [CCUtility createFileName:[asset valueForKey:@"filename"] fileDate:asset.creationDate fileType:asset.mediaType keyFileName:k_keyFileNameMask keyFileNameType:k_keyFileNameType keyFileNameOriginal:k_keyFileNameOriginal];
  787. NSDate *assetDate = asset.creationDate;
  788. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  789. // Detect LivePhoto Upload
  790. if ((asset.mediaSubtypes == PHAssetMediaSubtypePhotoLive || asset.mediaSubtypes == PHAssetMediaSubtypePhotoLive+PHAssetMediaSubtypePhotoHDR) && CCUtility.getLivePhoto) {
  791. livePhoto = true;
  792. }
  793. // Create serverUrl if use sub folder
  794. if (useSubFolder) {
  795. [formatter setDateFormat:@"yyyy"];
  796. NSString *yearString = [formatter stringFromDate:assetDate];
  797. [formatter setDateFormat:@"MM"];
  798. NSString *monthString = [formatter stringFromDate:assetDate];
  799. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", autoUploadPath, yearString, monthString];
  800. }
  801. // Check if is in upload
  802. 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];
  803. if ([isRecordInSessions count] > 0)
  804. continue;
  805. // Prepare record metadata
  806. tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] createMetadataWithAccount:appDelegate.account fileName:fileName ocId:[[NSUUID UUID] UUIDString] serverUrl:serverUrl urlBase:appDelegate.urlBase url:@"" contentType:@"" livePhoto:livePhoto];
  807. metadataForUpload.assetLocalIdentifier = asset.localIdentifier;
  808. metadataForUpload.session = session;
  809. metadataForUpload.sessionSelector = selectorUploadFile;
  810. metadataForUpload.size = [[NCUtilityFileSystem shared] getFileSizeWithAsset:asset];
  811. metadataForUpload.status = k_metadataStatusWaitUpload;
  812. if ([[NCUtility shared] getMetadataConflictWithAccount:appDelegate.account serverUrl:serverUrl fileName:fileName] != nil) {
  813. [metadatasUploadInConflict addObject:metadataForUpload];
  814. } else {
  815. [metadatasNOConflict addObject:metadataForUpload];
  816. }
  817. // Add Medtadata MOV LIVE PHOTO for upload
  818. if (livePhoto) {
  819. NSString *fileNameMove = [NSString stringWithFormat:@"%@.mov", fileName.stringByDeletingPathExtension];
  820. NSString *ocId = [[NSUUID UUID] UUIDString];
  821. NSString *filePath = [CCUtility getDirectoryProviderStorageOcId:ocId fileNameView:fileNameMove];
  822. dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
  823. [CCUtility extractLivePhotoAsset:asset filePath:filePath withCompletion:^(NSURL *url) {
  824. if (url != nil) {
  825. unsigned long long fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:url.path error:nil] fileSize];
  826. tableMetadata *metadataMOVForUpload = [[NCManageDatabase sharedInstance] createMetadataWithAccount:appDelegate.account fileName:fileNameMove ocId:ocId serverUrl:serverUrl urlBase:appDelegate.urlBase url:@"" contentType:@"" livePhoto:livePhoto];
  827. metadataMOVForUpload.session = session;
  828. metadataMOVForUpload.sessionSelector = selectorUploadFile;
  829. metadataMOVForUpload.size = fileSize;
  830. metadataMOVForUpload.status = k_metadataStatusWaitUpload;
  831. metadataMOVForUpload.typeFile = k_metadataTypeFile_video;
  832. [metadatasMOV addObject:metadataMOVForUpload];
  833. }
  834. dispatch_semaphore_signal(semaphore);
  835. }];
  836. while (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER))
  837. [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:30]];
  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 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.layoutViewSelect = 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. NSLog(@"[LOG] Cancel action");
  1120. }];
  1121. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  1122. UITextField *fileName = alertController.textFields.firstObject;
  1123. [[NCNetworking shared] createFolderWithFileName:[fileName.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] serverUrl:serverUrl account:appDelegate.account urlBase:appDelegate.urlBase overwrite:false completion:^(NSInteger errorCode, NSString *errorDescription) { }];
  1124. }];
  1125. okAction.enabled = NO;
  1126. [alertController addAction:cancelAction];
  1127. [alertController addAction:okAction];
  1128. [self presentViewController:alertController animated:YES completion:nil];
  1129. }
  1130. #pragma --------------------------------------------------------------------------------------------
  1131. #pragma mark ===== Progress & Task Button =====
  1132. #pragma --------------------------------------------------------------------------------------------
  1133. - (void)triggerProgressTask:(NSNotification *)notification
  1134. {
  1135. if (sectionDataSource.ocIdIndexPath != nil) {
  1136. [[NCMainCommon sharedInstance] triggerProgressTask:notification sectionDataSourceocIdIndexPath:sectionDataSource.ocIdIndexPath tableView:self.tableView viewController:self serverUrlViewController:self.serverUrl];
  1137. }
  1138. }
  1139. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  1140. {
  1141. UITouch *touch = [[event allTouches] anyObject];
  1142. CGPoint location = [touch locationInView:self.tableView];
  1143. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1144. if ([self indexPathIsValid:indexPath]) {
  1145. tableMetadata *metadataSection = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1146. if (metadataSection) {
  1147. [[NCMainCommon sharedInstance] cancelTransferMetadata:metadataSection reloadDatasource:true uploadStatusForcedStart:false];
  1148. }
  1149. }
  1150. }
  1151. - (void)cancelAllTask:(id)sender
  1152. {
  1153. CGPoint location = [sender locationInView:self.tableView];
  1154. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1155. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  1156. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_all_task_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  1157. [NCUtility.shared startActivityIndicatorWithView:self.view bottom:0];
  1158. [[NCMainCommon sharedInstance] cancelAllTransfer];
  1159. [NCUtility.shared stopActivityIndicator];
  1160. }]];
  1161. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) { }]];
  1162. alertController.popoverPresentationController.sourceView = self.tableView;
  1163. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  1164. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  1165. [alertController.view layoutIfNeeded];
  1166. [self presentViewController:alertController animated:YES completion:nil];
  1167. }
  1168. #pragma --------------------------------------------------------------------------------------------
  1169. #pragma mark ===== Tap =====
  1170. #pragma --------------------------------------------------------------------------------------------
  1171. - (void)tapActionComment:(UITapGestureRecognizer *)tapGesture
  1172. {
  1173. CGPoint location = [tapGesture locationInView:self.tableView];
  1174. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1175. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1176. if (metadata && ![CCUtility isFolderEncrypted:self.serverUrl e2eEncrypted:metadata.e2eEncrypted account:appDelegate.account urlBase: appDelegate.urlBase]) {
  1177. [[NCMainCommon sharedInstance] openShareWithViewController:self metadata:metadata indexPage:1];
  1178. }
  1179. }
  1180. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  1181. {
  1182. CGPoint location = [tapGesture locationInView:self.tableView];
  1183. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1184. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1185. if (metadata && ![CCUtility isFolderEncrypted:self.serverUrl e2eEncrypted:metadata.e2eEncrypted account:appDelegate.account urlBase:appDelegate.urlBase]) {
  1186. [[NCMainCommon sharedInstance] openShareWithViewController:self metadata:metadata indexPage:2];
  1187. }
  1188. }
  1189. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  1190. {
  1191. CGPoint location = [tapGesture locationInView:self.tableView];
  1192. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1193. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1194. if (metadata) {
  1195. }
  1196. }
  1197. #pragma --------------------------------------------------------------------------------------------
  1198. #pragma mark ===== Rich Workspace =====
  1199. #pragma --------------------------------------------------------------------------------------------
  1200. - (void)viewRichWorkspaceTapAction:(UITapGestureRecognizer *)tapGesture
  1201. {
  1202. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"NCViewerRichWorkspace" bundle:nil] instantiateInitialViewController];
  1203. NCViewerRichWorkspace *viewerRichWorkspace = (NCViewerRichWorkspace *)[navigationController topViewController];
  1204. viewerRichWorkspace.richWorkspaceText = self.richWorkspaceText;
  1205. viewerRichWorkspace.serverUrl = self.serverUrl;
  1206. navigationController.modalPresentationStyle = UIModalPresentationFullScreen;
  1207. [self presentViewController:navigationController animated:NO completion:NULL];
  1208. }
  1209. - (void)createRichWorkspace
  1210. {
  1211. NCRichWorkspaceCommon *richWorkspaceCommon = [NCRichWorkspaceCommon new];
  1212. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileNameView LIKE[c] %@", appDelegate.account, self.serverUrl, k_fileNameRichWorkspace.lowercaseString]];
  1213. if (metadata) {
  1214. [richWorkspaceCommon openViewerNextcloudTextWithServerUrl:self.serverUrl viewController:self];
  1215. } else {
  1216. [richWorkspaceCommon createViewerNextcloudTextWithServerUrl:self.serverUrl viewController:self];
  1217. }
  1218. }
  1219. - (void)toggleSortMenu
  1220. {
  1221. [self toggleMenuWithViewController:self.navigationController];
  1222. }
  1223. - (void)toggleSelectMenu
  1224. {
  1225. [self toggleSelectMenuWithViewController:self.navigationController];
  1226. }
  1227. #pragma --------------------------------------------------------------------------------------------
  1228. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  1229. #pragma --------------------------------------------------------------------------------------------
  1230. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  1231. {
  1232. if (recognizer.state == UIGestureRecognizerStateBegan) {
  1233. CGPoint touchPoint = [recognizer locationInView:self.tableView];
  1234. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:touchPoint];
  1235. NSMutableArray *items = [NSMutableArray new];
  1236. if ([self indexPathIsValid:indexPath])
  1237. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1238. [self becomeFirstResponder];
  1239. UIMenuController *menuController = [UIMenuController sharedMenuController];
  1240. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyTouchFile:)]];
  1241. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyTouchFiles:)]];
  1242. if ([NCBrandOptions sharedInstance].disable_openin_file == false) {
  1243. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinTouchFile:)]];
  1244. }
  1245. if ([[NCUtility shared] isQuickLookDisplayableWithMetadata:self.metadata]) {
  1246. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_quicklook_", nil) action:@selector(openQuickLookTouch:)]];
  1247. }
  1248. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteTouchFile:)]];
  1249. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteTouchFiles:)]];
  1250. [menuController setMenuItems:items];
  1251. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:self.tableView];
  1252. [menuController setMenuVisible:YES animated:YES];
  1253. }
  1254. }
  1255. - (BOOL)canBecomeFirstResponder
  1256. {
  1257. return YES;
  1258. }
  1259. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  1260. {
  1261. // For copy file, copy files, Open in ... :
  1262. //
  1263. // NO Directory
  1264. // NO Error Passcode
  1265. // NO In Session mode (download/upload)
  1266. // NO Template
  1267. if (@selector(copyTouchFile:) == action || @selector(openinTouchFile:) == action || @selector(openQuickLookTouch:) == action) {
  1268. if (_isSelectedMode == NO && self.metadata && !self.metadata.directory && self.metadata.status == k_metadataStatusNormal) return YES;
  1269. else return NO;
  1270. }
  1271. if (@selector(copyTouchFiles:) == action) {
  1272. if (_isSelectedMode) {
  1273. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1274. for (tableMetadata *metadata in selectedMetadatas) {
  1275. if (!metadata.directory && metadata.status == k_metadataStatusNormal)
  1276. return YES;
  1277. }
  1278. }
  1279. return NO;
  1280. }
  1281. if (@selector(pasteTouchFile:) == action) {
  1282. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1283. NSArray *items = [pasteboard items];
  1284. if ([items count] == 1) {
  1285. // Value : (NSData) ocId
  1286. NSDictionary *dic = [items objectAtIndex:0];
  1287. NSData *dataocId = [dic objectForKey: k_metadataKeyedUnarchiver];
  1288. NSString *ocId = [NSKeyedUnarchiver unarchiveObjectWithData:dataocId];
  1289. if (ocId) {
  1290. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocId]];
  1291. if (metadata) {
  1292. return [CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView];
  1293. } else {
  1294. return NO;
  1295. }
  1296. }
  1297. }
  1298. return NO;
  1299. }
  1300. if (@selector(pasteTouchFiles:) == action) {
  1301. BOOL isValid = NO;
  1302. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1303. NSArray *items = [pasteboard items];
  1304. if ([items count] <= 1) return NO;
  1305. for (NSDictionary *dic in items) {
  1306. // Value : (NSData) ocId
  1307. NSData *dataocId = [dic objectForKey: k_metadataKeyedUnarchiver];
  1308. NSString *ocId = [NSKeyedUnarchiver unarchiveObjectWithData:dataocId];
  1309. if (ocId) {
  1310. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocId]];
  1311. if (metadata) {
  1312. if ([CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView]) {
  1313. isValid = YES;
  1314. } else {
  1315. isValid = NO;
  1316. break;
  1317. }
  1318. } else {
  1319. isValid = NO;
  1320. break;
  1321. }
  1322. } else {
  1323. isValid = NO;
  1324. break;
  1325. }
  1326. }
  1327. return isValid;
  1328. }
  1329. return NO;
  1330. }
  1331. /************************************ COPY ************************************/
  1332. - (void)copyTouchFile:(id)sender
  1333. {
  1334. // Remove all item
  1335. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1336. pasteboard.items = [[NSArray alloc] init];
  1337. if ([CCUtility fileProviderStorageExists:self.metadata.ocId fileNameView:self.metadata.fileNameView]) {
  1338. [self copyFileToPasteboard:self.metadata];
  1339. } else {
  1340. [[NCNetworking shared] downloadWithMetadata:self.metadata selector:selectorLoadCopy setFavorite:false completion:^(NSInteger errorCode) { }];
  1341. }
  1342. }
  1343. - (void)copyTouchFiles:(id)sender
  1344. {
  1345. // Remove all item
  1346. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1347. pasteboard.items = [[NSArray alloc] init];
  1348. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1349. for (tableMetadata *metadata in selectedMetadatas) {
  1350. if ([CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView]) {
  1351. [self copyFileToPasteboard:metadata];
  1352. } else {
  1353. [[NCNetworking shared] downloadWithMetadata:metadata selector:selectorLoadCopy setFavorite:false completion:^(NSInteger errorCode) { }];
  1354. }
  1355. }
  1356. [self tableViewSelect:false];
  1357. }
  1358. - (void)copyFileToPasteboard:(tableMetadata *)metadata
  1359. {
  1360. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1361. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  1362. // Value : (NSData) ocId
  1363. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata.ocId], k_metadataKeyedUnarchiver,nil];
  1364. [items addObject:item];
  1365. [pasteboard setItems:items];
  1366. }
  1367. /************************************ OPEN IN ... ******************************/
  1368. - (void)openinTouchFile:(id)sender
  1369. {
  1370. [[NCMainCommon sharedInstance] downloadOpenWithMetadata:self.metadata selector:selectorOpenIn];
  1371. }
  1372. /************************************ OPEN QUICK LOOK ******************************/
  1373. - (void)openQuickLookTouch:(id)sender
  1374. {
  1375. [[NCMainCommon sharedInstance] downloadOpenWithMetadata:self.metadata selector:selectorLoadFileQuickLook];
  1376. }
  1377. /************************************ PASTE ************************************/
  1378. - (void)pasteTouchFile:(id)sender
  1379. {
  1380. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1381. [self uploadFilePasteArray:[pasteboard items]];
  1382. }
  1383. - (void)pasteTouchFiles:(id)sender
  1384. {
  1385. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1386. [self uploadFilePasteArray:[pasteboard items]];
  1387. }
  1388. - (void)uploadFilePasteArray:(NSArray *)items
  1389. {
  1390. for (NSDictionary *dic in items) {
  1391. // Value : (NSData) ocId
  1392. NSData *dataocId = [dic objectForKey: k_metadataKeyedUnarchiver];
  1393. NSString *ocId = [NSKeyedUnarchiver unarchiveObjectWithData:dataocId];
  1394. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocId]];
  1395. if (metadata) {
  1396. if ([CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView]) {
  1397. NSString *fileName = [[NCUtility shared] createFileName:metadata.fileNameView serverUrl:self.serverUrl account:appDelegate.account];
  1398. NSString *ocId = [[NSUUID UUID] UUIDString];
  1399. [CCUtility copyFileAtPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileNameView] toPath:[CCUtility getDirectoryProviderStorageOcId:ocId fileNameView:fileName]];
  1400. // Prepare record metadata
  1401. tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] createMetadataWithAccount:appDelegate.account fileName:fileName ocId:ocId serverUrl:self.serverUrl urlBase:appDelegate.urlBase url:@"" contentType:@"" livePhoto:false];
  1402. metadataForUpload.session = NCCommunicationCommon.shared.sessionIdentifierBackground;
  1403. metadataForUpload.sessionSelector = selectorUploadFile;
  1404. metadataForUpload.size = metadata.size;
  1405. metadataForUpload.status = k_metadataStatusWaitUpload;
  1406. // Add Medtadata for upload
  1407. [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1408. }
  1409. }
  1410. }
  1411. [[appDelegate networkingAutoUpload] startProcess];
  1412. }
  1413. #pragma mark -
  1414. #pragma --------------------------------------------------------------------------------------------
  1415. #pragma mark ===== menu action : Favorite, More, Delete [swipe] =====
  1416. #pragma --------------------------------------------------------------------------------------------
  1417. - (BOOL)canOpenMenuAction:(tableMetadata *)metadata
  1418. {
  1419. if (metadata == nil)
  1420. return NO;
  1421. // E2EE
  1422. if (_metadataFolder.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.account] == NO)
  1423. return NO;
  1424. return YES;
  1425. }
  1426. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell canSwipe:(MGSwipeDirection)direction
  1427. {
  1428. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  1429. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1430. return [self canOpenMenuAction:metadata];
  1431. }
  1432. -(void)swipeTableCell:(nonnull MGSwipeTableCell *)cell didChangeSwipeState:(MGSwipeState)state gestureIsActive:(BOOL)gestureIsActive
  1433. {
  1434. }
  1435. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell tappedButtonAtIndex:(NSInteger)index direction:(MGSwipeDirection)direction fromExpansion:(BOOL)fromExpansion
  1436. {
  1437. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  1438. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1439. if (direction == MGSwipeDirectionRightToLeft) {
  1440. [self actionDelete:indexPath];
  1441. }
  1442. if (direction == MGSwipeDirectionLeftToRight) {
  1443. [[NCNetworking shared] favoriteMetadata:self.metadata urlBase:appDelegate.urlBase completion:^(NSInteger errorCode, NSString *errorDescription) { }];
  1444. }
  1445. return YES;
  1446. }
  1447. - (void)actionDelete:(NSIndexPath *)indexPath
  1448. {
  1449. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1450. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  1451. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  1452. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  1453. [self performSelector:@selector(deleteMetadatas) withObject:nil];
  1454. }]];
  1455. if (localFile) {
  1456. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_remove_local_file_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  1457. tableMetadata *metadataLivePhoto = [[NCManageDatabase sharedInstance] isLivePhotoWithMetadata:metadata];
  1458. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  1459. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId] error:nil];
  1460. if (metadataLivePhoto) {
  1461. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadataLivePhoto.ocId]];
  1462. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageOcId:metadataLivePhoto.ocId] error:nil];
  1463. }
  1464. [self reloadDatasource:metadata.serverUrl ocId:metadata.ocId];
  1465. }]];
  1466. }
  1467. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  1468. }]];
  1469. alertController.popoverPresentationController.sourceView = self.tableView;
  1470. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  1471. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  1472. [alertController.view layoutIfNeeded];
  1473. [self presentViewController:alertController animated:YES completion:nil];
  1474. }
  1475. - (void)actionMore:(UITapGestureRecognizer *)gestureRecognizer
  1476. {
  1477. CGPoint touch = [gestureRecognizer locationInView:self.tableView];
  1478. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:touch];
  1479. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1480. [self toggleMoreMenuWithViewController:self.tabBarController indexPath:indexPath metadata:self.metadata metadataFolder:_metadataFolder];
  1481. }
  1482. #pragma --------------------------------------------------------------------------------------------
  1483. #pragma mark - ==== Datasource ====
  1484. #pragma --------------------------------------------------------------------------------------------
  1485. - (void)reloadDatasource:(NSNotification *)notification
  1486. {
  1487. NSDictionary *userInfo = notification.userInfo;
  1488. NSString *ocId = userInfo[@"ocId"];
  1489. NSString *serverUrl = userInfo[@"serverUrl"];
  1490. [self reloadDatasource:serverUrl ocId:ocId];
  1491. }
  1492. - (void)reloadDatasource:(NSString *)serverUrl ocId:(NSString *)ocId
  1493. {
  1494. // test
  1495. if (appDelegate.account.length == 0 || serverUrl.length == 0 || serverUrl == nil) // || self.view.window == nil)
  1496. return;
  1497. // Se non siamo nella dir appropriata esci
  1498. if ([serverUrl isEqualToString:self.serverUrl] == NO || self.serverUrl == nil)
  1499. return;
  1500. // live photo
  1501. livePhoto = [CCUtility getLivePhoto];
  1502. // load share
  1503. appDelegate.shares = [[NCManageDatabase sharedInstance] getTableSharesWithAccount:appDelegate.account];
  1504. // Search Mode
  1505. if (self.searchController.isActive) {
  1506. // Create metadatas
  1507. NSMutableArray *metadatas = [NSMutableArray new];
  1508. for (tableMetadata *resultMetadata in _searchResultMetadatas) {
  1509. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", resultMetadata.ocId]];
  1510. if (metadata) {
  1511. [metadatas addObject:metadata];
  1512. }
  1513. }
  1514. // [CCUtility getGroupBySettings]
  1515. sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:metadatas listProgressMetadata:nil groupByField:nil filterTypeFileImage:NO filterTypeFileVideo:NO filterLivePhoto:YES sorted:@"fileName" ascending:NO account:appDelegate.account];
  1516. [self tableViewReloadData];
  1517. if ([sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] >= k_minCharsSearch) {
  1518. _noFilesSearchTitle = NSLocalizedString(@"_search_no_record_found_", nil);
  1519. _noFilesSearchDescription = @"";
  1520. }
  1521. if ([sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] < k_minCharsSearch) {
  1522. _noFilesSearchTitle = @"";
  1523. _noFilesSearchDescription = NSLocalizedString(@"_search_instruction_", nil);
  1524. }
  1525. [self.tableView reloadEmptyDataSet];
  1526. return;
  1527. }
  1528. // Get MetadataFolder
  1529. if ([serverUrl isEqualToString:[[NCUtility shared] getHomeServerWithUrlBase:appDelegate.urlBase account:appDelegate.account]])
  1530. _metadataFolder = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.account, k_serverUrl_root]];
  1531. else
  1532. _metadataFolder = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.account, serverUrl]];
  1533. _autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  1534. _autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectoryWithUrlBase:appDelegate.urlBase account:appDelegate.account];
  1535. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1536. NSArray *recordsTableMetadata = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.account, serverUrl] page:0 limit:0 sorted:@"fileName" ascending:NO];
  1537. // [CCUtility getGroupBySettings]
  1538. CCSectionDataSourceMetadata *sectionDataSourceTemp = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil groupByField:nil filterTypeFileImage:NO filterTypeFileVideo:NO filterLivePhoto:YES sorted:[CCUtility getOrderSettings] ascending:[CCUtility getAscendingSettings] account:appDelegate.account];
  1539. dispatch_async(dispatch_get_main_queue(), ^{
  1540. sectionDataSource = sectionDataSourceTemp;
  1541. [self tableViewReloadData];
  1542. });
  1543. });
  1544. // BLINK
  1545. if (self.blinkFileNamePath != nil) {
  1546. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1547. for (NSString *key in sectionDataSource.allRecordsDataSource) {
  1548. tableMetadata *metadata = [sectionDataSource.allRecordsDataSource objectForKey:key];
  1549. NSString *metadataFileNamePath = [NSString stringWithFormat:@"%@/%@", metadata.serverUrl, metadata.fileName];
  1550. if ([metadataFileNamePath isEqualToString:self.blinkFileNamePath]) {
  1551. for (NSString *key in sectionDataSource.ocIdIndexPath) {
  1552. if ([key isEqualToString:metadata.ocId]) {
  1553. NSIndexPath *indexPath = [sectionDataSource.ocIdIndexPath objectForKey:key];
  1554. [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
  1555. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1556. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  1557. if (cell) {
  1558. self.blinkFileNamePath = nil;
  1559. [[NCUtility shared] blinkWithCell:cell];
  1560. }
  1561. });
  1562. }
  1563. }
  1564. }
  1565. }
  1566. });
  1567. }
  1568. }
  1569. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  1570. {
  1571. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1572. if (selectedRows.count > 0) {
  1573. for (NSIndexPath *selectionIndex in selectedRows) {
  1574. NSString *ocId = [[sectionDataSource.sectionArrayRow objectForKey:[sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  1575. tableMetadata *metadata = [sectionDataSource.allRecordsDataSource objectForKey:ocId];
  1576. [metadatas addObject:metadata];
  1577. }
  1578. }
  1579. return metadatas;
  1580. }
  1581. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  1582. {
  1583. NSInteger totSections =[sectionDataSource.sections count] ;
  1584. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  1585. return nil;
  1586. }
  1587. id valueSection = [sectionDataSource.sections objectAtIndex:section];
  1588. return [sectionDataSource.sectionArrayRow objectForKey:valueSection];
  1589. }
  1590. #pragma --------------------------------------------------------------------------------------------
  1591. #pragma mark - ==== Table ====
  1592. #pragma --------------------------------------------------------------------------------------------
  1593. - (void)tableViewToggle
  1594. {
  1595. [self tableViewSelect:!_isSelectedMode];
  1596. }
  1597. - (void)tableViewSelect:(BOOL)toggle
  1598. {
  1599. _isSelectedMode = toggle;
  1600. // chiudiamo eventuali swipe aperti
  1601. if (_isSelectedMode)
  1602. [self.tableView setEditing:NO animated:NO];
  1603. [self.tableView setAllowsMultipleSelectionDuringEditing:_isSelectedMode];
  1604. [self.tableView setEditing:_isSelectedMode animated:YES];
  1605. if (_isSelectedMode)
  1606. [self setUINavigationBarSelected];
  1607. else
  1608. [self setUINavigationBarDefault];
  1609. [_selectedocIdsMetadatas removeAllObjects];
  1610. [self setTitle];
  1611. }
  1612. - (void)tableViewReloadData
  1613. {
  1614. // store selected cells before relod
  1615. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  1616. // reload table view
  1617. [self.tableView reloadData];
  1618. // selected cells stored
  1619. for (NSIndexPath *path in indexPaths)
  1620. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  1621. [self setTableViewHeader];
  1622. [self setTableViewFooter];
  1623. if (self.tableView.editing)
  1624. [self setTitle];
  1625. [self.tableView reloadEmptyDataSet];
  1626. }
  1627. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  1628. {
  1629. if (tableView.editing == 1) {
  1630. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1631. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  1632. return NO;
  1633. if (metadata == nil || metadata.status != k_metadataStatusNormal)
  1634. return NO;
  1635. else
  1636. return YES;
  1637. } else {
  1638. [_selectedocIdsMetadatas removeAllObjects];
  1639. }
  1640. return YES;
  1641. }
  1642. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  1643. {
  1644. return 60;
  1645. }
  1646. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  1647. {
  1648. return [[sectionDataSource.sectionArrayRow allKeys] count];
  1649. }
  1650. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  1651. {
  1652. return [[sectionDataSource.sectionArrayRow objectForKey:[sectionDataSource.sections objectAtIndex:section]] count];
  1653. }
  1654. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  1655. {
  1656. NSArray *sections = [sectionDataSource.sectionArrayRow allKeys];
  1657. NSString *sectionTitle = [sections objectAtIndex:section];
  1658. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  1659. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  1660. if ([[CCUtility getGroupBySettings] isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  1661. return 20.f;
  1662. }
  1663. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  1664. {
  1665. float shift;
  1666. UIVisualEffectView *visualEffectView;
  1667. NSString *titleSection;
  1668. if (![self indexPathIsValid:[NSIndexPath indexPathForRow:0 inSection:section]])
  1669. return nil;
  1670. if ([[sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]])
  1671. titleSection = [sectionDataSource.sections objectAtIndex:section];
  1672. if ([[sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]])
  1673. titleSection = [CCUtility getTitleSectionDate:[sectionDataSource.sections objectAtIndex:section]];
  1674. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  1675. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  1676. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  1677. else titleSection = NSLocalizedString(titleSection,nil);
  1678. // Format title
  1679. UIVisualEffect *blurEffect;
  1680. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  1681. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  1682. visualEffectView.backgroundColor = [NCBrandColor.sharedInstance.brandElement colorWithAlphaComponent:0.2];
  1683. if ([[CCUtility getGroupBySettings] isEqualToString:@"alphabetic"]) {
  1684. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  1685. shift = - 35;
  1686. else
  1687. shift = - 20;
  1688. } else shift = - 10;
  1689. // Title
  1690. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  1691. titleLabel.backgroundColor = [UIColor clearColor];
  1692. titleLabel.textColor = NCBrandColor.sharedInstance.textView;
  1693. titleLabel.font = [UIFont systemFontOfSize:12];
  1694. titleLabel.textAlignment = NSTextAlignmentLeft;
  1695. titleLabel.text = titleSection;
  1696. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  1697. [visualEffectView.contentView addSubview:titleLabel];
  1698. // Elements
  1699. UILabel *elementLabel= [[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  1700. elementLabel.backgroundColor = [UIColor clearColor];
  1701. elementLabel.textColor = NCBrandColor.sharedInstance.textView;
  1702. elementLabel.font = [UIFont systemFontOfSize:12];
  1703. elementLabel.textAlignment = NSTextAlignmentRight;
  1704. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  1705. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  1706. NSUInteger rowsCount = [metadatas count];
  1707. if (rowsCount == 0) return nil;
  1708. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  1709. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  1710. [visualEffectView.contentView addSubview:elementLabel];
  1711. return visualEffectView;
  1712. }
  1713. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  1714. {
  1715. return [sectionDataSource.sections indexOfObject:title];
  1716. }
  1717. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  1718. {
  1719. if ([[CCUtility getGroupBySettings] isEqualToString:@"alphabetic"])
  1720. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  1721. else
  1722. return nil;
  1723. }
  1724. /*
  1725. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  1726. {
  1727. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  1728. }
  1729. }
  1730. */
  1731. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  1732. {
  1733. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1734. tableShare *shareCell;
  1735. if (metadata == nil || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata] || (_metadataFolder != nil && [[NCManageDatabase sharedInstance] isTableInvalidated:_metadataFolder])) {
  1736. return [CCCellMain new];
  1737. }
  1738. for (tableShare *share in appDelegate.shares) {
  1739. if ([share.serverUrl isEqualToString:metadata.serverUrl] && [share.fileName isEqualToString:metadata.fileName]) {
  1740. shareCell = share;
  1741. break;
  1742. }
  1743. }
  1744. UITableViewCell *cell = [[NCMainCommon sharedInstance] cellForRowAtIndexPath:indexPath tableView:tableView metadata:metadata metadataFolder:_metadataFolder serverUrl:self.serverUrl autoUploadFileName:_autoUploadFileName autoUploadDirectory:_autoUploadDirectory tableShare:shareCell livePhoto:livePhoto];
  1745. // NORMAL - > MAIN
  1746. if ([cell isKindOfClass:[CCCellMain class]]) {
  1747. // Comment tap
  1748. if (metadata.commentsUnread) {
  1749. UITapGestureRecognizer *tapComment = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionComment:)];
  1750. [tapComment setNumberOfTapsRequired:1];
  1751. ((CCCellMain *)cell).comment.userInteractionEnabled = YES;
  1752. [((CCCellMain *)cell).comment addGestureRecognizer:tapComment];
  1753. }
  1754. // Share add Tap
  1755. UITapGestureRecognizer *tapShare = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  1756. [tapShare setNumberOfTapsRequired:1];
  1757. ((CCCellMain *)cell).viewShared.userInteractionEnabled = YES;
  1758. [((CCCellMain *)cell).viewShared addGestureRecognizer:tapShare];
  1759. // More
  1760. if ([self canOpenMenuAction:metadata]) {
  1761. UITapGestureRecognizer *tapMore = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(actionMore:)];
  1762. [tapMore setNumberOfTapsRequired:1];
  1763. ((CCCellMain *)cell).more.userInteractionEnabled = YES;
  1764. [((CCCellMain *)cell).more addGestureRecognizer:tapMore];
  1765. }
  1766. // MGSwipeButton
  1767. ((CCCellMain *)cell).delegate = self;
  1768. // LEFT
  1769. ((CCCellMain *)cell).leftButtons = @[[MGSwipeButton buttonWithTitle:@"" icon:self.cellFavouriteImage backgroundColor:NCBrandColor.sharedInstance.yellowFavorite padding:25]];
  1770. ((CCCellMain *)cell).leftExpansion.buttonIndex = 0;
  1771. ((CCCellMain *)cell).leftExpansion.fillOnTrigger = NO;
  1772. //centerIconOverText
  1773. MGSwipeButton *favoriteButton = (MGSwipeButton *)[((CCCellMain *)cell).leftButtons objectAtIndex:0];
  1774. [favoriteButton centerIconOverText];
  1775. // RIGHT
  1776. ((CCCellMain *)cell).rightButtons = @[[MGSwipeButton buttonWithTitle:@"" icon:self.cellTrashImage backgroundColor:[UIColor redColor] padding:25]];
  1777. ((CCCellMain *)cell).rightExpansion.buttonIndex = 0;
  1778. ((CCCellMain *)cell).rightExpansion.fillOnTrigger = NO;
  1779. //centerIconOverText
  1780. MGSwipeButton *deleteButton = (MGSwipeButton *)[((CCCellMain *)cell).rightButtons objectAtIndex:0];
  1781. [deleteButton centerIconOverText];
  1782. }
  1783. // TRANSFER
  1784. if ([cell isKindOfClass:[CCCellMainTransfer class]]) {
  1785. // gesture Transfer
  1786. [((CCCellMainTransfer *)cell).transferButton.stopButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  1787. UILongPressGestureRecognizer *stopLongGesture = [UILongPressGestureRecognizer new];
  1788. [stopLongGesture addTarget:self action:@selector(cancelAllTask:)];
  1789. [((CCCellMainTransfer *)cell).transferButton.stopButton addGestureRecognizer:stopLongGesture];
  1790. }
  1791. return cell;
  1792. }
  1793. - (void)setTableViewHeader
  1794. {
  1795. NSInteger serverVersionMajor = [[NCManageDatabase sharedInstance] getCapabilitiesServerIntWithAccount:appDelegate.account elements:NCElementsJSON.shared.capabilitiesVersionMajor];
  1796. NSString *trimmedRichWorkspaceText = [self.richWorkspaceText stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
  1797. if (serverVersionMajor < k_nextcloud_version_18_0 || trimmedRichWorkspaceText.length == 0 ) {
  1798. [self.tableView.tableHeaderView setFrame:CGRectMake(self.tableView.tableHeaderView.frame.origin.x, self.tableView.tableHeaderView.frame.origin.y, self.tableView.frame.size.width, heightSearchBar)];
  1799. } else {
  1800. [self.viewRichWorkspace setFrame:CGRectMake(self.tableView.tableHeaderView.frame.origin.x, self.tableView.tableHeaderView.frame.origin.y, self.tableView.frame.size.width, heightRichWorkspace)];
  1801. }
  1802. if (self.searchController.isActive == true) {
  1803. [self.tableView.tableHeaderView setFrame:CGRectMake(self.tableView.tableHeaderView.frame.origin.x, self.tableView.tableHeaderView.frame.origin.y, self.tableView.frame.size.width, 0)];
  1804. }
  1805. [self.viewRichWorkspace setNeedsLayout];
  1806. [self.viewRichWorkspace loadWithRichWorkspaceText:self.richWorkspaceText];
  1807. }
  1808. - (void)setTableViewFooter
  1809. {
  1810. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  1811. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  1812. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  1813. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  1814. UIFont *appFont = [UIFont systemFontOfSize:12];
  1815. footerLabel.font = appFont;
  1816. footerLabel.textColor = [UIColor grayColor];
  1817. footerLabel.backgroundColor = [UIColor clearColor];
  1818. footerLabel.textAlignment = NSTextAlignmentCenter;
  1819. NSString *folders;
  1820. NSString *files;
  1821. NSString *footerText;
  1822. if (sectionDataSource.directories > 1) {
  1823. folders = [NSString stringWithFormat:@"%ld %@", (long)sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  1824. } else if (sectionDataSource.directories == 1){
  1825. folders = [NSString stringWithFormat:@"%ld %@", (long)sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  1826. } else {
  1827. folders = @"";
  1828. }
  1829. if (sectionDataSource.files > 1) {
  1830. files = [NSString stringWithFormat:@"%ld %@ %@", (long)sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:sectionDataSource.totalSize]];
  1831. } else if (sectionDataSource.files == 1){
  1832. files = [NSString stringWithFormat:@"%ld %@ %@", (long)sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:sectionDataSource.totalSize]];
  1833. } else {
  1834. files = @"";
  1835. }
  1836. if ([folders isEqualToString:@""]) {
  1837. footerText = files;
  1838. } else if ([files isEqualToString:@""]) {
  1839. footerText = folders;
  1840. } else {
  1841. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  1842. }
  1843. footerLabel.text = footerText;
  1844. [footerView addSubview:footerLabel];
  1845. [self.tableView setTableFooterView:footerView];
  1846. }
  1847. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  1848. {
  1849. CCCellMain *cell = [tableView cellForRowAtIndexPath:indexPath];
  1850. // settiamo il record file.
  1851. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1852. if (!self.metadata)
  1853. return;
  1854. // se non può essere selezionata deseleziona
  1855. if ([cell isEditing] == NO)
  1856. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  1857. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  1858. if (self.tableView.editing) {
  1859. [_selectedocIdsMetadatas setObject:self.metadata forKey:self.metadata.ocId];
  1860. [self setTitle];
  1861. return;
  1862. }
  1863. if (self.metadata.status != k_metadataStatusNormal && self.metadata.status != k_metadataStatusDownloadError) {
  1864. return;
  1865. }
  1866. // file
  1867. if (self.metadata.directory == NO) {
  1868. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  1869. if ([CCUtility fileProviderStorageExists:self.metadata.ocId fileNameView:self.metadata.fileNameView]) {
  1870. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_downloadedFile object:nil userInfo:@{@"metadata": self.metadata, @"selector": selectorLoadFileView, @"errorCode": @(0), @"errorDescription": @""}];
  1871. } else {
  1872. if (_metadataFolder.e2eEncrypted && ![CCUtility isEndToEndEnabled:appDelegate.account]) {
  1873. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:k_CCErrorE2EENotEnabled forced:true];
  1874. } else {
  1875. if (([self.metadata.typeFile isEqualToString: k_metadataTypeFile_video] || [self.metadata.typeFile isEqualToString: k_metadataTypeFile_audio]) && _metadataFolder.e2eEncrypted == NO) {
  1876. [self shouldPerformSegue:self.metadata selector:@""];
  1877. } else if ([self.metadata.typeFile isEqualToString: k_metadataTypeFile_document] && [[NCUtility shared] isDirectEditingWithAccount:self.metadata.account contentType:self.metadata.contentType] != nil) {
  1878. if (NCCommunication.shared.isNetworkReachable) {
  1879. [self shouldPerformSegue:self.metadata selector:@""];
  1880. } else {
  1881. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_go_online_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:k_CCErrorOffline forced:true];
  1882. }
  1883. } else if ([self.metadata.typeFile isEqualToString: k_metadataTypeFile_document] && [[NCUtility shared] isRichDocument:self.metadata]) {
  1884. if (NCCommunication.shared.isNetworkReachable) {
  1885. [self shouldPerformSegue:self.metadata selector:@""];
  1886. } else {
  1887. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_go_online_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:k_CCErrorOffline forced:true];
  1888. }
  1889. } else {
  1890. if ([self.metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  1891. [self shouldPerformSegue:self.metadata selector:selectorLoadFileView];
  1892. }
  1893. [[NCNetworking shared] downloadWithMetadata:self.metadata selector:selectorLoadFileView setFavorite:false completion:^(NSInteger errorCode) { }];
  1894. }
  1895. }
  1896. }
  1897. }
  1898. if (self.metadata.directory) {
  1899. [self performSegueDirectoryWithMetadata:self.metadata blinkFileNamePath:self.blinkFileNamePath];
  1900. }
  1901. }
  1902. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  1903. {
  1904. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1905. [_selectedocIdsMetadatas removeObjectForKey:metadata.ocId];
  1906. [self setTitle];
  1907. }
  1908. - (void)didSelectAll
  1909. {
  1910. for (int i = 0; i < self.tableView.numberOfSections; i++) {
  1911. for (int j = 0; j < [self.tableView numberOfRowsInSection:i]; j++) {
  1912. NSIndexPath *indexPath = [NSIndexPath indexPathForRow:j inSection:i];
  1913. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1914. [_selectedocIdsMetadatas setObject:metadata forKey:metadata.ocId];
  1915. [self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
  1916. }
  1917. }
  1918. [self setTitle];
  1919. }
  1920. - (BOOL)indexPathIsValid:(NSIndexPath *)indexPath
  1921. {
  1922. if (!indexPath)
  1923. return NO;
  1924. NSInteger section = indexPath.section;
  1925. NSInteger row = indexPath.row;
  1926. NSInteger lastSectionIndex = [self numberOfSectionsInTableView:self.tableView] - 1;
  1927. if (section > lastSectionIndex || lastSectionIndex < 0)
  1928. return NO;
  1929. NSInteger rowCount = [self.tableView numberOfRowsInSection:indexPath.section] - 1;
  1930. if (rowCount < 0)
  1931. return NO;
  1932. return row <= rowCount;
  1933. }
  1934. #pragma --------------------------------------------------------------------------------------------
  1935. #pragma mark ===== Navigation ====
  1936. #pragma --------------------------------------------------------------------------------------------
  1937. - (void)shouldPerformSegue:(tableMetadata *)metadata selector:(NSString *)selector
  1938. {
  1939. // if background return
  1940. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return;
  1941. if (self.view.window == NO)
  1942. return;
  1943. // Collapsed ma siamo già in detail esci
  1944. if (self.splitViewController.isCollapsed) {
  1945. if (appDelegate.activeDetail.isViewLoaded && appDelegate.activeDetail.view.window) return;
  1946. }
  1947. // Metadata for push detail
  1948. self.metadataForPushDetail = metadata;
  1949. self.selectorForPushDetail = selector;
  1950. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  1951. }
  1952. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  1953. {
  1954. tableMetadata *metadata;
  1955. NSMutableArray *photoDataSource = [NSMutableArray new];
  1956. UINavigationController *navigationController = segue.destinationViewController;
  1957. NCDetailViewController *detailViewController = (NCDetailViewController *)navigationController.topViewController;
  1958. if ([sender isKindOfClass:[tableMetadata class]]) {
  1959. metadata = sender;
  1960. [photoDataSource addObject:sender];
  1961. } else {
  1962. metadata = self.metadataForPushDetail;
  1963. for (NSString *ocId in sectionDataSource.allOcId) {
  1964. tableMetadata *metadata = [sectionDataSource.allRecordsDataSource objectForKey:ocId];
  1965. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  1966. [photoDataSource addObject:metadata];
  1967. }
  1968. }
  1969. detailViewController.metadata = metadata;
  1970. detailViewController.selector = self.selectorForPushDetail;
  1971. [detailViewController setTitle:metadata.fileNameView];
  1972. }
  1973. // can i go to next viewcontroller
  1974. - (void)performSegueDirectoryWithMetadata:(tableMetadata *)metadata blinkFileNamePath:(NSString *)blinkFileNamePath
  1975. {
  1976. NSString *nomeDir;
  1977. if (self.tableView.editing == NO) {
  1978. // E2EE Check enable
  1979. if (metadata.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.account] == NO) {
  1980. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:k_CCErrorE2EENotEnabled forced:true];
  1981. return;
  1982. }
  1983. nomeDir = metadata.fileName;
  1984. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:metadata.serverUrl addFileName:nomeDir];
  1985. CCMain *viewController = [appDelegate.listMainVC objectForKey:serverUrlPush];
  1986. if (!viewController) {
  1987. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMain"];
  1988. viewController.serverUrl = serverUrlPush;
  1989. viewController.titleMain = metadata.fileNameView;
  1990. viewController.blinkFileNamePath = blinkFileNamePath;
  1991. // save self
  1992. [appDelegate.listMainVC setObject:viewController forKey:serverUrlPush];
  1993. [self.navigationController pushViewController:viewController animated:YES];
  1994. } else {
  1995. if (viewController.isViewLoaded) {
  1996. viewController.titleMain = metadata.fileNameView;
  1997. viewController.blinkFileNamePath = blinkFileNamePath;
  1998. // Fix : Application tried to present modally an active controller
  1999. if ([self.navigationController isBeingPresented]) {
  2000. // being presented
  2001. } else if ([self.navigationController isMovingToParentViewController]) {
  2002. // being pushed
  2003. } else {
  2004. [self.navigationController pushViewController:viewController animated:YES];
  2005. }
  2006. }
  2007. }
  2008. }
  2009. }
  2010. @end