NCCollectionViewCommon.swift 85 KB

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