NCCollectionViewCommon.swift 84 KB

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