NCCollectionViewCommon.swift 85 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864
  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. class NCCollectionViewCommon: UIViewController, UIGestureRecognizerDelegate, UISearchResultsUpdating, UISearchControllerDelegate, UISearchBarDelegate, NCListCellDelegate, NCGridCellDelegate, NCSectionHeaderMenuDelegate, NCSectionFooterDelegate, UIAdaptivePresentationControllerDelegate, NCEmptyDataSetDelegate, UIContextMenuInteractionDelegate, NCAccountRequestDelegate, NCSelectableNavigationView {
  28. @IBOutlet weak var collectionView: UICollectionView!
  29. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  30. internal let refreshControl = UIRefreshControl()
  31. internal var searchController: UISearchController?
  32. internal var emptyDataSet: NCEmptyDataSet?
  33. internal var backgroundImageView = UIImageView()
  34. internal var serverUrl: String = ""
  35. internal var isEncryptedFolder = false
  36. internal var isEditMode = false
  37. internal var selectOcId: [String] = []
  38. internal var metadataFolder: tableMetadata?
  39. internal var dataSource = NCDataSource()
  40. internal var richWorkspaceText: String?
  41. internal var headerMenu: NCSectionHeaderMenu?
  42. internal var isSearchingMode: Bool = false
  43. internal var layoutForView: NCGlobal.layoutForViewType?
  44. internal var selectableDataSource: [RealmSwiftObject] { dataSource.getMetadataSourceForAllSections() }
  45. private var autoUploadFileName = ""
  46. private var autoUploadDirectory = ""
  47. internal var groupByField = "name"
  48. internal var providers: [NKSearchProvider]?
  49. internal var searchResults: [NKSearchResult]?
  50. internal var listLayout: NCListLayout!
  51. internal var gridLayout: NCGridLayout!
  52. internal var literalSearch: String?
  53. internal var isReloadDataSourceNetworkInProgress: Bool = false
  54. private var pushed: Bool = false
  55. private var tipView: EasyTipView?
  56. // DECLARE
  57. internal var layoutKey = ""
  58. internal var titleCurrentFolder = ""
  59. internal var enableSearchBar: Bool = false
  60. internal var headerMenuButtonsCommand: Bool = true
  61. internal var headerMenuButtonsView: Bool = true
  62. internal var headerRichWorkspaceDisable:Bool = false
  63. internal var emptyImage: UIImage?
  64. internal var emptyTitle: String = ""
  65. internal var emptyDescription: String = ""
  66. // MARK: - View Life Cycle
  67. required init?(coder aDecoder: NSCoder) {
  68. super.init(coder: aDecoder)
  69. }
  70. override func viewDidLoad() {
  71. super.viewDidLoad()
  72. self.navigationController?.presentationController?.delegate = self
  73. // CollectionView & layout
  74. listLayout = NCListLayout()
  75. gridLayout = NCGridLayout()
  76. layoutForView = NCUtility.shared.getLayoutForView(key: layoutKey, serverUrl: serverUrl)
  77. gridLayout.itemForLine = CGFloat(layoutForView?.itemForLine ?? 3)
  78. if layoutForView?.layout == NCGlobal.shared.layoutList {
  79. collectionView?.collectionViewLayout = listLayout
  80. } else {
  81. collectionView?.collectionViewLayout = gridLayout
  82. }
  83. collectionView.alwaysBounceVertical = true
  84. // Color
  85. view.backgroundColor = .systemBackground
  86. collectionView.backgroundColor = .systemBackground
  87. refreshControl.tintColor = .gray
  88. if enableSearchBar {
  89. searchController = UISearchController(searchResultsController: nil)
  90. searchController?.searchResultsUpdater = self
  91. searchController?.obscuresBackgroundDuringPresentation = false
  92. searchController?.delegate = self
  93. searchController?.searchBar.delegate = self
  94. searchController?.searchBar.autocapitalizationType = .none
  95. navigationItem.searchController = searchController
  96. navigationItem.hidesSearchBarWhenScrolling = true
  97. }
  98. // Cell
  99. collectionView.register(UINib(nibName: "NCListCell", bundle: nil), forCellWithReuseIdentifier: "listCell")
  100. collectionView.register(UINib(nibName: "NCGridCell", bundle: nil), forCellWithReuseIdentifier: "gridCell")
  101. collectionView.register(UINib(nibName: "NCTransferCell", bundle: nil), forCellWithReuseIdentifier: "transferCell")
  102. // Header
  103. collectionView.register(UINib(nibName: "NCSectionHeaderMenu", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeaderMenu")
  104. collectionView.register(UINib(nibName: "NCSectionHeader", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeader")
  105. // Footer
  106. collectionView.register(UINib(nibName: "NCSectionFooter", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "sectionFooter")
  107. // Refresh Control
  108. collectionView.addSubview(refreshControl)
  109. refreshControl.action(for: .valueChanged) { _ in
  110. self.dataSource.clearDirectory()
  111. self.reloadDataSourceNetwork(forced: true)
  112. }
  113. // Empty
  114. emptyDataSet = NCEmptyDataSet(view: collectionView, offset: getHeaderHeight(), delegate: self)
  115. // Long Press on CollectionView
  116. let longPressedGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPressCollecationView(_:)))
  117. longPressedGesture.minimumPressDuration = 0.5
  118. longPressedGesture.delegate = self
  119. longPressedGesture.delaysTouchesBegan = true
  120. collectionView.addGestureRecognizer(longPressedGesture)
  121. // TIP
  122. var preferences = EasyTipView.Preferences()
  123. preferences.drawing.foregroundColor = .white
  124. preferences.drawing.backgroundColor = NCBrandColor.shared.nextcloud
  125. preferences.drawing.textAlignment = .left
  126. preferences.drawing.arrowPosition = .top
  127. preferences.drawing.cornerRadius = 10
  128. preferences.animating.dismissTransform = CGAffineTransform(translationX: 0, y: 100)
  129. preferences.animating.showInitialTransform = CGAffineTransform(translationX: 0, y: -100)
  130. preferences.animating.showInitialAlpha = 0
  131. preferences.animating.showDuration = 1.5
  132. preferences.animating.dismissDuration = 1.5
  133. tipView = EasyTipView(text: NSLocalizedString("_tip_accountrequest_", comment: ""), preferences: preferences, delegate: self)
  134. // Notification
  135. NotificationCenter.default.addObserver(self, selector: #selector(initialize), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterInitialize), object: nil)
  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. appDelegate.activeViewController = self
  141. layoutForView = NCUtility.shared.getLayoutForView(key: layoutKey, serverUrl: serverUrl)
  142. gridLayout.itemForLine = CGFloat(layoutForView?.itemForLine ?? 3)
  143. if layoutForView?.layout == NCGlobal.shared.layoutList {
  144. collectionView?.collectionViewLayout = listLayout
  145. } else {
  146. collectionView?.collectionViewLayout = gridLayout
  147. }
  148. NotificationCenter.default.addObserver(self, selector: #selector(applicationWillResignActive(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationWillResignActive), object: nil)
  149. NotificationCenter.default.addObserver(self, selector: #selector(closeRichWorkspaceWebView), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCloseRichWorkspaceWebView), object: nil)
  150. NotificationCenter.default.addObserver(self, selector: #selector(changeStatusFolderE2EE(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterChangeStatusFolderE2EE), object: nil)
  151. NotificationCenter.default.addObserver(self, selector: #selector(setNavigationItem), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadAvatar), object: nil)
  152. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSource(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadDataSource), object: nil)
  153. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSourceNetwork), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadDataSourceNetwork), object: nil)
  154. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSourceNetworkForced(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadDataSourceNetworkForced), object: nil)
  155. NotificationCenter.default.addObserver(self, selector: #selector(deleteFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDeleteFile), object: nil)
  156. NotificationCenter.default.addObserver(self, selector: #selector(moveFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMoveFile), object: nil)
  157. NotificationCenter.default.addObserver(self, selector: #selector(copyFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCopyFile), object: nil)
  158. NotificationCenter.default.addObserver(self, selector: #selector(renameFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterRenameFile), object: nil)
  159. NotificationCenter.default.addObserver(self, selector: #selector(createFolder(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCreateFolder), object: nil)
  160. NotificationCenter.default.addObserver(self, selector: #selector(favoriteFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterFavoriteFile), object: nil)
  161. NotificationCenter.default.addObserver(self, selector: #selector(downloadStartFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadStartFile), object: nil)
  162. NotificationCenter.default.addObserver(self, selector: #selector(downloadedFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadedFile), object: nil)
  163. NotificationCenter.default.addObserver(self, selector: #selector(downloadCancelFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadCancelFile), object: nil)
  164. NotificationCenter.default.addObserver(self, selector: #selector(uploadStartFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadStartFile), object: nil)
  165. NotificationCenter.default.addObserver(self, selector: #selector(uploadedFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedFile), object: nil)
  166. NotificationCenter.default.addObserver(self, selector: #selector(uploadCancelFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadCancelFile), object: nil)
  167. NotificationCenter.default.addObserver(self, selector: #selector(triggerProgressTask(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterProgressTask), object: nil)
  168. if serverUrl == "" {
  169. appDelegate.activeServerUrl = NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate.urlBase, userId: appDelegate.userId)
  170. } else {
  171. appDelegate.activeServerUrl = serverUrl
  172. }
  173. navigationController?.navigationBar.prefersLargeTitles = true
  174. navigationController?.setNavigationBarHidden(false, animated: true)
  175. setNavigationItem()
  176. reloadDataSource(forced: false)
  177. if !isSearchingMode {
  178. reloadDataSourceNetwork()
  179. }
  180. //FIXME: iPAD PDF landscape mode iOS 16
  181. DispatchQueue.main.async {
  182. self.collectionView?.collectionViewLayout.invalidateLayout()
  183. }
  184. }
  185. override func viewDidAppear(_ animated: Bool) {
  186. super.viewDidAppear(animated)
  187. showTip()
  188. }
  189. override func viewWillDisappear(_ animated: Bool) {
  190. super.viewWillDisappear(animated)
  191. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationWillResignActive), object: nil)
  192. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCloseRichWorkspaceWebView), object: nil)
  193. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterChangeStatusFolderE2EE), object: nil)
  194. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadAvatar), object: nil)
  195. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadDataSource), object: nil)
  196. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadDataSourceNetwork), object: nil)
  197. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadDataSourceNetworkForced), object: nil)
  198. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDeleteFile), object: nil)
  199. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMoveFile), object: nil)
  200. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCopyFile), object: nil)
  201. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterRenameFile), object: nil)
  202. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCreateFolder), object: nil)
  203. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterProgressTask), object: nil)
  204. pushed = false
  205. // REQUEST
  206. NCNetworking.shared.cancelUnifiedSearchFiles()
  207. // TIP
  208. self.tipView?.dismiss()
  209. }
  210. func presentationControllerDidDismiss( _ presentationController: UIPresentationController) {
  211. let viewController = presentationController.presentedViewController
  212. if viewController is NCViewerRichWorkspaceWebView {
  213. closeRichWorkspaceWebView()
  214. }
  215. }
  216. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  217. super.viewWillTransition(to: size, with: coordinator)
  218. self.collectionView?.collectionViewLayout.invalidateLayout()
  219. self.collectionView?.reloadData()
  220. self.tipView?.dismiss()
  221. coordinator.animate(alongsideTransition: nil) { _ in
  222. self.showTip()
  223. }
  224. }
  225. override var canBecomeFirstResponder: Bool {
  226. return true
  227. }
  228. // MARK: - NotificationCenter
  229. @objc func initialize() {
  230. guard !appDelegate.account.isEmpty else { return }
  231. // Search
  232. if searchController?.isActive ?? false || isSearchingMode {
  233. searchController?.isActive = false
  234. isSearchingMode = false
  235. }
  236. // Select
  237. if isEditMode {
  238. isEditMode = !isEditMode
  239. selectOcId.removeAll()
  240. }
  241. if self.view?.window != nil {
  242. if serverUrl == "" {
  243. appDelegate.activeServerUrl = NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate.urlBase, userId: appDelegate.userId)
  244. } else {
  245. appDelegate.activeServerUrl = serverUrl
  246. }
  247. appDelegate.listFilesVC.removeAll()
  248. appDelegate.listFavoriteVC.removeAll()
  249. appDelegate.listOfflineVC.removeAll()
  250. }
  251. if serverUrl != "" {
  252. self.navigationController?.popToRootViewController(animated: false)
  253. }
  254. layoutForView = NCUtility.shared.getLayoutForView(key: layoutKey, serverUrl: serverUrl)
  255. gridLayout.itemForLine = CGFloat(layoutForView?.itemForLine ?? 3)
  256. if layoutForView?.layout == NCGlobal.shared.layoutList {
  257. collectionView?.collectionViewLayout = listLayout
  258. } else {
  259. collectionView?.collectionViewLayout = gridLayout
  260. }
  261. setNavigationItem()
  262. }
  263. @objc func applicationWillResignActive(_ notification: NSNotification) {
  264. self.refreshControl.endRefreshing()
  265. }
  266. @objc func changeTheming() {
  267. collectionView.reloadData()
  268. }
  269. @objc func reloadDataSource(_ notification: NSNotification) {
  270. reloadDataSource()
  271. }
  272. @objc func reloadDataSourceNetworkForced(_ notification: NSNotification) {
  273. if !isSearchingMode {
  274. reloadDataSourceNetwork(forced: true)
  275. }
  276. }
  277. @objc func changeStatusFolderE2EE(_ notification: NSNotification) {
  278. reloadDataSource()
  279. }
  280. @objc func closeRichWorkspaceWebView() {
  281. reloadDataSourceNetwork()
  282. }
  283. @objc func deleteFile(_ notification: NSNotification) {
  284. guard let userInfo = notification.userInfo as NSDictionary?,
  285. let ocId = userInfo["ocId"] as? String,
  286. let fileNameView = userInfo["fileNameView"] as? String,
  287. let serverUrl = userInfo["serverUrl"] as? String,
  288. serverUrl == self.serverUrl,
  289. let account = userInfo["account"] as? String,
  290. account == appDelegate.account,
  291. let onlyLocalCache = userInfo["onlyLocalCache"] as? Bool
  292. else { return }
  293. if fileNameView.lowercased() == NCGlobal.shared.fileNameRichWorkspace.lowercased() {
  294. reloadDataSourceNetwork(forced: true)
  295. } else if onlyLocalCache {
  296. self.collectionView?.reloadData()
  297. } else {
  298. let (indexPath, sameSections) = dataSource.deleteMetadata(ocId: ocId)
  299. if let indexPath = indexPath, dataSource.metadatas.count > 0 {
  300. if sameSections && (indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section)) {
  301. collectionView?.performBatchUpdates({
  302. collectionView?.deleteItems(at: [indexPath])
  303. }, completion: { _ in
  304. self.collectionView?.reloadData()
  305. })
  306. } else {
  307. self.collectionView?.reloadData()
  308. }
  309. } else {
  310. reloadDataSource()
  311. }
  312. }
  313. }
  314. @objc func moveFile(_ notification: NSNotification) {
  315. guard let userInfo = notification.userInfo as NSDictionary?,
  316. let ocId = userInfo["ocId"] as? String,
  317. let serverUrlFrom = userInfo["serverUrlFrom"] as? String,
  318. serverUrlFrom == self.serverUrl
  319. else { return }
  320. let (indexPath, sameSections) = dataSource.deleteMetadata(ocId: ocId)
  321. if let indexPath = indexPath {
  322. if sameSections && (indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section)) {
  323. collectionView?.performBatchUpdates({
  324. collectionView?.deleteItems(at: [indexPath])
  325. }, completion: { _ in
  326. self.collectionView?.reloadData()
  327. })
  328. } else {
  329. self.collectionView?.reloadData()
  330. }
  331. } else {
  332. reloadDataSource()
  333. }
  334. }
  335. @objc func copyFile(_ notification: NSNotification) {
  336. guard let userInfo = notification.userInfo as NSDictionary?,
  337. let serverUrlTo = userInfo["serverUrlTo"] as? String,
  338. serverUrlTo == self.serverUrl
  339. else { return }
  340. reloadDataSource()
  341. }
  342. @objc func renameFile(_ notification: NSNotification) {
  343. if isSearchingMode {
  344. reloadDataSourceNetwork()
  345. } else {
  346. reloadDataSource()
  347. }
  348. }
  349. @objc func createFolder(_ notification: NSNotification) {
  350. guard let userInfo = notification.userInfo as NSDictionary?,
  351. let ocId = userInfo["ocId"] as? String,
  352. let serverUrl = userInfo["serverUrl"] as? String,
  353. serverUrl == self.serverUrl,
  354. let account = userInfo["account"] as? String,
  355. account == appDelegate.account,
  356. let e2ee = userInfo["e2ee"] as? Bool
  357. else { return }
  358. if e2ee {
  359. reloadDataSourceNetwork(forced: true)
  360. } else if let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  361. reloadDataSource()
  362. pushMetadata(metadata)
  363. }
  364. }
  365. @objc func favoriteFile(_ notification: NSNotification) {
  366. guard let userInfo = notification.userInfo as NSDictionary?,
  367. let ocId = userInfo["ocId"] as? String,
  368. let serverUrl = userInfo["serverUrl"] as? String,
  369. serverUrl == self.serverUrl
  370. else {
  371. if self is NCFavorite {
  372. reloadDataSource()
  373. }
  374. return
  375. }
  376. dataSource.reloadMetadata(ocId: ocId)
  377. collectionView?.reloadData()
  378. }
  379. @objc func downloadStartFile(_ notification: NSNotification) {
  380. guard let userInfo = notification.userInfo as NSDictionary?,
  381. let ocId = userInfo["ocId"] as? String,
  382. let serverUrl = userInfo["serverUrl"] as? String,
  383. serverUrl == self.serverUrl,
  384. let account = userInfo["account"] as? String,
  385. account == appDelegate.account
  386. else { return }
  387. let (indexPath, sameSections) = dataSource.reloadMetadata(ocId: ocId)
  388. if let indexPath = indexPath {
  389. if sameSections && (indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section)) {
  390. collectionView?.reloadItems(at: [indexPath])
  391. } else {
  392. self.collectionView?.reloadData()
  393. }
  394. } else {
  395. reloadDataSource()
  396. }
  397. }
  398. @objc func downloadedFile(_ notification: NSNotification) {
  399. guard let userInfo = notification.userInfo as NSDictionary?,
  400. let ocId = userInfo["ocId"] as? String,
  401. let serverUrl = userInfo["serverUrl"] as? String,
  402. serverUrl == self.serverUrl,
  403. let account = userInfo["account"] as? String,
  404. account == appDelegate.account
  405. else { return }
  406. let (indexPath, sameSections) = dataSource.reloadMetadata(ocId: ocId)
  407. if let indexPath = indexPath {
  408. if sameSections && (indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section)) {
  409. collectionView?.reloadItems(at: [indexPath])
  410. } else {
  411. self.collectionView?.reloadData()
  412. }
  413. } else {
  414. reloadDataSource()
  415. }
  416. }
  417. @objc func downloadCancelFile(_ notification: NSNotification) {
  418. guard let userInfo = notification.userInfo as NSDictionary?,
  419. let ocId = userInfo["ocId"] as? String,
  420. let serverUrl = userInfo["serverUrl"] as? String,
  421. serverUrl == self.serverUrl,
  422. let account = userInfo["account"] as? String,
  423. account == appDelegate.account
  424. else { return }
  425. let (indexPath, sameSections) = dataSource.reloadMetadata(ocId: ocId)
  426. if let indexPath = indexPath {
  427. if sameSections && (indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section)) {
  428. collectionView?.reloadItems(at: [indexPath])
  429. } else {
  430. self.collectionView?.reloadData()
  431. }
  432. } else {
  433. reloadDataSource()
  434. }
  435. }
  436. @objc func uploadStartFile(_ notification: NSNotification) {
  437. guard let userInfo = notification.userInfo as NSDictionary?,
  438. let ocId = userInfo["ocId"] as? String,
  439. let serverUrl = userInfo["serverUrl"] as? String,
  440. serverUrl == self.serverUrl,
  441. let account = userInfo["account"] as? String,
  442. account == appDelegate.account
  443. else { return }
  444. guard !isSearchingMode, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) else { return }
  445. dataSource.addMetadata(metadata)
  446. self.collectionView?.reloadData()
  447. }
  448. @objc func uploadedFile(_ notification: NSNotification) {
  449. guard let userInfo = notification.userInfo as NSDictionary?,
  450. let ocId = userInfo["ocId"] as? String,
  451. let ocIdTemp = userInfo["ocIdTemp"] as? String,
  452. let serverUrl = userInfo["serverUrl"] as? String,
  453. serverUrl == self.serverUrl,
  454. let account = userInfo["account"] as? String,
  455. account == appDelegate.account
  456. else { return }
  457. // do not exists metadata ?
  458. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) else {
  459. reloadDataSource()
  460. return
  461. }
  462. if metadata.livePhoto && metadata.classFile == NKCommon.typeClassFile.video.rawValue { return }
  463. let (indexPath, sameSections) = dataSource.reloadMetadata(ocId: metadata.ocId, ocIdTemp: ocIdTemp)
  464. if let indexPath = indexPath {
  465. if sameSections && (indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section)) {
  466. collectionView?.performBatchUpdates({
  467. collectionView?.reloadItems(at: [indexPath])
  468. }, completion: { _ in
  469. self.collectionView?.reloadData()
  470. })
  471. } else {
  472. self.collectionView?.reloadData()
  473. }
  474. } else {
  475. reloadDataSource()
  476. }
  477. }
  478. @objc func uploadCancelFile(_ notification: NSNotification) {
  479. guard let userInfo = notification.userInfo as NSDictionary?,
  480. let ocId = userInfo["ocId"] as? String,
  481. let serverUrl = userInfo["serverUrl"] as? String,
  482. serverUrl == self.serverUrl,
  483. let account = userInfo["account"] as? String,
  484. account == appDelegate.account
  485. else { return }
  486. let (indexPath, sameSections) = dataSource.deleteMetadata(ocId: ocId)
  487. if let indexPath = indexPath {
  488. if sameSections && (indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section)) {
  489. collectionView?.performBatchUpdates({
  490. collectionView?.deleteItems(at: [indexPath])
  491. }, completion: { _ in
  492. self.collectionView?.reloadData()
  493. })
  494. } else {
  495. self.collectionView?.reloadData()
  496. }
  497. } else {
  498. reloadDataSource()
  499. }
  500. }
  501. @objc func triggerProgressTask(_ notification: NSNotification) {
  502. guard let userInfo = notification.userInfo as NSDictionary?,
  503. let progressNumber = userInfo["progress"] as? NSNumber,
  504. let totalBytes = userInfo["totalBytes"] as? Int64,
  505. let totalBytesExpected = userInfo["totalBytesExpected"] as? Int64,
  506. let ocId = userInfo["ocId"] as? String,
  507. let (indexPath, _) = self.dataSource.getIndexPathMetadata(ocId: ocId) as? (IndexPath, NCMetadataForSection?)
  508. else { return }
  509. let status = userInfo["status"] as? Int ?? NCGlobal.shared.metadataStatusNormal
  510. if let cell = collectionView?.cellForItem(at: indexPath) {
  511. if let cell = cell as? NCCellProtocol {
  512. if progressNumber.floatValue == 1 && !(cell is NCTransferCell) {
  513. cell.fileProgressView?.isHidden = true
  514. cell.fileProgressView?.progress = .zero
  515. cell.setButtonMore(named: NCGlobal.shared.buttonMoreMore, image: NCBrandColor.cacheImages.buttonMore)
  516. if let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  517. cell.writeInfoDateSize(date: metadata.date, size: metadata.size)
  518. } else {
  519. cell.fileInfoLabel?.text = ""
  520. }
  521. } else {
  522. cell.fileProgressView?.isHidden = false
  523. cell.fileProgressView?.progress = progressNumber.floatValue
  524. cell.setButtonMore(named: NCGlobal.shared.buttonMoreStop, image: NCBrandColor.cacheImages.buttonStop)
  525. if status == NCGlobal.shared.metadataStatusInDownload {
  526. cell.fileInfoLabel?.text = CCUtility.transformedSize(totalBytesExpected) + " - ↓ " + CCUtility.transformedSize(totalBytes)
  527. } else if status == NCGlobal.shared.metadataStatusInUpload {
  528. if totalBytes > 0 {
  529. cell.fileInfoLabel?.text = CCUtility.transformedSize(totalBytesExpected) + " - ↑ " + CCUtility.transformedSize(totalBytes)
  530. } else {
  531. cell.fileInfoLabel?.text = CCUtility.transformedSize(totalBytesExpected) + " - ↑ …"
  532. }
  533. }
  534. }
  535. }
  536. }
  537. }
  538. // MARK: - Tip
  539. func showTip() {
  540. if self is NCFiles, self.view.window != nil, !NCBrandOptions.shared.disable_multiaccount, !NCBrandOptions.shared.disable_manage_account, self.serverUrl == NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate.urlBase, userId: appDelegate.userId), let view = self.navigationItem.leftBarButtonItem?.customView {
  541. if !NCManageDatabase.shared.tipExists(NCGlobal.shared.tipNCCollectionViewCommonAccountRequest), NCManageDatabase.shared.getAllAccountOrderAlias().count > 0 {
  542. self.tipView?.show(forView: view)
  543. }
  544. }
  545. }
  546. // MARK: - Layout
  547. @objc func setNavigationItem() {
  548. self.setNavigationHeader()
  549. guard !isEditMode, layoutKey == NCGlobal.shared.layoutViewFiles else { return }
  550. // PROFILE BUTTON
  551. let activeAccount = NCManageDatabase.shared.getActiveAccount()
  552. let image = NCUtility.shared.loadUserImage(
  553. for: appDelegate.user,
  554. displayName: activeAccount?.displayName,
  555. userBaseUrl: appDelegate)
  556. let button = UIButton(type: .custom)
  557. button.setImage(image, for: .normal)
  558. if serverUrl == NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate.urlBase, userId: appDelegate.userId) {
  559. var titleButton = " "
  560. if getNavigationTitle() == activeAccount?.alias {
  561. titleButton = ""
  562. } else {
  563. titleButton += activeAccount?.displayName ?? ""
  564. }
  565. button.setTitle(titleButton, for: .normal)
  566. button.setTitleColor(.systemBlue, for: .normal)
  567. }
  568. button.semanticContentAttribute = .forceLeftToRight
  569. button.sizeToFit()
  570. button.action(for: .touchUpInside) { _ in
  571. let accounts = NCManageDatabase.shared.getAllAccountOrderAlias()
  572. if accounts.count > 0 && !NCBrandOptions.shared.disable_multiaccount && !NCBrandOptions.shared.disable_manage_account {
  573. if let vcAccountRequest = UIStoryboard(name: "NCAccountRequest", bundle: nil).instantiateInitialViewController() as? NCAccountRequest {
  574. vcAccountRequest.activeAccount = NCManageDatabase.shared.getActiveAccount()
  575. vcAccountRequest.accounts = accounts
  576. vcAccountRequest.enableTimerProgress = false
  577. vcAccountRequest.enableAddAccount = true
  578. vcAccountRequest.delegate = self
  579. vcAccountRequest.dismissDidEnterBackground = true
  580. let screenHeighMax = UIScreen.main.bounds.height - (UIScreen.main.bounds.height/5)
  581. let numberCell = accounts.count + 1
  582. let height = min(CGFloat(numberCell * Int(vcAccountRequest.heightCell) + 45), screenHeighMax)
  583. let popup = NCPopupViewController(contentController: vcAccountRequest, popupWidth: 300, popupHeight: height)
  584. UIApplication.shared.keyWindow?.rootViewController?.present(popup, animated: true)
  585. }
  586. // TIP
  587. self.dismissTip()
  588. }
  589. }
  590. navigationItem.setLeftBarButton(UIBarButtonItem(customView: button), animated: true)
  591. navigationItem.leftItemsSupplementBackButton = true
  592. }
  593. func getNavigationTitle() -> String {
  594. let activeAccount = NCManageDatabase.shared.getActiveAccount()
  595. guard let userAlias = activeAccount?.alias, !userAlias.isEmpty else {
  596. return NCBrandOptions.shared.brand
  597. }
  598. return userAlias
  599. }
  600. // MARK: - Empty
  601. func emptyDataSetView(_ view: NCEmptyView) {
  602. self.emptyDataSet?.setOffset(getHeaderHeight())
  603. if isSearchingMode {
  604. view.emptyImage.image = UIImage(named: "search")?.image(color: .gray, size: UIScreen.main.bounds.width)
  605. if isReloadDataSourceNetworkInProgress {
  606. view.emptyTitle.text = NSLocalizedString("_search_in_progress_", comment: "")
  607. } else {
  608. view.emptyTitle.text = NSLocalizedString("_search_no_record_found_", comment: "")
  609. }
  610. view.emptyDescription.text = NSLocalizedString("_search_instruction_", comment: "")
  611. } else if isReloadDataSourceNetworkInProgress {
  612. view.emptyImage.image = UIImage(named: "networkInProgress")?.image(color: .gray, size: UIScreen.main.bounds.width)
  613. view.emptyTitle.text = NSLocalizedString("_request_in_progress_", comment: "")
  614. view.emptyDescription.text = ""
  615. } else {
  616. if serverUrl == "" {
  617. view.emptyImage.image = emptyImage
  618. view.emptyTitle.text = NSLocalizedString(emptyTitle, comment: "")
  619. view.emptyDescription.text = NSLocalizedString(emptyDescription, comment: "")
  620. } else {
  621. view.emptyImage.image = UIImage(named: "folder")?.image(color: NCBrandColor.shared.brandElement, size: UIScreen.main.bounds.width)
  622. view.emptyTitle.text = NSLocalizedString("_files_no_files_", comment: "")
  623. view.emptyDescription.text = NSLocalizedString("_no_file_pull_down_", comment: "")
  624. }
  625. }
  626. }
  627. // MARK: - SEARCH
  628. func updateSearchResults(for searchController: UISearchController) {
  629. self.literalSearch = searchController.searchBar.text
  630. }
  631. func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
  632. isSearchingMode = true
  633. self.providers?.removeAll()
  634. self.dataSource.clearDataSource()
  635. self.collectionView.reloadData()
  636. // TIP
  637. self.tipView?.dismiss()
  638. }
  639. func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
  640. if isSearchingMode && self.literalSearch?.count ?? 0 >= 2 {
  641. reloadDataSourceNetwork()
  642. }
  643. }
  644. func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
  645. DispatchQueue.global().async {
  646. NCNetworking.shared.cancelUnifiedSearchFiles()
  647. self.isSearchingMode = false
  648. self.literalSearch = ""
  649. self.providers?.removeAll()
  650. self.dataSource.clearDataSource()
  651. self.reloadDataSource()
  652. }
  653. }
  654. // MARK: - TAP EVENT
  655. func accountRequestChangeAccount(account: String) {
  656. NCManageDatabase.shared.setAccountActive(account)
  657. if let activeAccount = NCManageDatabase.shared.getActiveAccount() {
  658. NCOperationQueue.shared.cancelAllQueue()
  659. NCNetworking.shared.cancelAllTask()
  660. appDelegate.settingAccount(activeAccount.account, urlBase: activeAccount.urlBase, user: activeAccount.user, userId: activeAccount.userId, password: CCUtility.getPassword(activeAccount.account))
  661. }
  662. }
  663. func accountRequestAddAccount() {
  664. appDelegate.openLogin(viewController: self, selector: NCGlobal.shared.introLogin, openLoginWeb: false)
  665. }
  666. func tapButtonSwitch(_ sender: Any) {
  667. if layoutForView?.layout == NCGlobal.shared.layoutGrid {
  668. // list layout
  669. headerMenu?.buttonSwitch.accessibilityLabel = NSLocalizedString("_grid_view_", comment: "")
  670. layoutForView?.layout = NCGlobal.shared.layoutList
  671. NCUtility.shared.setLayoutForView(key: layoutKey, serverUrl: serverUrl, layout: layoutForView?.layout)
  672. self.groupByField = "name"
  673. if self.dataSource.groupByField != self.groupByField {
  674. self.dataSource.changeGroupByField(self.groupByField)
  675. }
  676. self.collectionView.reloadData()
  677. self.collectionView.collectionViewLayout.invalidateLayout()
  678. self.collectionView.setCollectionViewLayout(self.listLayout, animated: true)
  679. } else {
  680. // grid layout
  681. headerMenu?.buttonSwitch.accessibilityLabel = NSLocalizedString("_list_view_", comment: "")
  682. layoutForView?.layout = NCGlobal.shared.layoutGrid
  683. NCUtility.shared.setLayoutForView(key: layoutKey, serverUrl: serverUrl, layout: layoutForView?.layout)
  684. if isSearchingMode {
  685. self.groupByField = "name"
  686. } else {
  687. self.groupByField = "classFile"
  688. }
  689. if self.dataSource.groupByField != self.groupByField {
  690. self.dataSource.changeGroupByField(self.groupByField)
  691. }
  692. self.collectionView.reloadData()
  693. self.collectionView.collectionViewLayout.invalidateLayout()
  694. self.collectionView.setCollectionViewLayout(self.gridLayout, animated: true)
  695. }
  696. }
  697. func tapButtonOrder(_ sender: Any) {
  698. let sortMenu = NCSortMenu()
  699. sortMenu.toggleMenu(viewController: self, key: layoutKey, sortButton: sender as? UIButton, serverUrl: serverUrl)
  700. }
  701. func tapButton1(_ sender: Any) {
  702. NCAskAuthorization.shared.askAuthorizationPhotoLibrary(viewController: self) { hasPermission in
  703. if hasPermission {
  704. NCPhotosPickerViewController.init(viewController: self, maxSelectedAssets: 0, singleSelectedMode: false)
  705. }
  706. }
  707. }
  708. func tapButton2(_ sender: Any) {
  709. guard !appDelegate.activeServerUrl.isEmpty else { return }
  710. let alertController = UIAlertController.createFolder(serverUrl: appDelegate.activeServerUrl, urlBase: appDelegate)
  711. appDelegate.window?.rootViewController?.present(alertController, animated: true, completion: nil)
  712. }
  713. func tapButton3(_ sender: Any) {
  714. if let viewController = appDelegate.window?.rootViewController {
  715. NCCreateScanDocument.shared.openScannerDocument(viewController: viewController)
  716. }
  717. }
  718. func tapMoreListItem(with objectId: String, namedButtonMore: String, image: UIImage?, sender: Any) {
  719. tapMoreGridItem(with: objectId, namedButtonMore: namedButtonMore, image: image, sender: sender)
  720. }
  721. func tapShareListItem(with objectId: String, sender: Any) {
  722. if isEditMode { return }
  723. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(objectId) else { return }
  724. NCFunctionCenter.shared.openShare(viewController: self, metadata: metadata, indexPage: .sharing)
  725. }
  726. func tapMoreGridItem(with objectId: String, namedButtonMore: String, image: UIImage?, sender: Any) {
  727. if isEditMode { return }
  728. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(objectId) else { return }
  729. if namedButtonMore == NCGlobal.shared.buttonMoreMore || namedButtonMore == NCGlobal.shared.buttonMoreLock {
  730. toggleMenu(metadata: metadata, imageIcon: image)
  731. } else if namedButtonMore == NCGlobal.shared.buttonMoreStop {
  732. NCNetworking.shared.cancelTransferMetadata(metadata) { }
  733. }
  734. }
  735. func tapRichWorkspace(_ sender: Any) {
  736. if let navigationController = UIStoryboard(name: "NCViewerRichWorkspace", bundle: nil).instantiateInitialViewController() as? UINavigationController {
  737. if let viewerRichWorkspace = navigationController.topViewController as? NCViewerRichWorkspace {
  738. viewerRichWorkspace.richWorkspaceText = richWorkspaceText ?? ""
  739. viewerRichWorkspace.serverUrl = serverUrl
  740. viewerRichWorkspace.delegate = self
  741. navigationController.modalPresentationStyle = .fullScreen
  742. self.present(navigationController, animated: true, completion: nil)
  743. }
  744. }
  745. }
  746. func tapButtonSection(_ sender: Any, metadataForSection: NCMetadataForSection?) {
  747. unifiedSearchMore(metadataForSection: metadataForSection)
  748. }
  749. func longPressListItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) {
  750. }
  751. func longPressGridItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) {
  752. }
  753. func longPressMoreListItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) {
  754. }
  755. func longPressMoreGridItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) {
  756. }
  757. @objc func longPressCollecationView(_ gestureRecognizer: UILongPressGestureRecognizer) {
  758. openMenuItems(with: nil, gestureRecognizer: gestureRecognizer)
  759. }
  760. func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
  761. return UIContextMenuConfiguration(identifier: nil, previewProvider: {
  762. return nil
  763. }, actionProvider: { _ in
  764. // let share = UIAction(title: "Share Pupper", image: UIImage(systemName: "square.and.arrow.up")) { action in
  765. // }
  766. // return UIMenu(title: "Main Menu", children: [share])
  767. return nil
  768. })
  769. }
  770. func openMenuItems(with objectId: String?, gestureRecognizer: UILongPressGestureRecognizer) {
  771. if gestureRecognizer.state != .began { return }
  772. var listMenuItems: [UIMenuItem] = []
  773. let touchPoint = gestureRecognizer.location(in: collectionView)
  774. becomeFirstResponder()
  775. if serverUrl != "" {
  776. listMenuItems.append(UIMenuItem(title: NSLocalizedString("_paste_file_", comment: ""), action: #selector(pasteFilesMenu)))
  777. }
  778. if listMenuItems.count > 0 {
  779. UIMenuController.shared.menuItems = listMenuItems
  780. UIMenuController.shared.setTargetRect(CGRect(x: touchPoint.x, y: touchPoint.y, width: 0, height: 0), in: collectionView)
  781. UIMenuController.shared.setMenuVisible(true, animated: true)
  782. }
  783. }
  784. // MARK: - Menu Item
  785. override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
  786. if #selector(pasteFilesMenu) == action {
  787. if UIPasteboard.general.items.count > 0 {
  788. return true
  789. }
  790. }
  791. return false
  792. }
  793. @objc func pasteFilesMenu() {
  794. NCFunctionCenter.shared.pastePasteboard(serverUrl: serverUrl)
  795. }
  796. // MARK: - DataSource + NC Endpoint
  797. @objc func reloadDataSource(forced: Bool = true) {
  798. guard !appDelegate.account.isEmpty else { return }
  799. // E2EE
  800. isEncryptedFolder = NCUtility.shared.isFolderEncrypted(serverUrl: serverUrl, e2eEncrypted: metadataFolder?.e2eEncrypted ?? false, userBase: appDelegate)
  801. // get auto upload folder
  802. autoUploadFileName = NCManageDatabase.shared.getAccountAutoUploadFileName()
  803. autoUploadDirectory = NCManageDatabase.shared.getAccountAutoUploadDirectory(urlBase: appDelegate.urlBase, userId: appDelegate.userId, account: appDelegate.account)
  804. // get layout for view
  805. layoutForView = NCUtility.shared.getLayoutForView(key: layoutKey, serverUrl: serverUrl)
  806. // set GroupField for Grid
  807. if !isSearchingMode && layoutForView?.layout == NCGlobal.shared.layoutGrid {
  808. groupByField = "classFile"
  809. } else {
  810. groupByField = "name"
  811. }
  812. }
  813. @objc func reloadDataSourceNetwork(forced: Bool = false) { }
  814. @objc func networkSearch() {
  815. guard !appDelegate.account.isEmpty, let literalSearch = literalSearch, !literalSearch.isEmpty
  816. else {
  817. self.refreshControl.endRefreshing()
  818. return
  819. }
  820. isReloadDataSourceNetworkInProgress = true
  821. self.dataSource.clearDataSource()
  822. self.refreshControl.beginRefreshing()
  823. self.collectionView.reloadData()
  824. let serverVersionMajor = NCManageDatabase.shared.getCapabilitiesServerInt(account: appDelegate.account, elements: NCElementsJSON.shared.capabilitiesVersionMajor)
  825. if serverVersionMajor >= NCGlobal.shared.nextcloudVersion20 {
  826. NCNetworking.shared.unifiedSearchFiles(userBaseUrl: appDelegate, literal: literalSearch) { account, searchProviders in
  827. self.providers = searchProviders
  828. self.searchResults = []
  829. self.dataSource = NCDataSource(
  830. metadatas: [] ,
  831. account: self.appDelegate.account,
  832. sort: self.layoutForView?.sort,
  833. ascending: self.layoutForView?.ascending,
  834. directoryOnTop: self.layoutForView?.directoryOnTop,
  835. favoriteOnTop: true,
  836. filterLivePhoto: true,
  837. providers: self.providers,
  838. searchResults: self.searchResults)
  839. } update: { account, id, searchResult, metadatas in
  840. guard let metadatas = metadatas, metadatas.count > 0, self.isSearchingMode , let searchResult = searchResult else { return }
  841. NCOperationQueue.shared.unifiedSearchAddSection(collectionViewCommon: self, metadatas: metadatas, searchResult: searchResult)
  842. } completion: { account, error in
  843. self.refreshControl.endRefreshing()
  844. self.isReloadDataSourceNetworkInProgress = false
  845. self.collectionView.reloadData()
  846. }
  847. } else {
  848. NCNetworking.shared.searchFiles(urlBase: appDelegate, literal: literalSearch) { metadatas, error in
  849. DispatchQueue.main.async {
  850. self.refreshControl.endRefreshing()
  851. self.collectionView.reloadData()
  852. }
  853. guard let metadatas = metadatas, error == .success, self.isSearchingMode else { return }
  854. self.dataSource = NCDataSource(
  855. metadatas: metadatas,
  856. account: self.appDelegate.account,
  857. sort: self.layoutForView?.sort,
  858. ascending: self.layoutForView?.ascending,
  859. directoryOnTop: self.layoutForView?.directoryOnTop,
  860. favoriteOnTop: true,
  861. filterLivePhoto: true,
  862. groupByField: self.groupByField,
  863. providers: self.providers,
  864. searchResults: self.searchResults)
  865. self.isReloadDataSourceNetworkInProgress = false
  866. }
  867. }
  868. }
  869. func unifiedSearchMore(metadataForSection: NCMetadataForSection?) {
  870. guard let metadataForSection = metadataForSection, let searchResult = metadataForSection.lastSearchResult, let cursor = searchResult.cursor, let term = literalSearch else { return }
  871. metadataForSection.unifiedSearchInProgress = true
  872. self.collectionView?.reloadData()
  873. NCNetworking.shared.unifiedSearchFilesProvider(userBaseUrl: appDelegate, id: searchResult.id, term: term, limit: 5, cursor: cursor) { account, searchResult, metadatas, error in
  874. if error != .success {
  875. NCContentPresenter.shared.showError(error: error)
  876. }
  877. metadataForSection.unifiedSearchInProgress = false
  878. guard let searchResult = searchResult, let metadatas = metadatas else { return }
  879. self.dataSource.appendMetadatasToSection(metadatas, metadataForSection: metadataForSection, lastSearchResult: searchResult)
  880. DispatchQueue.main.async {
  881. self.collectionView?.reloadData()
  882. }
  883. }
  884. }
  885. @objc func networkReadFolder(forced: Bool, completion: @escaping(_ tableDirectory: tableDirectory?, _ metadatas: [tableMetadata]?, _ metadatasUpdate: [tableMetadata]?, _ metadatasDelete: [tableMetadata]?, _ error: NKError) -> Void) {
  886. var tableDirectory: tableDirectory?
  887. NCNetworking.shared.readFile(serverUrlFileName: serverUrl) { (account, metadataFolder, error) in
  888. guard error == .success else {
  889. completion(nil, nil, nil, nil, error)
  890. return
  891. }
  892. if let metadataFolder = metadataFolder {
  893. tableDirectory = NCManageDatabase.shared.setDirectory(serverUrl: self.serverUrl, richWorkspace: metadataFolder.richWorkspace, account: account)
  894. }
  895. if forced || tableDirectory?.etag != metadataFolder?.etag || metadataFolder?.e2eEncrypted ?? false {
  896. NCNetworking.shared.readFolder(serverUrl: self.serverUrl, account: self.appDelegate.account) { account, metadataFolder, metadatas, metadatasUpdate, _, metadatasDelete, error in
  897. guard error == .success else {
  898. completion(tableDirectory, nil, nil, nil, error)
  899. return
  900. }
  901. self.metadataFolder = metadataFolder
  902. // E2EE
  903. if let metadataFolder = metadataFolder, metadataFolder.e2eEncrypted, CCUtility.isEnd(toEndEnabled: self.appDelegate.account) {
  904. NextcloudKit.shared.getE2EEMetadata(fileId: metadataFolder.ocId, e2eToken: nil) { account, e2eMetadata, data, error in
  905. if error == .success, let e2eMetadata = e2eMetadata {
  906. if NCEndToEndMetadata.shared.decoderMetadata(e2eMetadata, privateKey: CCUtility.getEndToEndPrivateKey(account), serverUrl: self.serverUrl, account: self.appDelegate.account, urlBase: self.appDelegate.urlBase, userId: self.appDelegate.userId) {
  907. self.reloadDataSource()
  908. } else {
  909. let error = NKError(errorCode: NCGlobal.shared.errorDecodeMetadata, errorDescription: "_e2e_error_decode_metadata_")
  910. NCContentPresenter.shared.messageNotification("_error_e2ee_", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error)
  911. }
  912. } else if error.errorCode != NCGlobal.shared.errorResourceNotFound {
  913. let error = NKError(errorCode: NCGlobal.shared.errorDecodeMetadata, errorDescription: "_e2e_error_decode_metadata_")
  914. NCContentPresenter.shared.messageNotification("_error_e2ee_", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error)
  915. }
  916. completion(tableDirectory, metadatas, metadatasUpdate, metadatasDelete, error)
  917. }
  918. } else {
  919. completion(tableDirectory, metadatas, metadatasUpdate, metadatasDelete, error)
  920. }
  921. }
  922. } else {
  923. completion(tableDirectory, nil, nil, nil, NKError())
  924. }
  925. }
  926. }
  927. // MARK: - Push metadata
  928. func pushMetadata(_ metadata: tableMetadata) {
  929. guard let serverUrlPush = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName) else { return }
  930. appDelegate.activeMetadata = metadata
  931. // FILES
  932. if layoutKey == NCGlobal.shared.layoutViewFiles && !pushed {
  933. if let viewController = appDelegate.listFilesVC[serverUrlPush] {
  934. if viewController.isViewLoaded {
  935. pushViewController(viewController: viewController)
  936. }
  937. } else {
  938. if let viewController: NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as? NCFiles {
  939. viewController.isRoot = false
  940. viewController.serverUrl = serverUrlPush
  941. viewController.titleCurrentFolder = metadata.fileNameView
  942. appDelegate.listFilesVC[serverUrlPush] = viewController
  943. pushViewController(viewController: viewController)
  944. }
  945. }
  946. }
  947. // FAVORITE
  948. if layoutKey == NCGlobal.shared.layoutViewFavorite && !pushed {
  949. if let viewController = appDelegate.listFavoriteVC[serverUrlPush] {
  950. if viewController.isViewLoaded {
  951. pushViewController(viewController: viewController)
  952. }
  953. } else {
  954. if let viewController: NCFavorite = UIStoryboard(name: "NCFavorite", bundle: nil).instantiateInitialViewController() as? NCFavorite {
  955. viewController.serverUrl = serverUrlPush
  956. viewController.titleCurrentFolder = metadata.fileNameView
  957. appDelegate.listFavoriteVC[serverUrlPush] = viewController
  958. pushViewController(viewController: viewController)
  959. }
  960. }
  961. }
  962. // OFFLINE
  963. if layoutKey == NCGlobal.shared.layoutViewOffline && !pushed {
  964. if let viewController = appDelegate.listOfflineVC[serverUrlPush] {
  965. if viewController.isViewLoaded {
  966. pushViewController(viewController: viewController)
  967. }
  968. } else {
  969. if let viewController: NCOffline = UIStoryboard(name: "NCOffline", bundle: nil).instantiateInitialViewController() as? NCOffline {
  970. viewController.serverUrl = serverUrlPush
  971. viewController.titleCurrentFolder = metadata.fileNameView
  972. appDelegate.listOfflineVC[serverUrlPush] = viewController
  973. pushViewController(viewController: viewController)
  974. }
  975. }
  976. }
  977. // RECENT ( for push use Files ... he he he )
  978. if layoutKey == NCGlobal.shared.layoutViewRecent && !pushed {
  979. if let viewController = appDelegate.listFilesVC[serverUrlPush] {
  980. if viewController.isViewLoaded {
  981. pushViewController(viewController: viewController)
  982. }
  983. } else {
  984. if let viewController: NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as? NCFiles {
  985. viewController.isRoot = false
  986. viewController.serverUrl = serverUrlPush
  987. viewController.titleCurrentFolder = metadata.fileNameView
  988. appDelegate.listFilesVC[serverUrlPush] = viewController
  989. pushViewController(viewController: viewController)
  990. }
  991. }
  992. }
  993. // SHARES ( for push use Files ... he he he )
  994. if layoutKey == NCGlobal.shared.layoutViewShares && !pushed {
  995. if let viewController = appDelegate.listFilesVC[serverUrlPush] {
  996. if viewController.isViewLoaded {
  997. pushViewController(viewController: viewController)
  998. }
  999. } else {
  1000. if let viewController: NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as? NCFiles {
  1001. viewController.isRoot = false
  1002. viewController.serverUrl = serverUrlPush
  1003. viewController.titleCurrentFolder = metadata.fileNameView
  1004. appDelegate.listFilesVC[serverUrlPush] = viewController
  1005. pushViewController(viewController: viewController)
  1006. }
  1007. }
  1008. }
  1009. }
  1010. }
  1011. // MARK: - Collection View
  1012. extension NCCollectionViewCommon: UICollectionViewDelegate {
  1013. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  1014. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  1015. appDelegate.activeMetadata = metadata
  1016. let metadataSourceForAllSections = dataSource.getMetadataSourceForAllSections()
  1017. if isEditMode {
  1018. if let index = selectOcId.firstIndex(of: metadata.ocId) {
  1019. selectOcId.remove(at: index)
  1020. } else {
  1021. selectOcId.append(metadata.ocId)
  1022. }
  1023. collectionView.reloadItems(at: [indexPath])
  1024. self.navigationItem.title = NSLocalizedString("_selected_", comment: "") + " : \(selectOcId.count)" + " / \(metadataSourceForAllSections.count)"
  1025. return
  1026. }
  1027. if metadata.e2eEncrypted && !CCUtility.isEnd(toEndEnabled: appDelegate.account) {
  1028. let error = NKError(errorCode: NCGlobal.shared.errorE2EENotEnabled, errorDescription: "_e2e_goto_settings_for_enable_")
  1029. NCContentPresenter.shared.showInfo(error: error)
  1030. return
  1031. }
  1032. if metadata.directory {
  1033. pushMetadata(metadata)
  1034. } else {
  1035. let imageIcon = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  1036. if metadata.classFile == NKCommon.typeClassFile.image.rawValue || metadata.classFile == NKCommon.typeClassFile.video.rawValue || metadata.classFile == NKCommon.typeClassFile.audio.rawValue {
  1037. var metadatas: [tableMetadata] = []
  1038. for metadata in metadataSourceForAllSections {
  1039. if metadata.classFile == NKCommon.typeClassFile.image.rawValue || metadata.classFile == NKCommon.typeClassFile.video.rawValue || metadata.classFile == NKCommon.typeClassFile.audio.rawValue {
  1040. metadatas.append(metadata)
  1041. }
  1042. }
  1043. NCViewer.shared.view(viewController: self, metadata: metadata, metadatas: metadatas, imageIcon: imageIcon)
  1044. return
  1045. }
  1046. if CCUtility.fileProviderStorageExists(metadata) {
  1047. NCViewer.shared.view(viewController: self, metadata: metadata, metadatas: [metadata], imageIcon: imageIcon)
  1048. } else if NextcloudKit.shared.isNetworkReachable() {
  1049. NCNetworking.shared.download(metadata: metadata, selector: NCGlobal.shared.selectorLoadFileView) { _, _ in }
  1050. } else {
  1051. let error = NKError(errorCode: NCGlobal.shared.errorOffline, errorDescription: "_go_online_")
  1052. NCContentPresenter.shared.showInfo(error: error)
  1053. }
  1054. }
  1055. }
  1056. func pushViewController(viewController: UIViewController) {
  1057. if pushed { return }
  1058. pushed = true
  1059. navigationController?.pushViewController(viewController, animated: true)
  1060. }
  1061. func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
  1062. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return nil }
  1063. if isEditMode || metadata.classFile == NKCommon.typeClassFile.url.rawValue { return nil }
  1064. let identifier = indexPath as NSCopying
  1065. var image: UIImage?
  1066. let cell = collectionView.cellForItem(at: indexPath)
  1067. if cell is NCListCell {
  1068. image = (cell as! NCListCell).imageItem.image
  1069. } else if cell is NCGridCell {
  1070. image = (cell as! NCGridCell).imageItem.image
  1071. }
  1072. return UIContextMenuConfiguration(identifier: identifier, previewProvider: {
  1073. return NCViewerProviderContextMenu(metadata: metadata, image: image)
  1074. }, actionProvider: { _ in
  1075. return NCFunctionCenter.shared.contextMenuConfiguration(ocId: metadata.ocId, viewController: self, enableDeleteLocal: true, enableViewInFolder: false, image: image)
  1076. })
  1077. }
  1078. func collectionView(_ collectionView: UICollectionView, willPerformPreviewActionForMenuWith configuration: UIContextMenuConfiguration, animator: UIContextMenuInteractionCommitAnimating) {
  1079. animator.addCompletion {
  1080. if let indexPath = configuration.identifier as? IndexPath {
  1081. self.collectionView(collectionView, didSelectItemAt: indexPath)
  1082. }
  1083. }
  1084. }
  1085. }
  1086. extension NCCollectionViewCommon: UICollectionViewDataSource {
  1087. func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  1088. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  1089. // Thumbnail
  1090. if !metadata.directory {
  1091. if metadata.name == NCGlobal.shared.appName {
  1092. if let image = NCUtility.shared.createFilePreviewImage(ocId: metadata.ocId, etag: metadata.etag, fileNameView: metadata.fileNameView, classFile: metadata.classFile, status: metadata.status, createPreviewMedia: !metadata.hasPreview) {
  1093. (cell as! NCCellProtocol).filePreviewImageView?.image = image
  1094. } else {
  1095. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, placeholder: true, cell: cell, view: collectionView)
  1096. }
  1097. } else {
  1098. // Unified search
  1099. switch metadata.iconName {
  1100. case let str where str.contains("contacts"):
  1101. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconContacts
  1102. case let str where str.contains("conversation"):
  1103. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconTalk
  1104. case let str where str.contains("calendar"):
  1105. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconCalendar
  1106. case let str where str.contains("deck"):
  1107. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconDeck
  1108. case let str where str.contains("mail"):
  1109. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconMail
  1110. case let str where str.contains("talk"):
  1111. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconTalk
  1112. case let str where str.contains("confirm"):
  1113. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconConfirm
  1114. case let str where str.contains("pages"):
  1115. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconPages
  1116. default:
  1117. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.file
  1118. }
  1119. if !metadata.iconUrl.isEmpty {
  1120. if let ownerId = NCUtility.shared.getAvatarFromIconUrl(metadata: metadata), let cell = cell as? NCCellProtocol {
  1121. let fileName = metadata.userBaseUrl + "-" + ownerId + ".png"
  1122. NCOperationQueue.shared.downloadAvatar(user: ownerId, dispalyName: nil, fileName: fileName, cell: cell, view: collectionView, cellImageView: cell.filePreviewImageView)
  1123. }
  1124. }
  1125. // if metadata.iconName.contains("contacts"), let subline = metadata.subline, !subline.isEmpty, let cell = cell as? NCCellProtocol {
  1126. // let components = subline.components(separatedBy: "@")
  1127. // if let user = components.first {
  1128. // let fileName = metadata.userBaseUrl + "-" + user + ".png"
  1129. // NCOperationQueue.shared.downloadAvatar(user: user, dispalyName: nil, fileName: fileName, cell: cell, view: collectionView, cellImageView: cell.filePreviewImageView)
  1130. // }
  1131. // }
  1132. }
  1133. }
  1134. // Avatar
  1135. if metadata.ownerId.count > 0,
  1136. metadata.ownerId != appDelegate.userId,
  1137. appDelegate.account == metadata.account,
  1138. let cell = cell as? NCCellProtocol {
  1139. let fileName = metadata.userBaseUrl + "-" + metadata.ownerId + ".png"
  1140. NCOperationQueue.shared.downloadAvatar(user: metadata.ownerId, dispalyName: metadata.ownerDisplayName, fileName: fileName, cell: cell, view: collectionView, cellImageView: cell.fileAvatarImageView)
  1141. }
  1142. }
  1143. func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { }
  1144. func numberOfSections(in collectionView: UICollectionView) -> Int {
  1145. return dataSource.numberOfSections()
  1146. }
  1147. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  1148. let numberItems = dataSource.numberOfItemsInSection(section)
  1149. emptyDataSet?.numberOfItemsInSection(numberItems, section: section)
  1150. return numberItems
  1151. }
  1152. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  1153. var cell: NCCellProtocol & UICollectionViewCell
  1154. // LAYOUT LIST
  1155. if layoutForView?.layout == NCGlobal.shared.layoutList {
  1156. guard let listCell = collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as? NCListCell else { return UICollectionViewCell() }
  1157. listCell.delegate = self
  1158. cell = listCell
  1159. } else {
  1160. // LAYOUT GRID
  1161. guard let gridCell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as? NCGridCell else { return UICollectionViewCell() }
  1162. gridCell.delegate = self
  1163. cell = gridCell
  1164. }
  1165. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return cell }
  1166. let tableShare = dataSource.metadatasForSection[indexPath.section].metadataShare[metadata.ocId]
  1167. let tableDirectory = dataSource.metadatasForSection[indexPath.section].directories?.filter({ $0.ocId == metadata.ocId }).first
  1168. var isShare = false
  1169. var isMounted = false
  1170. var a11yValues: [String] = []
  1171. if metadataFolder != nil {
  1172. isShare = metadata.permissions.contains(NCGlobal.shared.permissionShared) && !metadataFolder!.permissions.contains(NCGlobal.shared.permissionShared)
  1173. isMounted = metadata.permissions.contains(NCGlobal.shared.permissionMounted) && !metadataFolder!.permissions.contains(NCGlobal.shared.permissionMounted)
  1174. }
  1175. cell.fileSelectImage?.image = nil
  1176. cell.fileStatusImage?.image = nil
  1177. cell.fileLocalImage?.image = nil
  1178. cell.fileFavoriteImage?.image = nil
  1179. cell.fileSharedImage?.image = nil
  1180. cell.fileMoreImage?.image = nil
  1181. cell.filePreviewImageView?.image = nil
  1182. cell.filePreviewImageView?.backgroundColor = nil
  1183. cell.fileObjectId = metadata.ocId
  1184. cell.fileUser = metadata.ownerId
  1185. cell.fileProgressView?.isHidden = true
  1186. cell.fileProgressView?.progress = 0.0
  1187. cell.hideButtonShare(false)
  1188. cell.hideButtonMore(false)
  1189. cell.titleInfoTrailingDefault()
  1190. if isSearchingMode {
  1191. cell.fileTitleLabel?.text = metadata.fileName
  1192. cell.fileTitleLabel?.lineBreakMode = .byTruncatingTail
  1193. if metadata.name == NCGlobal.shared.appName {
  1194. cell.fileInfoLabel?.text = NSLocalizedString("_in_", comment: "") + " " + NCUtilityFileSystem.shared.getPath(path: metadata.path, user: metadata.user)
  1195. } else {
  1196. cell.fileInfoLabel?.text = metadata.subline
  1197. cell.titleInfoTrailingFull()
  1198. }
  1199. } else {
  1200. cell.fileTitleLabel?.text = metadata.fileNameView
  1201. cell.fileTitleLabel?.lineBreakMode = .byTruncatingMiddle
  1202. cell.writeInfoDateSize(date: metadata.date, size: metadata.size)
  1203. }
  1204. if metadata.status == NCGlobal.shared.metadataStatusDownloading || metadata.status == NCGlobal.shared.metadataStatusUploading {
  1205. cell.fileProgressView?.isHidden = false
  1206. }
  1207. // Accessibility [shared]
  1208. if metadata.ownerId != appDelegate.userId, appDelegate.account == metadata.account {
  1209. a11yValues.append(NSLocalizedString("_shared_with_you_by_", comment: "") + " " + metadata.ownerDisplayName)
  1210. }
  1211. if metadata.directory {
  1212. if metadata.e2eEncrypted {
  1213. cell.filePreviewImageView?.image = NCBrandColor.cacheImages.folderEncrypted
  1214. } else if isShare {
  1215. cell.filePreviewImageView?.image = NCBrandColor.cacheImages.folderSharedWithMe
  1216. } else if tableShare != nil && tableShare?.shareType != 3 {
  1217. cell.filePreviewImageView?.image = NCBrandColor.cacheImages.folderSharedWithMe
  1218. } else if tableShare != nil && tableShare?.shareType == 3 {
  1219. cell.filePreviewImageView?.image = NCBrandColor.cacheImages.folderPublic
  1220. } else if metadata.mountType == "group" {
  1221. cell.filePreviewImageView?.image = NCBrandColor.cacheImages.folderGroup
  1222. } else if isMounted {
  1223. cell.filePreviewImageView?.image = NCBrandColor.cacheImages.folderExternal
  1224. } else if metadata.fileName == autoUploadFileName && metadata.serverUrl == autoUploadDirectory {
  1225. cell.filePreviewImageView?.image = NCBrandColor.cacheImages.folderAutomaticUpload
  1226. } else {
  1227. cell.filePreviewImageView?.image = NCBrandColor.cacheImages.folder
  1228. }
  1229. // Local image: offline
  1230. if let tableDirectory = tableDirectory, tableDirectory.offline {
  1231. cell.fileLocalImage?.image = NCBrandColor.cacheImages.offlineFlag
  1232. }
  1233. // color folder
  1234. cell.filePreviewImageView?.image = cell.filePreviewImageView?.image?.colorizeFolder(metadata: metadata, tableDirectory: tableDirectory)
  1235. } else {
  1236. // image local
  1237. if dataSource.metadatasForSection[indexPath.section].metadataOffLine.contains(metadata.ocId) {
  1238. a11yValues.append(NSLocalizedString("_offline_", comment: ""))
  1239. cell.fileLocalImage?.image = NCBrandColor.cacheImages.offlineFlag
  1240. } else if CCUtility.fileProviderStorageExists(metadata) {
  1241. cell.fileLocalImage?.image = NCBrandColor.cacheImages.local
  1242. }
  1243. }
  1244. // image Favorite
  1245. if metadata.favorite {
  1246. cell.fileFavoriteImage?.image = NCBrandColor.cacheImages.favorite
  1247. a11yValues.append(NSLocalizedString("_favorite_", comment: ""))
  1248. }
  1249. // Share image
  1250. if isShare {
  1251. cell.fileSharedImage?.image = NCBrandColor.cacheImages.shared
  1252. } else if tableShare != nil && tableShare?.shareType == 3 {
  1253. cell.fileSharedImage?.image = NCBrandColor.cacheImages.shareByLink
  1254. } else if tableShare != nil && tableShare?.shareType != 3 {
  1255. cell.fileSharedImage?.image = NCBrandColor.cacheImages.shared
  1256. } else {
  1257. cell.fileSharedImage?.image = NCBrandColor.cacheImages.canShare
  1258. }
  1259. if appDelegate.account != metadata.account {
  1260. cell.fileSharedImage?.image = NCBrandColor.cacheImages.shared
  1261. }
  1262. // Button More
  1263. if metadata.status == NCGlobal.shared.metadataStatusInDownload || metadata.status == NCGlobal.shared.metadataStatusDownloading || metadata.status == NCGlobal.shared.metadataStatusInUpload || metadata.status == NCGlobal.shared.metadataStatusUploading {
  1264. cell.setButtonMore(named: NCGlobal.shared.buttonMoreStop, image: NCBrandColor.cacheImages.buttonStop)
  1265. } else if metadata.lock == true {
  1266. cell.setButtonMore(named: NCGlobal.shared.buttonMoreLock, image: NCBrandColor.cacheImages.buttonMoreLock)
  1267. a11yValues.append(String(format: NSLocalizedString("_locked_by_", comment: ""), metadata.lockOwnerDisplayName))
  1268. } else {
  1269. cell.setButtonMore(named: NCGlobal.shared.buttonMoreMore, image: NCBrandColor.cacheImages.buttonMore)
  1270. }
  1271. // Write status on Label Info
  1272. switch metadata.status {
  1273. case NCGlobal.shared.metadataStatusWaitDownload:
  1274. cell.fileInfoLabel?.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_download_", comment: "")
  1275. break
  1276. case NCGlobal.shared.metadataStatusInDownload:
  1277. cell.fileInfoLabel?.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_download_", comment: "")
  1278. break
  1279. case NCGlobal.shared.metadataStatusDownloading:
  1280. cell.fileInfoLabel?.text = CCUtility.transformedSize(metadata.size) + " - ↓ …"
  1281. break
  1282. case NCGlobal.shared.metadataStatusWaitUpload:
  1283. cell.fileInfoLabel?.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_upload_", comment: "")
  1284. break
  1285. case NCGlobal.shared.metadataStatusInUpload:
  1286. cell.fileInfoLabel?.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_upload_", comment: "")
  1287. break
  1288. case NCGlobal.shared.metadataStatusUploading:
  1289. cell.fileInfoLabel?.text = CCUtility.transformedSize(metadata.size) + " - ↑ …"
  1290. break
  1291. case NCGlobal.shared.metadataStatusUploadError:
  1292. if metadata.sessionError != "" {
  1293. cell.fileInfoLabel?.text = NSLocalizedString("_status_wait_upload_", comment: "") + " " + metadata.sessionError
  1294. } else {
  1295. cell.fileInfoLabel?.text = NSLocalizedString("_status_wait_upload_", comment: "")
  1296. }
  1297. break
  1298. default:
  1299. break
  1300. }
  1301. // Live Photo
  1302. if metadata.livePhoto {
  1303. cell.fileStatusImage?.image = NCBrandColor.cacheImages.livePhoto
  1304. a11yValues.append(NSLocalizedString("_upload_mov_livephoto_", comment: ""))
  1305. }
  1306. // E2EE
  1307. if metadata.e2eEncrypted || isEncryptedFolder {
  1308. cell.hideButtonShare(true)
  1309. }
  1310. // URL
  1311. if metadata.classFile == NKCommon.typeClassFile.url.rawValue {
  1312. cell.fileLocalImage?.image = nil
  1313. cell.hideButtonShare(true)
  1314. cell.hideButtonMore(true)
  1315. if let ownerId = NCUtility.shared.getAvatarFromIconUrl(metadata: metadata) {
  1316. cell.fileUser = ownerId
  1317. }
  1318. }
  1319. // Disable Share Button
  1320. if appDelegate.disableSharesView {
  1321. cell.hideButtonShare(true)
  1322. }
  1323. // Separator
  1324. if collectionView.numberOfItems(inSection: indexPath.section) == indexPath.row + 1 || isSearchingMode {
  1325. cell.cellSeparatorView?.isHidden = true
  1326. } else {
  1327. cell.cellSeparatorView?.isHidden = false
  1328. }
  1329. // Edit mode
  1330. if isEditMode {
  1331. cell.selectMode(true)
  1332. if selectOcId.contains(metadata.ocId) {
  1333. cell.selected(true)
  1334. a11yValues.append(NSLocalizedString("_selected_", comment: ""))
  1335. } else {
  1336. cell.selected(false)
  1337. }
  1338. } else {
  1339. cell.selectMode(false)
  1340. }
  1341. // Accessibility
  1342. cell.setAccessibility(label: metadata.fileNameView + ", " + (cell.fileInfoLabel?.text ?? ""), value: a11yValues.joined(separator: ", "))
  1343. // Color string find in search
  1344. if isSearchingMode, let literalSearch = self.literalSearch, let title = cell.fileTitleLabel?.text {
  1345. let longestWordRange = (title.lowercased() as NSString).range(of: literalSearch)
  1346. let attributedString = NSMutableAttributedString(string: title, attributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 15)])
  1347. attributedString.setAttributes([NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 15), NSAttributedString.Key.foregroundColor : UIColor.systemBlue], range: longestWordRange)
  1348. cell.fileTitleLabel?.attributedText = attributedString
  1349. }
  1350. return cell
  1351. }
  1352. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  1353. if kind == UICollectionView.elementKindSectionHeader {
  1354. if indexPath.section == 0 {
  1355. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeaderMenu", for: indexPath) as! NCSectionHeaderMenu
  1356. let (_, heightHeaderRichWorkspace, heightHeaderSection) = getHeaderHeight(section: indexPath.section)
  1357. self.headerMenu = header
  1358. if layoutForView?.layout == NCGlobal.shared.layoutGrid {
  1359. header.setImageSwitchList()
  1360. header.buttonSwitch.accessibilityLabel = NSLocalizedString("_list_view_", comment: "")
  1361. } else {
  1362. header.setImageSwitchGrid()
  1363. header.buttonSwitch.accessibilityLabel = NSLocalizedString("_grid_view_", comment: "")
  1364. }
  1365. header.delegate = self
  1366. if headerMenuButtonsCommand && !isSearchingMode {
  1367. header.setButtonsCommand(heigt: NCGlobal.shared.heightButtonsCommand, imageButton1: UIImage(named: "addImage"), titleButton1: NSLocalizedString("_upload_", comment: ""), imageButton2: UIImage(named: "folder"), titleButton2: NSLocalizedString("_create_folder_", comment: ""), imageButton3: UIImage(named: "scan"), titleButton3: NSLocalizedString("_scan_", comment: ""))
  1368. } else {
  1369. header.setButtonsCommand(heigt: 0)
  1370. }
  1371. if headerMenuButtonsView {
  1372. header.setStatusButtonsView(enable: !dataSource.getMetadataSourceForAllSections().isEmpty)
  1373. header.setButtonsView(heigt: NCGlobal.shared.heightButtonsView)
  1374. header.setSortedTitle(layoutForView?.titleButtonHeader ?? "")
  1375. } else {
  1376. header.setButtonsView(heigt: 0)
  1377. }
  1378. header.setRichWorkspaceHeight(heightHeaderRichWorkspace)
  1379. header.setRichWorkspaceText(richWorkspaceText)
  1380. header.setSectionHeight(heightHeaderSection)
  1381. if heightHeaderSection == 0 {
  1382. header.labelSection.text = ""
  1383. } else {
  1384. header.labelSection.text = self.dataSource.getSectionValueLocalization(indexPath: indexPath)
  1385. }
  1386. header.labelSection.textColor = .label
  1387. return header
  1388. } else {
  1389. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeader", for: indexPath) as! NCSectionHeader
  1390. header.labelSection.text = self.dataSource.getSectionValueLocalization(indexPath: indexPath)
  1391. header.labelSection.textColor = .label
  1392. return header
  1393. }
  1394. } else {
  1395. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  1396. let sections = dataSource.numberOfSections()
  1397. let section = indexPath.section
  1398. let metadataForSection = self.dataSource.getMetadataForSection(indexPath.section)
  1399. let isPaginated = metadataForSection?.lastSearchResult?.isPaginated ?? false
  1400. let metadatasCount: Int = metadataForSection?.metadatas.count ?? 0
  1401. let unifiedSearchInProgress = metadataForSection?.unifiedSearchInProgress ?? false
  1402. footer.delegate = self
  1403. footer.metadataForSection = metadataForSection
  1404. footer.setTitleLabel("")
  1405. footer.setButtonText(NSLocalizedString("_show_more_results_", comment: ""))
  1406. footer.separatorIsHidden(true)
  1407. footer.buttonIsHidden(true)
  1408. footer.hideActivityIndicatorSection()
  1409. if isSearchingMode {
  1410. if sections > 1 && section != sections - 1 {
  1411. footer.separatorIsHidden(false)
  1412. }
  1413. if isSearchingMode && isPaginated && metadatasCount > 0 {
  1414. footer.buttonIsHidden(false)
  1415. }
  1416. if unifiedSearchInProgress {
  1417. footer.showActivityIndicatorSection()
  1418. }
  1419. } else {
  1420. if sections == 1 || section == sections - 1 {
  1421. let info = dataSource.getFooterInformationAllMetadatas()
  1422. footer.setTitleLabel(directories: info.directories, files: info.files, size: info.size)
  1423. } else {
  1424. footer.separatorIsHidden(false)
  1425. }
  1426. }
  1427. return footer
  1428. }
  1429. }
  1430. }
  1431. extension NCCollectionViewCommon: UICollectionViewDelegateFlowLayout {
  1432. func getHeaderHeight() -> CGFloat {
  1433. var size: CGFloat = 0
  1434. if headerMenuButtonsCommand && !isSearchingMode {
  1435. size += NCGlobal.shared.heightButtonsCommand
  1436. }
  1437. if headerMenuButtonsView {
  1438. size += NCGlobal.shared.heightButtonsView
  1439. }
  1440. return size
  1441. }
  1442. func getHeaderHeight(section:Int) -> (heightHeaderCommands: CGFloat, heightHeaderRichWorkspace: CGFloat, heightHeaderSection: CGFloat) {
  1443. var headerRichWorkspace: CGFloat = 0
  1444. if let richWorkspaceText = richWorkspaceText, !headerRichWorkspaceDisable {
  1445. let trimmed = richWorkspaceText.trimmingCharacters(in: .whitespaces)
  1446. if trimmed.count > 0 && !isSearchingMode {
  1447. headerRichWorkspace = UIScreen.main.bounds.size.height / 6
  1448. }
  1449. }
  1450. if isSearchingMode || layoutForView?.layout == NCGlobal.shared.layoutGrid || dataSource.numberOfSections() > 1 {
  1451. if section == 0 {
  1452. return (getHeaderHeight(), headerRichWorkspace, NCGlobal.shared.heightSection)
  1453. } else {
  1454. return (0, 0, NCGlobal.shared.heightSection)
  1455. }
  1456. } else {
  1457. return (getHeaderHeight(), headerRichWorkspace, 0)
  1458. }
  1459. }
  1460. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  1461. let (heightHeaderCommands, heightHeaderRichWorkspace, heightHeaderSection) = getHeaderHeight(section: section)
  1462. let heightHeader = heightHeaderCommands + heightHeaderRichWorkspace + heightHeaderSection
  1463. return CGSize(width: collectionView.frame.width, height: heightHeader)
  1464. }
  1465. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  1466. let sections = dataSource.numberOfSections()
  1467. let metadataForSection = self.dataSource.getMetadataForSection(section)
  1468. let isPaginated = metadataForSection?.lastSearchResult?.isPaginated ?? false
  1469. let metadatasCount: Int = metadataForSection?.lastSearchResult?.entries.count ?? 0
  1470. var size = CGSize(width: collectionView.frame.width, height: 0)
  1471. if section == sections - 1 {
  1472. size.height += NCGlobal.shared.endHeightFooter
  1473. } else {
  1474. size.height += NCGlobal.shared.heightFooter
  1475. }
  1476. if isSearchingMode && isPaginated && metadatasCount > 0 {
  1477. size.height += NCGlobal.shared.heightFooterButton
  1478. }
  1479. return size
  1480. }
  1481. }
  1482. extension NCCollectionViewCommon: EasyTipViewDelegate {
  1483. func easyTipViewDidTap(_ tipView: EasyTipView) {
  1484. NCManageDatabase.shared.addTip(NCGlobal.shared.tipNCCollectionViewCommonAccountRequest)
  1485. }
  1486. func easyTipViewDidDismiss(_ tipView: EasyTipView) { }
  1487. func dismissTip() {
  1488. NCManageDatabase.shared.addTip(NCGlobal.shared.tipNCCollectionViewCommonAccountRequest)
  1489. self.tipView?.dismiss()
  1490. }
  1491. }