NCCollectionViewCommon.swift 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328
  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. accountButton.setImage(image, for: .normal)
  501. accountButton.setImage(image, for: .highlighted)
  502. accountButton.semanticContentAttribute = .forceLeftToRight
  503. accountButton.sizeToFit()
  504. if !accounts.isEmpty, !NCBrandOptions.shared.disable_multiaccount {
  505. let accountActions: [UIAction] = accounts.map { account in
  506. let image = utility.loadUserImage(for: account.user, displayName: account.displayName, userBaseUrl: account)
  507. var name: String = ""
  508. var url: String = ""
  509. if account.alias.isEmpty {
  510. name = account.displayName
  511. url = (URL(string: account.urlBase)?.host ?? "")
  512. } else {
  513. name = account.alias
  514. }
  515. let action = UIAction(title: name, image: image, state: account.active ? .on : .off) { _ in
  516. if !account.active {
  517. self.appDelegate.changeAccount(account.account, userProfile: nil) { }
  518. self.setEditMode(false)
  519. }
  520. }
  521. action.subtitle = url
  522. return action
  523. }
  524. let addAccountAction = UIAction(title: NSLocalizedString("_add_account_", comment: ""), image: utility.loadImage(named: "person.crop.circle.badge.plus", colors: NCBrandColor.shared.iconImageMultiColors)) { _ in
  525. self.appDelegate.openLogin(selector: NCGlobal.shared.introLogin, openLoginWeb: false)
  526. }
  527. let settingsAccountAction = UIAction(title: NSLocalizedString("_account_settings_", comment: ""), image: utility.loadImage(named: "gear", colors: [NCBrandColor.shared.iconImageColor])) { _ in
  528. let accountSettingsModel = NCAccountSettingsModel(controller: self.tabBarController as? NCMainTabBarController, delegate: self)
  529. let accountSettingsView = NCAccountSettingsView(model: accountSettingsModel)
  530. let accountSettingsController = UIHostingController(rootView: accountSettingsView)
  531. self.present(accountSettingsController, animated: true, completion: nil)
  532. }
  533. let addAccountSubmenu = UIMenu(title: "", options: .displayInline, children: [addAccountAction, settingsAccountAction])
  534. let menu = UIMenu(children: accountActions + [addAccountSubmenu])
  535. accountButton.menu = menu
  536. accountButton.showsMenuAsPrimaryAction = true
  537. accountButton.onMenuOpened = {
  538. self.dismissTip()
  539. }
  540. }
  541. navigationItem.leftItemsSupplementBackButton = true
  542. navigationItem.setLeftBarButtonItems([UIBarButtonItem(customView: accountButton)], animated: true)
  543. if titlePreviusFolder != nil {
  544. navigationController?.navigationBar.topItem?.title = titlePreviusFolder
  545. }
  546. navigationItem.title = titleCurrentFolder
  547. }
  548. func setNavigationRightItems() {
  549. guard layoutKey != NCGlobal.shared.layoutViewTransfers else { return }
  550. let isTabBarHidden = self.tabBarController?.tabBar.isHidden ?? true
  551. let isTabBarSelectHidden = tabBarSelect.isHidden()
  552. func createMenuActions() -> [UIMenuElement] {
  553. guard let layoutForView = NCManageDatabase.shared.getLayoutForView(account: appDelegate.account, key: layoutKey, serverUrl: serverUrl) else { return [] }
  554. let columnPhoto = self.layoutForView?.columnPhoto ?? 3
  555. func saveLayout(_ layoutForView: NCDBLayoutForView) {
  556. NCManageDatabase.shared.setLayoutForView(layoutForView: layoutForView)
  557. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSource)
  558. setNavigationRightItems()
  559. }
  560. if layoutForView.layout != NCGlobal.shared.layoutPhotoSquare && layoutForView.layout != NCGlobal.shared.layoutPhotoRatio {
  561. self.attributesZoomIn = .disabled
  562. self.attributesZoomOut = .disabled
  563. } else if CGFloat(columnPhoto) >= maxImageGrid - 1 {
  564. self.attributesZoomIn = []
  565. self.attributesZoomOut = .disabled
  566. } else if columnPhoto <= 1 {
  567. self.attributesZoomIn = .disabled
  568. self.attributesZoomOut = []
  569. } else {
  570. self.attributesZoomIn = []
  571. self.attributesZoomOut = []
  572. }
  573. let select = UIAction(title: NSLocalizedString("_select_", comment: ""), image: utility.loadImage(named: "checkmark.circle"), attributes: self.dataSource.getMetadataSourceForAllSections().isEmpty ? .disabled : []) { _ in
  574. self.setEditMode(true)
  575. }
  576. let list = UIAction(title: NSLocalizedString("_list_", comment: ""), image: utility.loadImage(named: "list.bullet"), state: layoutForView.layout == NCGlobal.shared.layoutList ? .on : .off) { _ in
  577. layoutForView.layout = NCGlobal.shared.layoutList
  578. self.layoutForView = NCManageDatabase.shared.setLayoutForView(layoutForView: layoutForView)
  579. self.collectionView.reloadData()
  580. self.collectionView.collectionViewLayout.invalidateLayout()
  581. self.collectionView.setCollectionViewLayout(self.listLayout, animated: true) {_ in self.isTransitioning = false }
  582. self.setNavigationRightItems()
  583. }
  584. let grid = UIAction(title: NSLocalizedString("_icons_", comment: ""), image: utility.loadImage(named: "square.grid.2x2"), state: layoutForView.layout == NCGlobal.shared.layoutGrid ? .on : .off) { _ in
  585. layoutForView.layout = NCGlobal.shared.layoutGrid
  586. self.layoutForView = NCManageDatabase.shared.setLayoutForView(layoutForView: layoutForView)
  587. self.collectionView.reloadData()
  588. self.collectionView.collectionViewLayout.invalidateLayout()
  589. self.collectionView.setCollectionViewLayout(self.gridLayout, animated: true) {_ in self.isTransitioning = false }
  590. self.setNavigationRightItems()
  591. }
  592. let menuPhoto = UIMenu(title: "", options: .displayInline, children: [
  593. UIAction(title: NSLocalizedString("_media_square_", comment: ""), image: utility.loadImage(named: "square.grid.3x3"), state: layoutForView.layout == NCGlobal.shared.layoutPhotoSquare ? .on : .off) { _ in
  594. layoutForView.layout = NCGlobal.shared.layoutPhotoSquare
  595. self.layoutForView = NCManageDatabase.shared.setLayoutForView(layoutForView: layoutForView)
  596. self.collectionView.reloadData()
  597. self.collectionView.collectionViewLayout.invalidateLayout()
  598. self.collectionView.setCollectionViewLayout(self.mediaLayout, animated: true) {_ in self.isTransitioning = false }
  599. self.reloadDataSource()
  600. self.setNavigationRightItems()
  601. },
  602. UIAction(title: NSLocalizedString("_media_ratio_", comment: ""), image: utility.loadImage(named: "rectangle.grid.3x2"), state: layoutForView.layout == NCGlobal.shared.layoutPhotoRatio ? .on : .off) { _ in
  603. layoutForView.layout = NCGlobal.shared.layoutPhotoRatio
  604. self.layoutForView = NCManageDatabase.shared.setLayoutForView(layoutForView: layoutForView)
  605. self.collectionView.reloadData()
  606. self.collectionView.collectionViewLayout.invalidateLayout()
  607. self.collectionView.setCollectionViewLayout(self.mediaLayout, animated: true) {_ in self.isTransitioning = false }
  608. self.reloadDataSource()
  609. self.setNavigationRightItems()
  610. }
  611. ])
  612. let menuZoom = UIMenu(title: "", options: .displayInline, children: [
  613. UIAction(title: NSLocalizedString("_zoom_out_", comment: ""), image: utility.loadImage(named: "minus.magnifyingglass"), attributes: self.attributesZoomOut) { _ in
  614. UIView.animate(withDuration: 0.0, animations: {
  615. layoutForView.columnPhoto = columnPhoto + 1
  616. self.layoutForView = NCManageDatabase.shared.setLayoutForView(layoutForView: layoutForView)
  617. self.collectionView.reloadData()
  618. self.setNavigationRightItems()
  619. })
  620. },
  621. UIAction(title: NSLocalizedString("_zoom_in_", comment: ""), image: utility.loadImage(named: "plus.magnifyingglass"), attributes: self.attributesZoomIn) { _ in
  622. UIView.animate(withDuration: 0.0, animations: {
  623. layoutForView.columnPhoto = columnPhoto - 1
  624. self.layoutForView = NCManageDatabase.shared.setLayoutForView(layoutForView: layoutForView)
  625. self.collectionView.reloadData()
  626. self.setNavigationRightItems()
  627. })
  628. }
  629. ])
  630. let viewStyleSubmenu = UIMenu(title: "", options: .displayInline, children: [list, grid, UIMenu(title: NSLocalizedString("_photo_", comment: ""), children: [menuPhoto, menuZoom])])
  631. let ascending = layoutForView.ascending
  632. let ascendingChevronImage = utility.loadImage(named: ascending ? "chevron.up" : "chevron.down")
  633. let isName = layoutForView.sort == "fileName"
  634. let isDate = layoutForView.sort == "date"
  635. let isSize = layoutForView.sort == "size"
  636. let byName = UIAction(title: NSLocalizedString("_name_", comment: ""), image: isName ? ascendingChevronImage : nil, state: isName ? .on : .off) { _ in
  637. if isName { // repeated press
  638. layoutForView.ascending = !layoutForView.ascending
  639. }
  640. layoutForView.sort = "fileName"
  641. saveLayout(layoutForView)
  642. }
  643. let byNewest = UIAction(title: NSLocalizedString("_date_", comment: ""), image: isDate ? ascendingChevronImage : nil, state: isDate ? .on : .off) { _ in
  644. if isDate { // repeated press
  645. layoutForView.ascending = !layoutForView.ascending
  646. }
  647. layoutForView.sort = "date"
  648. saveLayout(layoutForView)
  649. }
  650. let byLargest = UIAction(title: NSLocalizedString("_size_", comment: ""), image: isSize ? ascendingChevronImage : nil, state: isSize ? .on : .off) { _ in
  651. if isSize { // repeated press
  652. layoutForView.ascending = !layoutForView.ascending
  653. }
  654. layoutForView.sort = "size"
  655. saveLayout(layoutForView)
  656. }
  657. let sortSubmenu = UIMenu(title: NSLocalizedString("_order_by_", comment: ""), options: .displayInline, children: [byName, byNewest, byLargest])
  658. let foldersOnTop = UIAction(title: NSLocalizedString("_directory_on_top_no_", comment: ""), image: utility.loadImage(named: "folder"), state: layoutForView.directoryOnTop ? .on : .off) { _ in
  659. layoutForView.directoryOnTop = !layoutForView.directoryOnTop
  660. saveLayout(layoutForView)
  661. }
  662. let personalFilesOnly = NCKeychain().getPersonalFilesOnly(account: appDelegate.account)
  663. 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
  664. NCKeychain().setPersonalFilesOnly(account: self.appDelegate.account, value: !personalFilesOnly)
  665. self.reloadDataSource()
  666. }
  667. let showDescriptionKeychain = NCKeychain().showDescription
  668. 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
  669. NCKeychain().showDescription = !showDescriptionKeychain
  670. self.collectionView.reloadData()
  671. self.setNavigationRightItems()
  672. }
  673. showDescription.subtitle = richWorkspaceText == nil ? NSLocalizedString("_no_description_available_", comment: "") : ""
  674. if layoutKey == NCGlobal.shared.layoutViewRecent {
  675. return [select]
  676. } else {
  677. var additionalSubmenu = UIMenu()
  678. if layoutKey == NCGlobal.shared.layoutViewFiles {
  679. additionalSubmenu = UIMenu(title: "", options: .displayInline, children: [foldersOnTop, personalFilesOnlyAction, showDescription])
  680. } else {
  681. additionalSubmenu = UIMenu(title: "", options: .displayInline, children: [foldersOnTop, showDescription])
  682. }
  683. return [select, viewStyleSubmenu, sortSubmenu, additionalSubmenu]
  684. }
  685. }
  686. if isEditMode {
  687. tabBarSelect.update(selectOcId: selectOcId, metadatas: getSelectedMetadatas(), userId: appDelegate.userId)
  688. tabBarSelect.show()
  689. let select = UIBarButtonItem(title: NSLocalizedString("_cancel_", comment: ""), style: .done) {
  690. self.setEditMode(false)
  691. }
  692. navigationItem.rightBarButtonItems = [select]
  693. } else if navigationItem.rightBarButtonItems == nil || (!isEditMode && !tabBarSelect.isHidden()) {
  694. tabBarSelect.hide()
  695. let menuButton = UIBarButtonItem(image: utility.loadImage(named: "ellipsis.circle"), menu: UIMenu(children: createMenuActions()))
  696. menuButton.tintColor = NCBrandColor.shared.iconImageColor
  697. if layoutKey == NCGlobal.shared.layoutViewFiles {
  698. let notification = UIBarButtonItem(image: utility.loadImage(named: "bell"), style: .plain) {
  699. if let viewController = UIStoryboard(name: "NCNotification", bundle: nil).instantiateInitialViewController() as? NCNotification {
  700. self.navigationController?.pushViewController(viewController, animated: true)
  701. }
  702. }
  703. notification.tintColor = NCBrandColor.shared.iconImageColor
  704. navigationItem.rightBarButtonItems = [menuButton, notification]
  705. } else {
  706. navigationItem.rightBarButtonItems = [menuButton]
  707. }
  708. } else {
  709. navigationItem.rightBarButtonItems?.first?.menu = navigationItem.rightBarButtonItems?.first?.menu?.replacingChildren(createMenuActions())
  710. }
  711. // fix, if the tabbar was hidden before the update, set it in hidden
  712. if isTabBarHidden, isTabBarSelectHidden {
  713. self.tabBarController?.tabBar.isHidden = true
  714. }
  715. }
  716. func getNavigationTitle() -> String {
  717. let activeAccount = NCManageDatabase.shared.getActiveAccount()
  718. guard let userAlias = activeAccount?.alias, !userAlias.isEmpty else {
  719. return NCBrandOptions.shared.brand
  720. }
  721. return userAlias
  722. }
  723. func accountSettingsDidDismiss(tableAccount: tableAccount?) { }
  724. // MARK: - SEARCH
  725. func searchController(enabled: Bool) {
  726. guard enableSearchBar else { return }
  727. searchController?.searchBar.isUserInteractionEnabled = enabled
  728. if enabled {
  729. searchController?.searchBar.alpha = 1
  730. } else {
  731. searchController?.searchBar.alpha = 0.3
  732. }
  733. }
  734. func updateSearchResults(for searchController: UISearchController) {
  735. self.literalSearch = searchController.searchBar.text
  736. }
  737. func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
  738. isSearchingMode = true
  739. self.providers?.removeAll()
  740. self.dataSource.clearDataSource()
  741. self.collectionView.reloadData()
  742. // TIP
  743. dismissTip()
  744. }
  745. func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
  746. if isSearchingMode && self.literalSearch?.count ?? 0 >= 2 {
  747. reloadDataSourceNetwork()
  748. }
  749. }
  750. func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
  751. DispatchQueue.global().async {
  752. NCNetworking.shared.cancelUnifiedSearchFiles()
  753. self.isSearchingMode = false
  754. self.literalSearch = ""
  755. self.providers?.removeAll()
  756. self.dataSource.clearDataSource()
  757. self.reloadDataSource()
  758. }
  759. }
  760. // MARK: - TAP EVENT
  761. // sessionIdentifierDownload: String = "com.nextcloud.nextcloudkit.session.download"
  762. // sessionIdentifierUpload: String = "com.nextcloud.nextcloudkit.session.upload"
  763. // sessionUploadBackground: String = "com.nextcloud.session.upload.background"
  764. // sessionUploadBackgroundWWan: String = "com.nextcloud.session.upload.backgroundWWan"
  765. // sessionUploadBackgroundExtension: String = "com.nextcloud.session.upload.extension"
  766. func cancelSession(metadata: tableMetadata) async {
  767. let fileNameLocalPath = utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)
  768. utilityFileSystem.removeFile(atPath: utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId))
  769. // No session found
  770. if metadata.session.isEmpty {
  771. NCNetworking.shared.uploadRequest.removeValue(forKey: fileNameLocalPath)
  772. NCNetworking.shared.downloadRequest.removeValue(forKey: fileNameLocalPath)
  773. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  774. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSource)
  775. return
  776. }
  777. // DOWNLOAD FOREGROUND
  778. if metadata.session == NextcloudKit.shared.nkCommonInstance.sessionIdentifierDownload {
  779. if let request = NCNetworking.shared.downloadRequest[fileNameLocalPath] {
  780. request.cancel()
  781. } else if let metadata = NCManageDatabase.shared.getMetadataFromOcId(metadata.ocId) {
  782. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId,
  783. session: "",
  784. sessionError: "",
  785. selector: "",
  786. status: NCGlobal.shared.metadataStatusNormal)
  787. NotificationCenter.default.post(name: Notification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadCancelFile),
  788. object: nil,
  789. userInfo: ["ocId": metadata.ocId,
  790. "serverUrl": metadata.serverUrl,
  791. "account": metadata.account])
  792. }
  793. return
  794. }
  795. // DOWNLOAD BACKGROUND
  796. if metadata.session == NCNetworking.shared.sessionDownloadBackground {
  797. let session: URLSession? = NCNetworking.shared.sessionManagerDownloadBackground
  798. if let tasks = await session?.tasks {
  799. for task in tasks.2 { // ([URLSessionDataTask], [URLSessionUploadTask], [URLSessionDownloadTask])
  800. if task.taskIdentifier == metadata.sessionTaskIdentifier {
  801. task.cancel()
  802. }
  803. }
  804. }
  805. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId,
  806. session: "",
  807. sessionError: "",
  808. selector: "",
  809. status: NCGlobal.shared.metadataStatusNormal)
  810. NotificationCenter.default.post(name: Notification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadCancelFile),
  811. object: nil,
  812. userInfo: ["ocId": metadata.ocId,
  813. "serverUrl": metadata.serverUrl,
  814. "account": metadata.account])
  815. }
  816. // UPLOAD FOREGROUND
  817. if metadata.session == NextcloudKit.shared.nkCommonInstance.sessionIdentifierUpload {
  818. if let request = NCNetworking.shared.uploadRequest[fileNameLocalPath] {
  819. request.cancel()
  820. NCNetworking.shared.uploadRequest.removeValue(forKey: fileNameLocalPath)
  821. }
  822. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  823. NotificationCenter.default.post(name: Notification.Name(rawValue: NCGlobal.shared.notificationCenterUploadCancelFile),
  824. object: nil,
  825. userInfo: ["ocId": metadata.ocId,
  826. "serverUrl": metadata.serverUrl,
  827. "account": metadata.account])
  828. return
  829. }
  830. // UPLOAD BACKGROUND
  831. var session: URLSession?
  832. if metadata.session == NCNetworking.shared.sessionUploadBackground {
  833. session = NCNetworking.shared.sessionManagerUploadBackground
  834. } else if metadata.session == NCNetworking.shared.sessionUploadBackgroundWWan {
  835. session = NCNetworking.shared.sessionManagerUploadBackgroundWWan
  836. } else if metadata.session == NCNetworking.shared.sessionUploadBackgroundExtension {
  837. session = NCNetworking.shared.sessionManagerUploadBackgroundExtension
  838. }
  839. if let tasks = await session?.tasks {
  840. for task in tasks.1 { // ([URLSessionDataTask], [URLSessionUploadTask], [URLSessionDownloadTask])
  841. if task.taskIdentifier == metadata.sessionTaskIdentifier {
  842. task.cancel()
  843. }
  844. }
  845. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  846. NotificationCenter.default.post(name: Notification.Name(rawValue: NCGlobal.shared.notificationCenterUploadCancelFile),
  847. object: nil,
  848. userInfo: ["ocId": metadata.ocId,
  849. "serverUrl": metadata.serverUrl,
  850. "account": metadata.account])
  851. }
  852. }
  853. func tapMoreListItem(with objectId: String, namedButtonMore: String, image: UIImage?, indexPath: IndexPath, sender: Any) {
  854. tapMoreGridItem(with: objectId, namedButtonMore: namedButtonMore, image: image, indexPath: indexPath, sender: sender)
  855. }
  856. func tapShareListItem(with objectId: String, indexPath: IndexPath, sender: Any) {
  857. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(objectId) else { return }
  858. NCActionCenter.shared.openShare(viewController: self, metadata: metadata, page: .sharing)
  859. }
  860. func tapMoreGridItem(with objectId: String, namedButtonMore: String, image: UIImage?, indexPath: IndexPath, sender: Any) {
  861. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(objectId) else { return }
  862. if namedButtonMore == NCGlobal.shared.buttonMoreMore || namedButtonMore == NCGlobal.shared.buttonMoreLock {
  863. toggleMenu(metadata: metadata, indexPath: indexPath, imageIcon: image)
  864. } else if namedButtonMore == NCGlobal.shared.buttonMoreStop {
  865. Task {
  866. await cancelSession(metadata: metadata)
  867. }
  868. }
  869. }
  870. func tapRichWorkspace(_ sender: Any) {
  871. if let navigationController = UIStoryboard(name: "NCViewerRichWorkspace", bundle: nil).instantiateInitialViewController() as? UINavigationController {
  872. if let viewerRichWorkspace = navigationController.topViewController as? NCViewerRichWorkspace {
  873. viewerRichWorkspace.richWorkspaceText = richWorkspaceText ?? ""
  874. viewerRichWorkspace.serverUrl = serverUrl
  875. viewerRichWorkspace.delegate = self
  876. navigationController.modalPresentationStyle = .fullScreen
  877. self.present(navigationController, animated: true, completion: nil)
  878. }
  879. }
  880. }
  881. func tapButtonSection(_ sender: Any, metadataForSection: NCMetadataForSection?) {
  882. unifiedSearchMore(metadataForSection: metadataForSection)
  883. }
  884. func tapButtonTransfer(_ sender: Any) {
  885. if let ocId = NCNetworking.shared.transferInForegorund?.ocId,
  886. let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  887. Task {
  888. await cancelSession(metadata: metadata)
  889. }
  890. }
  891. }
  892. func longPressListItem(with objectId: String, indexPath: IndexPath, gestureRecognizer: UILongPressGestureRecognizer) {
  893. }
  894. func longPressGridItem(with objectId: String, indexPath: IndexPath, gestureRecognizer: UILongPressGestureRecognizer) {
  895. }
  896. func longPressMoreListItem(with objectId: String, namedButtonMore: String, indexPath: IndexPath, gestureRecognizer: UILongPressGestureRecognizer) {
  897. }
  898. func longPressMoreGridItem(with objectId: String, namedButtonMore: String, indexPath: IndexPath, gestureRecognizer: UILongPressGestureRecognizer) {
  899. }
  900. @objc func longPressCollecationView(_ gestureRecognizer: UILongPressGestureRecognizer) {
  901. openMenuItems(with: nil, gestureRecognizer: gestureRecognizer)
  902. }
  903. func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
  904. return UIContextMenuConfiguration(identifier: nil, previewProvider: {
  905. return nil
  906. }, actionProvider: { _ in
  907. return nil
  908. })
  909. }
  910. func openMenuItems(with objectId: String?, gestureRecognizer: UILongPressGestureRecognizer) {
  911. if gestureRecognizer.state != .began { return }
  912. var listMenuItems: [UIMenuItem] = []
  913. let touchPoint = gestureRecognizer.location(in: collectionView)
  914. becomeFirstResponder()
  915. if !serverUrl.isEmpty {
  916. listMenuItems.append(UIMenuItem(title: NSLocalizedString("_paste_file_", comment: ""), action: #selector(pasteFilesMenu)))
  917. }
  918. if !listMenuItems.isEmpty {
  919. UIMenuController.shared.menuItems = listMenuItems
  920. UIMenuController.shared.showMenu(from: collectionView, rect: CGRect(x: touchPoint.x, y: touchPoint.y, width: 0, height: 0))
  921. }
  922. }
  923. // MARK: - Menu Item
  924. override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
  925. if #selector(pasteFilesMenu) == action {
  926. if !UIPasteboard.general.items.isEmpty, !(metadataFolder?.e2eEncrypted ?? false) {
  927. return true
  928. }
  929. } else if #selector(copyMenuFile) == action {
  930. return true
  931. } else if #selector(moveMenuFile) == action {
  932. return true
  933. }
  934. return false
  935. }
  936. @objc func pasteFilesMenu() {
  937. NCActionCenter.shared.pastePasteboard(serverUrl: serverUrl, hudView: tabBarController?.view)
  938. }
  939. // MARK: - DataSource + NC Endpoint
  940. func queryDB() { }
  941. @objc func reloadDataSource(withQueryDB: Bool = true) {
  942. guard !appDelegate.account.isEmpty, !self.isSearchingMode else { return }
  943. // get auto upload folder
  944. autoUploadFileName = NCManageDatabase.shared.getAccountAutoUploadFileName()
  945. autoUploadDirectory = NCManageDatabase.shared.getAccountAutoUploadDirectory(urlBase: appDelegate.urlBase, userId: appDelegate.userId, account: appDelegate.account)
  946. // get layout for view
  947. layoutForView = NCManageDatabase.shared.getLayoutForView(account: appDelegate.account, key: layoutKey, serverUrl: serverUrl)
  948. DispatchQueue.global(qos: .userInteractive).async {
  949. if withQueryDB { self.queryDB() }
  950. DispatchQueue.main.async {
  951. self.refreshControl.endRefreshing()
  952. self.collectionView.reloadData()
  953. self.setNavigationRightItems()
  954. }
  955. }
  956. }
  957. @objc func reloadDataSourceNetwork(withQueryDB: Bool = false) {
  958. DispatchQueue.main.async {
  959. self.collectionView?.reloadData()
  960. }
  961. }
  962. @objc func networkSearch() {
  963. guard !appDelegate.account.isEmpty, let literalSearch = literalSearch, !literalSearch.isEmpty
  964. else { return self.refreshControl.endRefreshing() }
  965. self.dataSource.clearDataSource()
  966. self.refreshControl.beginRefreshing()
  967. self.collectionView.reloadData()
  968. if NCGlobal.shared.capabilityServerVersionMajor >= NCGlobal.shared.nextcloudVersion20 {
  969. NCNetworking.shared.unifiedSearchFiles(userBaseUrl: appDelegate, literal: literalSearch) { task in
  970. self.dataSourceTask = task
  971. self.collectionView.reloadData()
  972. } providers: { _, searchProviders in
  973. self.providers = searchProviders
  974. self.searchResults = []
  975. self.dataSource = NCDataSource(metadatas: [], account: self.appDelegate.account, layoutForView: self.layoutForView, providers: self.providers, searchResults: self.searchResults)
  976. } update: { _, _, searchResult, metadatas in
  977. guard let metadatas, !metadatas.isEmpty, self.isSearchingMode, let searchResult else { return }
  978. NCNetworking.shared.unifiedSearchQueue.addOperation(NCCollectionViewUnifiedSearch(collectionViewCommon: self, metadatas: metadatas, searchResult: searchResult))
  979. } completion: { _, _ in
  980. self.refreshControl.endRefreshing()
  981. self.collectionView.reloadData()
  982. }
  983. } else {
  984. NCNetworking.shared.searchFiles(urlBase: appDelegate, literal: literalSearch) { task in
  985. self.dataSourceTask = task
  986. self.collectionView.reloadData()
  987. } completion: { metadatas, error in
  988. DispatchQueue.main.async {
  989. self.refreshControl.endRefreshing()
  990. self.collectionView.reloadData()
  991. }
  992. guard let metadatas = metadatas, error == .success, self.isSearchingMode else { return }
  993. self.dataSource = NCDataSource(metadatas: metadatas, account: self.appDelegate.account, layoutForView: self.layoutForView, providers: self.providers, searchResults: self.searchResults)
  994. }
  995. }
  996. }
  997. func unifiedSearchMore(metadataForSection: NCMetadataForSection?) {
  998. guard let metadataForSection = metadataForSection, let lastSearchResult = metadataForSection.lastSearchResult, let cursor = lastSearchResult.cursor, let term = literalSearch else { return }
  999. metadataForSection.unifiedSearchInProgress = true
  1000. self.collectionView?.reloadData()
  1001. NCNetworking.shared.unifiedSearchFilesProvider(userBaseUrl: appDelegate, id: lastSearchResult.id, term: term, limit: 5, cursor: cursor) { task in
  1002. self.dataSourceTask = task
  1003. self.collectionView.reloadData()
  1004. } completion: { _, searchResult, metadatas, error in
  1005. if error != .success {
  1006. NCContentPresenter().showError(error: error)
  1007. }
  1008. metadataForSection.unifiedSearchInProgress = false
  1009. guard let searchResult = searchResult, let metadatas = metadatas else { return }
  1010. self.dataSource.appendMetadatasToSection(metadatas, metadataForSection: metadataForSection, lastSearchResult: searchResult)
  1011. DispatchQueue.main.async {
  1012. self.collectionView?.reloadData()
  1013. }
  1014. }
  1015. }
  1016. // MARK: - Push metadata
  1017. func pushMetadata(_ metadata: tableMetadata) {
  1018. guard let filesServerUrl = (tabBarController as? NCMainTabBarController)?.filesServerUrl else { return }
  1019. let serverUrlPush = utilityFileSystem.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)
  1020. if let viewController = filesServerUrl[serverUrlPush], viewController.isViewLoaded {
  1021. navigationController?.pushViewController(viewController, animated: true)
  1022. } else {
  1023. if let viewController: NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as? NCFiles {
  1024. viewController.isRoot = false
  1025. viewController.serverUrl = serverUrlPush
  1026. viewController.titlePreviusFolder = navigationItem.title
  1027. viewController.titleCurrentFolder = metadata.fileNameView
  1028. filesServerUrl[serverUrlPush] = viewController
  1029. navigationController?.pushViewController(viewController, animated: true)
  1030. }
  1031. }
  1032. }
  1033. // MARK: - Header size
  1034. func isHeaderMenuTransferViewEnabled() -> Bool {
  1035. if headerMenuTransferView,
  1036. let metadata = NCManageDatabase.shared.getMetadataFromOcId(NCNetworking.shared.transferInForegorund?.ocId),
  1037. metadata.isTransferInForeground {
  1038. return true
  1039. }
  1040. return false
  1041. }
  1042. func getHeaderHeight(section: Int) -> (heightHeaderCommands: CGFloat, heightHeaderRichWorkspace: CGFloat, heightHeaderSection: CGFloat) {
  1043. var headerRichWorkspace: CGFloat = 0
  1044. func getHeaderHeight() -> CGFloat {
  1045. var size: CGFloat = 0
  1046. if isHeaderMenuTransferViewEnabled() {
  1047. if !isSearchingMode {
  1048. size += NCGlobal.shared.heightHeaderTransfer
  1049. }
  1050. } else {
  1051. NCNetworking.shared.transferInForegorund = nil
  1052. }
  1053. return size
  1054. }
  1055. if let richWorkspaceText = richWorkspaceText, showDescription {
  1056. let trimmed = richWorkspaceText.trimmingCharacters(in: .whitespaces)
  1057. if !trimmed.isEmpty && !isSearchingMode {
  1058. headerRichWorkspace = UIScreen.main.bounds.size.height / 6
  1059. }
  1060. }
  1061. if isSearchingMode || layoutForView?.groupBy != "none" || dataSource.numberOfSections() > 1 {
  1062. if section == 0 {
  1063. return (getHeaderHeight(), headerRichWorkspace, NCGlobal.shared.heightSection)
  1064. } else {
  1065. return (0, 0, NCGlobal.shared.heightSection)
  1066. }
  1067. } else {
  1068. return (getHeaderHeight(), headerRichWorkspace, 0)
  1069. }
  1070. }
  1071. func sizeForHeaderInSection(section: Int) -> CGSize {
  1072. var height: CGFloat = 0
  1073. if isEditMode {
  1074. return CGSize.zero
  1075. } else if dataSource.getMetadataSourceForAllSections().isEmpty {
  1076. height = NCGlobal.shared.getHeightHeaderEmptyData(view: view, portraitOffset: emptyDataPortaitOffset, landscapeOffset: emptyDataLandscapeOffset, isHeaderMenuTransferViewEnabled: isHeaderMenuTransferViewEnabled())
  1077. } else {
  1078. let (heightHeaderCommands, heightHeaderRichWorkspace, heightHeaderSection) = getHeaderHeight(section: section)
  1079. height = heightHeaderCommands + heightHeaderRichWorkspace + heightHeaderSection
  1080. }
  1081. return CGSize(width: collectionView.frame.width, height: height)
  1082. }
  1083. // MARK: - Footer size
  1084. func sizeForFooterInSection(section: Int) -> CGSize {
  1085. let sections = dataSource.numberOfSections()
  1086. let metadataForSection = self.dataSource.getMetadataForSection(section)
  1087. let isPaginated = metadataForSection?.lastSearchResult?.isPaginated ?? false
  1088. let metadatasCount: Int = metadataForSection?.lastSearchResult?.entries.count ?? 0
  1089. var size = CGSize(width: collectionView.frame.width, height: 0)
  1090. if section == sections - 1 {
  1091. size.height += NCGlobal.shared.endHeightFooter
  1092. } else {
  1093. size.height += NCGlobal.shared.heightFooter
  1094. }
  1095. if isSearchingMode && isPaginated && metadatasCount > 0 {
  1096. size.height += NCGlobal.shared.heightFooterButton
  1097. }
  1098. return size
  1099. }
  1100. }
  1101. // MARK: -
  1102. private class AccountSwitcherButton: UIButton {
  1103. var onMenuOpened: (() -> Void)?
  1104. override func contextMenuInteraction(_ interaction: UIContextMenuInteraction, willDisplayMenuFor configuration: UIContextMenuConfiguration, animator: UIContextMenuInteractionAnimating?) {
  1105. super.contextMenuInteraction(interaction, willDisplayMenuFor: configuration, animator: animator)
  1106. onMenuOpened?()
  1107. }
  1108. }