CCMain.m 114 KB

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