CCMain.m 125 KB

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