CCMain.m 114 KB

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