NCCollectionViewCommon.swift 82 KB

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