CCMain.m 127 KB

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