CCMain.m 114 KB

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