NCCollectionViewCommon.swift 83 KB

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