NCCollectionViewCommon.swift 66 KB

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