NCCollectionViewCommon.swift 84 KB

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