NCCollectionViewCommon.swift 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344
  1. //
  2. // NCCollectionViewCommon.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 12/09/2020.
  6. // Copyright © 2020 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 UIKit
  24. import SwiftUI
  25. import RealmSwift
  26. import NextcloudKit
  27. import EasyTipView
  28. import JGProgressHUD
  29. class NCCollectionViewCommon: UIViewController, UIGestureRecognizerDelegate, UISearchResultsUpdating, UISearchControllerDelegate, UISearchBarDelegate, NCListCellDelegate, NCGridCellDelegate, NCPhotoCellDelegate, NCSectionFirstHeaderDelegate, NCSectionFooterDelegate, NCSectionFirstHeaderEmptyDataDelegate, NCAccountSettingsModelDelegate, UIAdaptivePresentationControllerDelegate, UIContextMenuInteractionDelegate {
  30. @IBOutlet weak var collectionView: UICollectionView!
  31. var autoUploadFileName = ""
  32. var autoUploadDirectory = ""
  33. var isTransitioning: Bool = false
  34. let appDelegate = (UIApplication.shared.delegate as? AppDelegate)!
  35. let utilityFileSystem = NCUtilityFileSystem()
  36. let utility = NCUtility()
  37. let refreshControl = UIRefreshControl()
  38. var searchController: UISearchController?
  39. var backgroundImageView = UIImageView()
  40. var serverUrl: String = ""
  41. var isEditMode = false
  42. var selectOcId: [String] = []
  43. var metadataFolder: tableMetadata?
  44. var dataSource = NCDataSource()
  45. var richWorkspaceText: String?
  46. var sectionFirstHeader: NCSectionFirstHeader?
  47. var sectionFirstHeaderEmptyData: NCSectionFirstHeaderEmptyData?
  48. var isSearchingMode: Bool = false
  49. var layoutForView: NCDBLayoutForView?
  50. var dataSourceTask: URLSessionTask?
  51. var providers: [NKSearchProvider]?
  52. var searchResults: [NKSearchResult]?
  53. var listLayout = NCListLayout()
  54. var gridLayout = NCGridLayout()
  55. var mediaLayout = NCMediaLayout()
  56. var layoutType = NCGlobal.shared.layoutList
  57. var literalSearch: String?
  58. var tabBarSelect: NCCollectionViewCommonSelectTabBar!
  59. var timerNotificationCenter: Timer?
  60. var notificationReloadDataSource: Int = 0
  61. var notificationReloadDataSourceNetwork: Int = 0
  62. var attributesZoomIn: UIMenuElement.Attributes = []
  63. var attributesZoomOut: UIMenuElement.Attributes = []
  64. let maxImageGrid: CGFloat = 7
  65. // DECLARE
  66. var layoutKey = ""
  67. var titleCurrentFolder = ""
  68. var titlePreviusFolder: String?
  69. var enableSearchBar: Bool = false
  70. var headerMenuTransferView = false
  71. var headerRichWorkspaceDisable: Bool = false
  72. var emptyImage: UIImage?
  73. var emptyTitle: String = ""
  74. var emptyDescription: String = ""
  75. var emptyDataPortaitOffset: CGFloat = 0
  76. var emptyDataLandscapeOffset: CGFloat = -20
  77. var showDescription: Bool {
  78. !headerRichWorkspaceDisable && NCKeychain().showDescription
  79. }
  80. var infoLabelsSeparator: String {
  81. layoutForView?.layout == NCGlobal.shared.layoutList ? " - " : ""
  82. }
  83. // MARK: - View Life Cycle
  84. override func viewDidLoad() {
  85. super.viewDidLoad()
  86. tabBarSelect = NCCollectionViewCommonSelectTabBar(controller: tabBarController as? NCMainTabBarController, delegate: self)
  87. self.navigationController?.presentationController?.delegate = self
  88. collectionView.alwaysBounceVertical = true
  89. // Color
  90. view.backgroundColor = .systemBackground
  91. collectionView.backgroundColor = .systemBackground
  92. refreshControl.tintColor = NCBrandColor.shared.textColor2
  93. if enableSearchBar {
  94. searchController = UISearchController(searchResultsController: nil)
  95. searchController?.searchResultsUpdater = self
  96. searchController?.obscuresBackgroundDuringPresentation = false
  97. searchController?.delegate = self
  98. searchController?.searchBar.delegate = self
  99. searchController?.searchBar.autocapitalizationType = .none
  100. navigationItem.searchController = searchController
  101. navigationItem.hidesSearchBarWhenScrolling = true
  102. }
  103. // Cell
  104. collectionView.register(UINib(nibName: "NCListCell", bundle: nil), forCellWithReuseIdentifier: "listCell")
  105. collectionView.register(UINib(nibName: "NCGridCell", bundle: nil), forCellWithReuseIdentifier: "gridCell")
  106. collectionView.register(UINib(nibName: "NCPhotoCell", bundle: nil), forCellWithReuseIdentifier: "photoCell")
  107. collectionView.register(UINib(nibName: "NCTransferCell", bundle: nil), forCellWithReuseIdentifier: "transferCell")
  108. // Header
  109. collectionView.register(UINib(nibName: "NCSectionFirstHeader", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionFirstHeader")
  110. collectionView.register(UINib(nibName: "NCSectionFirstHeader", bundle: nil), forSupplementaryViewOfKind: mediaSectionHeader, withReuseIdentifier: "sectionFirstHeader")
  111. collectionView.register(UINib(nibName: "NCSectionHeader", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeader")
  112. collectionView.register(UINib(nibName: "NCSectionHeader", bundle: nil), forSupplementaryViewOfKind: mediaSectionHeader, withReuseIdentifier: "sectionHeader")
  113. collectionView.register(UINib(nibName: "NCSectionFirstHeaderEmptyData", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionFirstHeaderEmptyData")
  114. collectionView.register(UINib(nibName: "NCSectionFirstHeaderEmptyData", bundle: nil), forSupplementaryViewOfKind: mediaSectionHeader, withReuseIdentifier: "sectionFirstHeaderEmptyData")
  115. // Footer
  116. collectionView.register(UINib(nibName: "NCSectionFooter", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "sectionFooter")
  117. collectionView.register(UINib(nibName: "NCSectionFooter", bundle: nil), forSupplementaryViewOfKind: mediaSectionFooter, withReuseIdentifier: "sectionFooter")
  118. // Refresh Control
  119. collectionView.refreshControl = refreshControl
  120. refreshControl.action(for: .valueChanged) { _ in
  121. self.dataSource.clearDirectory()
  122. NCManageDatabase.shared.cleanEtagDirectory(account: self.appDelegate.account, serverUrl: self.serverUrl)
  123. self.reloadDataSourceNetwork()
  124. }
  125. // Long Press on CollectionView
  126. let longPressedGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPressCollecationView(_:)))
  127. longPressedGesture.minimumPressDuration = 0.5
  128. longPressedGesture.delegate = self
  129. longPressedGesture.delaysTouchesBegan = true
  130. collectionView.addGestureRecognizer(longPressedGesture)
  131. // Drag & Drop
  132. collectionView.dragInteractionEnabled = true
  133. collectionView.dragDelegate = self
  134. collectionView.dropDelegate = self
  135. let dropInteraction = UIDropInteraction(delegate: self)
  136. self.navigationController?.navigationItem.leftBarButtonItems?.first?.customView?.addInteraction(dropInteraction)
  137. NotificationCenter.default.addObserver(self, selector: #selector(changeTheming), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterChangeTheming), object: nil)
  138. }
  139. override func viewWillAppear(_ animated: Bool) {
  140. super.viewWillAppear(animated)
  141. navigationController?.setNavigationBarAppearance()
  142. navigationController?.navigationBar.prefersLargeTitles = true
  143. navigationController?.setNavigationBarHidden(false, animated: true)
  144. navigationItem.title = titleCurrentFolder
  145. isEditMode = false
  146. setNavigationLeftItems()
  147. setNavigationRightItems()
  148. layoutForView = NCManageDatabase.shared.getLayoutForView(account: appDelegate.account, key: layoutKey, serverUrl: serverUrl)
  149. if layoutForView?.layout == NCGlobal.shared.layoutList {
  150. collectionView?.collectionViewLayout = listLayout
  151. self.layoutType = NCGlobal.shared.layoutList
  152. } else if layoutForView?.layout == NCGlobal.shared.layoutGrid {
  153. collectionView?.collectionViewLayout = gridLayout
  154. self.layoutType = NCGlobal.shared.layoutGrid
  155. } else if layoutForView?.layout == NCGlobal.shared.layoutPhotoRatio {
  156. collectionView?.collectionViewLayout = mediaLayout
  157. self.layoutType = NCGlobal.shared.layoutPhotoRatio
  158. } else if layoutForView?.layout == NCGlobal.shared.layoutPhotoSquare {
  159. collectionView?.collectionViewLayout = mediaLayout
  160. self.layoutType = NCGlobal.shared.layoutPhotoSquare
  161. }
  162. // FIXME: iPAD PDF landscape mode iOS 16
  163. DispatchQueue.main.async {
  164. self.collectionView?.collectionViewLayout.invalidateLayout()
  165. }
  166. }
  167. override func viewDidAppear(_ animated: Bool) {
  168. super.viewDidAppear(animated)
  169. timerNotificationCenter = Timer.scheduledTimer(timeInterval: 1.5, target: self, selector: #selector(notificationCenterEvents), userInfo: nil, repeats: true)
  170. NotificationCenter.default.addObserver(self, selector: #selector(applicationWillResignActive(_:)), name: UIApplication.willResignActiveNotification, object: nil)
  171. NotificationCenter.default.addObserver(self, selector: #selector(closeRichWorkspaceWebView), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCloseRichWorkspaceWebView), object: nil)
  172. NotificationCenter.default.addObserver(self, selector: #selector(changeStatusFolderE2EE(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterChangeStatusFolderE2EE), object: nil)
  173. NotificationCenter.default.addObserver(self, selector: #selector(reloadAvatar(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadAvatar), object: nil)
  174. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSource(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadDataSource), object: nil)
  175. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSourceNetwork(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadDataSourceNetwork), object: nil)
  176. NotificationCenter.default.addObserver(self, selector: #selector(deleteFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDeleteFile), object: nil)
  177. NotificationCenter.default.addObserver(self, selector: #selector(moveFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMoveFile), object: nil)
  178. NotificationCenter.default.addObserver(self, selector: #selector(copyFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCopyFile), object: nil)
  179. NotificationCenter.default.addObserver(self, selector: #selector(renameFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterRenameFile), object: nil)
  180. NotificationCenter.default.addObserver(self, selector: #selector(createFolder(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCreateFolder), object: nil)
  181. NotificationCenter.default.addObserver(self, selector: #selector(favoriteFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterFavoriteFile), object: nil)
  182. NotificationCenter.default.addObserver(self, selector: #selector(downloadStartFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadStartFile), object: nil)
  183. NotificationCenter.default.addObserver(self, selector: #selector(downloadedFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadedFile), object: nil)
  184. NotificationCenter.default.addObserver(self, selector: #selector(downloadCancelFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadCancelFile), object: nil)
  185. NotificationCenter.default.addObserver(self, selector: #selector(uploadStartFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadStartFile), object: nil)
  186. NotificationCenter.default.addObserver(self, selector: #selector(uploadedFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedFile), object: nil)
  187. NotificationCenter.default.addObserver(self, selector: #selector(uploadedLivePhoto(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedLivePhoto), object: nil)
  188. NotificationCenter.default.addObserver(self, selector: #selector(uploadCancelFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadCancelFile), object: nil)
  189. NotificationCenter.default.addObserver(self, selector: #selector(triggerProgressTask(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterProgressTask), object: nil)
  190. }
  191. override func viewWillDisappear(_ animated: Bool) {
  192. super.viewWillDisappear(animated)
  193. NCNetworking.shared.cancelUnifiedSearchFiles()
  194. dismissTip()
  195. // Cancel Queue & Retrieves Properties
  196. NCNetworking.shared.downloadThumbnailQueue.cancelAll()
  197. NCNetworking.shared.unifiedSearchQueue.cancelAll()
  198. dataSourceTask?.cancel()
  199. }
  200. override func viewDidDisappear(_ animated: Bool) {
  201. super.viewDidDisappear(animated)
  202. timerNotificationCenter?.invalidate()
  203. NotificationCenter.default.removeObserver(self, name: UIApplication.willResignActiveNotification, object: nil)
  204. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCloseRichWorkspaceWebView), object: nil)
  205. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterChangeStatusFolderE2EE), object: nil)
  206. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadAvatar), object: nil)
  207. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadDataSource), object: nil)
  208. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadDataSourceNetwork), object: nil)
  209. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDeleteFile), object: nil)
  210. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMoveFile), object: nil)
  211. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCopyFile), object: nil)
  212. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterRenameFile), object: nil)
  213. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCreateFolder), object: nil)
  214. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterFavoriteFile), object: nil)
  215. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadStartFile), object: nil)
  216. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadedFile), object: nil)
  217. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadCancelFile), object: nil)
  218. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadStartFile), object: nil)
  219. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedFile), object: nil)
  220. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedLivePhoto), object: nil)
  221. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadCancelFile), object: nil)
  222. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterProgressTask), object: nil)
  223. }
  224. func presentationControllerDidDismiss( _ presentationController: UIPresentationController) {
  225. let viewController = presentationController.presentedViewController
  226. if viewController is NCViewerRichWorkspaceWebView {
  227. closeRichWorkspaceWebView()
  228. }
  229. }
  230. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  231. super.viewWillTransition(to: size, with: coordinator)
  232. collectionView?.collectionViewLayout.invalidateLayout()
  233. collectionView?.reloadData()
  234. dismissTip()
  235. }
  236. override var canBecomeFirstResponder: Bool {
  237. return true
  238. }
  239. override func viewWillLayoutSubviews() {
  240. super.viewWillLayoutSubviews()
  241. if let frame = tabBarController?.tabBar.frame {
  242. tabBarSelect.hostingController?.view.frame = frame
  243. }
  244. }
  245. // MARK: - NotificationCenter
  246. @objc func notificationCenterEvents() {
  247. if notificationReloadDataSource > 0 {
  248. print("notificationReloadDataSource: \(notificationReloadDataSource)")
  249. reloadDataSource()
  250. notificationReloadDataSource = 0
  251. }
  252. }
  253. @objc func applicationWillResignActive(_ notification: NSNotification) {
  254. self.refreshControl.endRefreshing()
  255. }
  256. @objc func reloadAvatar(_ notification: NSNotification) {
  257. DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
  258. self.showTip()
  259. }
  260. guard let userInfo = notification.userInfo as NSDictionary?,
  261. let error = userInfo["error"] as? NKError,
  262. error.errorCode != NCGlobal.shared.errorNotModified else { return }
  263. setNavigationLeftItems()
  264. }
  265. @objc func changeTheming() {
  266. collectionView.reloadData()
  267. }
  268. @objc func reloadDataSource(_ notification: NSNotification) {
  269. notificationReloadDataSource += 1
  270. }
  271. @objc func reloadDataSourceNetwork(_ notification: NSNotification) {
  272. var withQueryDB = false
  273. if let userInfo = notification.userInfo as NSDictionary?,
  274. let reload = userInfo["withQueryDB"] as? Bool {
  275. withQueryDB = reload
  276. }
  277. if !isSearchingMode {
  278. reloadDataSourceNetwork(withQueryDB: withQueryDB)
  279. }
  280. }
  281. @objc func changeStatusFolderE2EE(_ notification: NSNotification) {
  282. notificationReloadDataSource += 1
  283. }
  284. @objc func closeRichWorkspaceWebView() {
  285. reloadDataSourceNetwork()
  286. }
  287. @objc func deleteFile(_ notification: NSNotification) {
  288. guard let userInfo = notification.userInfo as NSDictionary?,
  289. let error = userInfo["error"] as? NKError else { return }
  290. if error == .success {
  291. reloadDataSource()
  292. } else {
  293. NCContentPresenter().showError(error: error)
  294. }
  295. }
  296. @objc func moveFile(_ notification: NSNotification) {
  297. guard let userInfo = notification.userInfo as NSDictionary?,
  298. let error = userInfo["error"] as? NKError else { return }
  299. if error == .success {
  300. if !isSearchingMode, let dragDrop = userInfo["dragdrop"] as? Bool, dragDrop {
  301. setEditMode(false)
  302. reloadDataSourceNetwork(withQueryDB: true)
  303. } else {
  304. reloadDataSource()
  305. }
  306. } else {
  307. NCContentPresenter().showError(error: error)
  308. }
  309. }
  310. @objc func copyFile(_ notification: NSNotification) {
  311. guard let userInfo = notification.userInfo as NSDictionary?,
  312. let error = userInfo["error"] as? NKError else { return }
  313. if error == .success {
  314. if !isSearchingMode, let dragDrop = userInfo["dragdrop"] as? Bool, dragDrop {
  315. setEditMode(false)
  316. reloadDataSourceNetwork(withQueryDB: true)
  317. } else {
  318. reloadDataSource()
  319. }
  320. } else {
  321. NCContentPresenter().showError(error: error)
  322. }
  323. }
  324. @objc func renameFile(_ notification: NSNotification) {
  325. guard let userInfo = notification.userInfo as NSDictionary?,
  326. let account = userInfo["account"] as? String,
  327. account == appDelegate.account
  328. else { return }
  329. reloadDataSource()
  330. }
  331. @objc func createFolder(_ notification: NSNotification) {
  332. guard let userInfo = notification.userInfo as NSDictionary?,
  333. let ocId = userInfo["ocId"] as? String,
  334. let serverUrl = userInfo["serverUrl"] as? String,
  335. serverUrl == self.serverUrl,
  336. let account = userInfo["account"] as? String,
  337. account == appDelegate.account,
  338. let withPush = userInfo["withPush"] as? Bool
  339. else { return }
  340. notificationReloadDataSource += 1
  341. if withPush, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  342. if let sceneIdentifier = userInfo["sceneIdentifier"] as? String {
  343. if sceneIdentifier == (self.tabBarController as? NCMainTabBarController)?.sceneIdentifier {
  344. pushMetadata(metadata)
  345. }
  346. } else {
  347. pushMetadata(metadata)
  348. }
  349. }
  350. }
  351. @objc func favoriteFile(_ notification: NSNotification) {
  352. if self is NCFavorite {
  353. return notificationReloadDataSource += 1
  354. }
  355. guard let userInfo = notification.userInfo as NSDictionary?,
  356. let serverUrl = userInfo["serverUrl"] as? String,
  357. serverUrl == self.serverUrl
  358. else { return }
  359. reloadDataSource()
  360. }
  361. @objc func downloadStartFile(_ notification: NSNotification) {
  362. guard let userInfo = notification.userInfo as NSDictionary?,
  363. let serverUrl = userInfo["serverUrl"] as? String,
  364. serverUrl == self.serverUrl || self.serverUrl.isEmpty,
  365. let account = userInfo["account"] as? String,
  366. account == appDelegate.account
  367. else { return }
  368. self.notificationReloadDataSource += 1
  369. }
  370. @objc func downloadedFile(_ notification: NSNotification) {
  371. guard let userInfo = notification.userInfo as NSDictionary?,
  372. let serverUrl = userInfo["serverUrl"] as? String,
  373. serverUrl == self.serverUrl || self.serverUrl.isEmpty,
  374. let account = userInfo["account"] as? String,
  375. account == appDelegate.account,
  376. let error = userInfo["error"] as? NKError
  377. else { return }
  378. if error != .success {
  379. NCContentPresenter().showError(error: error)
  380. }
  381. notificationReloadDataSource += 1
  382. }
  383. @objc func downloadCancelFile(_ notification: NSNotification) {
  384. guard let userInfo = notification.userInfo as NSDictionary?,
  385. let serverUrl = userInfo["serverUrl"] as? String,
  386. serverUrl == self.serverUrl || self.serverUrl.isEmpty,
  387. let account = userInfo["account"] as? String,
  388. account == appDelegate.account
  389. else { return }
  390. reloadDataSource()
  391. }
  392. @objc func uploadStartFile(_ notification: NSNotification) {
  393. guard let userInfo = notification.userInfo as NSDictionary?,
  394. let ocId = userInfo["ocId"] as? String,
  395. let serverUrl = userInfo["serverUrl"] as? String,
  396. let account = userInfo["account"] as? String,
  397. !isSearchingMode,
  398. let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId)
  399. else { return }
  400. // Header view trasfer
  401. if metadata.isTransferInForeground {
  402. NCNetworking.shared.transferInForegorund = NCNetworking.TransferInForegorund(ocId: ocId, progress: 0)
  403. DispatchQueue.main.async { self.collectionView?.reloadData() }
  404. }
  405. if serverUrl == self.serverUrl, account == appDelegate.account {
  406. notificationReloadDataSource += 1
  407. }
  408. }
  409. @objc func uploadedFile(_ notification: NSNotification) {
  410. guard let userInfo = notification.userInfo as NSDictionary?,
  411. let ocIdTemp = userInfo["ocIdTemp"] as? String,
  412. let serverUrl = userInfo["serverUrl"] as? String,
  413. let account = userInfo["account"] as? String
  414. else { return }
  415. if ocIdTemp == NCNetworking.shared.transferInForegorund?.ocId {
  416. NCNetworking.shared.transferInForegorund = nil
  417. DispatchQueue.main.async { self.collectionView?.reloadData() }
  418. }
  419. if account == appDelegate.account, serverUrl == self.serverUrl {
  420. notificationReloadDataSource += 1
  421. }
  422. }
  423. @objc func uploadedLivePhoto(_ notification: NSNotification) {
  424. guard let userInfo = notification.userInfo as NSDictionary?,
  425. let serverUrl = userInfo["serverUrl"] as? String,
  426. serverUrl == self.serverUrl,
  427. let account = userInfo["account"] as? String,
  428. account == appDelegate.account
  429. else { return }
  430. notificationReloadDataSource += 1
  431. }
  432. @objc func uploadCancelFile(_ notification: NSNotification) {
  433. guard let userInfo = notification.userInfo as NSDictionary?,
  434. let ocId = userInfo["ocId"] as? String,
  435. let serverUrl = userInfo["serverUrl"] as? String,
  436. let account = userInfo["account"] as? String
  437. else { return }
  438. if ocId == NCNetworking.shared.transferInForegorund?.ocId {
  439. NCNetworking.shared.transferInForegorund = nil
  440. DispatchQueue.main.async { self.collectionView?.reloadData() }
  441. }
  442. if account == appDelegate.account, serverUrl == self.serverUrl {
  443. reloadDataSource()
  444. }
  445. }
  446. @objc func triggerProgressTask(_ notification: NSNotification) {
  447. guard let userInfo = notification.userInfo as NSDictionary?,
  448. let progressNumber = userInfo["progress"] as? NSNumber,
  449. let totalBytes = userInfo["totalBytes"] as? Int64,
  450. let totalBytesExpected = userInfo["totalBytesExpected"] as? Int64,
  451. let ocId = userInfo["ocId"] as? String
  452. else { return }
  453. let chunk: Int = userInfo["chunk"] as? Int ?? 0
  454. let e2eEncrypted: Bool = userInfo["e2eEncrypted"] as? Bool ?? false
  455. DispatchQueue.main.async {
  456. if self.headerMenuTransferView && (chunk > 0 || e2eEncrypted) {
  457. if NCNetworking.shared.transferInForegorund?.ocId == ocId {
  458. NCNetworking.shared.transferInForegorund?.progress = progressNumber.floatValue
  459. } else {
  460. NCNetworking.shared.transferInForegorund = NCNetworking.TransferInForegorund(ocId: ocId, progress: progressNumber.floatValue)
  461. self.collectionView.reloadData()
  462. }
  463. self.sectionFirstHeader?.progressTransfer.progress = progressNumber.floatValue
  464. self.sectionFirstHeaderEmptyData?.progressTransfer.progress = progressNumber.floatValue
  465. } else {
  466. guard let indexPath = self.dataSource.getIndexPathMetadata(ocId: ocId).indexPath,
  467. let cell = self.collectionView?.cellForItem(at: indexPath),
  468. let cell = cell as? NCCellProtocol else { return }
  469. if progressNumber.floatValue == 1 && !(cell is NCTransferCell) {
  470. cell.fileProgressView?.isHidden = true
  471. cell.fileProgressView?.progress = .zero
  472. cell.setButtonMore(named: NCGlobal.shared.buttonMoreMore, image: NCImageCache.images.buttonMore)
  473. if let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  474. cell.writeInfoDateSize(date: metadata.date, size: metadata.size)
  475. } else {
  476. cell.fileInfoLabel?.text = ""
  477. cell.fileSubinfoLabel?.text = ""
  478. }
  479. } else {
  480. cell.fileProgressView?.isHidden = false
  481. cell.fileProgressView?.progress = progressNumber.floatValue
  482. cell.setButtonMore(named: NCGlobal.shared.buttonMoreStop, image: NCImageCache.images.buttonStop)
  483. let status = userInfo["status"] as? Int ?? NCGlobal.shared.metadataStatusNormal
  484. if status == NCGlobal.shared.metadataStatusDownloading {
  485. cell.fileInfoLabel?.text = self.utilityFileSystem.transformedSize(totalBytesExpected)
  486. cell.fileSubinfoLabel?.text = self.infoLabelsSeparator + "↓ " + self.utilityFileSystem.transformedSize(totalBytes)
  487. } else if status == NCGlobal.shared.metadataStatusUploading {
  488. if totalBytes > 0 {
  489. cell.fileInfoLabel?.text = self.utilityFileSystem.transformedSize(totalBytesExpected)
  490. cell.fileSubinfoLabel?.text = self.infoLabelsSeparator + "↑ " + self.utilityFileSystem.transformedSize(totalBytes)
  491. } else {
  492. cell.fileInfoLabel?.text = self.utilityFileSystem.transformedSize(totalBytesExpected)
  493. cell.fileSubinfoLabel?.text = self.infoLabelsSeparator + "↑ …"
  494. }
  495. }
  496. }
  497. }
  498. }
  499. }
  500. // MARK: - Layout
  501. func setNavigationLeftItems() {
  502. guard layoutKey == NCGlobal.shared.layoutViewFiles else { return }
  503. let activeAccount = NCManageDatabase.shared.getActiveAccount()
  504. let image = utility.loadUserImage(for: appDelegate.user, displayName: activeAccount?.displayName, userBaseUrl: appDelegate)
  505. let accountButton = AccountSwitcherButton(type: .custom)
  506. let accounts = NCManageDatabase.shared.getAllAccountOrderAlias()
  507. var childrenAccountSubmenu: [UIMenuElement] = []
  508. accountButton.setImage(image, for: .normal)
  509. accountButton.setImage(image, for: .highlighted)
  510. accountButton.semanticContentAttribute = .forceLeftToRight
  511. accountButton.sizeToFit()
  512. if !accounts.isEmpty {
  513. let accountActions: [UIAction] = accounts.map { account in
  514. let image = utility.loadUserImage(for: account.user, displayName: account.displayName, userBaseUrl: account)
  515. var name: String = ""
  516. var url: String = ""
  517. if account.alias.isEmpty {
  518. name = account.displayName
  519. url = (URL(string: account.urlBase)?.host ?? "")
  520. } else {
  521. name = account.alias
  522. }
  523. let action = UIAction(title: name, image: image, state: account.active ? .on : .off) { _ in
  524. if !account.active {
  525. self.appDelegate.changeAccount(account.account, userProfile: nil) { }
  526. self.setEditMode(false)
  527. }
  528. }
  529. action.subtitle = url
  530. return action
  531. }
  532. let addAccountAction = UIAction(title: NSLocalizedString("_add_account_", comment: ""), image: utility.loadImage(named: "person.crop.circle.badge.plus", colors: NCBrandColor.shared.iconImageMultiColors)) { _ in
  533. self.appDelegate.openLogin(selector: NCGlobal.shared.introLogin, openLoginWeb: false)
  534. }
  535. let settingsAccountAction = UIAction(title: NSLocalizedString("_account_settings_", comment: ""), image: utility.loadImage(named: "gear", colors: [NCBrandColor.shared.iconImageColor])) { _ in
  536. let accountSettingsModel = NCAccountSettingsModel(controller: self.tabBarController as? NCMainTabBarController, delegate: self)
  537. let accountSettingsView = NCAccountSettingsView(model: accountSettingsModel)
  538. let accountSettingsController = UIHostingController(rootView: accountSettingsView)
  539. self.present(accountSettingsController, animated: true, completion: nil)
  540. }
  541. if !NCBrandOptions.shared.disable_multiaccount {
  542. childrenAccountSubmenu.append(addAccountAction)
  543. }
  544. childrenAccountSubmenu.append(settingsAccountAction)
  545. let addAccountSubmenu = UIMenu(title: "", options: .displayInline, children: childrenAccountSubmenu)
  546. let menu = UIMenu(children: accountActions + [addAccountSubmenu])
  547. accountButton.menu = menu
  548. accountButton.showsMenuAsPrimaryAction = true
  549. accountButton.onMenuOpened = {
  550. self.dismissTip()
  551. }
  552. }
  553. navigationItem.leftItemsSupplementBackButton = true
  554. navigationItem.setLeftBarButtonItems([UIBarButtonItem(customView: accountButton)], animated: true)
  555. if titlePreviusFolder != nil {
  556. navigationController?.navigationBar.topItem?.title = titlePreviusFolder
  557. }
  558. navigationItem.title = titleCurrentFolder
  559. }
  560. func setNavigationRightItems() {
  561. guard layoutKey != NCGlobal.shared.layoutViewTransfers else { return }
  562. let isTabBarHidden = self.tabBarController?.tabBar.isHidden ?? true
  563. let isTabBarSelectHidden = tabBarSelect.isHidden()
  564. func createMenuActions() -> [UIMenuElement] {
  565. guard let layoutForView = NCManageDatabase.shared.getLayoutForView(account: appDelegate.account, key: layoutKey, serverUrl: serverUrl) else { return [] }
  566. let columnPhoto = self.layoutForView?.columnPhoto ?? 3
  567. func saveLayout(_ layoutForView: NCDBLayoutForView) {
  568. NCManageDatabase.shared.setLayoutForView(layoutForView: layoutForView)
  569. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSource)
  570. setNavigationRightItems()
  571. }
  572. if layoutForView.layout != NCGlobal.shared.layoutPhotoSquare && layoutForView.layout != NCGlobal.shared.layoutPhotoRatio {
  573. self.attributesZoomIn = .disabled
  574. self.attributesZoomOut = .disabled
  575. } else if CGFloat(columnPhoto) >= maxImageGrid - 1 {
  576. self.attributesZoomIn = []
  577. self.attributesZoomOut = .disabled
  578. } else if columnPhoto <= 1 {
  579. self.attributesZoomIn = .disabled
  580. self.attributesZoomOut = []
  581. } else {
  582. self.attributesZoomIn = []
  583. self.attributesZoomOut = []
  584. }
  585. let select = UIAction(title: NSLocalizedString("_select_", comment: ""), image: utility.loadImage(named: "checkmark.circle"), attributes: self.dataSource.getMetadataSourceForAllSections().isEmpty ? .disabled : []) { _ in
  586. self.setEditMode(true)
  587. }
  588. let list = UIAction(title: NSLocalizedString("_list_", comment: ""), image: utility.loadImage(named: "list.bullet"), state: layoutForView.layout == NCGlobal.shared.layoutList ? .on : .off) { _ in
  589. layoutForView.layout = NCGlobal.shared.layoutList
  590. self.layoutForView = NCManageDatabase.shared.setLayoutForView(layoutForView: layoutForView)
  591. self.layoutType = NCGlobal.shared.layoutList
  592. self.collectionView.reloadData()
  593. self.collectionView.collectionViewLayout.invalidateLayout()
  594. self.collectionView.setCollectionViewLayout(self.listLayout, animated: true) {_ in self.isTransitioning = false }
  595. self.setNavigationRightItems()
  596. }
  597. let grid = UIAction(title: NSLocalizedString("_icons_", comment: ""), image: utility.loadImage(named: "square.grid.2x2"), state: layoutForView.layout == NCGlobal.shared.layoutGrid ? .on : .off) { _ in
  598. layoutForView.layout = NCGlobal.shared.layoutGrid
  599. self.layoutForView = NCManageDatabase.shared.setLayoutForView(layoutForView: layoutForView)
  600. self.layoutType = NCGlobal.shared.layoutGrid
  601. self.collectionView.reloadData()
  602. self.collectionView.collectionViewLayout.invalidateLayout()
  603. self.collectionView.setCollectionViewLayout(self.gridLayout, animated: true) {_ in self.isTransitioning = false }
  604. self.setNavigationRightItems()
  605. }
  606. let menuPhoto = UIMenu(title: "", options: .displayInline, children: [
  607. UIAction(title: NSLocalizedString("_media_square_", comment: ""), image: utility.loadImage(named: "square.grid.3x3"), state: layoutForView.layout == NCGlobal.shared.layoutPhotoSquare ? .on : .off) { _ in
  608. layoutForView.layout = NCGlobal.shared.layoutPhotoSquare
  609. self.layoutForView = NCManageDatabase.shared.setLayoutForView(layoutForView: layoutForView)
  610. self.layoutType = NCGlobal.shared.layoutPhotoSquare
  611. self.collectionView.reloadData()
  612. self.collectionView.collectionViewLayout.invalidateLayout()
  613. self.collectionView.setCollectionViewLayout(self.mediaLayout, animated: true) {_ in self.isTransitioning = false }
  614. self.reloadDataSource()
  615. self.setNavigationRightItems()
  616. },
  617. UIAction(title: NSLocalizedString("_media_ratio_", comment: ""), image: utility.loadImage(named: "rectangle.grid.3x2"), state: layoutForView.layout == NCGlobal.shared.layoutPhotoRatio ? .on : .off) { _ in
  618. layoutForView.layout = NCGlobal.shared.layoutPhotoRatio
  619. self.layoutForView = NCManageDatabase.shared.setLayoutForView(layoutForView: layoutForView)
  620. self.layoutType = NCGlobal.shared.layoutPhotoRatio
  621. self.collectionView.reloadData()
  622. self.collectionView.collectionViewLayout.invalidateLayout()
  623. self.collectionView.setCollectionViewLayout(self.mediaLayout, animated: true) {_ in self.isTransitioning = false }
  624. self.reloadDataSource()
  625. self.setNavigationRightItems()
  626. }
  627. ])
  628. let menuZoom = UIMenu(title: "", options: .displayInline, children: [
  629. UIAction(title: NSLocalizedString("_zoom_out_", comment: ""), image: utility.loadImage(named: "minus.magnifyingglass"), attributes: self.attributesZoomOut) { _ in
  630. UIView.animate(withDuration: 0.0, animations: {
  631. layoutForView.columnPhoto = columnPhoto + 1
  632. self.layoutForView = NCManageDatabase.shared.setLayoutForView(layoutForView: layoutForView)
  633. self.collectionView.reloadData()
  634. self.setNavigationRightItems()
  635. })
  636. },
  637. UIAction(title: NSLocalizedString("_zoom_in_", comment: ""), image: utility.loadImage(named: "plus.magnifyingglass"), attributes: self.attributesZoomIn) { _ in
  638. UIView.animate(withDuration: 0.0, animations: {
  639. layoutForView.columnPhoto = columnPhoto - 1
  640. self.layoutForView = NCManageDatabase.shared.setLayoutForView(layoutForView: layoutForView)
  641. self.collectionView.reloadData()
  642. self.setNavigationRightItems()
  643. })
  644. }
  645. ])
  646. let viewStyleSubmenu = UIMenu(title: "", options: .displayInline, children: [list, grid, UIMenu(title: NSLocalizedString("_additional_view_options_", comment: ""), children: [menuPhoto, menuZoom])])
  647. let ascending = layoutForView.ascending
  648. let ascendingChevronImage = utility.loadImage(named: ascending ? "chevron.up" : "chevron.down")
  649. let isName = layoutForView.sort == "fileName"
  650. let isDate = layoutForView.sort == "date"
  651. let isSize = layoutForView.sort == "size"
  652. let byName = UIAction(title: NSLocalizedString("_name_", comment: ""), image: isName ? ascendingChevronImage : nil, state: isName ? .on : .off) { _ in
  653. if isName { // repeated press
  654. layoutForView.ascending = !layoutForView.ascending
  655. }
  656. layoutForView.sort = "fileName"
  657. saveLayout(layoutForView)
  658. }
  659. let byNewest = UIAction(title: NSLocalizedString("_date_", comment: ""), image: isDate ? ascendingChevronImage : nil, state: isDate ? .on : .off) { _ in
  660. if isDate { // repeated press
  661. layoutForView.ascending = !layoutForView.ascending
  662. }
  663. layoutForView.sort = "date"
  664. saveLayout(layoutForView)
  665. }
  666. let byLargest = UIAction(title: NSLocalizedString("_size_", comment: ""), image: isSize ? ascendingChevronImage : nil, state: isSize ? .on : .off) { _ in
  667. if isSize { // repeated press
  668. layoutForView.ascending = !layoutForView.ascending
  669. }
  670. layoutForView.sort = "size"
  671. saveLayout(layoutForView)
  672. }
  673. let sortSubmenu = UIMenu(title: NSLocalizedString("_order_by_", comment: ""), options: .displayInline, children: [byName, byNewest, byLargest])
  674. let foldersOnTop = UIAction(title: NSLocalizedString("_directory_on_top_no_", comment: ""), image: utility.loadImage(named: "folder"), state: layoutForView.directoryOnTop ? .on : .off) { _ in
  675. layoutForView.directoryOnTop = !layoutForView.directoryOnTop
  676. saveLayout(layoutForView)
  677. }
  678. let personalFilesOnly = NCKeychain().getPersonalFilesOnly(account: appDelegate.account)
  679. let personalFilesOnlyAction = UIAction(title: NSLocalizedString("_personal_files_only_", comment: ""), image: utility.loadImage(named: "folder.badge.person.crop", colors: NCBrandColor.shared.iconImageMultiColors), state: personalFilesOnly ? .on : .off) { _ in
  680. NCKeychain().setPersonalFilesOnly(account: self.appDelegate.account, value: !personalFilesOnly)
  681. self.reloadDataSource()
  682. }
  683. let showDescriptionKeychain = NCKeychain().showDescription
  684. let showDescription = UIAction(title: NSLocalizedString("_show_description_", comment: ""), image: utility.loadImage(named: "list.dash.header.rectangle"), attributes: richWorkspaceText == nil ? .disabled : [], state: showDescriptionKeychain && richWorkspaceText != nil ? .on : .off) { _ in
  685. NCKeychain().showDescription = !showDescriptionKeychain
  686. self.collectionView.reloadData()
  687. self.setNavigationRightItems()
  688. }
  689. showDescription.subtitle = richWorkspaceText == nil ? NSLocalizedString("_no_description_available_", comment: "") : ""
  690. if layoutKey == NCGlobal.shared.layoutViewRecent {
  691. return [select]
  692. } else {
  693. var additionalSubmenu = UIMenu()
  694. if layoutKey == NCGlobal.shared.layoutViewFiles {
  695. additionalSubmenu = UIMenu(title: "", options: .displayInline, children: [foldersOnTop, personalFilesOnlyAction, showDescription])
  696. } else {
  697. additionalSubmenu = UIMenu(title: "", options: .displayInline, children: [foldersOnTop, showDescription])
  698. }
  699. return [select, viewStyleSubmenu, sortSubmenu, additionalSubmenu]
  700. }
  701. }
  702. if isEditMode {
  703. tabBarSelect.update(selectOcId: selectOcId, metadatas: getSelectedMetadatas(), userId: appDelegate.userId)
  704. tabBarSelect.show()
  705. let select = UIBarButtonItem(title: NSLocalizedString("_cancel_", comment: ""), style: .done) {
  706. self.setEditMode(false)
  707. }
  708. navigationItem.rightBarButtonItems = [select]
  709. } else if navigationItem.rightBarButtonItems == nil || (!isEditMode && !tabBarSelect.isHidden()) {
  710. tabBarSelect.hide()
  711. let menuButton = UIBarButtonItem(image: utility.loadImage(named: "ellipsis.circle"), menu: UIMenu(children: createMenuActions()))
  712. menuButton.tintColor = NCBrandColor.shared.iconImageColor
  713. if layoutKey == NCGlobal.shared.layoutViewFiles {
  714. let notification = UIBarButtonItem(image: utility.loadImage(named: "bell"), style: .plain) {
  715. if let viewController = UIStoryboard(name: "NCNotification", bundle: nil).instantiateInitialViewController() as? NCNotification {
  716. self.navigationController?.pushViewController(viewController, animated: true)
  717. }
  718. }
  719. notification.tintColor = NCBrandColor.shared.iconImageColor
  720. navigationItem.rightBarButtonItems = [menuButton, notification]
  721. } else {
  722. navigationItem.rightBarButtonItems = [menuButton]
  723. }
  724. } else {
  725. navigationItem.rightBarButtonItems?.first?.menu = navigationItem.rightBarButtonItems?.first?.menu?.replacingChildren(createMenuActions())
  726. }
  727. // fix, if the tabbar was hidden before the update, set it in hidden
  728. if isTabBarHidden, isTabBarSelectHidden {
  729. self.tabBarController?.tabBar.isHidden = true
  730. }
  731. }
  732. func getNavigationTitle() -> String {
  733. let activeAccount = NCManageDatabase.shared.getActiveAccount()
  734. guard let userAlias = activeAccount?.alias, !userAlias.isEmpty else {
  735. return NCBrandOptions.shared.brand
  736. }
  737. return userAlias
  738. }
  739. func accountSettingsDidDismiss(tableAccount: tableAccount?) { }
  740. // MARK: - SEARCH
  741. func searchController(enabled: Bool) {
  742. guard enableSearchBar else { return }
  743. searchController?.searchBar.isUserInteractionEnabled = enabled
  744. if enabled {
  745. searchController?.searchBar.alpha = 1
  746. } else {
  747. searchController?.searchBar.alpha = 0.3
  748. }
  749. }
  750. func updateSearchResults(for searchController: UISearchController) {
  751. self.literalSearch = searchController.searchBar.text
  752. }
  753. func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
  754. isSearchingMode = true
  755. self.providers?.removeAll()
  756. self.dataSource.clearDataSource()
  757. self.collectionView.reloadData()
  758. // TIP
  759. dismissTip()
  760. }
  761. func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
  762. if isSearchingMode && self.literalSearch?.count ?? 0 >= 2 {
  763. reloadDataSourceNetwork()
  764. }
  765. }
  766. func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
  767. DispatchQueue.global().async {
  768. NCNetworking.shared.cancelUnifiedSearchFiles()
  769. self.isSearchingMode = false
  770. self.literalSearch = ""
  771. self.providers?.removeAll()
  772. self.dataSource.clearDataSource()
  773. self.reloadDataSource()
  774. }
  775. }
  776. // MARK: - TAP EVENT
  777. // sessionIdentifierDownload: String = "com.nextcloud.nextcloudkit.session.download"
  778. // sessionIdentifierUpload: String = "com.nextcloud.nextcloudkit.session.upload"
  779. // sessionUploadBackground: String = "com.nextcloud.session.upload.background"
  780. // sessionUploadBackgroundWWan: String = "com.nextcloud.session.upload.backgroundWWan"
  781. // sessionUploadBackgroundExtension: String = "com.nextcloud.session.upload.extension"
  782. func cancelSession(metadata: tableMetadata) async {
  783. let fileNameLocalPath = utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)
  784. utilityFileSystem.removeFile(atPath: utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId))
  785. // No session found
  786. if metadata.session.isEmpty {
  787. NCNetworking.shared.uploadRequest.removeValue(forKey: fileNameLocalPath)
  788. NCNetworking.shared.downloadRequest.removeValue(forKey: fileNameLocalPath)
  789. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  790. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSource)
  791. return
  792. }
  793. // DOWNLOAD FOREGROUND
  794. if metadata.session == NextcloudKit.shared.nkCommonInstance.sessionIdentifierDownload {
  795. if let request = NCNetworking.shared.downloadRequest[fileNameLocalPath] {
  796. request.cancel()
  797. } else if let metadata = NCManageDatabase.shared.getMetadataFromOcId(metadata.ocId) {
  798. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId,
  799. session: "",
  800. sessionError: "",
  801. selector: "",
  802. status: NCGlobal.shared.metadataStatusNormal)
  803. NotificationCenter.default.post(name: Notification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadCancelFile),
  804. object: nil,
  805. userInfo: ["ocId": metadata.ocId,
  806. "serverUrl": metadata.serverUrl,
  807. "account": metadata.account])
  808. }
  809. return
  810. }
  811. // DOWNLOAD BACKGROUND
  812. if metadata.session == NCNetworking.shared.sessionDownloadBackground {
  813. let session: URLSession? = NCNetworking.shared.sessionManagerDownloadBackground
  814. if let tasks = await session?.tasks {
  815. for task in tasks.2 { // ([URLSessionDataTask], [URLSessionUploadTask], [URLSessionDownloadTask])
  816. if task.taskIdentifier == metadata.sessionTaskIdentifier {
  817. task.cancel()
  818. }
  819. }
  820. }
  821. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId,
  822. session: "",
  823. sessionError: "",
  824. selector: "",
  825. status: NCGlobal.shared.metadataStatusNormal)
  826. NotificationCenter.default.post(name: Notification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadCancelFile),
  827. object: nil,
  828. userInfo: ["ocId": metadata.ocId,
  829. "serverUrl": metadata.serverUrl,
  830. "account": metadata.account])
  831. }
  832. // UPLOAD FOREGROUND
  833. if metadata.session == NextcloudKit.shared.nkCommonInstance.sessionIdentifierUpload {
  834. if let request = NCNetworking.shared.uploadRequest[fileNameLocalPath] {
  835. request.cancel()
  836. NCNetworking.shared.uploadRequest.removeValue(forKey: fileNameLocalPath)
  837. }
  838. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  839. NotificationCenter.default.post(name: Notification.Name(rawValue: NCGlobal.shared.notificationCenterUploadCancelFile),
  840. object: nil,
  841. userInfo: ["ocId": metadata.ocId,
  842. "serverUrl": metadata.serverUrl,
  843. "account": metadata.account])
  844. return
  845. }
  846. // UPLOAD BACKGROUND
  847. var session: URLSession?
  848. if metadata.session == NCNetworking.shared.sessionUploadBackground {
  849. session = NCNetworking.shared.sessionManagerUploadBackground
  850. } else if metadata.session == NCNetworking.shared.sessionUploadBackgroundWWan {
  851. session = NCNetworking.shared.sessionManagerUploadBackgroundWWan
  852. } else if metadata.session == NCNetworking.shared.sessionUploadBackgroundExtension {
  853. session = NCNetworking.shared.sessionManagerUploadBackgroundExtension
  854. }
  855. if let tasks = await session?.tasks {
  856. for task in tasks.1 { // ([URLSessionDataTask], [URLSessionUploadTask], [URLSessionDownloadTask])
  857. if task.taskIdentifier == metadata.sessionTaskIdentifier {
  858. task.cancel()
  859. }
  860. }
  861. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  862. NotificationCenter.default.post(name: Notification.Name(rawValue: NCGlobal.shared.notificationCenterUploadCancelFile),
  863. object: nil,
  864. userInfo: ["ocId": metadata.ocId,
  865. "serverUrl": metadata.serverUrl,
  866. "account": metadata.account])
  867. }
  868. }
  869. func tapMoreListItem(with objectId: String, namedButtonMore: String, image: UIImage?, indexPath: IndexPath, sender: Any) {
  870. tapMoreGridItem(with: objectId, namedButtonMore: namedButtonMore, image: image, indexPath: indexPath, sender: sender)
  871. }
  872. func tapShareListItem(with objectId: String, indexPath: IndexPath, sender: Any) {
  873. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(objectId) else { return }
  874. NCActionCenter.shared.openShare(viewController: self, metadata: metadata, page: .sharing)
  875. }
  876. func tapMoreGridItem(with objectId: String, namedButtonMore: String, image: UIImage?, indexPath: IndexPath, sender: Any) {
  877. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(objectId) else { return }
  878. if namedButtonMore == NCGlobal.shared.buttonMoreMore || namedButtonMore == NCGlobal.shared.buttonMoreLock {
  879. toggleMenu(metadata: metadata, indexPath: indexPath, imageIcon: image)
  880. } else if namedButtonMore == NCGlobal.shared.buttonMoreStop {
  881. Task {
  882. await cancelSession(metadata: metadata)
  883. }
  884. }
  885. }
  886. func tapRichWorkspace(_ sender: Any) {
  887. if let navigationController = UIStoryboard(name: "NCViewerRichWorkspace", bundle: nil).instantiateInitialViewController() as? UINavigationController {
  888. if let viewerRichWorkspace = navigationController.topViewController as? NCViewerRichWorkspace {
  889. viewerRichWorkspace.richWorkspaceText = richWorkspaceText ?? ""
  890. viewerRichWorkspace.serverUrl = serverUrl
  891. viewerRichWorkspace.delegate = self
  892. navigationController.modalPresentationStyle = .fullScreen
  893. self.present(navigationController, animated: true, completion: nil)
  894. }
  895. }
  896. }
  897. func tapButtonSection(_ sender: Any, metadataForSection: NCMetadataForSection?) {
  898. unifiedSearchMore(metadataForSection: metadataForSection)
  899. }
  900. func tapButtonTransfer(_ sender: Any) {
  901. if let ocId = NCNetworking.shared.transferInForegorund?.ocId,
  902. let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  903. Task {
  904. await cancelSession(metadata: metadata)
  905. }
  906. }
  907. }
  908. func longPressListItem(with objectId: String, indexPath: IndexPath, gestureRecognizer: UILongPressGestureRecognizer) {
  909. }
  910. func longPressGridItem(with objectId: String, indexPath: IndexPath, gestureRecognizer: UILongPressGestureRecognizer) {
  911. }
  912. func longPressMoreListItem(with objectId: String, namedButtonMore: String, indexPath: IndexPath, gestureRecognizer: UILongPressGestureRecognizer) {
  913. }
  914. func longPressMoreGridItem(with objectId: String, namedButtonMore: String, indexPath: IndexPath, gestureRecognizer: UILongPressGestureRecognizer) {
  915. }
  916. @objc func longPressCollecationView(_ gestureRecognizer: UILongPressGestureRecognizer) {
  917. openMenuItems(with: nil, gestureRecognizer: gestureRecognizer)
  918. }
  919. func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
  920. return UIContextMenuConfiguration(identifier: nil, previewProvider: {
  921. return nil
  922. }, actionProvider: { _ in
  923. return nil
  924. })
  925. }
  926. func openMenuItems(with objectId: String?, gestureRecognizer: UILongPressGestureRecognizer) {
  927. if gestureRecognizer.state != .began { return }
  928. var listMenuItems: [UIMenuItem] = []
  929. let touchPoint = gestureRecognizer.location(in: collectionView)
  930. becomeFirstResponder()
  931. if !serverUrl.isEmpty {
  932. listMenuItems.append(UIMenuItem(title: NSLocalizedString("_paste_file_", comment: ""), action: #selector(pasteFilesMenu)))
  933. }
  934. if !listMenuItems.isEmpty {
  935. UIMenuController.shared.menuItems = listMenuItems
  936. UIMenuController.shared.showMenu(from: collectionView, rect: CGRect(x: touchPoint.x, y: touchPoint.y, width: 0, height: 0))
  937. }
  938. }
  939. // MARK: - Menu Item
  940. override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
  941. if #selector(pasteFilesMenu) == action {
  942. if !UIPasteboard.general.items.isEmpty, !(metadataFolder?.e2eEncrypted ?? false) {
  943. return true
  944. }
  945. } else if #selector(copyMenuFile) == action {
  946. return true
  947. } else if #selector(moveMenuFile) == action {
  948. return true
  949. }
  950. return false
  951. }
  952. @objc func pasteFilesMenu() {
  953. NCActionCenter.shared.pastePasteboard(serverUrl: serverUrl, account: appDelegate.account, hudView: tabBarController?.view)
  954. }
  955. // MARK: - DataSource + NC Endpoint
  956. func queryDB() { }
  957. @objc func reloadDataSource(withQueryDB: Bool = true) {
  958. guard !appDelegate.account.isEmpty, !self.isSearchingMode else { return }
  959. // get auto upload folder
  960. autoUploadFileName = NCManageDatabase.shared.getAccountAutoUploadFileName()
  961. autoUploadDirectory = NCManageDatabase.shared.getAccountAutoUploadDirectory(urlBase: appDelegate.urlBase, userId: appDelegate.userId, account: appDelegate.account)
  962. // get layout for view
  963. layoutForView = NCManageDatabase.shared.getLayoutForView(account: appDelegate.account, key: layoutKey, serverUrl: serverUrl)
  964. DispatchQueue.global(qos: .userInteractive).async {
  965. if withQueryDB { self.queryDB() }
  966. DispatchQueue.main.async {
  967. self.refreshControl.endRefreshing()
  968. self.collectionView.reloadData()
  969. self.setNavigationRightItems()
  970. }
  971. }
  972. }
  973. @objc func reloadDataSourceNetwork(withQueryDB: Bool = false) {
  974. DispatchQueue.main.async {
  975. self.collectionView?.reloadData()
  976. }
  977. }
  978. @objc func networkSearch() {
  979. guard !appDelegate.account.isEmpty, let literalSearch = literalSearch, !literalSearch.isEmpty
  980. else { return self.refreshControl.endRefreshing() }
  981. self.dataSource.clearDataSource()
  982. self.refreshControl.beginRefreshing()
  983. self.collectionView.reloadData()
  984. if NCGlobal.shared.capabilityServerVersionMajor >= NCGlobal.shared.nextcloudVersion20 {
  985. NCNetworking.shared.unifiedSearchFiles(userBaseUrl: appDelegate, literal: literalSearch) { task in
  986. self.dataSourceTask = task
  987. self.collectionView.reloadData()
  988. } providers: { _, searchProviders in
  989. self.providers = searchProviders
  990. self.searchResults = []
  991. self.dataSource = NCDataSource(metadatas: [], account: self.appDelegate.account, layoutForView: self.layoutForView, providers: self.providers, searchResults: self.searchResults)
  992. } update: { _, _, searchResult, metadatas in
  993. guard let metadatas, !metadatas.isEmpty, self.isSearchingMode, let searchResult else { return }
  994. NCNetworking.shared.unifiedSearchQueue.addOperation(NCCollectionViewUnifiedSearch(collectionViewCommon: self, metadatas: metadatas, searchResult: searchResult))
  995. } completion: { _, _ in
  996. self.refreshControl.endRefreshing()
  997. self.collectionView.reloadData()
  998. }
  999. } else {
  1000. NCNetworking.shared.searchFiles(urlBase: appDelegate, literal: literalSearch, account: appDelegate.account) { task in
  1001. self.dataSourceTask = task
  1002. self.collectionView.reloadData()
  1003. } completion: { metadatas, error in
  1004. DispatchQueue.main.async {
  1005. self.refreshControl.endRefreshing()
  1006. self.collectionView.reloadData()
  1007. }
  1008. guard let metadatas = metadatas, error == .success, self.isSearchingMode else { return }
  1009. self.dataSource = NCDataSource(metadatas: metadatas, account: self.appDelegate.account, layoutForView: self.layoutForView, providers: self.providers, searchResults: self.searchResults)
  1010. }
  1011. }
  1012. }
  1013. func unifiedSearchMore(metadataForSection: NCMetadataForSection?) {
  1014. guard let metadataForSection = metadataForSection, let lastSearchResult = metadataForSection.lastSearchResult, let cursor = lastSearchResult.cursor, let term = literalSearch else { return }
  1015. metadataForSection.unifiedSearchInProgress = true
  1016. self.collectionView?.reloadData()
  1017. NCNetworking.shared.unifiedSearchFilesProvider(userBaseUrl: appDelegate, id: lastSearchResult.id, term: term, limit: 5, cursor: cursor) { task in
  1018. self.dataSourceTask = task
  1019. self.collectionView.reloadData()
  1020. } completion: { _, searchResult, metadatas, error in
  1021. if error != .success {
  1022. NCContentPresenter().showError(error: error)
  1023. }
  1024. metadataForSection.unifiedSearchInProgress = false
  1025. guard let searchResult = searchResult, let metadatas = metadatas else { return }
  1026. self.dataSource.appendMetadatasToSection(metadatas, metadataForSection: metadataForSection, lastSearchResult: searchResult)
  1027. DispatchQueue.main.async {
  1028. self.collectionView?.reloadData()
  1029. }
  1030. }
  1031. }
  1032. // MARK: - Push metadata
  1033. func pushMetadata(_ metadata: tableMetadata) {
  1034. guard let navigationCollectionViewCommon = (tabBarController as? NCMainTabBarController)?.navigationCollectionViewCommon else { return }
  1035. let serverUrlPush = utilityFileSystem.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)
  1036. if let viewController = navigationCollectionViewCommon.first(where: { $0.navigationController == self.navigationController && $0.serverUrl == serverUrlPush})?.viewController, viewController.isViewLoaded {
  1037. navigationController?.pushViewController(viewController, animated: true)
  1038. } else {
  1039. if let viewController: NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as? NCFiles {
  1040. viewController.isRoot = false
  1041. viewController.serverUrl = serverUrlPush
  1042. viewController.titlePreviusFolder = navigationItem.title
  1043. viewController.titleCurrentFolder = metadata.fileNameView
  1044. navigationCollectionViewCommon.append(NavigationCollectionViewCommon(serverUrl: serverUrlPush, navigationController: self.navigationController, viewController: viewController))
  1045. navigationController?.pushViewController(viewController, animated: true)
  1046. }
  1047. }
  1048. }
  1049. // MARK: - Header size
  1050. func isHeaderMenuTransferViewEnabled() -> Bool {
  1051. if headerMenuTransferView {
  1052. return NCManageDatabase.shared.getResultMetadataFromOcId(NCNetworking.shared.transferInForegorund?.ocId)?.isTransferInForeground ?? false
  1053. }
  1054. return false
  1055. }
  1056. func getHeaderHeight(section: Int) -> (heightHeaderCommands: CGFloat, heightHeaderRichWorkspace: CGFloat, heightHeaderSection: CGFloat) {
  1057. var headerRichWorkspace: CGFloat = 0
  1058. func getHeaderHeight() -> CGFloat {
  1059. var size: CGFloat = 0
  1060. if isHeaderMenuTransferViewEnabled() {
  1061. if !isSearchingMode {
  1062. size += NCGlobal.shared.heightHeaderTransfer
  1063. }
  1064. } else {
  1065. NCNetworking.shared.transferInForegorund = nil
  1066. }
  1067. return size
  1068. }
  1069. if let richWorkspaceText = richWorkspaceText, showDescription {
  1070. let trimmed = richWorkspaceText.trimmingCharacters(in: .whitespaces)
  1071. if !trimmed.isEmpty && !isSearchingMode {
  1072. headerRichWorkspace = UIScreen.main.bounds.size.height / 6
  1073. }
  1074. }
  1075. if isSearchingMode || layoutForView?.groupBy != "none" || dataSource.numberOfSections() > 1 {
  1076. if section == 0 {
  1077. return (getHeaderHeight(), headerRichWorkspace, NCGlobal.shared.heightSection)
  1078. } else {
  1079. return (0, 0, NCGlobal.shared.heightSection)
  1080. }
  1081. } else {
  1082. return (getHeaderHeight(), headerRichWorkspace, 0)
  1083. }
  1084. }
  1085. func sizeForHeaderInSection(section: Int) -> CGSize {
  1086. var height: CGFloat = 0
  1087. if isEditMode {
  1088. return CGSize.zero
  1089. } else if dataSource.getMetadataSourceForAllSections().isEmpty {
  1090. height = NCGlobal.shared.getHeightHeaderEmptyData(view: view, portraitOffset: emptyDataPortaitOffset, landscapeOffset: emptyDataLandscapeOffset, isHeaderMenuTransferViewEnabled: isHeaderMenuTransferViewEnabled())
  1091. } else {
  1092. let (heightHeaderCommands, heightHeaderRichWorkspace, heightHeaderSection) = getHeaderHeight(section: section)
  1093. height = heightHeaderCommands + heightHeaderRichWorkspace + heightHeaderSection
  1094. }
  1095. return CGSize(width: collectionView.frame.width, height: height)
  1096. }
  1097. // MARK: - Footer size
  1098. func sizeForFooterInSection(section: Int) -> CGSize {
  1099. let sections = dataSource.numberOfSections()
  1100. let metadataForSection = self.dataSource.getMetadataForSection(section)
  1101. let isPaginated = metadataForSection?.lastSearchResult?.isPaginated ?? false
  1102. let metadatasCount: Int = metadataForSection?.lastSearchResult?.entries.count ?? 0
  1103. var size = CGSize(width: collectionView.frame.width, height: 0)
  1104. if section == sections - 1 {
  1105. size.height += NCGlobal.shared.endHeightFooter
  1106. } else {
  1107. size.height += NCGlobal.shared.heightFooter
  1108. }
  1109. if isSearchingMode && isPaginated && metadatasCount > 0 {
  1110. size.height += NCGlobal.shared.heightFooterButton
  1111. }
  1112. return size
  1113. }
  1114. }
  1115. // MARK: -
  1116. private class AccountSwitcherButton: UIButton {
  1117. var onMenuOpened: (() -> Void)?
  1118. override func contextMenuInteraction(_ interaction: UIContextMenuInteraction, willDisplayMenuFor configuration: UIContextMenuConfiguration, animator: UIContextMenuInteractionAnimating?) {
  1119. super.contextMenuInteraction(interaction, willDisplayMenuFor: configuration, animator: animator)
  1120. onMenuOpened?()
  1121. }
  1122. }