NCCollectionViewCommon.swift 83 KB

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