NCCollectionViewCommon.swift 80 KB

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