CCMain.m 114 KB

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