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