NCCollectionViewCommon.swift 84 KB

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