CCMain.m 126 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937
  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, 35, 0);
  149. // long press recognizer TableView
  150. UILongPressGestureRecognizer* longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPressTableView:)];
  151. [self.tableView addGestureRecognizer:longPressRecognizer];
  152. // Pull-to-Refresh
  153. [self createRefreshControl];
  154. // Register for 3D Touch Previewing if available
  155. if ([self.traitCollection respondsToSelector:@selector(forceTouchCapability)] && (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable)) {
  156. [self registerForPreviewingWithDelegate:self sourceView:self.view];
  157. }
  158. // if this is not Main (the Main uses inizializeMain)
  159. if (_isRoot == NO && appDelegate.activeAccount.length > 0) {
  160. // Read (File) Folder
  161. [self readFileReloadFolder];
  162. }
  163. // Title
  164. [self setTitle];
  165. // changeTheming
  166. [self changeTheming];
  167. }
  168. - (void)willDismissSearchController:(UISearchController *)searchController
  169. {
  170. [self.tableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
  171. }
  172. - (void)willPresentSearchController:(UISearchController *)searchController
  173. {
  174. [self updateNavBarShadow:self.tableView force:true];
  175. }
  176. - (void)viewWillAppear:(BOOL)animated
  177. {
  178. [super viewWillAppear:animated];
  179. [self updateNavBarShadow:self.tableView force:false];
  180. if (@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 (_isRoot) {
  577. self.navigationItem.title = NCBrandOptions.sharedInstance.brand;
  578. self.navigationItem.largeTitleDisplayMode = UINavigationItemLargeTitleDisplayModeAlways;
  579. } else {
  580. self.navigationItem.title = _titleMain;
  581. self.navigationItem.largeTitleDisplayMode = UINavigationItemLargeTitleDisplayModeAlways;
  582. }
  583. }
  584. [self SetSortButtonText];
  585. }
  586. - (void)setUINavigationBarDefault
  587. {
  588. UIBarButtonItem *buttonSelect = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_select_", @"") style:UIBarButtonItemStylePlain target:self action:@selector(tableViewToggle)];
  589. self.navigationController.navigationBar.hidden = NO;
  590. self.navigationItem.rightBarButtonItem = buttonSelect;
  591. self.navigationItem.leftBarButtonItem = nil;
  592. }
  593. - (void)setUINavigationBarSelected
  594. {
  595. UIBarButtonItem *buttonMore = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationMore"] style:UIBarButtonItemStylePlain target:self action:@selector(toggleReSelectMenu)];
  596. UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(cancelSelect)];
  597. self.navigationItem.leftBarButtonItem = leftButton;
  598. self.navigationItem.rightBarButtonItem = buttonMore; //[[NSArray alloc] initWithObjects:buttonMore, nil];
  599. }
  600. - (void)cancelSelect
  601. {
  602. [self tableViewSelect:false];
  603. }
  604. #pragma --------------------------------------------------------------------------------------------
  605. #pragma mark ===== Document Picker =====
  606. #pragma --------------------------------------------------------------------------------------------
  607. - (void)documentMenuWasCancelled:(UIDocumentMenuViewController *)documentMenu
  608. {
  609. NSLog(@"[LOG] Cancelled");
  610. }
  611. - (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller
  612. {
  613. NSLog(@"[LOG] Cancelled");
  614. }
  615. - (void)documentMenu:(UIDocumentMenuViewController *)documentMenu didPickDocumentPicker:(UIDocumentPickerViewController *)documentPicker
  616. {
  617. documentPicker.delegate = self;
  618. [self presentViewController:documentPicker animated:YES completion:nil];
  619. }
  620. - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
  621. {
  622. if (controller.documentPickerMode == UIDocumentPickerModeImport) {
  623. NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
  624. __block NSError *error;
  625. [coordinator coordinateReadingItemAtURL:url options:NSFileCoordinatorReadingForUploading error:&error byAccessor:^(NSURL *newURL) {
  626. NSString *serverUrl = [appDelegate getTabBarControllerActiveServerUrl];
  627. NSString *fileName = [url lastPathComponent];
  628. NSString *ocId = [[NSUUID UUID] UUIDString];
  629. NSData *data = [NSData dataWithContentsOfURL:newURL];
  630. if (data && error == nil) {
  631. if ([data writeToFile:[CCUtility getDirectoryProviderStorageOcId:ocId fileNameView:fileName] options:NSDataWritingAtomic error:&error]) {
  632. tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] createMetadataWithAccount:appDelegate.activeAccount fileName:fileName ocId:ocId serverUrl:serverUrl url:@"" contentType:@""];
  633. metadataForUpload.session = k_upload_session;
  634. metadataForUpload.sessionSelector = selectorUploadFile;
  635. metadataForUpload.size = data.length;
  636. metadataForUpload.status = k_metadataStatusWaitUpload;
  637. if ([[NCUtility sharedInstance] getMetadataConflictWithAccount:appDelegate.activeAccount serverUrl:serverUrl fileName:fileName] != nil) {
  638. NCCreateFormUploadConflict *conflict = [[UIStoryboard storyboardWithName:@"NCCreateFormUploadConflict" bundle:nil] instantiateInitialViewController];
  639. conflict.serverUrl = self.serverUrl;
  640. conflict.metadatasUploadInConflict = @[metadataForUpload];
  641. [self presentViewController:conflict animated:YES completion:nil];
  642. } else {
  643. [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  644. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  645. [appDelegate startLoadAutoDownloadUpload];
  646. }
  647. } else {
  648. [[NCContentPresenter shared] messageNotification:@"_error_" description:error.description delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code];
  649. }
  650. } else {
  651. [[NCContentPresenter shared] messageNotification:@"_error_" description:@"_read_file_error_" delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code];
  652. }
  653. }];
  654. }
  655. }
  656. - (void)openImportDocumentPicker
  657. {
  658. UIDocumentMenuViewController *documentProviderMenu = [[UIDocumentMenuViewController alloc] initWithDocumentTypes:@[@"public.data"] inMode:UIDocumentPickerModeImport];
  659. documentProviderMenu.modalPresentationStyle = UIModalPresentationFormSheet;
  660. documentProviderMenu.popoverPresentationController.sourceView = self.tabBarController.tabBar;
  661. documentProviderMenu.popoverPresentationController.sourceRect = self.tabBarController.tabBar.bounds;
  662. documentProviderMenu.delegate = self;
  663. [self presentViewController:documentProviderMenu animated:YES completion:nil];
  664. }
  665. #pragma --------------------------------------------------------------------------------------------
  666. #pragma mark ===== Assets Picker =====
  667. #pragma --------------------------------------------------------------------------------------------
  668. -(void)dismissFormUploadAssets
  669. {
  670. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  671. }
  672. - (void)openAssetsPickerController
  673. {
  674. NCPhotosPickerViewController *viewController = [[NCPhotosPickerViewController alloc] init:self maxSelectedAssets:100 singleSelectedMode:false];
  675. [viewController openPhotosPickerViewControllerWithPhAssets:^(NSArray<PHAsset *> * _Nullable assets, NSArray<NSURL *> * urls) {
  676. if (assets.count > 0) {
  677. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  678. NSString *serverUrl = [appDelegate getTabBarControllerActiveServerUrl];
  679. NCCreateFormUploadAssets *form = [[NCCreateFormUploadAssets alloc] initWithServerUrl:serverUrl assets:(NSMutableArray *)assets urls:(NSMutableArray *)urls cryptated:NO session:k_upload_session delegate:self];
  680. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:form];
  681. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  682. [self presentViewController:navigationController animated:YES completion:nil];
  683. });
  684. }
  685. }];
  686. }
  687. #pragma --------------------------------------------------------------------------------------------
  688. #pragma mark ===== Save selected File =====
  689. #pragma --------------------------------------------------------------------------------------------
  690. - (void)saveToPhotoAlbum:(tableMetadata *)metadata
  691. {
  692. NSString *fileNamePath = [CCUtility getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileNameView];
  693. PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
  694. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] && status == PHAuthorizationStatusAuthorized) {
  695. UIImage *image = [UIImage imageWithContentsOfFile:fileNamePath];
  696. if (image)
  697. UIImageWriteToSavedPhotosAlbum(image, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  698. else
  699. [[NCContentPresenter shared] messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  700. }
  701. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video] && status == PHAuthorizationStatusAuthorized) {
  702. if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(fileNamePath)) {
  703. UISaveVideoAtPathToSavedPhotosAlbum(fileNamePath, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  704. } else {
  705. [[NCContentPresenter shared] messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  706. }
  707. }
  708. if (status != PHAuthorizationStatusAuthorized) {
  709. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil) message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil) preferredStyle:UIAlertControllerStyleAlert];
  710. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  711. [alertController addAction:okAction];
  712. [self presentViewController:alertController animated:YES completion:nil];
  713. }
  714. }
  715. - (void)saveSelectedFilesSelector:(NSString *)path didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
  716. {
  717. if (error) {
  718. [[NCContentPresenter shared] messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code];
  719. }
  720. }
  721. - (void)saveSelectedFiles
  722. {
  723. if (_isSelectedMode && [_selectedocIdsMetadatas count] == 0)
  724. return;
  725. NSLog(@"[LOG] Start download selected files ...");
  726. [_hud visibleHudTitle:@"" mode:MBProgressHUDModeIndeterminate color:nil];
  727. NSArray *metadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  728. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  729. for (tableMetadata *metadata in metadatas) {
  730. if (metadata.directory == NO && ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])) {
  731. metadata.session = k_download_session;
  732. metadata.sessionError = @"";
  733. metadata.sessionSelector = selectorSave;
  734. metadata.status = k_metadataStatusWaitDownload;
  735. // Add Metadata for Download
  736. [[NCManageDatabase sharedInstance] addMetadata:metadata];
  737. [appDelegate startLoadAutoDownloadUpload];
  738. }
  739. }
  740. [_hud hideHud];
  741. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  742. });
  743. [self tableViewSelect:false];
  744. }
  745. #pragma mark -
  746. #pragma --------------------------------------------------------------------------------------------
  747. #pragma mark ===== Peek & Pop =====
  748. #pragma --------------------------------------------------------------------------------------------
  749. - (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
  750. {
  751. CGPoint convertedLocation = [self.view convertPoint:location toView:self.tableView];
  752. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:convertedLocation];
  753. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  754. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  755. if (cell) {
  756. previewingContext.sourceRect = cell.frame;
  757. CCPeekPop *viewController = [[UIStoryboard storyboardWithName:@"CCPeekPop" bundle:nil] instantiateViewControllerWithIdentifier:@"PeekPopImagePreview"];
  758. viewController.metadata = metadata;
  759. viewController.imageFile = cell.file.image;
  760. viewController.showOpenIn = true;
  761. viewController.showShare = true;
  762. viewController.showOpenQuickLook = [[NCUtility sharedInstance] isQuickLookDisplayableWithMetadata:metadata];
  763. return viewController;
  764. }
  765. return nil;
  766. }
  767. - (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit
  768. {
  769. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:previewingContext.sourceRect.origin];
  770. [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
  771. }
  772. #pragma --------------------------------------------------------------------------------------------
  773. #pragma mark ==== Download ====
  774. #pragma --------------------------------------------------------------------------------------------
  775. - (void)downloadSelectedFilesFolders
  776. {
  777. if (_isSelectedMode && [_selectedocIdsMetadatas count] == 0)
  778. return;
  779. NSLog(@"[LOG] Start download selected ...");
  780. [_hud visibleHudTitle:NSLocalizedString(@"_downloading_progress_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  781. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  782. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  783. for (tableMetadata *metadata in selectedMetadatas) {
  784. if (metadata.directory) {
  785. [[CCSynchronize sharedSynchronize] readFolder:[CCUtility stringAppendServerUrl:metadata.serverUrl addFileName:metadata.fileName] selector:selectorReadFolderWithDownload account:appDelegate.activeAccount];
  786. } else {
  787. [[CCSynchronize sharedSynchronize] readFile:metadata.ocId fileName:metadata.fileName serverUrl:metadata.serverUrl selector:selectorReadFileWithDownload account:appDelegate.activeAccount];
  788. }
  789. }
  790. [_hud hideHud];
  791. });
  792. [self tableViewSelect:false];
  793. }
  794. #pragma --------------------------------------------------------------------------------------------
  795. #pragma mark ===== Upload new Photos/Videos =====
  796. #pragma --------------------------------------------------------------------------------------------
  797. //
  798. // This procedure with performSelectorOnMainThread it's necessary after (Bridge) for use the function "Sync" in OCNetworking
  799. //
  800. - (void)uploadFileAsset:(NSMutableArray *)assets urls:(NSMutableArray *)urls serverUrl:(NSString *)serverUrl useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  801. {
  802. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  803. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:appDelegate.activeUrl];
  804. // if request create the folder for Auto Upload & the subfolders
  805. if ([autoUploadPath isEqualToString:serverUrl])
  806. if (![[NCAutoUpload sharedInstance] createAutoUploadFolderWithSubFolder:useSubFolder assets:(PHFetchResult *)assets selector:selectorUploadFile])
  807. return;
  808. dispatch_async(dispatch_get_main_queue(), ^{
  809. [self uploadFileAsset:assets urls:urls serverUrl:serverUrl autoUploadPath:autoUploadPath useSubFolder:useSubFolder session:session];
  810. });
  811. });
  812. }
  813. - (void)uploadFileAsset:(NSArray *)assets urls:(NSArray *)urls serverUrl:(NSString *)serverUrl autoUploadPath:(NSString *)autoUploadPath useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  814. {
  815. NSMutableArray *metadatasNOConflict = [NSMutableArray new];
  816. NSMutableArray *metadatasMOV = [NSMutableArray new];
  817. NSMutableArray *metadatasUploadInConflict = [NSMutableArray new];
  818. for (PHAsset *asset in assets) {
  819. NSString *fileName = [CCUtility createFileName:[asset valueForKey:@"filename"] fileDate:asset.creationDate fileType:asset.mediaType keyFileName:k_keyFileNameMask keyFileNameType:k_keyFileNameType keyFileNameOriginal:k_keyFileNameOriginal];
  820. NSDate *assetDate = asset.creationDate;
  821. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  822. // Create serverUrl if use sub folder
  823. if (useSubFolder) {
  824. [formatter setDateFormat:@"yyyy"];
  825. NSString *yearString = [formatter stringFromDate:assetDate];
  826. [formatter setDateFormat:@"MM"];
  827. NSString *monthString = [formatter stringFromDate:assetDate];
  828. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", autoUploadPath, yearString, monthString];
  829. }
  830. // Check if is in upload
  831. NSArray *isRecordInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileName == %@ AND session != ''", appDelegate.activeAccount, serverUrl, fileName] sorted:nil ascending:NO];
  832. if ([isRecordInSessions count] > 0)
  833. continue;
  834. // Prepare record metadata
  835. tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] createMetadataWithAccount:appDelegate.activeAccount fileName:fileName ocId:[[NSUUID UUID] UUIDString] serverUrl:serverUrl url:@"" contentType:@""];
  836. metadataForUpload.assetLocalIdentifier = asset.localIdentifier;
  837. metadataForUpload.session = session;
  838. metadataForUpload.sessionSelector = selectorUploadFile;
  839. metadataForUpload.size = [[NCUtility sharedInstance] getFileSizeWithAsset:asset];
  840. metadataForUpload.status = k_metadataStatusWaitUpload;
  841. if ([[NCUtility sharedInstance] getMetadataConflictWithAccount:appDelegate.activeAccount serverUrl:serverUrl fileName:fileName] != nil) {
  842. [metadatasUploadInConflict addObject:metadataForUpload];
  843. } else {
  844. [metadatasNOConflict addObject:metadataForUpload];
  845. }
  846. // Add Medtadata MOV LIVE PHOTO for upload
  847. if ((asset.mediaSubtypes == PHAssetMediaSubtypePhotoLive || asset.mediaSubtypes == PHAssetMediaSubtypePhotoLive+PHAssetMediaSubtypePhotoHDR) && CCUtility.getLivePhoto && urls.count == assets.count) {
  848. NSUInteger index = [assets indexOfObject:asset];
  849. NSURL *url = [urls objectAtIndex:index];
  850. NSString *fileNameNoExt = [fileName stringByDeletingPathExtension];
  851. NSString *fileName = [NSString stringWithFormat:@"%@.mov", fileNameNoExt];
  852. unsigned long long fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:url.path error:nil] fileSize];
  853. tableMetadata *metadataMOVForUpload = [[NCManageDatabase sharedInstance] createMetadataWithAccount:appDelegate.activeAccount fileName:fileName ocId:[[NSUUID UUID] UUIDString] serverUrl:serverUrl url:@"" contentType:@""];
  854. metadataMOVForUpload.session = session;
  855. metadataMOVForUpload.sessionSelector = selectorUploadFile;
  856. metadataMOVForUpload.size = fileSize;
  857. metadataMOVForUpload.status = k_metadataStatusWaitUpload;
  858. // Prepare file and directory
  859. [CCUtility moveFileAtPath:url.path toPath:[CCUtility getDirectoryProviderStorageOcId:metadataMOVForUpload.ocId fileNameView:fileName]];
  860. [metadatasMOV addObject:metadataMOVForUpload];
  861. }
  862. }
  863. // Verify if file(s) exists
  864. if (metadatasUploadInConflict.count > 0) {
  865. NCCreateFormUploadConflict *conflict = [[UIStoryboard storyboardWithName:@"NCCreateFormUploadConflict" bundle:nil] instantiateInitialViewController];
  866. conflict.serverUrl = self.serverUrl;
  867. conflict.metadatasNOConflict = metadatasNOConflict;
  868. conflict.metadatasMOV = metadatasMOV;
  869. conflict.metadatasUploadInConflict = metadatasUploadInConflict;
  870. [self presentViewController:conflict animated:YES completion:nil];
  871. } else {
  872. [[NCManageDatabase sharedInstance] addMetadatas:metadatasNOConflict];
  873. [[NCManageDatabase sharedInstance] addMetadatas:metadatasMOV];
  874. [appDelegate startLoadAutoDownloadUpload];
  875. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  876. }
  877. }
  878. #pragma --------------------------------------------------------------------------------------------
  879. #pragma mark ==== Read Folder ====
  880. #pragma --------------------------------------------------------------------------------------------
  881. - (void)readFolder:(NSString *)serverUrl
  882. {
  883. // init control
  884. if (!serverUrl || !appDelegate.activeAccount || appDelegate.maintenanceMode) {
  885. [refreshControl endRefreshing];
  886. return;
  887. }
  888. // Search Mode
  889. if (self.searchController.isActive) {
  890. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:serverUrl account:appDelegate.activeAccount];
  891. _searchFileName = @""; // forced reload searchg
  892. [self updateSearchResultsForSearchController:self.searchController];
  893. return;
  894. }
  895. _loadingFolder = YES;
  896. [self tableViewReloadData];
  897. [[NCNetworking sharedInstance] readFolderWithServerUrl:serverUrl account:appDelegate.activeAccount completion:^(NSString *account, tableMetadata *metadataFolder, NSArray *metadatas, NSInteger errorCode, NSString *errorDescription) {
  898. [refreshControl endRefreshing];
  899. if (errorCode == 0 ) {
  900. _metadataFolder = metadataFolder;
  901. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:serverUrl e2eEncrypted:_metadataFolder.e2eEncrypted account:appDelegate.activeAccount];
  902. [self setTitle];
  903. // File is changed ??
  904. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  905. [[CCSynchronize sharedSynchronize] verifyChangeMedatas:metadatas serverUrl:serverUrl account:account withDownload:NO];
  906. });
  907. // E2EE Is encrypted folder get metadata
  908. if (isFolderEncrypted) {
  909. NSString *metadataFolderFileId = metadataFolder.fileId;
  910. // Read Metadata
  911. if ([CCUtility isEndToEndEnabled:account]) {
  912. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  913. NSString *metadata;
  914. NSError *error = [[NCNetworkingEndToEnd sharedManager] getEndToEndMetadata:&metadata fileId:metadataFolderFileId user:appDelegate.activeUser userID:appDelegate.activeUserID password:[CCUtility getPassword:appDelegate.activeAccount] url:appDelegate.activeUrl];
  915. dispatch_async(dispatch_get_main_queue(), ^{
  916. if (error) {
  917. if (error.code != kOCErrorServerPathNotFound)
  918. [[NCContentPresenter shared] messageNotification:@"_e2e_error_get_metadata_" description:error.localizedDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code];
  919. } else {
  920. if ([[NCEndToEndMetadata sharedInstance] decoderMetadata:metadata privateKey:[CCUtility getEndToEndPrivateKey:account] serverUrl:self.serverUrl account:account url:appDelegate.activeUrl] == false)
  921. [[NCContentPresenter shared] messageNotification:@"_error_e2ee_" description:@"_e2e_error_decode_metadata_" delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code];
  922. else
  923. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:serverUrl ocId:nil action:k_action_NULL];
  924. }
  925. });
  926. });
  927. } else {
  928. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  929. }
  930. }
  931. if ([serverUrl isEqualToString:_serverUrl]) {
  932. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:serverUrl ocId:nil action:k_action_NULL];
  933. [self tableViewReloadData];
  934. }
  935. } else {
  936. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  937. }
  938. _loadingFolder = NO;
  939. }];
  940. }
  941. - (void)readFileReloadFolder
  942. {
  943. if (!_serverUrl || !appDelegate.activeAccount || appDelegate.maintenanceMode)
  944. return;
  945. // RichWorkspace
  946. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, self.serverUrl]];
  947. self.richWorkspaceText = directory.richWorkspace;
  948. [self setTableViewHeader];
  949. // Load Datasource
  950. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.001 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  951. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  952. });
  953. [[NCNetworking sharedInstance] readFileWithServerUrlFileName:self.serverUrl account:appDelegate.activeAccount completion:^(NSString *account, tableMetadata *metadata, NSInteger errorCode, NSString *errorDescription) {
  954. if (errorCode == 0 && [account isEqualToString:appDelegate.activeAccount]) {
  955. // Rich Workspace
  956. [[NCManageDatabase sharedInstance] setDirectoryWithOcId:metadata.ocId serverUrl:self.serverUrl richWorkspace:metadata.richWorkspace account:account];
  957. self.richWorkspaceText = metadata.richWorkspace;
  958. [self setTableViewHeader];
  959. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", account, self.serverUrl]];
  960. // Read folder: No record, Change etag or BLINK
  961. if ([sectionDataSource.allRecordsDataSource count] == 0 || [metadata.etag isEqualToString:directory.etag] == NO || self.blinkFileNamePath != nil) {
  962. [self readFolder:self.serverUrl];
  963. }
  964. } else if (errorCode != 0) {
  965. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  966. }
  967. }];
  968. }
  969. #pragma mark -
  970. #pragma --------------------------------------------------------------------------------------------
  971. #pragma mark ===== Search =====
  972. #pragma --------------------------------------------------------------------------------------------
  973. - (void)searchStartTimer
  974. {
  975. if (self.searchController.isActive == false) {
  976. return;
  977. }
  978. [[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) {
  979. if (errorCode == 0 && [account isEqualToString:appDelegate.activeAccount] && files != nil) {
  980. [[NCManageDatabase sharedInstance] convertNCFilesToMetadatas:files useMetadataFolder:false account:account completion:^(tableMetadata *metadataFolder, NSArray<tableMetadata *> *metadatasFolder, NSArray<tableMetadata *> *metadatas) {
  981. NSMutableArray *metadatasDB = (NSMutableArray *)[[NCManageDatabase sharedInstance] addMetadatas:metadatas];
  982. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatasDB];
  983. _metadataFolder = nil;
  984. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:_serverUrl ocId:nil action:k_action_NULL];
  985. [self tableViewReloadData];
  986. [self setTitle];
  987. }];
  988. } else {
  989. if (errorCode != 0) {
  990. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  991. }
  992. _searchFileName = @"";
  993. }
  994. }];
  995. _noFilesSearchTitle = @"";
  996. _noFilesSearchDescription = NSLocalizedString(@"_search_in_progress_", nil);
  997. [self.tableView reloadEmptyDataSet];
  998. }
  999. - (void)updateSearchResultsForSearchController:(UISearchController *)searchController
  1000. {
  1001. // Color text "Cancel"
  1002. [[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setTintColor:NCBrandColor.sharedInstance.brand];
  1003. if (searchController.isActive) {
  1004. [self deleteRefreshControl];
  1005. NSString *fileName = [CCUtility removeForbiddenCharactersServer:searchController.searchBar.text];
  1006. if (fileName.length >= k_minCharsSearch && [fileName isEqualToString:_searchFileName] == NO) {
  1007. _searchFileName = fileName;
  1008. _metadataFolder = nil;
  1009. // First : filter
  1010. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileNameView CONTAINS[cd] %@", appDelegate.activeAccount, _serverUrl, fileName] sorted:nil ascending:NO];
  1011. [_searchResultMetadatas removeAllObjects];
  1012. for (tableMetadata *record in records) {
  1013. [_searchResultMetadatas addObject:record];
  1014. }
  1015. // Version >= 12
  1016. if ([[NCManageDatabase sharedInstance] getCapabilitiesServerVersionMajorWithAccount:appDelegate.activeAccount] >= 12) {
  1017. [_timerWaitInput invalidate];
  1018. _timerWaitInput = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(searchStartTimer) userInfo:nil repeats:NO];
  1019. }
  1020. [self setTitle];
  1021. }
  1022. if (_searchResultMetadatas.count == 0 && fileName.length == 0) {
  1023. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1024. }
  1025. } else {
  1026. [self createRefreshControl];
  1027. [self reloadDatasource:self.serverUrl ocId:nil action:k_action_NULL];
  1028. }
  1029. }
  1030. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  1031. {
  1032. [self cancelSearchBar];
  1033. }
  1034. - (void)cancelSearchBar
  1035. {
  1036. if (self.searchController.active) {
  1037. [self.searchController setActive:NO];
  1038. _searchFileName = @"";
  1039. _dateReadDataSource = nil;
  1040. _searchResultMetadatas = [NSMutableArray new];
  1041. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1042. }
  1043. }
  1044. #pragma mark -
  1045. #pragma --------------------------------------------------------------------------------------------
  1046. #pragma mark ===== Delete File or Folder =====
  1047. #pragma --------------------------------------------------------------------------------------------
  1048. - (void)deleteMetadatas
  1049. {
  1050. if (_isSelectedMode && [_selectedocIdsMetadatas count] == 0)
  1051. return;
  1052. if ([_selectedocIdsMetadatas count] > 0) {
  1053. [appDelegate.arrayDeleteMetadata addObjectsFromArray:[_selectedocIdsMetadatas allValues]];
  1054. } else {
  1055. [appDelegate.arrayDeleteMetadata addObject:self.metadata];
  1056. }
  1057. [[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) { }];
  1058. [appDelegate.arrayDeleteMetadata removeObjectAtIndex:0];
  1059. // End Select Table View
  1060. [self tableViewSelect:false];
  1061. }
  1062. #pragma --------------------------------------------------------------------------------------------
  1063. #pragma mark ===== Move / Copy =====
  1064. #pragma --------------------------------------------------------------------------------------------
  1065. - (void)moveCopyFileOrFolderMetadata:(tableMetadata *)metadata serverUrlTo:(NSString *)serverUrlTo move:(BOOL)move overwrite:(BOOL)overwrite
  1066. {
  1067. if (_isSelectedMode && [_selectedocIdsMetadatas count] == 0)
  1068. return;
  1069. NSMutableArray *arrayMetadata, *arrayServerUrlTo;
  1070. if (move) {
  1071. arrayMetadata = appDelegate.arrayMoveMetadata;
  1072. arrayServerUrlTo = appDelegate.arrayMoveServerUrlTo;
  1073. } else {
  1074. arrayMetadata = appDelegate.arrayCopyMetadata;
  1075. arrayServerUrlTo = appDelegate.arrayCopyServerUrlTo;
  1076. }
  1077. if ([_selectedocIdsMetadatas count] > 0) {
  1078. for (NSString *key in _selectedocIdsMetadatas) {
  1079. tableMetadata *metadata = [_selectedocIdsMetadatas objectForKey:key];
  1080. [arrayMetadata addObject:metadata];
  1081. [arrayServerUrlTo addObject:serverUrlTo];
  1082. }
  1083. } else {
  1084. [arrayMetadata addObject:metadata];
  1085. [arrayServerUrlTo addObject:serverUrlTo];
  1086. }
  1087. if (move) {
  1088. [[NCNetworking sharedInstance] moveMetadata:arrayMetadata.firstObject serverUrlTo:arrayServerUrlTo.firstObject overwrite:overwrite completion:^(NSInteger errorCode, NSString * errorDesctiption) { }];
  1089. } else {
  1090. [[NCNetworking sharedInstance] copyMetadata:arrayMetadata.firstObject serverUrlTo:arrayServerUrlTo.firstObject overwrite:overwrite completion:^(NSInteger errorCode, NSString * errorDesctiption) { }];
  1091. }
  1092. [arrayMetadata removeObjectAtIndex:0];
  1093. [arrayServerUrlTo removeObjectAtIndex:0];
  1094. // End Select Table View
  1095. [self tableViewSelect:false];
  1096. }
  1097. // DELEGATE : Select
  1098. - (void)dismissSelectWithServerUrl:(NSString *)serverUrl metadata:(tableMetadata *)metadata type:(NSString *)type buttonType:(NSString *)buttonType overwrite:(BOOL)overwrite
  1099. {
  1100. if (serverUrl == nil) {
  1101. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1102. } else {
  1103. // E2EE DENIED
  1104. if ([CCUtility isFolderEncrypted:serverUrl e2eEncrypted:metadata.e2eEncrypted account:appDelegate.activeAccount]) {
  1105. [[NCContentPresenter shared] messageNotification:@"_move_" description:@"Not possible move files to encrypted directory" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  1106. return;
  1107. }
  1108. BOOL move = true;
  1109. if ([buttonType isEqualToString:@"done1"]) { move = false; }
  1110. if ([_selectedocIdsMetadatas count] > 0) {
  1111. NSArray *metadatas = [_selectedocIdsMetadatas allValues];
  1112. [self moveCopyFileOrFolderMetadata:[metadatas objectAtIndex:0] serverUrlTo:serverUrl move:move overwrite:overwrite];
  1113. } else {
  1114. [self moveCopyFileOrFolderMetadata:self.metadata serverUrlTo:serverUrl move:move overwrite:overwrite];
  1115. }
  1116. }
  1117. }
  1118. - (void)moveOpenWindow:(NSArray *)indexPaths
  1119. {
  1120. if (_isSelectedMode && [_selectedocIdsMetadatas count] == 0)
  1121. return;
  1122. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"NCSelect" bundle:nil] instantiateInitialViewController];
  1123. NCSelect *viewController = (NCSelect *)navigationController.topViewController;
  1124. viewController.delegate = self;
  1125. viewController.hideButtonCreateFolder = false;
  1126. viewController.selectFile = false;
  1127. viewController.includeDirectoryE2EEncryption = false;
  1128. viewController.includeImages = false;
  1129. viewController.type = @"";
  1130. viewController.titleButtonDone = NSLocalizedString(@"_move_", nil);
  1131. viewController.titleButtonDone1 = NSLocalizedString(@"_copy_", nil);
  1132. viewController.isButtonDone1Hide = false;
  1133. viewController.isOverwriteHide = false;
  1134. viewController.layoutViewSelect = k_layout_view_move;
  1135. [navigationController setModalPresentationStyle:UIModalPresentationFullScreen];
  1136. [self presentViewController:navigationController animated:YES completion:nil];
  1137. }
  1138. #pragma --------------------------------------------------------------------------------------------
  1139. #pragma mark ===== Create folder =====
  1140. #pragma --------------------------------------------------------------------------------------------
  1141. - (void)createFolder
  1142. {
  1143. NSString *serverUrl = [appDelegate getTabBarControllerActiveServerUrl];
  1144. NSString *message;
  1145. UIAlertController *alertController;
  1146. if ([serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]]) {
  1147. message = @"/";
  1148. } else {
  1149. message = [serverUrl lastPathComponent];
  1150. }
  1151. alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_create_folder_on_",nil) message:message preferredStyle:UIAlertControllerStyleAlert];
  1152. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  1153. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  1154. textField.autocapitalizationType = UITextAutocapitalizationTypeSentences;
  1155. }];
  1156. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  1157. NSLog(@"[LOG] Cancel action");
  1158. }];
  1159. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  1160. UITextField *fileName = alertController.textFields.firstObject;
  1161. [[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) { }];
  1162. }];
  1163. okAction.enabled = NO;
  1164. [alertController addAction:cancelAction];
  1165. [alertController addAction:okAction];
  1166. [self presentViewController:alertController animated:YES completion:nil];
  1167. }
  1168. #pragma --------------------------------------------------------------------------------------------
  1169. #pragma mark ===== Progress & Task Button =====
  1170. #pragma --------------------------------------------------------------------------------------------
  1171. - (void)triggerProgressTask:(NSNotification *)notification
  1172. {
  1173. if (sectionDataSource.ocIdIndexPath != nil) {
  1174. [[NCMainCommon sharedInstance] triggerProgressTask:notification sectionDataSourceocIdIndexPath:sectionDataSource.ocIdIndexPath tableView:self.tableView viewController:self serverUrlViewController:self.serverUrl];
  1175. }
  1176. }
  1177. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  1178. {
  1179. UITouch *touch = [[event allTouches] anyObject];
  1180. CGPoint location = [touch locationInView:self.tableView];
  1181. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1182. if ([self indexPathIsValid:indexPath]) {
  1183. tableMetadata *metadataSection = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1184. if (metadataSection) {
  1185. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadataSection.ocId]];
  1186. if (metadata)
  1187. [[NCMainCommon sharedInstance] cancelTransferMetadata:metadata reloadDatasource:true uploadStatusForcedStart:false];
  1188. }
  1189. }
  1190. }
  1191. - (void)cancelAllTask:(id)sender
  1192. {
  1193. CGPoint location = [sender locationInView:self.tableView];
  1194. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1195. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  1196. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_all_task_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  1197. [NCUtility.sharedInstance startActivityIndicatorWithView:self.view bottom:0];
  1198. [[NCMainCommon sharedInstance] cancelAllTransfer];
  1199. [NCUtility.sharedInstance stopActivityIndicator];
  1200. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:nil ocId:nil action:k_action_NULL];
  1201. }]];
  1202. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) { }]];
  1203. alertController.popoverPresentationController.sourceView = self.tableView;
  1204. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  1205. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  1206. [alertController.view layoutIfNeeded];
  1207. [self presentViewController:alertController animated:YES completion:nil];
  1208. }
  1209. #pragma --------------------------------------------------------------------------------------------
  1210. #pragma mark ===== Tap =====
  1211. #pragma --------------------------------------------------------------------------------------------
  1212. - (void)tapActionComment:(UITapGestureRecognizer *)tapGesture
  1213. {
  1214. CGPoint location = [tapGesture locationInView:self.tableView];
  1215. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1216. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1217. if (metadata && ![CCUtility isFolderEncrypted:self.serverUrl e2eEncrypted:metadata.e2eEncrypted account:appDelegate.activeAccount]) {
  1218. [[NCMainCommon sharedInstance] openShareWithViewController:self metadata:metadata indexPage:1];
  1219. }
  1220. }
  1221. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  1222. {
  1223. CGPoint location = [tapGesture locationInView:self.tableView];
  1224. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1225. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1226. if (metadata && ![CCUtility isFolderEncrypted:self.serverUrl e2eEncrypted:metadata.e2eEncrypted account:appDelegate.activeAccount]) {
  1227. [[NCMainCommon sharedInstance] openShareWithViewController:self metadata:metadata indexPage:2];
  1228. }
  1229. }
  1230. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  1231. {
  1232. CGPoint location = [tapGesture locationInView:self.tableView];
  1233. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1234. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1235. if (metadata) {
  1236. }
  1237. }
  1238. #pragma --------------------------------------------------------------------------------------------
  1239. #pragma mark ===== Rich Workspace =====
  1240. #pragma --------------------------------------------------------------------------------------------
  1241. - (void)viewRichWorkspaceTapAction:(UITapGestureRecognizer *)tapGesture
  1242. {
  1243. [UIView animateWithDuration:0.5 animations:^{
  1244. [self.tableView setContentOffset:CGPointMake(0, heightSearchBar)];
  1245. } completion:^(BOOL finished) {
  1246. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"NCViewerRichWorkspace" bundle:nil] instantiateInitialViewController];
  1247. NCViewerRichWorkspace *viewerRichWorkspace = (NCViewerRichWorkspace *)[navigationController topViewController];
  1248. viewerRichWorkspace.richWorkspaceText = self.richWorkspaceText;
  1249. viewerRichWorkspace.serverUrl = self.serverUrl;
  1250. navigationController.modalPresentationStyle = UIModalPresentationFullScreen;
  1251. [self presentViewController:navigationController animated:NO completion:NULL];
  1252. }];
  1253. }
  1254. - (void)createRichWorkspace
  1255. {
  1256. NCRichWorkspaceCommon *richWorkspaceCommon = [NCRichWorkspaceCommon new];
  1257. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileNameView LIKE[c] %@", appDelegate.activeAccount, self.serverUrl, k_fileNameRichWorkspace.lowercaseString]];
  1258. if (metadata) {
  1259. [richWorkspaceCommon openViewerNextcloudTextWithServerUrl:self.serverUrl viewController:self];
  1260. } else {
  1261. [richWorkspaceCommon createViewerNextcloudTextWithServerUrl:self.serverUrl viewController:self];
  1262. }
  1263. }
  1264. #pragma --------------------------------------------------------------------------------------------
  1265. #pragma mark ==== Menu LOGO ====
  1266. #pragma --------------------------------------------------------------------------------------------
  1267. - (void)menuLogo:(UIGestureRecognizer *)theGestureRecognizer
  1268. {
  1269. // Brand
  1270. if ([NCBrandOptions sharedInstance].disable_multiaccount)
  1271. return;
  1272. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  1273. NSMutableArray *menuArray = [NSMutableArray new];
  1274. for (NSString *account in listAccount) {
  1275. CCMenuItem *item = [[CCMenuItem alloc] init];
  1276. item.title = [account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  1277. item.argument = account;
  1278. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ ", account]];
  1279. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@-%@.png", [CCUtility getDirectoryUserData], [CCUtility getStringUser:tableAccount.user activeUrl:tableAccount.url], tableAccount.user];
  1280. UIImage *avatar = [UIImage imageWithContentsOfFile:fileNamePath];
  1281. if (avatar) {
  1282. avatar = [CCGraphics scaleImage:avatar toSize:CGSizeMake(25, 25) isAspectRation:YES];
  1283. CCAvatar *avatarImageView = [[CCAvatar alloc] initWithImage:avatar borderColor:[UIColor lightGrayColor] borderWidth:0.5];
  1284. CGSize imageSize = avatarImageView.bounds.size;
  1285. UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
  1286. CGContextRef context = UIGraphicsGetCurrentContext();
  1287. [avatarImageView.layer renderInContext:context];
  1288. avatar = UIGraphicsGetImageFromCurrentImageContext();
  1289. UIGraphicsEndImageContext();
  1290. } else {
  1291. avatar = [UIImage imageNamed:@"menuLogoUser"];
  1292. }
  1293. item.image = avatar;
  1294. item.target = self;
  1295. if ([account isEqualToString:appDelegate.activeAccount]) {
  1296. item.action = nil;
  1297. [menuArray insertObject:item atIndex:0];
  1298. } else {
  1299. item.action = @selector(changeDefaultAccount:);
  1300. [menuArray addObject:item];
  1301. }
  1302. }
  1303. // Add + new account
  1304. CCMenuItem *item = [[CCMenuItem alloc] init];
  1305. item.title = NSLocalizedString(@"_add_account_", nil);
  1306. item.argument = @"";
  1307. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"add"] width:50 height:50 color:NCBrandColor.sharedInstance.textView];
  1308. item.target = self;
  1309. item.action = @selector(addNewAccount:);
  1310. [menuArray addObject:item];
  1311. OptionalConfiguration options;
  1312. Color backgroundColor;
  1313. const CGFloat *componentsBackgroundColor = CGColorGetComponents(NCBrandColor.sharedInstance.backgroundForm.CGColor);
  1314. backgroundColor.R = componentsBackgroundColor[0];
  1315. backgroundColor.G = componentsBackgroundColor[1];
  1316. backgroundColor.B = componentsBackgroundColor[2];
  1317. options.arrowSize = 9;
  1318. options.marginXSpacing = 7;
  1319. options.marginYSpacing = 10;
  1320. options.intervalSpacing = 20;
  1321. options.menuCornerRadius = 6.5;
  1322. options.maskToBackground = NO;
  1323. options.shadowOfMenu = YES;
  1324. options.hasSeperatorLine = YES;
  1325. options.seperatorLineHasInsets = YES;
  1326. options.textColor = NCBrandColor.sharedInstance.textView;
  1327. options.menuBackgroundColor = backgroundColor;
  1328. options.separatorColor = NCBrandColor.sharedInstance.separator;
  1329. CGRect rect = self.view.frame;
  1330. CGFloat locationY = [theGestureRecognizer locationInView: self.navigationController.navigationBar].y;
  1331. CGFloat safeAreaTop = 0;
  1332. CGFloat offsetY = 35;
  1333. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top / 2;
  1334. rect.origin.y = locationY + safeAreaTop + offsetY;
  1335. rect.size.height = rect.size.height - locationY - safeAreaTop - offsetY;
  1336. [CCMenuAccount setTitleFont:[UIFont systemFontOfSize:12.0]];
  1337. [CCMenuAccount showMenuInView:self.navigationController.view fromRect:rect menuItems:menuArray withOptions:options];
  1338. }
  1339. - (void)changeDefaultAccount:(CCMenuItem *)sender
  1340. {
  1341. // LOGOUT
  1342. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:[sender argument]];
  1343. if (tableAccount) {
  1344. // LOGIN
  1345. [appDelegate settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activeUserID:tableAccount.userID activePassword:[CCUtility getPassword:tableAccount.account]];
  1346. // go to home sweet home
  1347. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_initializeMain object:nil userInfo:nil];
  1348. }
  1349. }
  1350. - (void)addNewAccount:(CCMenuItem *)sender
  1351. {
  1352. [appDelegate openLoginView:self selector:k_intro_login openLoginWeb:false];
  1353. }
  1354. - (void)toggleReMainMenu
  1355. {
  1356. [self toggleMenuWithViewController:self.navigationController];
  1357. }
  1358. - (void)toggleReSelectMenu
  1359. {
  1360. [self toggleSelectMenuWithViewController:self.navigationController];
  1361. }
  1362. #pragma --------------------------------------------------------------------------------------------
  1363. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  1364. #pragma --------------------------------------------------------------------------------------------
  1365. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  1366. {
  1367. if (recognizer.state == UIGestureRecognizerStateBegan) {
  1368. CGPoint touchPoint = [recognizer locationInView:self.tableView];
  1369. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:touchPoint];
  1370. NSMutableArray *items = [NSMutableArray new];
  1371. if ([self indexPathIsValid:indexPath])
  1372. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1373. [self becomeFirstResponder];
  1374. UIMenuController *menuController = [UIMenuController sharedMenuController];
  1375. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyTouchFile:)]];
  1376. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyTouchFiles:)]];
  1377. if ([NCBrandOptions sharedInstance].disable_openin_file == false) {
  1378. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinTouchFile:)]];
  1379. }
  1380. if ([[NCUtility sharedInstance] isQuickLookDisplayableWithMetadata:self.metadata]) {
  1381. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_quicklook_", nil) action:@selector(openQuickLookTouch:)]];
  1382. }
  1383. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteTouchFile:)]];
  1384. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteTouchFiles:)]];
  1385. [menuController setMenuItems:items];
  1386. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:self.tableView];
  1387. [menuController setMenuVisible:YES animated:YES];
  1388. }
  1389. }
  1390. - (BOOL)canBecomeFirstResponder
  1391. {
  1392. return YES;
  1393. }
  1394. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  1395. {
  1396. // For copy file, copy files, Open in ... :
  1397. //
  1398. // NO Directory
  1399. // NO Error Passcode
  1400. // NO In Session mode (download/upload)
  1401. // NO Template
  1402. if (@selector(copyTouchFile:) == action || @selector(openinTouchFile:) == action || @selector(openQuickLookTouch:) == action) {
  1403. if (_isSelectedMode == NO && self.metadata && !self.metadata.directory && self.metadata.status == k_metadataStatusNormal) return YES;
  1404. else return NO;
  1405. }
  1406. if (@selector(copyTouchFiles:) == action) {
  1407. if (_isSelectedMode) {
  1408. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1409. for (tableMetadata *metadata in selectedMetadatas) {
  1410. if (!metadata.directory && metadata.status == k_metadataStatusNormal)
  1411. return YES;
  1412. }
  1413. }
  1414. return NO;
  1415. }
  1416. if (@selector(pasteTouchFile:) == action) {
  1417. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1418. NSArray *items = [pasteboard items];
  1419. if ([items count] == 1) {
  1420. // Value : (NSData) ocId
  1421. NSDictionary *dic = [items objectAtIndex:0];
  1422. NSData *dataocId = [dic objectForKey: k_metadataKeyedUnarchiver];
  1423. NSString *ocId = [NSKeyedUnarchiver unarchiveObjectWithData:dataocId];
  1424. if (ocId) {
  1425. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocId]];
  1426. if (metadata) {
  1427. return [CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView];
  1428. } else {
  1429. return NO;
  1430. }
  1431. }
  1432. }
  1433. return NO;
  1434. }
  1435. if (@selector(pasteTouchFiles:) == action) {
  1436. BOOL isValid = NO;
  1437. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1438. NSArray *items = [pasteboard items];
  1439. if ([items count] <= 1) return NO;
  1440. for (NSDictionary *dic in items) {
  1441. // Value : (NSData) ocId
  1442. NSData *dataocId = [dic objectForKey: k_metadataKeyedUnarchiver];
  1443. NSString *ocId = [NSKeyedUnarchiver unarchiveObjectWithData:dataocId];
  1444. if (ocId) {
  1445. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocId]];
  1446. if (metadata) {
  1447. if ([CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView]) {
  1448. isValid = YES;
  1449. } else {
  1450. isValid = NO;
  1451. break;
  1452. }
  1453. } else {
  1454. isValid = NO;
  1455. break;
  1456. }
  1457. } else {
  1458. isValid = NO;
  1459. break;
  1460. }
  1461. }
  1462. return isValid;
  1463. }
  1464. return NO;
  1465. }
  1466. /************************************ COPY ************************************/
  1467. - (void)copyTouchFile:(id)sender
  1468. {
  1469. // Remove all item
  1470. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1471. pasteboard.items = [[NSArray alloc] init];
  1472. if ([CCUtility fileProviderStorageExists:self.metadata.ocId fileNameView:self.metadata.fileNameView]) {
  1473. [self copyFileToPasteboard:self.metadata];
  1474. } else {
  1475. self.metadata.session = k_download_session;
  1476. self.metadata.sessionError = @"";
  1477. self.metadata.sessionSelector = selectorLoadCopy;
  1478. self.metadata.status = k_metadataStatusWaitDownload;
  1479. // Add Metadata for Download
  1480. [[NCManageDatabase sharedInstance] addMetadata:self.metadata];
  1481. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:self.metadata.ocId action:k_action_MOD];
  1482. [appDelegate startLoadAutoDownloadUpload];
  1483. }
  1484. }
  1485. - (void)copyTouchFiles:(id)sender
  1486. {
  1487. // Remove all item
  1488. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1489. pasteboard.items = [[NSArray alloc] init];
  1490. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1491. for (tableMetadata *metadata in selectedMetadatas) {
  1492. if ([CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView]) {
  1493. [self copyFileToPasteboard:metadata];
  1494. } else {
  1495. metadata.session = k_download_session;
  1496. metadata.sessionError = @"";
  1497. metadata.sessionSelector = selectorLoadCopy;
  1498. metadata.status = k_metadataStatusWaitDownload;
  1499. // Add Metadata for Download
  1500. [[NCManageDatabase sharedInstance] addMetadata:metadata];
  1501. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:metadata.ocId action:k_action_MOD];
  1502. [appDelegate startLoadAutoDownloadUpload];
  1503. }
  1504. }
  1505. [self tableViewSelect:false];
  1506. }
  1507. - (void)copyFileToPasteboard:(tableMetadata *)metadata
  1508. {
  1509. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1510. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  1511. // Value : (NSData) ocId
  1512. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata.ocId], k_metadataKeyedUnarchiver,nil];
  1513. [items addObject:item];
  1514. [pasteboard setItems:items];
  1515. }
  1516. /************************************ OPEN IN ... ******************************/
  1517. - (void)openinTouchFile:(id)sender
  1518. {
  1519. [[NCMainCommon sharedInstance] downloadOpenWithMetadata:self.metadata selector:selectorOpenIn];
  1520. }
  1521. /************************************ OPEN QUICK LOOK ******************************/
  1522. - (void)openQuickLookTouch:(id)sender
  1523. {
  1524. [[NCMainCommon sharedInstance] downloadOpenWithMetadata:self.metadata selector:selectorLoadFileQuickLook];
  1525. }
  1526. /************************************ PASTE ************************************/
  1527. - (void)pasteTouchFile:(id)sender
  1528. {
  1529. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1530. [self uploadFilePasteArray:[pasteboard items]];
  1531. }
  1532. - (void)pasteTouchFiles:(id)sender
  1533. {
  1534. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1535. [self uploadFilePasteArray:[pasteboard items]];
  1536. }
  1537. - (void)uploadFilePasteArray:(NSArray *)items
  1538. {
  1539. for (NSDictionary *dic in items) {
  1540. // Value : (NSData) ocId
  1541. NSData *dataocId = [dic objectForKey: k_metadataKeyedUnarchiver];
  1542. NSString *ocId = [NSKeyedUnarchiver unarchiveObjectWithData:dataocId];
  1543. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocId]];
  1544. if (metadata) {
  1545. if ([CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView]) {
  1546. NSString *fileName = [[NCUtility sharedInstance] createFileName:metadata.fileNameView serverUrl:self.serverUrl account:appDelegate.activeAccount];
  1547. NSString *ocId = [[NSUUID UUID] UUIDString];
  1548. [CCUtility copyFileAtPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileNameView] toPath:[CCUtility getDirectoryProviderStorageOcId:ocId fileNameView:fileName]];
  1549. // Prepare record metadata
  1550. tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] createMetadataWithAccount:appDelegate.activeAccount fileName:fileName ocId:ocId serverUrl:self.serverUrl url:@"" contentType:@""];
  1551. metadataForUpload.session = k_upload_session;
  1552. metadataForUpload.sessionSelector = selectorUploadFile;
  1553. metadataForUpload.size = metadata.size;
  1554. metadataForUpload.status = k_metadataStatusWaitUpload;
  1555. // Add Medtadata for upload
  1556. [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1557. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1558. }
  1559. }
  1560. }
  1561. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1562. [appDelegate startLoadAutoDownloadUpload];
  1563. }
  1564. #pragma mark -
  1565. #pragma --------------------------------------------------------------------------------------------
  1566. #pragma mark ===== menu action : Favorite, More, Delete [swipe] =====
  1567. #pragma --------------------------------------------------------------------------------------------
  1568. - (BOOL)canOpenMenuAction:(tableMetadata *)metadata
  1569. {
  1570. if (metadata == nil || _metadataFolder == nil || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata] || metadata.status != k_metadataStatusNormal || [[NCManageDatabase sharedInstance] isTableInvalidated:_metadataFolder])
  1571. return NO;
  1572. // E2EE
  1573. if (_metadataFolder.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount] == NO)
  1574. return NO;
  1575. return YES;
  1576. }
  1577. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell canSwipe:(MGSwipeDirection)direction
  1578. {
  1579. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  1580. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1581. return [self canOpenMenuAction:metadata];
  1582. }
  1583. -(void)swipeTableCell:(nonnull MGSwipeTableCell *)cell didChangeSwipeState:(MGSwipeState)state gestureIsActive:(BOOL)gestureIsActive
  1584. {
  1585. }
  1586. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell tappedButtonAtIndex:(NSInteger)index direction:(MGSwipeDirection)direction fromExpansion:(BOOL)fromExpansion
  1587. {
  1588. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  1589. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1590. if (direction == MGSwipeDirectionRightToLeft) {
  1591. [self actionDelete:indexPath];
  1592. }
  1593. if (direction == MGSwipeDirectionLeftToRight) {
  1594. [[NCNetworking sharedInstance] favoriteMetadata:self.metadata url:appDelegate.activeUrl completion:^(NSInteger errorCode, NSString *errorDescription) { }];
  1595. }
  1596. return YES;
  1597. }
  1598. - (void)actionDelete:(NSIndexPath *)indexPath
  1599. {
  1600. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1601. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  1602. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  1603. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  1604. [self performSelector:@selector(deleteMetadatas) withObject:nil];
  1605. }]];
  1606. if (localFile) {
  1607. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_remove_local_file_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  1608. tableMetadata *metadataLivePhoto = [[NCUtility sharedInstance] isLivePhotoWithMetadata:metadata];
  1609. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  1610. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId] error:nil];
  1611. if (metadataLivePhoto) {
  1612. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadataLivePhoto.ocId]];
  1613. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageOcId:metadataLivePhoto.ocId] error:nil];
  1614. }
  1615. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1616. }]];
  1617. }
  1618. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  1619. }]];
  1620. alertController.popoverPresentationController.sourceView = self.tableView;
  1621. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  1622. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  1623. [alertController.view layoutIfNeeded];
  1624. [self presentViewController:alertController animated:YES completion:nil];
  1625. }
  1626. - (void)actionMore:(UITapGestureRecognizer *)gestureRecognizer
  1627. {
  1628. CGPoint touch = [gestureRecognizer locationInView:self.tableView];
  1629. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:touch];
  1630. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1631. [self toggleMoreMenuWithViewController:self.tabBarController indexPath:indexPath metadata:self.metadata metadataFolder:_metadataFolder];
  1632. }
  1633. #pragma --------------------------------------------------------------------------------------------
  1634. #pragma mark - ==== Datasource ====
  1635. #pragma --------------------------------------------------------------------------------------------
  1636. - (void)clearDateReadDataSource:(NSNotification *)notification
  1637. {
  1638. _dateReadDataSource = Nil;
  1639. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1640. }
  1641. - (void)reloadDatasource:(NSString *)serverUrl ocId:(NSString *)ocId action:(NSInteger)action
  1642. {
  1643. // test
  1644. if (appDelegate.activeAccount.length == 0 || serverUrl.length == 0 || serverUrl == nil || self.view.window == nil)
  1645. return;
  1646. // Search Mode
  1647. if (self.searchController.isActive) {
  1648. // Create metadatas
  1649. NSMutableArray *metadatas = [NSMutableArray new];
  1650. for (tableMetadata *resultMetadata in _searchResultMetadatas) {
  1651. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", resultMetadata.ocId]];
  1652. if (metadata) {
  1653. [metadatas addObject:metadata];
  1654. }
  1655. }
  1656. // [CCUtility getGroupBySettings]
  1657. sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:metadatas listProgressMetadata:nil groupByField:nil filterTypeFileImage:NO filterTypeFileVideo:NO sorted:@"fileName" ascending:NO activeAccount:appDelegate.activeAccount];
  1658. [self tableViewReloadData];
  1659. if ([sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] >= k_minCharsSearch) {
  1660. _noFilesSearchTitle = NSLocalizedString(@"_search_no_record_found_", nil);
  1661. _noFilesSearchDescription = @"";
  1662. }
  1663. if ([sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] < k_minCharsSearch) {
  1664. _noFilesSearchTitle = @"";
  1665. _noFilesSearchDescription = NSLocalizedString(@"_search_instruction_", nil);
  1666. }
  1667. [self.tableView reloadEmptyDataSet];
  1668. return;
  1669. }
  1670. // Se non siamo nella dir appropriata esci
  1671. if ([serverUrl isEqualToString:self.serverUrl] == NO || self.serverUrl == nil) {
  1672. return;
  1673. }
  1674. // Controllo data lettura Data Source
  1675. tableDirectory *tableDirectory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, serverUrl]];
  1676. if (tableDirectory == nil) {
  1677. return;
  1678. }
  1679. // Get MetadataFolder
  1680. if ([serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]])
  1681. _metadataFolder = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, k_serverUrl_root]];
  1682. else
  1683. _metadataFolder = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", tableDirectory.ocId]];
  1684. // Remove optimization for encrypted directory
  1685. if (_metadataFolder.e2eEncrypted)
  1686. _dateReadDataSource = nil;
  1687. NSDate *dateDateRecordDirectory = tableDirectory.dateReadDirectory;
  1688. if ([dateDateRecordDirectory compare:_dateReadDataSource] == NSOrderedDescending || dateDateRecordDirectory == nil || _dateReadDataSource == nil) {
  1689. NSLog(@"[LOG] Rebuild Data Source File : %@", _serverUrl);
  1690. _dateReadDataSource = [NSDate date];
  1691. // Data Source
  1692. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1693. CCSectionDataSourceMetadata *sectionDataSourceTemp = [self queryDatasourceWithReloadData:NO serverUrl:serverUrl];
  1694. dispatch_async(dispatch_get_main_queue(), ^{
  1695. sectionDataSource = sectionDataSourceTemp;
  1696. [self tableViewReloadData];
  1697. });
  1698. });
  1699. } else {
  1700. [self tableViewReloadData];
  1701. NSLog(@"[LOG] [OPTIMIZATION] Rebuild Data Source File : %@ - %@", _serverUrl, _dateReadDataSource);
  1702. }
  1703. // BLINK
  1704. if (self.blinkFileNamePath != nil) {
  1705. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1706. for (NSString *key in sectionDataSource.allRecordsDataSource) {
  1707. tableMetadata *metadata = [sectionDataSource.allRecordsDataSource objectForKey:key];
  1708. NSString *metadataFileNamePath = [NSString stringWithFormat:@"%@/%@", metadata.serverUrl, metadata.fileName];
  1709. if ([metadataFileNamePath isEqualToString:self.blinkFileNamePath]) {
  1710. for (NSString *key in sectionDataSource.ocIdIndexPath) {
  1711. if ([key isEqualToString:metadata.ocId]) {
  1712. NSIndexPath *indexPath = [sectionDataSource.ocIdIndexPath objectForKey:key];
  1713. [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
  1714. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1715. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  1716. if (cell) {
  1717. self.blinkFileNamePath = nil;
  1718. [[NCUtility sharedInstance] blinkWithCell:cell];
  1719. }
  1720. });
  1721. }
  1722. }
  1723. }
  1724. }
  1725. });
  1726. }
  1727. }
  1728. - (CCSectionDataSourceMetadata *)queryDatasourceWithReloadData:(BOOL)withReloadData serverUrl:(NSString *)serverUrl
  1729. {
  1730. // test
  1731. if (appDelegate.activeAccount.length == 0 || serverUrl == nil) {
  1732. return nil;
  1733. }
  1734. // get auto upload folder
  1735. _autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  1736. _autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:appDelegate.activeUrl];
  1737. CCSectionDataSourceMetadata *sectionDataSourceTemp = [CCSectionDataSourceMetadata new];
  1738. NSArray *recordsTableMetadata = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, serverUrl] sorted:nil ascending:NO];
  1739. // [CCUtility getGroupBySettings]
  1740. sectionDataSourceTemp = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil groupByField:nil filterTypeFileImage:NO filterTypeFileVideo:NO sorted:[CCUtility getOrderSettings] ascending:[CCUtility getAscendingSettings] activeAccount:appDelegate.activeAccount];
  1741. if (withReloadData) {
  1742. sectionDataSource = sectionDataSourceTemp;
  1743. [self tableViewReloadData];
  1744. }
  1745. return sectionDataSourceTemp;
  1746. }
  1747. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  1748. {
  1749. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1750. if (selectedRows.count > 0) {
  1751. for (NSIndexPath *selectionIndex in selectedRows) {
  1752. NSString *ocId = [[sectionDataSource.sectionArrayRow objectForKey:[sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  1753. tableMetadata *metadata = [sectionDataSource.allRecordsDataSource objectForKey:ocId];
  1754. [metadatas addObject:metadata];
  1755. }
  1756. }
  1757. return metadatas;
  1758. }
  1759. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  1760. {
  1761. NSInteger totSections =[sectionDataSource.sections count] ;
  1762. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  1763. return nil;
  1764. }
  1765. id valueSection = [sectionDataSource.sections objectAtIndex:section];
  1766. return [sectionDataSource.sectionArrayRow objectForKey:valueSection];
  1767. }
  1768. #pragma --------------------------------------------------------------------------------------------
  1769. #pragma mark - ==== Table ====
  1770. #pragma --------------------------------------------------------------------------------------------
  1771. - (void)tableViewToggle
  1772. {
  1773. [self tableViewSelect:!_isSelectedMode];
  1774. }
  1775. - (void)tableViewSelect:(BOOL)toggle
  1776. {
  1777. _isSelectedMode = toggle;
  1778. // chiudiamo eventuali swipe aperti
  1779. if (_isSelectedMode)
  1780. [self.tableView setEditing:NO animated:NO];
  1781. [self.tableView setAllowsMultipleSelectionDuringEditing:_isSelectedMode];
  1782. [self.tableView setEditing:_isSelectedMode animated:YES];
  1783. if (_isSelectedMode)
  1784. [self setUINavigationBarSelected];
  1785. else
  1786. [self setUINavigationBarDefault];
  1787. [_selectedocIdsMetadatas removeAllObjects];
  1788. [self setTitle];
  1789. }
  1790. - (void)tableViewReloadData
  1791. {
  1792. // store selected cells before relod
  1793. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  1794. // reload table view
  1795. [self.tableView reloadData];
  1796. // selected cells stored
  1797. for (NSIndexPath *path in indexPaths)
  1798. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  1799. [self setTableViewHeader];
  1800. [self setTableViewFooter];
  1801. if (self.tableView.editing)
  1802. [self setTitle];
  1803. [self.tableView reloadEmptyDataSet];
  1804. }
  1805. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  1806. {
  1807. if (tableView.editing == 1) {
  1808. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1809. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  1810. return NO;
  1811. if (metadata == nil || metadata.status != k_metadataStatusNormal)
  1812. return NO;
  1813. else
  1814. return YES;
  1815. } else {
  1816. [_selectedocIdsMetadatas removeAllObjects];
  1817. }
  1818. return YES;
  1819. }
  1820. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  1821. {
  1822. return 60;
  1823. }
  1824. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  1825. {
  1826. return [[sectionDataSource.sectionArrayRow allKeys] count];
  1827. }
  1828. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  1829. {
  1830. return [[sectionDataSource.sectionArrayRow objectForKey:[sectionDataSource.sections objectAtIndex:section]] count];
  1831. }
  1832. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  1833. {
  1834. NSArray *sections = [sectionDataSource.sectionArrayRow allKeys];
  1835. NSString *sectionTitle = [sections objectAtIndex:section];
  1836. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  1837. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  1838. if ([[CCUtility getGroupBySettings] isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  1839. return 20.f;
  1840. }
  1841. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  1842. {
  1843. float shift;
  1844. UIVisualEffectView *visualEffectView;
  1845. NSString *titleSection;
  1846. if (![self indexPathIsValid:[NSIndexPath indexPathForRow:0 inSection:section]])
  1847. return nil;
  1848. if ([[sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]])
  1849. titleSection = [sectionDataSource.sections objectAtIndex:section];
  1850. if ([[sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]])
  1851. titleSection = [CCUtility getTitleSectionDate:[sectionDataSource.sections objectAtIndex:section]];
  1852. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  1853. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  1854. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  1855. else titleSection = NSLocalizedString(titleSection,nil);
  1856. // Format title
  1857. UIVisualEffect *blurEffect;
  1858. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  1859. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  1860. visualEffectView.backgroundColor = [NCBrandColor.sharedInstance.brand colorWithAlphaComponent:0.2];
  1861. if ([[CCUtility getGroupBySettings] isEqualToString:@"alphabetic"]) {
  1862. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  1863. shift = - 35;
  1864. else
  1865. shift = - 20;
  1866. } else shift = - 10;
  1867. // Title
  1868. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  1869. titleLabel.backgroundColor = [UIColor clearColor];
  1870. titleLabel.textColor = NCBrandColor.sharedInstance.textView;
  1871. titleLabel.font = [UIFont systemFontOfSize:12];
  1872. titleLabel.textAlignment = NSTextAlignmentLeft;
  1873. titleLabel.text = titleSection;
  1874. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  1875. [visualEffectView.contentView addSubview:titleLabel];
  1876. // Elements
  1877. UILabel *elementLabel= [[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  1878. elementLabel.backgroundColor = [UIColor clearColor];
  1879. elementLabel.textColor = NCBrandColor.sharedInstance.textView;
  1880. elementLabel.font = [UIFont systemFontOfSize:12];
  1881. elementLabel.textAlignment = NSTextAlignmentRight;
  1882. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  1883. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  1884. NSUInteger rowsCount = [metadatas count];
  1885. if (rowsCount == 0) return nil;
  1886. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  1887. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  1888. [visualEffectView.contentView addSubview:elementLabel];
  1889. return visualEffectView;
  1890. }
  1891. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  1892. {
  1893. return [sectionDataSource.sections indexOfObject:title];
  1894. }
  1895. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  1896. {
  1897. if ([[CCUtility getGroupBySettings] isEqualToString:@"alphabetic"])
  1898. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  1899. else
  1900. return nil;
  1901. }
  1902. /*
  1903. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  1904. {
  1905. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  1906. }
  1907. }
  1908. */
  1909. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  1910. {
  1911. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1912. tableShare *shareCell;
  1913. if (metadata == nil || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata] || (_metadataFolder != nil && [[NCManageDatabase sharedInstance] isTableInvalidated:_metadataFolder])) {
  1914. return [CCCellMain new];
  1915. }
  1916. for (tableShare *share in appDelegate.shares) {
  1917. if ([share.serverUrl isEqualToString:metadata.serverUrl] && [share.fileName isEqualToString:metadata.fileName]) {
  1918. shareCell = share;
  1919. break;
  1920. }
  1921. }
  1922. UITableViewCell *cell = [[NCMainCommon sharedInstance] cellForRowAtIndexPath:indexPath tableView:tableView metadata:metadata metadataFolder:_metadataFolder serverUrl:self.serverUrl autoUploadFileName:_autoUploadFileName autoUploadDirectory:_autoUploadDirectory tableShare:shareCell];
  1923. // NORMAL - > MAIN
  1924. if ([cell isKindOfClass:[CCCellMain class]]) {
  1925. // Comment tap
  1926. if (metadata.commentsUnread) {
  1927. UITapGestureRecognizer *tapComment = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionComment:)];
  1928. [tapComment setNumberOfTapsRequired:1];
  1929. ((CCCellMain *)cell).comment.userInteractionEnabled = YES;
  1930. [((CCCellMain *)cell).comment addGestureRecognizer:tapComment];
  1931. }
  1932. // Share add Tap
  1933. UITapGestureRecognizer *tapShare = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  1934. [tapShare setNumberOfTapsRequired:1];
  1935. ((CCCellMain *)cell).viewShared.userInteractionEnabled = YES;
  1936. [((CCCellMain *)cell).viewShared addGestureRecognizer:tapShare];
  1937. // More
  1938. if ([self canOpenMenuAction:metadata]) {
  1939. UITapGestureRecognizer *tapMore = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(actionMore:)];
  1940. [tapMore setNumberOfTapsRequired:1];
  1941. ((CCCellMain *)cell).more.userInteractionEnabled = YES;
  1942. [((CCCellMain *)cell).more addGestureRecognizer:tapMore];
  1943. }
  1944. // MGSwipeButton
  1945. ((CCCellMain *)cell).delegate = self;
  1946. // LEFT
  1947. ((CCCellMain *)cell).leftButtons = @[[MGSwipeButton buttonWithTitle:@"" icon:self.cellFavouriteImage backgroundColor:NCBrandColor.sharedInstance.yellowFavorite padding:25]];
  1948. ((CCCellMain *)cell).leftExpansion.buttonIndex = 0;
  1949. ((CCCellMain *)cell).leftExpansion.fillOnTrigger = NO;
  1950. //centerIconOverText
  1951. MGSwipeButton *favoriteButton = (MGSwipeButton *)[((CCCellMain *)cell).leftButtons objectAtIndex:0];
  1952. [favoriteButton centerIconOverText];
  1953. // RIGHT
  1954. ((CCCellMain *)cell).rightButtons = @[[MGSwipeButton buttonWithTitle:@"" icon:self.cellTrashImage backgroundColor:[UIColor redColor] padding:25]];
  1955. ((CCCellMain *)cell).rightExpansion.buttonIndex = 0;
  1956. ((CCCellMain *)cell).rightExpansion.fillOnTrigger = NO;
  1957. //centerIconOverText
  1958. MGSwipeButton *deleteButton = (MGSwipeButton *)[((CCCellMain *)cell).rightButtons objectAtIndex:0];
  1959. [deleteButton centerIconOverText];
  1960. }
  1961. // TRANSFER
  1962. if ([cell isKindOfClass:[CCCellMainTransfer class]]) {
  1963. // gesture Transfer
  1964. [((CCCellMainTransfer *)cell).transferButton.stopButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  1965. UILongPressGestureRecognizer *stopLongGesture = [UILongPressGestureRecognizer new];
  1966. [stopLongGesture addTarget:self action:@selector(cancelAllTask:)];
  1967. [((CCCellMainTransfer *)cell).transferButton.stopButton addGestureRecognizer:stopLongGesture];
  1968. }
  1969. return cell;
  1970. }
  1971. - (void)setTableViewHeader
  1972. {
  1973. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilitesWithAccount:appDelegate.activeAccount];
  1974. NSString *trimmedRichWorkspaceText = [self.richWorkspaceText stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
  1975. if (capabilities.versionMajor < k_nextcloud_version_18_0 || trimmedRichWorkspaceText.length == 0 ) {
  1976. [self.tableView.tableHeaderView setFrame:CGRectMake(self.tableView.tableHeaderView.frame.origin.x, self.tableView.tableHeaderView.frame.origin.y, self.tableView.frame.size.width, heightSearchBar)];
  1977. } else {
  1978. [self.viewRichWorkspace setFrame:CGRectMake(self.tableView.tableHeaderView.frame.origin.x, self.tableView.tableHeaderView.frame.origin.y, self.tableView.frame.size.width, heightRichWorkspace)];
  1979. }
  1980. if (self.searchController.isActive == true) {
  1981. [self.tableView.tableHeaderView setFrame:CGRectMake(self.tableView.tableHeaderView.frame.origin.x, self.tableView.tableHeaderView.frame.origin.y, self.tableView.frame.size.width, 0)];
  1982. }
  1983. [self.viewRichWorkspace setNeedsLayout];
  1984. [self.viewRichWorkspace loadWithRichWorkspaceText:self.richWorkspaceText];
  1985. }
  1986. - (void)setTableViewFooter
  1987. {
  1988. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  1989. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  1990. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  1991. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  1992. UIFont *appFont = [UIFont systemFontOfSize:12];
  1993. footerLabel.font = appFont;
  1994. footerLabel.textColor = [UIColor grayColor];
  1995. footerLabel.backgroundColor = [UIColor clearColor];
  1996. footerLabel.textAlignment = NSTextAlignmentCenter;
  1997. NSString *folders;
  1998. NSString *files;
  1999. NSString *footerText;
  2000. if (sectionDataSource.directories > 1) {
  2001. folders = [NSString stringWithFormat:@"%ld %@", (long)sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  2002. } else if (sectionDataSource.directories == 1){
  2003. folders = [NSString stringWithFormat:@"%ld %@", (long)sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  2004. } else {
  2005. folders = @"";
  2006. }
  2007. if (sectionDataSource.files > 1) {
  2008. files = [NSString stringWithFormat:@"%ld %@ %@", (long)sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:sectionDataSource.totalSize]];
  2009. } else if (sectionDataSource.files == 1){
  2010. files = [NSString stringWithFormat:@"%ld %@ %@", (long)sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:sectionDataSource.totalSize]];
  2011. } else {
  2012. files = @"";
  2013. }
  2014. if ([folders isEqualToString:@""]) {
  2015. footerText = files;
  2016. } else if ([files isEqualToString:@""]) {
  2017. footerText = folders;
  2018. } else {
  2019. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  2020. }
  2021. footerLabel.text = footerText;
  2022. [footerView addSubview:footerLabel];
  2023. [self.tableView setTableFooterView:footerView];
  2024. }
  2025. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  2026. {
  2027. CCCellMain *cell = [tableView cellForRowAtIndexPath:indexPath];
  2028. // settiamo il record file.
  2029. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2030. if (!self.metadata)
  2031. return;
  2032. // se non può essere selezionata deseleziona
  2033. if ([cell isEditing] == NO)
  2034. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  2035. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  2036. if (self.tableView.editing) {
  2037. [_selectedocIdsMetadatas setObject:self.metadata forKey:self.metadata.ocId];
  2038. [self setTitle];
  2039. return;
  2040. }
  2041. // se è in corso una sessione
  2042. if (self.metadata.status != k_metadataStatusNormal)
  2043. return;
  2044. // file
  2045. if (self.metadata.directory == NO) {
  2046. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  2047. if ([CCUtility fileProviderStorageExists:self.metadata.ocId fileNameView:self.metadata.fileNameView]) {
  2048. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_downloadedFile object:nil userInfo:@{@"metadata": self.metadata, @"selector": selectorLoadFileView, @"errorCode": @(0), @"errorDescription": @""}];
  2049. } else {
  2050. if (_metadataFolder.e2eEncrypted && ![CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  2051. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  2052. } else {
  2053. if (([self.metadata.typeFile isEqualToString: k_metadataTypeFile_video] || [self.metadata.typeFile isEqualToString: k_metadataTypeFile_audio]) && _metadataFolder.e2eEncrypted == NO) {
  2054. [self shouldPerformSegue:self.metadata selector:@""];
  2055. } else if ([self.metadata.typeFile isEqualToString: k_metadataTypeFile_document] && [[NCUtility sharedInstance] isDirectEditing:self.metadata] != nil) {
  2056. if (appDelegate.reachability.isReachable) {
  2057. [self shouldPerformSegue:self.metadata selector:@""];
  2058. } else {
  2059. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_go_online_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  2060. }
  2061. } else if ([self.metadata.typeFile isEqualToString: k_metadataTypeFile_document] && [[NCUtility sharedInstance] isRichDocument:self.metadata]) {
  2062. if (appDelegate.reachability.isReachable) {
  2063. [self shouldPerformSegue:self.metadata selector:@""];
  2064. } else {
  2065. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_go_online_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  2066. }
  2067. } else {
  2068. if ([self.metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  2069. [self shouldPerformSegue:self.metadata selector:selectorLoadFileView];
  2070. }
  2071. self.metadata.session = k_download_session;
  2072. self.metadata.sessionError = @"";
  2073. self.metadata.sessionSelector = selectorLoadFileView;
  2074. self.metadata.status = k_metadataStatusWaitDownload;
  2075. // Add Metadata for Download
  2076. [[NCManageDatabase sharedInstance] addMetadata:self.metadata];
  2077. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:self.metadata.ocId action:k_action_MOD];
  2078. [appDelegate startLoadAutoDownloadUpload];
  2079. }
  2080. }
  2081. }
  2082. }
  2083. if (self.metadata.directory) {
  2084. [self performSegueDirectoryWithMetadata:self.metadata blinkFileNamePath:self.blinkFileNamePath];
  2085. }
  2086. }
  2087. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  2088. {
  2089. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2090. [_selectedocIdsMetadatas removeObjectForKey:metadata.ocId];
  2091. [self setTitle];
  2092. }
  2093. - (void)didSelectAll
  2094. {
  2095. for (int i = 0; i < self.tableView.numberOfSections; i++) {
  2096. for (int j = 0; j < [self.tableView numberOfRowsInSection:i]; j++) {
  2097. NSIndexPath *indexPath = [NSIndexPath indexPathForRow:j inSection:i];
  2098. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2099. [_selectedocIdsMetadatas setObject:metadata forKey:metadata.ocId];
  2100. [self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
  2101. }
  2102. }
  2103. [self setTitle];
  2104. }
  2105. - (BOOL)indexPathIsValid:(NSIndexPath *)indexPath
  2106. {
  2107. if (!indexPath)
  2108. return NO;
  2109. NSInteger section = indexPath.section;
  2110. NSInteger row = indexPath.row;
  2111. NSInteger lastSectionIndex = [self numberOfSectionsInTableView:self.tableView] - 1;
  2112. if (section > lastSectionIndex || lastSectionIndex < 0)
  2113. return NO;
  2114. NSInteger rowCount = [self.tableView numberOfRowsInSection:indexPath.section] - 1;
  2115. if (rowCount < 0)
  2116. return NO;
  2117. return row <= rowCount;
  2118. }
  2119. #pragma --------------------------------------------------------------------------------------------
  2120. #pragma mark ===== Navigation ====
  2121. #pragma --------------------------------------------------------------------------------------------
  2122. - (void)shouldPerformSegue:(tableMetadata *)metadata selector:(NSString *)selector
  2123. {
  2124. // if background return
  2125. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return;
  2126. if (self.view.window == NO)
  2127. return;
  2128. // Collapsed ma siamo già in detail esci
  2129. if (self.splitViewController.isCollapsed) {
  2130. if (appDelegate.activeDetail.isViewLoaded && appDelegate.activeDetail.view.window) return;
  2131. }
  2132. // Metadata for push detail
  2133. self.metadataForPushDetail = metadata;
  2134. self.selectorForPushDetail = selector;
  2135. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  2136. }
  2137. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  2138. {
  2139. tableMetadata *metadata;
  2140. NSMutableArray *photoDataSource = [NSMutableArray new];
  2141. UINavigationController *navigationController = segue.destinationViewController;
  2142. NCDetailViewController *detailViewController = (NCDetailViewController *)navigationController.topViewController;
  2143. if ([sender isKindOfClass:[tableMetadata class]]) {
  2144. metadata = sender;
  2145. [photoDataSource addObject:sender];
  2146. } else {
  2147. metadata = self.metadataForPushDetail;
  2148. for (NSString *ocId in sectionDataSource.allOcId) {
  2149. tableMetadata *metadata = [sectionDataSource.allRecordsDataSource objectForKey:ocId];
  2150. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  2151. [photoDataSource addObject:metadata];
  2152. }
  2153. }
  2154. detailViewController.metadata = metadata;
  2155. detailViewController.selector = self.selectorForPushDetail;
  2156. [detailViewController setTitle:metadata.fileNameView];
  2157. }
  2158. // can i go to next viewcontroller
  2159. - (void)performSegueDirectoryWithMetadata:(tableMetadata *)metadata blinkFileNamePath:(NSString *)blinkFileNamePath
  2160. {
  2161. NSString *nomeDir;
  2162. if (self.tableView.editing == NO) {
  2163. // E2EE Check enable
  2164. if (metadata.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount] == NO) {
  2165. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  2166. return;
  2167. }
  2168. nomeDir = metadata.fileName;
  2169. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:metadata.serverUrl addFileName:nomeDir];
  2170. CCMain *viewController = [appDelegate.listMainVC objectForKey:serverUrlPush];
  2171. if (!viewController) {
  2172. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMain"];
  2173. viewController.serverUrl = serverUrlPush;
  2174. viewController.titleMain = metadata.fileNameView;
  2175. viewController.blinkFileNamePath = blinkFileNamePath;
  2176. // save self
  2177. [appDelegate.listMainVC setObject:viewController forKey:serverUrlPush];
  2178. [self.navigationController pushViewController:viewController animated:YES];
  2179. } else {
  2180. if (viewController.isViewLoaded) {
  2181. viewController.titleMain = metadata.fileNameView;
  2182. viewController.blinkFileNamePath = blinkFileNamePath;
  2183. // Fix : Application tried to present modally an active controller
  2184. if ([self.navigationController isBeingPresented]) {
  2185. // being presented
  2186. } else if ([self.navigationController isMovingToParentViewController]) {
  2187. // being pushed
  2188. } else {
  2189. [self.navigationController pushViewController:viewController animated:YES];
  2190. }
  2191. }
  2192. }
  2193. }
  2194. }
  2195. @end