NCCollectionViewCommon.swift 89 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888
  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 Realm
  25. import NextcloudKit
  26. import EasyTipView
  27. import JGProgressHUD
  28. class NCCollectionViewCommon: UIViewController, UIGestureRecognizerDelegate, UISearchResultsUpdating, UISearchControllerDelegate, UISearchBarDelegate, NCListCellDelegate, NCGridCellDelegate, NCSectionHeaderMenuDelegate, NCSectionFooterDelegate, NCSectionHeaderEmptyDataDelegate, UIAdaptivePresentationControllerDelegate, UIContextMenuInteractionDelegate, NCAccountRequestDelegate {
  29. @IBOutlet weak var collectionView: UICollectionView!
  30. private var autoUploadFileName = ""
  31. private var autoUploadDirectory = ""
  32. private var tipView: EasyTipView?
  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 headerMenu: NCSectionHeaderMenu?
  47. var isSearchingMode: Bool = false
  48. var layoutForView: NCDBLayoutForView?
  49. var dataSourceTask: URLSessionTask?
  50. var groupByField = "name"
  51. var providers: [NKSearchProvider]?
  52. var searchResults: [NKSearchResult]?
  53. var listLayout: NCListLayout!
  54. var gridLayout: NCGridLayout!
  55. var literalSearch: String?
  56. var tabBarSelect: NCCollectionViewCommonSelectTabBar!
  57. var timerNotificationCenter: Timer?
  58. var notificationReloadDataSource: Int = 0
  59. var notificationReloadDataSourceNetwork: Int = 0
  60. // DECLARE
  61. var layoutKey = ""
  62. var titleCurrentFolder = ""
  63. var titlePreviusFolder: String?
  64. var enableSearchBar: Bool = false
  65. var headerMenuTransferView = false
  66. var headerRichWorkspaceDisable: Bool = false
  67. var emptyImage: UIImage?
  68. var emptyTitle: String = ""
  69. var emptyDescription: String = ""
  70. var emptyDataPortaitOffset: CGFloat = 0
  71. var emptyDataLandscapeOffset: CGFloat = -20
  72. private var showDescription: Bool {
  73. !headerRichWorkspaceDisable && NCKeychain().showDescription
  74. }
  75. private var infoLabelsSeparator: String {
  76. layoutForView?.layout == NCGlobal.shared.layoutList ? " - " : ""
  77. }
  78. // MARK: - View Life Cycle
  79. override func viewDidLoad() {
  80. super.viewDidLoad()
  81. tabBarSelect = NCCollectionViewCommonSelectTabBar(tabBarController: tabBarController as? NCMainTabBarController, delegate: self)
  82. self.navigationController?.presentationController?.delegate = self
  83. // CollectionView & layout
  84. collectionView.alwaysBounceVertical = true
  85. listLayout = NCListLayout()
  86. gridLayout = NCGridLayout()
  87. // Color
  88. view.backgroundColor = .systemBackground
  89. collectionView.backgroundColor = .systemBackground
  90. refreshControl.tintColor = .gray
  91. if enableSearchBar {
  92. searchController = UISearchController(searchResultsController: nil)
  93. searchController?.searchResultsUpdater = self
  94. searchController?.obscuresBackgroundDuringPresentation = false
  95. searchController?.delegate = self
  96. searchController?.searchBar.delegate = self
  97. searchController?.searchBar.autocapitalizationType = .none
  98. navigationItem.searchController = searchController
  99. navigationItem.hidesSearchBarWhenScrolling = true
  100. }
  101. // Cell
  102. collectionView.register(UINib(nibName: "NCListCell", bundle: nil), forCellWithReuseIdentifier: "listCell")
  103. collectionView.register(UINib(nibName: "NCGridCell", bundle: nil), forCellWithReuseIdentifier: "gridCell")
  104. collectionView.register(UINib(nibName: "NCTransferCell", bundle: nil), forCellWithReuseIdentifier: "transferCell")
  105. // Header
  106. collectionView.register(UINib(nibName: "NCSectionHeaderMenu", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeaderMenu")
  107. collectionView.register(UINib(nibName: "NCSectionHeader", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeader")
  108. collectionView.register(UINib(nibName: "NCSectionHeaderEmptyData", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeaderEmptyData")
  109. // Footer
  110. collectionView.register(UINib(nibName: "NCSectionFooter", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "sectionFooter")
  111. // Refresh Control
  112. collectionView.refreshControl = refreshControl
  113. refreshControl.action(for: .valueChanged) { _ in
  114. self.dataSource.clearDirectory()
  115. NCManageDatabase.shared.cleanEtagDirectory(account: self.appDelegate.account, serverUrl: self.serverUrl)
  116. self.reloadDataSourceNetwork()
  117. }
  118. // Long Press on CollectionView
  119. let longPressedGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPressCollecationView(_:)))
  120. longPressedGesture.minimumPressDuration = 0.5
  121. longPressedGesture.delegate = self
  122. longPressedGesture.delaysTouchesBegan = true
  123. collectionView.addGestureRecognizer(longPressedGesture)
  124. // TIP
  125. var preferences = EasyTipView.Preferences()
  126. preferences.drawing.foregroundColor = .white
  127. preferences.drawing.backgroundColor = NCBrandColor.shared.nextcloud
  128. preferences.drawing.textAlignment = .left
  129. preferences.drawing.arrowPosition = .top
  130. preferences.drawing.cornerRadius = 10
  131. preferences.animating.dismissTransform = CGAffineTransform(translationX: 0, y: 100)
  132. preferences.animating.showInitialTransform = CGAffineTransform(translationX: 0, y: -100)
  133. preferences.animating.showInitialAlpha = 0
  134. preferences.animating.showDuration = 1.5
  135. preferences.animating.dismissDuration = 1.5
  136. tipView = EasyTipView(text: NSLocalizedString("_tip_accountrequest_", comment: ""), preferences: preferences, delegate: self)
  137. NotificationCenter.default.addObserver(self, selector: #selector(changeTheming), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterChangeTheming), object: nil)
  138. }
  139. override func viewWillAppear(_ animated: Bool) {
  140. super.viewWillAppear(animated)
  141. navigationController?.setNavigationBarAppearance()
  142. navigationController?.navigationBar.prefersLargeTitles = true
  143. navigationController?.setNavigationBarHidden(false, animated: true)
  144. navigationItem.title = titleCurrentFolder
  145. setNavigationLeftItems()
  146. setNavigationRightItems()
  147. if serverUrl.isEmpty {
  148. appDelegate.activeServerUrl = utilityFileSystem.getHomeServer(urlBase: appDelegate.urlBase, userId: appDelegate.userId)
  149. } else {
  150. appDelegate.activeServerUrl = serverUrl
  151. }
  152. layoutForView = NCManageDatabase.shared.getLayoutForView(account: appDelegate.account, key: layoutKey, serverUrl: serverUrl)
  153. gridLayout.itemForLine = CGFloat(layoutForView?.itemForLine ?? 3)
  154. if layoutForView?.layout == NCGlobal.shared.layoutList {
  155. collectionView?.collectionViewLayout = listLayout
  156. } else {
  157. collectionView?.collectionViewLayout = gridLayout
  158. }
  159. // FIXME: iPAD PDF landscape mode iOS 16
  160. DispatchQueue.main.async {
  161. self.collectionView?.collectionViewLayout.invalidateLayout()
  162. }
  163. }
  164. override func viewDidAppear(_ animated: Bool) {
  165. super.viewDidAppear(animated)
  166. appDelegate.activeViewController = self
  167. timerNotificationCenter = Timer.scheduledTimer(timeInterval: 1.5, target: self, selector: #selector(notificationCenterEvents), userInfo: nil, repeats: true)
  168. NotificationCenter.default.addObserver(self, selector: #selector(applicationWillResignActive(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationWillResignActive), object: nil)
  169. NotificationCenter.default.addObserver(self, selector: #selector(closeRichWorkspaceWebView), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCloseRichWorkspaceWebView), object: nil)
  170. NotificationCenter.default.addObserver(self, selector: #selector(changeStatusFolderE2EE(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterChangeStatusFolderE2EE), object: nil)
  171. NotificationCenter.default.addObserver(self, selector: #selector(reloadAvatar(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadAvatar), object: nil)
  172. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSource(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadDataSource), object: nil)
  173. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSourceNetwork(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadDataSourceNetwork), object: nil)
  174. NotificationCenter.default.addObserver(self, selector: #selector(deleteFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDeleteFile), object: nil)
  175. NotificationCenter.default.addObserver(self, selector: #selector(moveFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMoveFile), object: nil)
  176. NotificationCenter.default.addObserver(self, selector: #selector(copyFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCopyFile), object: nil)
  177. NotificationCenter.default.addObserver(self, selector: #selector(renameFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterRenameFile), object: nil)
  178. NotificationCenter.default.addObserver(self, selector: #selector(createFolder(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCreateFolder), object: nil)
  179. NotificationCenter.default.addObserver(self, selector: #selector(favoriteFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterFavoriteFile), object: nil)
  180. NotificationCenter.default.addObserver(self, selector: #selector(downloadStartFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadStartFile), object: nil)
  181. NotificationCenter.default.addObserver(self, selector: #selector(downloadedFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadedFile), object: nil)
  182. NotificationCenter.default.addObserver(self, selector: #selector(downloadCancelFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadCancelFile), object: nil)
  183. NotificationCenter.default.addObserver(self, selector: #selector(uploadStartFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadStartFile), object: nil)
  184. NotificationCenter.default.addObserver(self, selector: #selector(uploadedFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedFile), object: nil)
  185. NotificationCenter.default.addObserver(self, selector: #selector(uploadedLivePhoto(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedLivePhoto), object: nil)
  186. NotificationCenter.default.addObserver(self, selector: #selector(uploadCancelFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadCancelFile), object: nil)
  187. NotificationCenter.default.addObserver(self, selector: #selector(triggerProgressTask(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterProgressTask), object: nil)
  188. }
  189. override func viewWillDisappear(_ animated: Bool) {
  190. super.viewWillDisappear(animated)
  191. NCNetworking.shared.cancelUnifiedSearchFiles()
  192. tipView?.dismiss()
  193. setEditMode(false)
  194. }
  195. override func viewDidDisappear(_ animated: Bool) {
  196. super.viewDidDisappear(animated)
  197. timerNotificationCenter?.invalidate()
  198. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationWillResignActive), object: nil)
  199. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCloseRichWorkspaceWebView), object: nil)
  200. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterChangeStatusFolderE2EE), object: nil)
  201. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadAvatar), object: nil)
  202. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadDataSource), object: nil)
  203. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadDataSourceNetwork), object: nil)
  204. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDeleteFile), object: nil)
  205. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMoveFile), object: nil)
  206. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCopyFile), object: nil)
  207. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterRenameFile), object: nil)
  208. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCreateFolder), object: nil)
  209. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterFavoriteFile), object: nil)
  210. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadStartFile), object: nil)
  211. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadedFile), object: nil)
  212. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadCancelFile), object: nil)
  213. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadStartFile), object: nil)
  214. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedFile), object: nil)
  215. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedLivePhoto), object: nil)
  216. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadCancelFile), object: nil)
  217. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterProgressTask), object: nil)
  218. }
  219. func presentationControllerDidDismiss( _ presentationController: UIPresentationController) {
  220. let viewController = presentationController.presentedViewController
  221. if viewController is NCViewerRichWorkspaceWebView {
  222. closeRichWorkspaceWebView()
  223. }
  224. }
  225. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  226. super.viewWillTransition(to: size, with: coordinator)
  227. self.collectionView?.collectionViewLayout.invalidateLayout()
  228. self.collectionView?.reloadData()
  229. self.tipView?.dismiss()
  230. coordinator.animate(alongsideTransition: nil) { _ in
  231. self.showTip()
  232. }
  233. }
  234. override var canBecomeFirstResponder: Bool {
  235. return true
  236. }
  237. override func viewWillLayoutSubviews() {
  238. super.viewWillLayoutSubviews()
  239. if let frame = tabBarController?.tabBar.frame {
  240. tabBarSelect.hostingController?.view.frame = frame
  241. }
  242. }
  243. // MARK: - NotificationCenter
  244. @objc func notificationCenterEvents() {
  245. if notificationReloadDataSource > 0 {
  246. print("notificationReloadDataSource: \(notificationReloadDataSource)")
  247. reloadDataSource()
  248. notificationReloadDataSource = 0
  249. }
  250. }
  251. @objc func applicationWillResignActive(_ notification: NSNotification) {
  252. self.refreshControl.endRefreshing()
  253. }
  254. @objc func reloadAvatar(_ notification: NSNotification) {
  255. DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
  256. self.showTip()
  257. }
  258. guard let userInfo = notification.userInfo as NSDictionary?,
  259. let error = userInfo["error"] as? NKError,
  260. error.errorCode != NCGlobal.shared.errorNotModified else { return }
  261. setNavigationLeftItems()
  262. }
  263. @objc func changeTheming() {
  264. collectionView.reloadData()
  265. }
  266. @objc func reloadDataSource(_ notification: NSNotification) {
  267. notificationReloadDataSource += 1
  268. }
  269. @objc func reloadDataSourceNetwork(_ notification: NSNotification) {
  270. if !isSearchingMode {
  271. reloadDataSourceNetwork()
  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. notificationReloadDataSource += 1
  284. if error != .success {
  285. NCContentPresenter().showError(error: error)
  286. }
  287. }
  288. @objc func moveFile(_ notification: NSNotification) {
  289. deleteFile(notification)
  290. }
  291. @objc func copyFile(_ notification: NSNotification) {
  292. guard let userInfo = notification.userInfo as NSDictionary?,
  293. let error = userInfo["error"] as? NKError else { return }
  294. if error != .success {
  295. NCContentPresenter().showError(error: error)
  296. }
  297. }
  298. @objc func renameFile(_ notification: NSNotification) {
  299. guard let userInfo = notification.userInfo as NSDictionary?,
  300. let account = userInfo["account"] as? String,
  301. account == appDelegate.account
  302. else { return }
  303. notificationReloadDataSource += 1
  304. }
  305. @objc func createFolder(_ notification: NSNotification) {
  306. guard let userInfo = notification.userInfo as NSDictionary?,
  307. let ocId = userInfo["ocId"] as? String,
  308. let serverUrl = userInfo["serverUrl"] as? String,
  309. serverUrl == self.serverUrl,
  310. let account = userInfo["account"] as? String,
  311. account == appDelegate.account,
  312. let withPush = userInfo["withPush"] as? Bool
  313. else { return }
  314. notificationReloadDataSource += 1
  315. if withPush, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  316. pushMetadata(metadata)
  317. }
  318. }
  319. @objc func favoriteFile(_ notification: NSNotification) {
  320. if self is NCFavorite {
  321. return notificationReloadDataSource += 1
  322. }
  323. guard let userInfo = notification.userInfo as NSDictionary?,
  324. let serverUrl = userInfo["serverUrl"] as? String,
  325. serverUrl == self.serverUrl
  326. else { return }
  327. notificationReloadDataSource += 1
  328. }
  329. @objc func downloadStartFile(_ notification: NSNotification) {
  330. guard let userInfo = notification.userInfo as NSDictionary?,
  331. let serverUrl = userInfo["serverUrl"] as? String,
  332. serverUrl == self.serverUrl,
  333. let account = userInfo["account"] as? String,
  334. account == appDelegate.account
  335. else { return }
  336. self.notificationReloadDataSource += 1
  337. }
  338. @objc func downloadedFile(_ notification: NSNotification) {
  339. guard let userInfo = notification.userInfo as NSDictionary?,
  340. let serverUrl = userInfo["serverUrl"] as? String,
  341. serverUrl == self.serverUrl,
  342. let account = userInfo["account"] as? String,
  343. account == appDelegate.account,
  344. let error = userInfo["error"] as? NKError
  345. else { return }
  346. if error != .success {
  347. NCContentPresenter().showError(error: error)
  348. }
  349. notificationReloadDataSource += 1
  350. }
  351. @objc func downloadCancelFile(_ notification: NSNotification) {
  352. guard let userInfo = notification.userInfo as NSDictionary?,
  353. let serverUrl = userInfo["serverUrl"] as? String,
  354. serverUrl == self.serverUrl,
  355. let account = userInfo["account"] as? String,
  356. account == appDelegate.account
  357. else { return }
  358. notificationReloadDataSource += 1
  359. }
  360. @objc func uploadStartFile(_ notification: NSNotification) {
  361. guard let userInfo = notification.userInfo as NSDictionary?,
  362. let ocId = userInfo["ocId"] as? String,
  363. let serverUrl = userInfo["serverUrl"] as? String,
  364. let account = userInfo["account"] as? String,
  365. !isSearchingMode,
  366. let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId)
  367. else { return }
  368. // Header view trasfer
  369. if metadata.isTransferInForeground {
  370. NCNetworking.shared.transferInForegorund = NCNetworking.TransferInForegorund(ocId: ocId, progress: 0)
  371. DispatchQueue.main.async { self.collectionView?.reloadData() }
  372. }
  373. if serverUrl == self.serverUrl, account == appDelegate.account {
  374. notificationReloadDataSource += 1
  375. }
  376. }
  377. @objc func uploadedFile(_ notification: NSNotification) {
  378. guard let userInfo = notification.userInfo as NSDictionary?,
  379. let ocIdTemp = userInfo["ocIdTemp"] as? String,
  380. let serverUrl = userInfo["serverUrl"] as? String,
  381. let account = userInfo["account"] as? String
  382. else { return }
  383. if ocIdTemp == NCNetworking.shared.transferInForegorund?.ocId {
  384. NCNetworking.shared.transferInForegorund = nil
  385. DispatchQueue.main.async { self.collectionView?.reloadData() }
  386. }
  387. if account == appDelegate.account, serverUrl == self.serverUrl {
  388. notificationReloadDataSource += 1
  389. }
  390. }
  391. @objc func uploadedLivePhoto(_ notification: NSNotification) {
  392. guard let userInfo = notification.userInfo as NSDictionary?,
  393. let serverUrl = userInfo["serverUrl"] as? String,
  394. serverUrl == self.serverUrl,
  395. let account = userInfo["account"] as? String,
  396. account == appDelegate.account
  397. else { return }
  398. notificationReloadDataSource += 1
  399. }
  400. @objc func uploadCancelFile(_ notification: NSNotification) {
  401. guard let userInfo = notification.userInfo as NSDictionary?,
  402. let ocId = userInfo["ocId"] as? String,
  403. let serverUrl = userInfo["serverUrl"] as? String,
  404. let account = userInfo["account"] as? String
  405. else { return }
  406. if ocId == NCNetworking.shared.transferInForegorund?.ocId {
  407. NCNetworking.shared.transferInForegorund = nil
  408. DispatchQueue.main.async { self.collectionView?.reloadData() }
  409. }
  410. if account == appDelegate.account, serverUrl == self.serverUrl {
  411. notificationReloadDataSource += 1
  412. }
  413. }
  414. @objc func triggerProgressTask(_ notification: NSNotification) {
  415. guard let userInfo = notification.userInfo as NSDictionary?,
  416. let progressNumber = userInfo["progress"] as? NSNumber,
  417. let totalBytes = userInfo["totalBytes"] as? Int64,
  418. let totalBytesExpected = userInfo["totalBytesExpected"] as? Int64,
  419. let ocId = userInfo["ocId"] as? String
  420. else { return }
  421. let chunk: Int = userInfo["chunk"] as? Int ?? 0
  422. let e2eEncrypted: Bool = userInfo["e2eEncrypted"] as? Bool ?? false
  423. DispatchQueue.main.async {
  424. if self.headerMenuTransferView && (chunk > 0 || e2eEncrypted) {
  425. if NCNetworking.shared.transferInForegorund?.ocId == ocId {
  426. NCNetworking.shared.transferInForegorund?.progress = progressNumber.floatValue
  427. } else {
  428. NCNetworking.shared.transferInForegorund = NCNetworking.TransferInForegorund(ocId: ocId, progress: progressNumber.floatValue)
  429. self.collectionView.reloadData()
  430. }
  431. self.headerMenu?.progressTransfer.progress = progressNumber.floatValue
  432. } else {
  433. guard let indexPath = self.dataSource.getIndexPathMetadata(ocId: ocId).indexPath,
  434. let cell = self.collectionView?.cellForItem(at: indexPath),
  435. let cell = cell as? NCCellProtocol else { return }
  436. if progressNumber.floatValue == 1 && !(cell is NCTransferCell) {
  437. cell.fileProgressView?.isHidden = true
  438. cell.fileProgressView?.progress = .zero
  439. cell.setButtonMore(named: NCGlobal.shared.buttonMoreMore, image: NCImageCache.images.buttonMore)
  440. if let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  441. cell.writeInfoDateSize(date: metadata.date, size: metadata.size)
  442. } else {
  443. cell.fileInfoLabel?.text = ""
  444. cell.fileSubinfoLabel?.text = ""
  445. }
  446. } else {
  447. cell.fileProgressView?.isHidden = false
  448. cell.fileProgressView?.progress = progressNumber.floatValue
  449. cell.setButtonMore(named: NCGlobal.shared.buttonMoreStop, image: NCImageCache.images.buttonStop)
  450. let status = userInfo["status"] as? Int ?? NCGlobal.shared.metadataStatusNormal
  451. if status == NCGlobal.shared.metadataStatusDownloading {
  452. cell.fileInfoLabel?.text = self.utilityFileSystem.transformedSize(totalBytesExpected)
  453. cell.fileSubinfoLabel?.text = self.infoLabelsSeparator + "↓ " + self.utilityFileSystem.transformedSize(totalBytes)
  454. } else if status == NCGlobal.shared.metadataStatusUploading {
  455. if totalBytes > 0 {
  456. cell.fileInfoLabel?.text = self.utilityFileSystem.transformedSize(totalBytesExpected)
  457. cell.fileSubinfoLabel?.text = self.infoLabelsSeparator + "↑ " + self.utilityFileSystem.transformedSize(totalBytes)
  458. } else {
  459. cell.fileInfoLabel?.text = self.utilityFileSystem.transformedSize(totalBytesExpected)
  460. cell.fileSubinfoLabel?.text = self.infoLabelsSeparator + "↑ …"
  461. }
  462. }
  463. }
  464. }
  465. }
  466. }
  467. // MARK: - Tip
  468. func showTip() {
  469. if self is NCFiles, self.view.window != nil, !NCBrandOptions.shared.disable_multiaccount, !NCBrandOptions.shared.disable_manage_account, self.serverUrl == utilityFileSystem.getHomeServer(urlBase: appDelegate.urlBase, userId: appDelegate.userId), let view = self.navigationItem.leftBarButtonItem?.customView {
  470. if !NCManageDatabase.shared.tipExists(NCGlobal.shared.tipNCCollectionViewCommonAccountRequest), !NCManageDatabase.shared.getAllAccountOrderAlias().isEmpty {
  471. self.tipView?.show(forView: view)
  472. }
  473. }
  474. }
  475. // MARK: - Layout
  476. func setNavigationLeftItems() {
  477. guard layoutKey == NCGlobal.shared.layoutViewFiles else { return }
  478. // PROFILE BUTTON
  479. let activeAccount = NCManageDatabase.shared.getActiveAccount()
  480. let image = utility.loadUserImage(for: appDelegate.user, displayName: activeAccount?.displayName, userBaseUrl: appDelegate)
  481. let button = AccountSwitcherButton(type: .custom)
  482. button.setImage(image, for: .normal)
  483. button.setImage(image, for: .highlighted)
  484. button.semanticContentAttribute = .forceLeftToRight
  485. button.sizeToFit()
  486. let accounts = NCManageDatabase.shared.getAllAccountOrderAlias()
  487. if !accounts.isEmpty, !NCBrandOptions.shared.disable_multiaccount, !NCBrandOptions.shared.disable_manage_account {
  488. let accountActions: [UIAction] = accounts.map { account in
  489. let image = utility.loadUserImage(for: account.user, displayName: account.displayName, userBaseUrl: account)
  490. var name: String = ""
  491. var url: String = ""
  492. if account.alias.isEmpty {
  493. name = account.displayName
  494. url = (URL(string: account.urlBase)?.host ?? "")
  495. } else {
  496. name = account.alias
  497. }
  498. let action = UIAction(title: name, image: image, state: account.active ? .on : .off) { _ in
  499. if !account.active {
  500. self.appDelegate.changeAccount(account.account, userProfile: nil)
  501. self.setEditMode(false)
  502. }
  503. }
  504. action.subtitle = url
  505. return action
  506. }
  507. let addAccountAction = UIAction(title: NSLocalizedString("_add_account_", comment: ""), image: .init(systemName: "person.crop.circle.badge.plus")) { _ in
  508. self.appDelegate.openLogin(viewController: self, selector: NCGlobal.shared.introLogin, openLoginWeb: false)
  509. }
  510. let addAccountSubmenu = UIMenu(title: "", options: .displayInline, children: [addAccountAction])
  511. let menu = UIMenu(children: accountActions + [addAccountSubmenu])
  512. button.menu = menu
  513. button.showsMenuAsPrimaryAction = true
  514. button.onMenuOpened = {
  515. self.dismissTip()
  516. }
  517. }
  518. navigationItem.setLeftBarButton(UIBarButtonItem(customView: button), animated: true)
  519. navigationItem.leftItemsSupplementBackButton = true
  520. if titlePreviusFolder != nil {
  521. navigationController?.navigationBar.topItem?.title = titlePreviusFolder
  522. }
  523. navigationItem.title = titleCurrentFolder
  524. }
  525. func setNavigationRightItems(enableMenu: Bool = false) {
  526. guard layoutKey != NCGlobal.shared.layoutViewTransfers else { return }
  527. let isTabBarHidden = self.tabBarController?.tabBar.isHidden ?? true
  528. let isTabBarSelectHidden = tabBarSelect.isHidden()
  529. func createMenuActions() -> [UIMenuElement] {
  530. guard let layoutForView = NCManageDatabase.shared.getLayoutForView(account: appDelegate.account, key: layoutKey, serverUrl: serverUrl) else { return [] }
  531. let select = UIAction(title: NSLocalizedString("_select_", comment: ""), image: .init(systemName: "checkmark.circle"), attributes: self.dataSource.getMetadataSourceForAllSections().isEmpty ? .disabled : []) { _ in
  532. self.setEditMode(true)
  533. }
  534. let list = UIAction(title: NSLocalizedString("_list_", comment: ""), image: .init(systemName: "list.bullet"), state: layoutForView.layout == NCGlobal.shared.layoutList ? .on : .off) { _ in
  535. self.onListSelected()
  536. self.setNavigationRightItems()
  537. }
  538. let grid = UIAction(title: NSLocalizedString("_icons_", comment: ""), image: .init(systemName: "square.grid.2x2"), state: layoutForView.layout == NCGlobal.shared.layoutGrid ? .on : .off) { _ in
  539. self.onGridSelected()
  540. self.setNavigationRightItems()
  541. }
  542. let viewStyleSubmenu = UIMenu(title: "", options: .displayInline, children: [list, grid])
  543. let ascending = layoutForView.ascending
  544. let ascendingChevronImage = UIImage(systemName: ascending ? "chevron.up" : "chevron.down")
  545. let isName = layoutForView.sort == "fileName"
  546. let isDate = layoutForView.sort == "date"
  547. let isSize = layoutForView.sort == "size"
  548. let byName = UIAction(title: NSLocalizedString("_name_", comment: ""), image: isName ? ascendingChevronImage : nil, state: isName ? .on : .off) { _ in
  549. if isName { // repeated press
  550. layoutForView.ascending = !layoutForView.ascending
  551. }
  552. layoutForView.sort = "fileName"
  553. self.saveLayout(layoutForView)
  554. }
  555. let byNewest = UIAction(title: NSLocalizedString("_date_", comment: ""), image: isDate ? ascendingChevronImage : nil, state: isDate ? .on : .off) { _ in
  556. if isDate { // repeated press
  557. layoutForView.ascending = !layoutForView.ascending
  558. }
  559. layoutForView.sort = "date"
  560. self.saveLayout(layoutForView)
  561. }
  562. let byLargest = UIAction(title: NSLocalizedString("_size_", comment: ""), image: isSize ? ascendingChevronImage : nil, state: isSize ? .on : .off) { _ in
  563. if isSize { // repeated press
  564. layoutForView.ascending = !layoutForView.ascending
  565. }
  566. layoutForView.sort = "size"
  567. self.saveLayout(layoutForView)
  568. }
  569. let sortSubmenu = UIMenu(title: NSLocalizedString("_order_by_", comment: ""), options: .displayInline, children: [byName, byNewest, byLargest])
  570. let foldersOnTop = UIAction(title: NSLocalizedString("_directory_on_top_no_", comment: ""), image: UIImage(systemName: "folder"), state: layoutForView.directoryOnTop ? .on : .off) { _ in
  571. layoutForView.directoryOnTop = !layoutForView.directoryOnTop
  572. self.saveLayout(layoutForView)
  573. }
  574. let personalFilesOnly = NCKeychain().getPersonalFilesOnly(account: appDelegate.account)
  575. let personalFilesOnlyAction = UIAction(title: NSLocalizedString("_personal_files_only_", comment: ""), image: UIImage(systemName: "folder.badge.person.crop"), state: personalFilesOnly ? .on : .off) { _ in
  576. NCKeychain().setPersonalFilesOnly(account: self.appDelegate.account, value: !personalFilesOnly)
  577. self.reloadDataSource()
  578. }
  579. let showDescriptionKeychain = NCKeychain().showDescription
  580. let showDescription = UIAction(title: NSLocalizedString("_show_description_", comment: ""), image: UIImage(systemName: "list.dash.header.rectangle"), attributes: richWorkspaceText == nil ? .disabled : [], state: showDescriptionKeychain && richWorkspaceText != nil ? .on : .off) { _ in
  581. NCKeychain().showDescription = !showDescriptionKeychain
  582. self.collectionView.reloadData()
  583. self.setNavigationRightItems()
  584. }
  585. showDescription.subtitle = richWorkspaceText == nil ? NSLocalizedString("_no_description_available_", comment: "") : ""
  586. if layoutKey == NCGlobal.shared.layoutViewRecent {
  587. return [select]
  588. } else {
  589. var additionalSubmenu = UIMenu()
  590. if layoutKey == NCGlobal.shared.layoutViewFiles {
  591. additionalSubmenu = UIMenu(title: "", options: .displayInline, children: [foldersOnTop, personalFilesOnlyAction, showDescription])
  592. } else {
  593. additionalSubmenu = UIMenu(title: "", options: .displayInline, children: [foldersOnTop, showDescription])
  594. }
  595. return [select, viewStyleSubmenu, sortSubmenu, additionalSubmenu]
  596. }
  597. }
  598. if isEditMode {
  599. tabBarSelect.update(selectOcId: selectOcId, metadatas: getSelectedMetadatas(), userId: appDelegate.userId)
  600. tabBarSelect.show()
  601. let select = UIBarButtonItem(title: NSLocalizedString("_cancel_", comment: ""), style: .done) {
  602. self.setEditMode(false)
  603. }
  604. navigationItem.rightBarButtonItems = [select]
  605. } else {
  606. tabBarSelect.hide()
  607. if navigationItem.rightBarButtonItems == nil || enableMenu {
  608. let menuButton = UIBarButtonItem(image: .init(systemName: "ellipsis.circle"), menu: UIMenu(children: createMenuActions()))
  609. if layoutKey == NCGlobal.shared.layoutViewFiles {
  610. let notification = UIBarButtonItem(image: .init(systemName: "bell"), style: .plain) {
  611. if let viewController = UIStoryboard(name: "NCNotification", bundle: nil).instantiateInitialViewController() as? NCNotification {
  612. self.navigationController?.pushViewController(viewController, animated: true)
  613. }
  614. }
  615. navigationItem.rightBarButtonItems = [menuButton, notification]
  616. } else {
  617. navigationItem.rightBarButtonItems = [menuButton]
  618. }
  619. } else {
  620. navigationItem.rightBarButtonItems?.first?.menu = navigationItem.rightBarButtonItems?.first?.menu?.replacingChildren(createMenuActions())
  621. }
  622. }
  623. // fix, if the tabbar was hidden before the update, set it in hidden
  624. if isTabBarHidden, isTabBarSelectHidden {
  625. self.tabBarController?.tabBar.isHidden = true
  626. }
  627. }
  628. func getNavigationTitle() -> String {
  629. let activeAccount = NCManageDatabase.shared.getActiveAccount()
  630. guard let userAlias = activeAccount?.alias, !userAlias.isEmpty else {
  631. return NCBrandOptions.shared.brand
  632. }
  633. return userAlias
  634. }
  635. // MARK: - SEARCH
  636. func updateSearchResults(for searchController: UISearchController) {
  637. self.literalSearch = searchController.searchBar.text
  638. }
  639. func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
  640. isSearchingMode = true
  641. self.providers?.removeAll()
  642. self.dataSource.clearDataSource()
  643. self.collectionView.reloadData()
  644. // TIP
  645. self.tipView?.dismiss()
  646. }
  647. func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
  648. if isSearchingMode && self.literalSearch?.count ?? 0 >= 2 {
  649. reloadDataSourceNetwork()
  650. }
  651. }
  652. func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
  653. DispatchQueue.global().async {
  654. NCNetworking.shared.cancelUnifiedSearchFiles()
  655. self.isSearchingMode = false
  656. self.literalSearch = ""
  657. self.providers?.removeAll()
  658. self.dataSource.clearDataSource()
  659. self.reloadDataSource()
  660. }
  661. }
  662. // MARK: - TAP EVENT
  663. func accountRequestChangeAccount(account: String) {
  664. appDelegate.changeAccount(account, userProfile: nil)
  665. }
  666. func accountRequestAddAccount() {
  667. appDelegate.openLogin(viewController: self, selector: NCGlobal.shared.introLogin, openLoginWeb: false)
  668. }
  669. func tapButtonOrder(_ sender: Any) {
  670. let sortMenu = NCSortMenu()
  671. sortMenu.toggleMenu(viewController: self, account: appDelegate.account, key: layoutKey, sortButton: sender as? UIButton, serverUrl: serverUrl)
  672. }
  673. func tapMoreListItem(with objectId: String, namedButtonMore: String, image: UIImage?, indexPath: IndexPath, sender: Any) {
  674. tapMoreGridItem(with: objectId, namedButtonMore: namedButtonMore, image: image, indexPath: indexPath, sender: sender)
  675. }
  676. func tapShareListItem(with objectId: String, indexPath: IndexPath, sender: Any) {
  677. if isEditMode { return }
  678. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(objectId) else { return }
  679. NCActionCenter.shared.openShare(viewController: self, metadata: metadata, page: .sharing)
  680. }
  681. func tapMoreGridItem(with objectId: String, namedButtonMore: String, image: UIImage?, indexPath: IndexPath, sender: Any) {
  682. if isEditMode { return }
  683. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(objectId) else { return }
  684. if namedButtonMore == NCGlobal.shared.buttonMoreMore || namedButtonMore == NCGlobal.shared.buttonMoreLock {
  685. toggleMenu(metadata: metadata, indexPath: indexPath, imageIcon: image)
  686. } else if namedButtonMore == NCGlobal.shared.buttonMoreStop {
  687. Task {
  688. await cancelSession(metadata: metadata)
  689. }
  690. }
  691. }
  692. func tapRichWorkspace(_ sender: Any) {
  693. if let navigationController = UIStoryboard(name: "NCViewerRichWorkspace", bundle: nil).instantiateInitialViewController() as? UINavigationController {
  694. if let viewerRichWorkspace = navigationController.topViewController as? NCViewerRichWorkspace {
  695. viewerRichWorkspace.richWorkspaceText = richWorkspaceText ?? ""
  696. viewerRichWorkspace.serverUrl = serverUrl
  697. viewerRichWorkspace.delegate = self
  698. navigationController.modalPresentationStyle = .fullScreen
  699. self.present(navigationController, animated: true, completion: nil)
  700. }
  701. }
  702. }
  703. func tapButtonSection(_ sender: Any, metadataForSection: NCMetadataForSection?) {
  704. unifiedSearchMore(metadataForSection: metadataForSection)
  705. }
  706. func tapButtonTransfer(_ sender: Any) {
  707. if let ocId = NCNetworking.shared.transferInForegorund?.ocId,
  708. let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  709. Task {
  710. await cancelSession(metadata: metadata)
  711. }
  712. }
  713. }
  714. func longPressListItem(with objectId: String, indexPath: IndexPath, gestureRecognizer: UILongPressGestureRecognizer) {
  715. }
  716. func longPressGridItem(with objectId: String, indexPath: IndexPath, gestureRecognizer: UILongPressGestureRecognizer) {
  717. }
  718. func longPressMoreListItem(with objectId: String, namedButtonMore: String, indexPath: IndexPath, gestureRecognizer: UILongPressGestureRecognizer) {
  719. }
  720. func longPressMoreGridItem(with objectId: String, namedButtonMore: String, indexPath: IndexPath, gestureRecognizer: UILongPressGestureRecognizer) {
  721. }
  722. @objc func longPressCollecationView(_ gestureRecognizer: UILongPressGestureRecognizer) {
  723. openMenuItems(with: nil, gestureRecognizer: gestureRecognizer)
  724. }
  725. func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
  726. return UIContextMenuConfiguration(identifier: nil, previewProvider: {
  727. return nil
  728. }, actionProvider: { _ in
  729. return nil
  730. })
  731. }
  732. func openMenuItems(with objectId: String?, gestureRecognizer: UILongPressGestureRecognizer) {
  733. if gestureRecognizer.state != .began { return }
  734. var listMenuItems: [UIMenuItem] = []
  735. let touchPoint = gestureRecognizer.location(in: collectionView)
  736. becomeFirstResponder()
  737. if !serverUrl.isEmpty {
  738. listMenuItems.append(UIMenuItem(title: NSLocalizedString("_paste_file_", comment: ""), action: #selector(pasteFilesMenu)))
  739. }
  740. if !listMenuItems.isEmpty {
  741. UIMenuController.shared.menuItems = listMenuItems
  742. UIMenuController.shared.showMenu(from: collectionView, rect: CGRect(x: touchPoint.x, y: touchPoint.y, width: 0, height: 0))
  743. }
  744. }
  745. // MARK: - Menu Item
  746. override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
  747. if #selector(pasteFilesMenu) == action {
  748. if !UIPasteboard.general.items.isEmpty, !(metadataFolder?.e2eEncrypted ?? false) {
  749. return true
  750. }
  751. }
  752. return false
  753. }
  754. @objc func pasteFilesMenu() {
  755. NCActionCenter.shared.pastePasteboard(serverUrl: serverUrl)
  756. }
  757. // MARK: - DataSource + NC Endpoint
  758. func queryDB() { }
  759. @objc func reloadDataSource(withQueryDB: Bool = true) {
  760. guard !appDelegate.account.isEmpty, !self.isSearchingMode else { return }
  761. // get auto upload folder
  762. autoUploadFileName = NCManageDatabase.shared.getAccountAutoUploadFileName()
  763. autoUploadDirectory = NCManageDatabase.shared.getAccountAutoUploadDirectory(urlBase: appDelegate.urlBase, userId: appDelegate.userId, account: appDelegate.account)
  764. // get layout for view
  765. layoutForView = NCManageDatabase.shared.getLayoutForView(account: appDelegate.account, key: layoutKey, serverUrl: serverUrl)
  766. // set GroupField for Grid
  767. if !isSearchingMode && layoutForView?.layout == NCGlobal.shared.layoutGrid {
  768. groupByField = "classFile"
  769. } else {
  770. groupByField = "name"
  771. }
  772. DispatchQueue.global().async {
  773. if withQueryDB { self.queryDB() }
  774. DispatchQueue.main.async {
  775. self.refreshControl.endRefreshing()
  776. self.collectionView.reloadData()
  777. self.setNavigationRightItems()
  778. }
  779. }
  780. }
  781. @objc func reloadDataSourceNetwork() {
  782. DispatchQueue.main.async {
  783. self.collectionView?.reloadData()
  784. }
  785. }
  786. @objc func networkSearch() {
  787. guard !appDelegate.account.isEmpty, let literalSearch = literalSearch, !literalSearch.isEmpty
  788. else { return self.refreshControl.endRefreshing() }
  789. self.dataSource.clearDataSource()
  790. self.refreshControl.beginRefreshing()
  791. self.collectionView.reloadData()
  792. if NCGlobal.shared.capabilityServerVersionMajor >= NCGlobal.shared.nextcloudVersion20 {
  793. NCNetworking.shared.unifiedSearchFiles(userBaseUrl: appDelegate, literal: literalSearch) { task in
  794. self.dataSourceTask = task
  795. self.collectionView.reloadData()
  796. } providers: { _, searchProviders in
  797. self.providers = searchProviders
  798. self.searchResults = []
  799. self.dataSource = NCDataSource(
  800. metadatas: [],
  801. account: self.appDelegate.account,
  802. sort: self.layoutForView?.sort,
  803. ascending: self.layoutForView?.ascending,
  804. directoryOnTop: self.layoutForView?.directoryOnTop,
  805. favoriteOnTop: true,
  806. providers: self.providers,
  807. searchResults: self.searchResults)
  808. } update: { _, _, searchResult, metadatas in
  809. guard let metadatas, !metadatas.isEmpty, self.isSearchingMode, let searchResult else { return }
  810. NCNetworking.shared.unifiedSearchQueue.addOperation(NCCollectionViewUnifiedSearch(collectionViewCommon: self, metadatas: metadatas, searchResult: searchResult))
  811. } completion: { _, _ in
  812. self.refreshControl.endRefreshing()
  813. self.collectionView.reloadData()
  814. }
  815. } else {
  816. NCNetworking.shared.searchFiles(urlBase: appDelegate, literal: literalSearch) { task in
  817. self.dataSourceTask = task
  818. self.collectionView.reloadData()
  819. } completion: { metadatas, error in
  820. DispatchQueue.main.async {
  821. self.refreshControl.endRefreshing()
  822. self.collectionView.reloadData()
  823. }
  824. guard let metadatas = metadatas, error == .success, self.isSearchingMode else { return }
  825. self.dataSource = NCDataSource(
  826. metadatas: metadatas,
  827. account: self.appDelegate.account,
  828. sort: self.layoutForView?.sort,
  829. ascending: self.layoutForView?.ascending,
  830. directoryOnTop: self.layoutForView?.directoryOnTop,
  831. favoriteOnTop: true,
  832. groupByField: self.groupByField,
  833. providers: self.providers,
  834. searchResults: self.searchResults)
  835. }
  836. }
  837. }
  838. func unifiedSearchMore(metadataForSection: NCMetadataForSection?) {
  839. guard let metadataForSection = metadataForSection, let lastSearchResult = metadataForSection.lastSearchResult, let cursor = lastSearchResult.cursor, let term = literalSearch else { return }
  840. metadataForSection.unifiedSearchInProgress = true
  841. self.collectionView?.reloadData()
  842. NCNetworking.shared.unifiedSearchFilesProvider(userBaseUrl: appDelegate, id: lastSearchResult.id, term: term, limit: 5, cursor: cursor) { task in
  843. self.dataSourceTask = task
  844. self.collectionView.reloadData()
  845. } completion: { _, searchResult, metadatas, error in
  846. if error != .success {
  847. NCContentPresenter().showError(error: error)
  848. }
  849. metadataForSection.unifiedSearchInProgress = false
  850. guard let searchResult = searchResult, let metadatas = metadatas else { return }
  851. self.dataSource.appendMetadatasToSection(metadatas, metadataForSection: metadataForSection, lastSearchResult: searchResult)
  852. DispatchQueue.main.async {
  853. self.collectionView?.reloadData()
  854. }
  855. }
  856. }
  857. // MARK: - Push metadata
  858. func pushMetadata(_ metadata: tableMetadata) {
  859. let serverUrlPush = utilityFileSystem.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)
  860. appDelegate.activeMetadata = metadata
  861. if let viewController = appDelegate.listFilesVC[serverUrlPush], viewController.isViewLoaded {
  862. navigationController?.pushViewController(viewController, animated: true)
  863. } else {
  864. if let viewController: NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as? NCFiles {
  865. viewController.isRoot = false
  866. viewController.serverUrl = serverUrlPush
  867. viewController.titlePreviusFolder = navigationItem.title
  868. viewController.titleCurrentFolder = metadata.fileNameView
  869. appDelegate.listFilesVC[serverUrlPush] = viewController
  870. navigationController?.pushViewController(viewController, animated: true)
  871. }
  872. }
  873. }
  874. }
  875. // MARK: - E2EE
  876. extension NCCollectionViewCommon: NCEndToEndInitializeDelegate {
  877. func endToEndInitializeSuccess() {
  878. if let metadata = appDelegate.activeMetadata {
  879. pushMetadata(metadata)
  880. }
  881. }
  882. }
  883. // MARK: - Collection View
  884. extension NCCollectionViewCommon: UICollectionViewDelegate {
  885. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  886. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  887. appDelegate.activeMetadata = metadata
  888. if isEditMode {
  889. if let index = selectOcId.firstIndex(of: metadata.ocId) {
  890. selectOcId.remove(at: index)
  891. } else {
  892. selectOcId.append(metadata.ocId)
  893. }
  894. collectionView.reloadItems(at: [indexPath])
  895. tabBarSelect.update(selectOcId: selectOcId, metadatas: getSelectedMetadatas(), userId: appDelegate.userId)
  896. return
  897. }
  898. if metadata.e2eEncrypted {
  899. if NCGlobal.shared.capabilityE2EEEnabled {
  900. if !NCKeychain().isEndToEndEnabled(account: appDelegate.account) {
  901. let e2ee = NCEndToEndInitialize()
  902. e2ee.delegate = self
  903. e2ee.initEndToEndEncryption()
  904. return
  905. }
  906. } else {
  907. NCContentPresenter().showInfo(error: NKError(errorCode: NCGlobal.shared.errorE2EENotEnabled, errorDescription: "_e2e_server_disabled_"))
  908. return
  909. }
  910. }
  911. if metadata.directory {
  912. pushMetadata(metadata)
  913. } else {
  914. let imageIcon = UIImage(contentsOfFile: utilityFileSystem.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  915. if !metadata.isDirectoryE2EE && (metadata.isImage || metadata.isAudioOrVideo) {
  916. var metadatas: [tableMetadata] = []
  917. for metadata in dataSource.getMetadataSourceForAllSections() {
  918. if metadata.isImage || metadata.isAudioOrVideo {
  919. metadatas.append(metadata)
  920. }
  921. }
  922. NCViewer().view(viewController: self, metadata: metadata, metadatas: metadatas, imageIcon: imageIcon)
  923. return
  924. }
  925. if utilityFileSystem.fileProviderStorageExists(metadata) {
  926. NCViewer().view(viewController: self, metadata: metadata, metadatas: [metadata], imageIcon: imageIcon)
  927. } else if NextcloudKit.shared.isNetworkReachable(),
  928. let metadata = NCManageDatabase.shared.setMetadatasSessionInWaitDownload(metadatas: [metadata],
  929. session: NextcloudKit.shared.nkCommonInstance.sessionIdentifierDownload,
  930. selector: NCGlobal.shared.selectorLoadFileView) {
  931. NCNetworking.shared.download(metadata: metadata, withNotificationProgressTask: true)
  932. } else {
  933. let error = NKError(errorCode: NCGlobal.shared.errorOffline, errorDescription: "_go_online_")
  934. NCContentPresenter().showInfo(error: error)
  935. }
  936. }
  937. }
  938. func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
  939. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return nil }
  940. if isEditMode || metadata.classFile == NKCommon.TypeClassFile.url.rawValue { return nil }
  941. let identifier = indexPath as NSCopying
  942. var image: UIImage?
  943. let cell = collectionView.cellForItem(at: indexPath)
  944. if cell is NCListCell {
  945. image = (cell as? NCListCell)?.imageItem.image
  946. } else if cell is NCGridCell {
  947. image = (cell as? NCGridCell)?.imageItem.image
  948. }
  949. return UIContextMenuConfiguration(identifier: identifier, previewProvider: {
  950. return NCViewerProviderContextMenu(metadata: metadata, image: image)
  951. }, actionProvider: { _ in
  952. return NCContextMenu().viewMenu(ocId: metadata.ocId, viewController: self, image: image)
  953. })
  954. }
  955. func collectionView(_ collectionView: UICollectionView, willPerformPreviewActionForMenuWith configuration: UIContextMenuConfiguration, animator: UIContextMenuInteractionCommitAnimating) {
  956. animator.addCompletion {
  957. if let indexPath = configuration.identifier as? IndexPath {
  958. self.collectionView(collectionView, didSelectItemAt: indexPath)
  959. }
  960. }
  961. }
  962. }
  963. extension NCCollectionViewCommon: UICollectionViewDataSource {
  964. func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  965. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath),
  966. let cell = (cell as? NCCellProtocol) else { return }
  967. cell.filePreviewImageView?.layer.borderWidth = 0
  968. if metadata.isImage {
  969. cell.filePreviewImageView?.contentMode = .scaleAspectFill
  970. } else {
  971. cell.filePreviewImageView?.contentMode = .scaleAspectFit
  972. }
  973. // Thumbnail
  974. if !metadata.directory {
  975. if metadata.hasPreviewBorder {
  976. cell.filePreviewImageView?.layer.borderWidth = 0.2
  977. cell.filePreviewImageView?.layer.borderColor = UIColor.systemGray3.cgColor
  978. }
  979. if metadata.name == NCGlobal.shared.appName {
  980. if let image = utility.createFilePreviewImage(ocId: metadata.ocId, etag: metadata.etag, fileNameView: metadata.fileNameView, classFile: metadata.classFile, status: metadata.status, createPreviewMedia: !metadata.hasPreview) {
  981. cell.filePreviewImageView?.image = image
  982. } else {
  983. if metadata.iconName.isEmpty {
  984. cell.filePreviewImageView?.image = NCImageCache.images.file
  985. } else {
  986. cell.filePreviewImageView?.image = UIImage(named: metadata.iconName)
  987. }
  988. if metadata.hasPreview && metadata.status == NCGlobal.shared.metadataStatusNormal && (!utilityFileSystem.fileProviderStoragePreviewIconExists(metadata.ocId, etag: metadata.etag)) {
  989. for case let operation as NCCollectionViewDownloadThumbnail in NCNetworking.shared.downloadThumbnailQueue.operations where operation.metadata.ocId == metadata.ocId { return }
  990. NCNetworking.shared.downloadThumbnailQueue.addOperation(NCCollectionViewDownloadThumbnail(metadata: metadata, cell: cell, collectionView: collectionView))
  991. }
  992. }
  993. } else {
  994. // Unified search
  995. switch metadata.iconName {
  996. case let str where str.contains("contacts"):
  997. cell.filePreviewImageView?.image = NCImageCache.images.iconContacts
  998. case let str where str.contains("conversation"):
  999. cell.filePreviewImageView?.image = NCImageCache.images.iconTalk
  1000. case let str where str.contains("calendar"):
  1001. cell.filePreviewImageView?.image = NCImageCache.images.iconCalendar
  1002. case let str where str.contains("deck"):
  1003. cell.filePreviewImageView?.image = NCImageCache.images.iconDeck
  1004. case let str where str.contains("mail"):
  1005. cell.filePreviewImageView?.image = NCImageCache.images.iconMail
  1006. case let str where str.contains("talk"):
  1007. cell.filePreviewImageView?.image = NCImageCache.images.iconTalk
  1008. case let str where str.contains("confirm"):
  1009. cell.filePreviewImageView?.image = NCImageCache.images.iconConfirm
  1010. case let str where str.contains("pages"):
  1011. cell.filePreviewImageView?.image = NCImageCache.images.iconPages
  1012. default:
  1013. cell.filePreviewImageView?.image = NCImageCache.images.file
  1014. }
  1015. if !metadata.iconUrl.isEmpty {
  1016. if let ownerId = getAvatarFromIconUrl(metadata: metadata) {
  1017. let fileName = metadata.userBaseUrl + "-" + ownerId + ".png"
  1018. NCNetworking.shared.downloadAvatar(user: ownerId, dispalyName: nil, fileName: fileName, cell: cell, view: collectionView, cellImageView: cell.filePreviewImageView)
  1019. }
  1020. }
  1021. }
  1022. }
  1023. // Avatar
  1024. if !metadata.ownerId.isEmpty,
  1025. metadata.ownerId != appDelegate.userId,
  1026. appDelegate.account == metadata.account {
  1027. let fileName = metadata.userBaseUrl + "-" + metadata.ownerId + ".png"
  1028. NCNetworking.shared.downloadAvatar(user: metadata.ownerId, dispalyName: metadata.ownerDisplayName, fileName: fileName, cell: cell, view: collectionView, cellImageView: cell.fileAvatarImageView)
  1029. }
  1030. }
  1031. func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  1032. if !collectionView.indexPathsForVisibleItems.contains(indexPath) {
  1033. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  1034. for case let operation as NCCollectionViewDownloadThumbnail in NCNetworking.shared.downloadThumbnailQueue.operations where operation.metadata.ocId == metadata.ocId {
  1035. operation.cancel()
  1036. }
  1037. }
  1038. }
  1039. func numberOfSections(in collectionView: UICollectionView) -> Int {
  1040. return dataSource.numberOfSections()
  1041. }
  1042. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  1043. return dataSource.numberOfItemsInSection(section)
  1044. }
  1045. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  1046. var cell: NCCellProtocol & UICollectionViewCell
  1047. // LAYOUT LIST
  1048. if layoutForView?.layout == NCGlobal.shared.layoutList {
  1049. guard let listCell = collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as? NCListCell else { return NCListCell() }
  1050. listCell.listCellDelegate = self
  1051. cell = listCell
  1052. } else {
  1053. // LAYOUT GRID
  1054. guard let gridCell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as? NCGridCell else { return NCGridCell() }
  1055. gridCell.gridCellDelegate = self
  1056. cell = gridCell
  1057. }
  1058. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return cell }
  1059. defer {
  1060. if appDelegate.disableSharesView || !metadata.isSharable() {
  1061. cell.hideButtonShare(true)
  1062. }
  1063. }
  1064. var isShare = false
  1065. var isMounted = false
  1066. var a11yValues: [String] = []
  1067. if metadataFolder != nil {
  1068. isShare = metadata.permissions.contains(NCGlobal.shared.permissionShared) && !metadataFolder!.permissions.contains(NCGlobal.shared.permissionShared)
  1069. isMounted = metadata.permissions.contains(NCGlobal.shared.permissionMounted) && !metadataFolder!.permissions.contains(NCGlobal.shared.permissionMounted)
  1070. }
  1071. cell.fileSelectImage?.image = nil
  1072. cell.fileStatusImage?.image = nil
  1073. cell.fileLocalImage?.image = nil
  1074. cell.fileFavoriteImage?.image = nil
  1075. cell.fileSharedImage?.image = nil
  1076. cell.fileMoreImage?.image = nil
  1077. cell.filePreviewImageView?.image = nil
  1078. cell.filePreviewImageView?.backgroundColor = nil
  1079. cell.fileObjectId = metadata.ocId
  1080. cell.indexPath = indexPath
  1081. cell.fileUser = metadata.ownerId
  1082. cell.fileProgressView?.isHidden = true
  1083. cell.fileProgressView?.progress = 0.0
  1084. cell.hideButtonShare(false)
  1085. cell.hideButtonMore(false)
  1086. cell.titleInfoTrailingDefault()
  1087. if isSearchingMode {
  1088. cell.fileTitleLabel?.text = metadata.fileName
  1089. cell.fileTitleLabel?.lineBreakMode = .byTruncatingTail
  1090. if metadata.name == NCGlobal.shared.appName {
  1091. cell.fileInfoLabel?.text = NSLocalizedString("_in_", comment: "") + " " + utilityFileSystem.getPath(path: metadata.path, user: metadata.user)
  1092. } else {
  1093. cell.fileInfoLabel?.text = metadata.subline
  1094. }
  1095. cell.fileSubinfoLabel?.isHidden = true
  1096. } else {
  1097. cell.fileSubinfoLabel?.isHidden = false
  1098. cell.fileTitleLabel?.text = metadata.fileNameView
  1099. cell.fileTitleLabel?.lineBreakMode = .byTruncatingMiddle
  1100. cell.writeInfoDateSize(date: metadata.date, size: metadata.size)
  1101. }
  1102. if metadata.status == NCGlobal.shared.metadataStatusDownloading || metadata.status == NCGlobal.shared.metadataStatusUploading {
  1103. cell.fileProgressView?.isHidden = false
  1104. }
  1105. // Accessibility [shared]
  1106. if metadata.ownerId != appDelegate.userId, appDelegate.account == metadata.account {
  1107. a11yValues.append(NSLocalizedString("_shared_with_you_by_", comment: "") + " " + metadata.ownerDisplayName)
  1108. }
  1109. if metadata.directory {
  1110. let tableDirectory = NCManageDatabase.shared.getTableDirectory(ocId: metadata.ocId)
  1111. if metadata.e2eEncrypted {
  1112. cell.filePreviewImageView?.image = NCImageCache.images.folderEncrypted
  1113. } else if isShare {
  1114. cell.filePreviewImageView?.image = NCImageCache.images.folderSharedWithMe
  1115. } else if !metadata.shareType.isEmpty {
  1116. metadata.shareType.contains(3) ?
  1117. (cell.filePreviewImageView?.image = NCImageCache.images.folderPublic) :
  1118. (cell.filePreviewImageView?.image = NCImageCache.images.folderSharedWithMe)
  1119. } else if !metadata.shareType.isEmpty && metadata.shareType.contains(3) {
  1120. cell.filePreviewImageView?.image = NCImageCache.images.folderPublic
  1121. } else if metadata.mountType == "group" {
  1122. cell.filePreviewImageView?.image = NCImageCache.images.folderGroup
  1123. } else if isMounted {
  1124. cell.filePreviewImageView?.image = NCImageCache.images.folderExternal
  1125. } else if metadata.fileName == autoUploadFileName && metadata.serverUrl == autoUploadDirectory {
  1126. cell.filePreviewImageView?.image = NCImageCache.images.folderAutomaticUpload
  1127. } else {
  1128. cell.filePreviewImageView?.image = NCImageCache.images.folder
  1129. }
  1130. // Local image: offline
  1131. if let tableDirectory, tableDirectory.offline {
  1132. cell.fileLocalImage?.image = NCImageCache.images.offlineFlag
  1133. }
  1134. // color folder
  1135. cell.filePreviewImageView?.image = cell.filePreviewImageView?.image?.colorizeFolder(metadata: metadata, tableDirectory: tableDirectory)
  1136. } else {
  1137. let tableLocalFile = NCManageDatabase.shared.getResultsTableLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))?.first
  1138. // image local
  1139. if let tableLocalFile, tableLocalFile.offline {
  1140. a11yValues.append(NSLocalizedString("_offline_", comment: ""))
  1141. cell.fileLocalImage?.image = NCImageCache.images.offlineFlag
  1142. } else if utilityFileSystem.fileProviderStorageExists(metadata) {
  1143. cell.fileLocalImage?.image = NCImageCache.images.local
  1144. }
  1145. }
  1146. // image Favorite
  1147. if metadata.favorite {
  1148. cell.fileFavoriteImage?.image = NCImageCache.images.favorite
  1149. a11yValues.append(NSLocalizedString("_favorite_short_", comment: ""))
  1150. }
  1151. // Share image
  1152. if isShare {
  1153. cell.fileSharedImage?.image = NCImageCache.images.shared
  1154. } else if !metadata.shareType.isEmpty {
  1155. metadata.shareType.contains(3) ?
  1156. (cell.fileSharedImage?.image = NCImageCache.images.shareByLink) :
  1157. (cell.fileSharedImage?.image = NCImageCache.images.shared)
  1158. } else {
  1159. cell.fileSharedImage?.image = NCImageCache.images.canShare
  1160. }
  1161. if appDelegate.account != metadata.account {
  1162. cell.fileSharedImage?.image = NCImageCache.images.shared
  1163. }
  1164. // Button More
  1165. if metadata.isInTransfer || metadata.isWaitingTransfer {
  1166. cell.setButtonMore(named: NCGlobal.shared.buttonMoreStop, image: NCImageCache.images.buttonStop)
  1167. } else if metadata.lock == true {
  1168. cell.setButtonMore(named: NCGlobal.shared.buttonMoreLock, image: NCImageCache.images.buttonMoreLock)
  1169. a11yValues.append(String(format: NSLocalizedString("_locked_by_", comment: ""), metadata.lockOwnerDisplayName))
  1170. } else {
  1171. cell.setButtonMore(named: NCGlobal.shared.buttonMoreMore, image: NCImageCache.images.buttonMore)
  1172. }
  1173. // Write status on Label Info
  1174. switch metadata.status {
  1175. case NCGlobal.shared.metadataStatusWaitDownload:
  1176. cell.fileInfoLabel?.text = utilityFileSystem.transformedSize(metadata.size)
  1177. cell.fileSubinfoLabel?.text = infoLabelsSeparator + NSLocalizedString("_status_wait_download_", comment: "")
  1178. case NCGlobal.shared.metadataStatusDownloading:
  1179. cell.fileInfoLabel?.text = utilityFileSystem.transformedSize(metadata.size)
  1180. cell.fileSubinfoLabel?.text = infoLabelsSeparator + "↓ …"
  1181. case NCGlobal.shared.metadataStatusWaitUpload:
  1182. cell.fileInfoLabel?.text = utilityFileSystem.transformedSize(metadata.size)
  1183. cell.fileSubinfoLabel?.text = infoLabelsSeparator + NSLocalizedString("_status_wait_upload_", comment: "")
  1184. cell.fileLocalImage?.image = nil
  1185. case NCGlobal.shared.metadataStatusUploading:
  1186. cell.fileInfoLabel?.text = utilityFileSystem.transformedSize(metadata.size)
  1187. cell.fileSubinfoLabel?.text = infoLabelsSeparator + "↑ …"
  1188. cell.fileLocalImage?.image = nil
  1189. case NCGlobal.shared.metadataStatusUploadError:
  1190. if metadata.sessionError.isEmpty {
  1191. cell.fileInfoLabel?.text = NSLocalizedString("_status_wait_upload_", comment: "")
  1192. } else {
  1193. cell.fileInfoLabel?.text = NSLocalizedString("_status_wait_upload_", comment: "") + " " + metadata.sessionError
  1194. }
  1195. default:
  1196. break
  1197. }
  1198. // Live Photo
  1199. if metadata.isLivePhoto {
  1200. cell.fileStatusImage?.image = NCImageCache.images.livePhoto
  1201. a11yValues.append(NSLocalizedString("_upload_mov_livephoto_", comment: ""))
  1202. }
  1203. // URL
  1204. if metadata.classFile == NKCommon.TypeClassFile.url.rawValue {
  1205. cell.fileLocalImage?.image = nil
  1206. cell.hideButtonShare(true)
  1207. cell.hideButtonMore(true)
  1208. if let ownerId = getAvatarFromIconUrl(metadata: metadata) {
  1209. cell.fileUser = ownerId
  1210. }
  1211. }
  1212. // Separator
  1213. if collectionView.numberOfItems(inSection: indexPath.section) == indexPath.row + 1 || isSearchingMode {
  1214. cell.cellSeparatorView?.isHidden = true
  1215. } else {
  1216. cell.cellSeparatorView?.isHidden = false
  1217. }
  1218. // Edit mode
  1219. if isEditMode {
  1220. cell.selectMode(true)
  1221. if selectOcId.contains(metadata.ocId) {
  1222. cell.selected(true)
  1223. a11yValues.append(NSLocalizedString("_selected_", comment: ""))
  1224. } else {
  1225. cell.selected(false)
  1226. }
  1227. } else {
  1228. cell.selectMode(false)
  1229. }
  1230. // Accessibility
  1231. cell.setAccessibility(label: metadata.fileNameView + ", " + (cell.fileInfoLabel?.text ?? "") + (cell.fileSubinfoLabel?.text ?? ""), value: a11yValues.joined(separator: ", "))
  1232. // Color string find in search
  1233. cell.fileTitleLabel?.textColor = .label
  1234. cell.fileTitleLabel?.font = .systemFont(ofSize: 15)
  1235. if isSearchingMode, let literalSearch = self.literalSearch, let title = cell.fileTitleLabel?.text {
  1236. let longestWordRange = (title.lowercased() as NSString).range(of: literalSearch)
  1237. let attributedString = NSMutableAttributedString(string: title, attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 15)])
  1238. attributedString.setAttributes([NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 15), NSAttributedString.Key.foregroundColor: UIColor.systemBlue], range: longestWordRange)
  1239. cell.fileTitleLabel?.attributedText = attributedString
  1240. }
  1241. // Add TAGS
  1242. cell.setTags(tags: Array(metadata.tags))
  1243. // Hide buttons
  1244. if metadata.name != NCGlobal.shared.appName {
  1245. cell.titleInfoTrailingFull()
  1246. cell.hideButtonShare(true)
  1247. cell.hideButtonMore(true)
  1248. }
  1249. cell.setIconOutlines()
  1250. return cell
  1251. }
  1252. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  1253. if kind == UICollectionView.elementKindSectionHeader {
  1254. if dataSource.getMetadataSourceForAllSections().isEmpty {
  1255. guard let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeaderEmptyData", for: indexPath) as? NCSectionHeaderEmptyData else { return NCSectionHeaderEmptyData() }
  1256. header.delegate = self
  1257. if !isSearchingMode, headerMenuTransferView, let ocId = NCNetworking.shared.transferInForegorund?.ocId {
  1258. let text = String(format: NSLocalizedString("_upload_foreground_msg_", comment: ""), NCBrandOptions.shared.brand)
  1259. header.setViewTransfer(isHidden: false, ocId: ocId, text: text, progress: NCNetworking.shared.transferInForegorund?.progress)
  1260. } else {
  1261. header.setViewTransfer(isHidden: true)
  1262. }
  1263. if isSearchingMode {
  1264. header.emptyImage.image = UIImage(named: "search")?.image(color: .gray, size: UIScreen.main.bounds.width)
  1265. if self.dataSourceTask?.state == .running {
  1266. header.emptyTitle.text = NSLocalizedString("_search_in_progress_", comment: "")
  1267. } else {
  1268. header.emptyTitle.text = NSLocalizedString("_search_no_record_found_", comment: "")
  1269. }
  1270. header.emptyDescription.text = NSLocalizedString("_search_instruction_", comment: "")
  1271. } else if self.dataSourceTask?.state == .running {
  1272. header.emptyImage.image = UIImage(named: "networkInProgress")?.image(color: .gray, size: UIScreen.main.bounds.width)
  1273. header.emptyTitle.text = NSLocalizedString("_request_in_progress_", comment: "")
  1274. header.emptyDescription.text = ""
  1275. } else {
  1276. if serverUrl.isEmpty {
  1277. header.emptyImage.image = emptyImage
  1278. header.emptyTitle.text = NSLocalizedString(emptyTitle, comment: "")
  1279. header.emptyDescription.text = NSLocalizedString(emptyDescription, comment: "")
  1280. } else {
  1281. header.emptyImage.image = UIImage(named: "folder")?.image(color: NCBrandColor.shared.brandElement, size: UIScreen.main.bounds.width)
  1282. header.emptyTitle.text = NSLocalizedString("_files_no_files_", comment: "")
  1283. header.emptyDescription.text = NSLocalizedString("_no_file_pull_down_", comment: "")
  1284. }
  1285. }
  1286. return header
  1287. } else if indexPath.section == 0 {
  1288. guard let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeaderMenu", for: indexPath) as? NCSectionHeaderMenu else { return NCSectionHeaderMenu() }
  1289. let (_, heightHeaderRichWorkspace, heightHeaderSection) = getHeaderHeight(section: indexPath.section)
  1290. self.headerMenu = header
  1291. header.delegate = self
  1292. if !isSearchingMode, headerMenuTransferView, let ocId = NCNetworking.shared.transferInForegorund?.ocId {
  1293. let text = String(format: NSLocalizedString("_upload_foreground_msg_", comment: ""), NCBrandOptions.shared.brand)
  1294. header.setViewTransfer(isHidden: false, ocId: ocId, text: text, progress: NCNetworking.shared.transferInForegorund?.progress)
  1295. } else {
  1296. header.setViewTransfer(isHidden: true)
  1297. }
  1298. header.setRichWorkspaceHeight(heightHeaderRichWorkspace)
  1299. header.setRichWorkspaceText(richWorkspaceText)
  1300. header.setSectionHeight(heightHeaderSection)
  1301. if heightHeaderSection == 0 {
  1302. header.labelSection.text = ""
  1303. } else {
  1304. header.labelSection.text = self.dataSource.getSectionValueLocalization(indexPath: indexPath)
  1305. }
  1306. header.labelSection.textColor = .label
  1307. return header
  1308. } else {
  1309. guard let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeader", for: indexPath) as? NCSectionHeader else { return NCSectionHeader() }
  1310. header.labelSection.text = self.dataSource.getSectionValueLocalization(indexPath: indexPath)
  1311. header.labelSection.textColor = .label
  1312. return header
  1313. }
  1314. } else {
  1315. guard let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as? NCSectionFooter else { return NCSectionFooter() }
  1316. let sections = dataSource.numberOfSections()
  1317. let section = indexPath.section
  1318. let metadataForSection = self.dataSource.getMetadataForSection(indexPath.section)
  1319. let isPaginated = metadataForSection?.lastSearchResult?.isPaginated ?? false
  1320. let metadatasCount: Int = metadataForSection?.metadatas.count ?? 0
  1321. let unifiedSearchInProgress = metadataForSection?.unifiedSearchInProgress ?? false
  1322. footer.delegate = self
  1323. footer.metadataForSection = metadataForSection
  1324. footer.setTitleLabel("")
  1325. footer.setButtonText(NSLocalizedString("_show_more_results_", comment: ""))
  1326. footer.separatorIsHidden(true)
  1327. footer.buttonIsHidden(true)
  1328. footer.hideActivityIndicatorSection()
  1329. if isSearchingMode {
  1330. if sections > 1 && section != sections - 1 {
  1331. footer.separatorIsHidden(false)
  1332. }
  1333. // If the number of entries(metadatas) is lower than the cursor, then there are no more entries.
  1334. // The blind spot in this is when the number of entries is the same as the cursor. If so, we don't have a way of knowing if there are no more entries.
  1335. // This is as good as it gets for determining last page without server-side flag.
  1336. let isLastPage = (metadatasCount < metadataForSection?.lastSearchResult?.cursor ?? 0) || metadataForSection?.lastSearchResult?.entries.isEmpty == true
  1337. if isSearchingMode && isPaginated && metadatasCount > 0 && !isLastPage {
  1338. footer.buttonIsHidden(false)
  1339. }
  1340. if unifiedSearchInProgress {
  1341. footer.showActivityIndicatorSection()
  1342. }
  1343. } else {
  1344. if sections == 1 || section == sections - 1 {
  1345. let info = dataSource.getFooterInformationAllMetadatas()
  1346. footer.setTitleLabel(directories: info.directories, files: info.files, size: info.size)
  1347. } else {
  1348. footer.separatorIsHidden(false)
  1349. }
  1350. }
  1351. return footer
  1352. }
  1353. }
  1354. }
  1355. extension NCCollectionViewCommon: UICollectionViewDelegateFlowLayout {
  1356. func isHeaderMenuTransferViewEnabled() -> Bool {
  1357. if headerMenuTransferView, let metadata = NCManageDatabase.shared.getMetadataFromOcId(NCNetworking.shared.transferInForegorund?.ocId), metadata.isTransferInForeground {
  1358. return true
  1359. }
  1360. return false
  1361. }
  1362. func getHeaderHeight() -> CGFloat {
  1363. var size: CGFloat = 0
  1364. if isHeaderMenuTransferViewEnabled() {
  1365. if !isSearchingMode {
  1366. size += NCGlobal.shared.heightHeaderTransfer
  1367. }
  1368. } else {
  1369. NCNetworking.shared.transferInForegorund = nil
  1370. }
  1371. return size
  1372. }
  1373. func getHeaderHeight(section: Int) -> (heightHeaderCommands: CGFloat, heightHeaderRichWorkspace: CGFloat, heightHeaderSection: CGFloat) {
  1374. var headerRichWorkspace: CGFloat = 0
  1375. if let richWorkspaceText = richWorkspaceText, showDescription {
  1376. let trimmed = richWorkspaceText.trimmingCharacters(in: .whitespaces)
  1377. if !trimmed.isEmpty && !isSearchingMode {
  1378. headerRichWorkspace = UIScreen.main.bounds.size.height / 6
  1379. }
  1380. }
  1381. if isSearchingMode || layoutForView?.layout == NCGlobal.shared.layoutGrid || dataSource.numberOfSections() > 1 {
  1382. if section == 0 {
  1383. return (getHeaderHeight(), headerRichWorkspace, NCGlobal.shared.heightSection)
  1384. } else {
  1385. return (0, 0, NCGlobal.shared.heightSection)
  1386. }
  1387. } else {
  1388. return (getHeaderHeight(), headerRichWorkspace, 0)
  1389. }
  1390. }
  1391. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  1392. var height: CGFloat = 0
  1393. if dataSource.getMetadataSourceForAllSections().isEmpty {
  1394. height = NCGlobal.shared.getHeightHeaderEmptyData(view: view, portraitOffset: emptyDataPortaitOffset, landscapeOffset: emptyDataLandscapeOffset, isHeaderMenuTransferViewEnabled: isHeaderMenuTransferViewEnabled())
  1395. } else {
  1396. let (heightHeaderCommands, heightHeaderRichWorkspace, heightHeaderSection) = getHeaderHeight(section: section)
  1397. height = heightHeaderCommands + heightHeaderRichWorkspace + heightHeaderSection
  1398. }
  1399. return CGSize(width: collectionView.frame.width, height: height)
  1400. }
  1401. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  1402. let sections = dataSource.numberOfSections()
  1403. let metadataForSection = self.dataSource.getMetadataForSection(section)
  1404. let isPaginated = metadataForSection?.lastSearchResult?.isPaginated ?? false
  1405. let metadatasCount: Int = metadataForSection?.lastSearchResult?.entries.count ?? 0
  1406. var size = CGSize(width: collectionView.frame.width, height: 0)
  1407. if section == sections - 1 {
  1408. size.height += NCGlobal.shared.endHeightFooter
  1409. } else {
  1410. size.height += NCGlobal.shared.heightFooter
  1411. }
  1412. if isSearchingMode && isPaginated && metadatasCount > 0 {
  1413. size.height += NCGlobal.shared.heightFooterButton
  1414. }
  1415. return size
  1416. }
  1417. }
  1418. extension NCCollectionViewCommon: EasyTipViewDelegate {
  1419. func easyTipViewDidTap(_ tipView: EasyTipView) {
  1420. NCManageDatabase.shared.addTip(NCGlobal.shared.tipNCCollectionViewCommonAccountRequest)
  1421. }
  1422. func easyTipViewDidDismiss(_ tipView: EasyTipView) { }
  1423. func dismissTip() {
  1424. NCManageDatabase.shared.addTip(NCGlobal.shared.tipNCCollectionViewCommonAccountRequest)
  1425. self.tipView?.dismiss()
  1426. }
  1427. }
  1428. extension NCCollectionViewCommon {
  1429. func getAvatarFromIconUrl(metadata: tableMetadata) -> String? {
  1430. var ownerId: String?
  1431. if metadata.iconUrl.contains("http") && metadata.iconUrl.contains("avatar") {
  1432. let splitIconUrl = metadata.iconUrl.components(separatedBy: "/")
  1433. var found: Bool = false
  1434. for item in splitIconUrl {
  1435. if found {
  1436. ownerId = item
  1437. break
  1438. }
  1439. if item == "avatar" { found = true}
  1440. }
  1441. }
  1442. return ownerId
  1443. }
  1444. // MARK: - Cancel (Download Upload)
  1445. // sessionIdentifierDownload: String = "com.nextcloud.nextcloudkit.session.download"
  1446. // sessionIdentifierUpload: String = "com.nextcloud.nextcloudkit.session.upload"
  1447. // sessionUploadBackground: String = "com.nextcloud.session.upload.background"
  1448. // sessionUploadBackgroundWWan: String = "com.nextcloud.session.upload.backgroundWWan"
  1449. // sessionUploadBackgroundExtension: String = "com.nextcloud.session.upload.extension"
  1450. func cancelSession(metadata: tableMetadata) async {
  1451. let fileNameLocalPath = utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)
  1452. utilityFileSystem.removeFile(atPath: utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId))
  1453. // No session found
  1454. if metadata.session.isEmpty {
  1455. NCNetworking.shared.uploadRequest.removeValue(forKey: fileNameLocalPath)
  1456. NCNetworking.shared.downloadRequest.removeValue(forKey: fileNameLocalPath)
  1457. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  1458. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSource)
  1459. return
  1460. }
  1461. // DOWNLOAD FOREGROUND
  1462. if metadata.session == NextcloudKit.shared.nkCommonInstance.sessionIdentifierDownload {
  1463. if let request = NCNetworking.shared.downloadRequest[fileNameLocalPath] {
  1464. request.cancel()
  1465. } else if let metadata = NCManageDatabase.shared.getMetadataFromOcId(metadata.ocId) {
  1466. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId,
  1467. session: "",
  1468. sessionError: "",
  1469. selector: "",
  1470. status: NCGlobal.shared.metadataStatusNormal)
  1471. NotificationCenter.default.post(name: Notification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadCancelFile),
  1472. object: nil,
  1473. userInfo: ["ocId": metadata.ocId,
  1474. "serverUrl": metadata.serverUrl,
  1475. "account": metadata.account])
  1476. }
  1477. return
  1478. }
  1479. // DOWNLOAD BACKGROUND
  1480. if metadata.session == NCNetworking.shared.sessionDownloadBackground {
  1481. let session: URLSession? = NCNetworking.shared.sessionManagerDownloadBackground
  1482. if let tasks = await session?.tasks {
  1483. for task in tasks.2 { // ([URLSessionDataTask], [URLSessionUploadTask], [URLSessionDownloadTask])
  1484. if task.taskIdentifier == metadata.sessionTaskIdentifier {
  1485. task.cancel()
  1486. }
  1487. }
  1488. }
  1489. }
  1490. // UPLOAD FOREGROUND
  1491. if metadata.session == NextcloudKit.shared.nkCommonInstance.sessionIdentifierUpload {
  1492. if let request = NCNetworking.shared.uploadRequest[fileNameLocalPath] {
  1493. request.cancel()
  1494. NCNetworking.shared.uploadRequest.removeValue(forKey: fileNameLocalPath)
  1495. }
  1496. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  1497. NotificationCenter.default.post(name: Notification.Name(rawValue: NCGlobal.shared.notificationCenterUploadCancelFile),
  1498. object: nil,
  1499. userInfo: ["ocId": metadata.ocId,
  1500. "serverUrl": metadata.serverUrl,
  1501. "account": metadata.account])
  1502. return
  1503. }
  1504. // UPLOAD BACKGROUND
  1505. var session: URLSession?
  1506. if metadata.session == NCNetworking.shared.sessionUploadBackground {
  1507. session = NCNetworking.shared.sessionManagerUploadBackground
  1508. } else if metadata.session == NCNetworking.shared.sessionUploadBackgroundWWan {
  1509. session = NCNetworking.shared.sessionManagerUploadBackgroundWWan
  1510. }
  1511. if let tasks = await session?.tasks {
  1512. for task in tasks.1 { // ([URLSessionDataTask], [URLSessionUploadTask], [URLSessionDownloadTask])
  1513. if task.taskIdentifier == metadata.sessionTaskIdentifier {
  1514. task.cancel()
  1515. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  1516. NotificationCenter.default.post(name: Notification.Name(rawValue: NCGlobal.shared.notificationCenterUploadCancelFile),
  1517. object: nil,
  1518. userInfo: ["ocId": metadata.ocId,
  1519. "serverUrl": metadata.serverUrl,
  1520. "account": metadata.account])
  1521. }
  1522. }
  1523. }
  1524. }
  1525. }
  1526. // MARK: -
  1527. private class AccountSwitcherButton: UIButton {
  1528. var onMenuOpened: (() -> Void)?
  1529. override func contextMenuInteraction(_ interaction: UIContextMenuInteraction, willDisplayMenuFor configuration: UIContextMenuConfiguration, animator: UIContextMenuInteractionAnimating?) {
  1530. super.contextMenuInteraction(interaction, willDisplayMenuFor: configuration, animator: animator)
  1531. onMenuOpened?()
  1532. }
  1533. }