NCCollectionViewCommon.swift 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726
  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 row = dataSource.deleteMetadata(ocId: ocId) {
  288. let indexPath = IndexPath(row: row, section: 0)
  289. collectionView?.performBatchUpdates({
  290. collectionView?.deleteItems(at: [indexPath])
  291. }, completion: { _ in
  292. self.collectionView?.reloadData()
  293. })
  294. }
  295. }
  296. }
  297. }
  298. @objc func moveFile(_ notification: NSNotification) {
  299. 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) {
  300. // DEL
  301. if serverUrlFrom == serverUrl && metadata.account == appDelegate.account {
  302. if let row = dataSource.deleteMetadata(ocId: ocId) {
  303. let indexPath = IndexPath(row: row, section: 0)
  304. collectionView?.performBatchUpdates({
  305. collectionView?.deleteItems(at: [indexPath])
  306. }, completion: { _ in
  307. self.collectionView?.reloadData()
  308. })
  309. }
  310. // ADD
  311. } else if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  312. if let row = dataSource.addMetadata(metadata) {
  313. let indexPath = IndexPath(row: row, section: 0)
  314. collectionView?.performBatchUpdates({
  315. collectionView?.insertItems(at: [indexPath])
  316. }, completion: { _ in
  317. self.collectionView?.reloadData()
  318. })
  319. }
  320. }
  321. }
  322. }
  323. @objc func copyFile(_ notification: NSNotification) {
  324. if let userInfo = notification.userInfo as NSDictionary?, let serverUrlTo = userInfo["serverUrlTo"] as? String {
  325. if serverUrlTo == self.serverUrl {
  326. reloadDataSource()
  327. }
  328. }
  329. }
  330. @objc func renameFile(_ notification: NSNotification) {
  331. reloadDataSource()
  332. }
  333. @objc func createFolder(_ notification: NSNotification) {
  334. if let userInfo = notification.userInfo as NSDictionary?, let ocId = userInfo["ocId"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  335. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  336. pushMetadata(metadata)
  337. }
  338. } else {
  339. reloadDataSourceNetwork()
  340. }
  341. }
  342. @objc func favoriteFile(_ notification: NSNotification) {
  343. if let userInfo = notification.userInfo as NSDictionary?, let ocId = userInfo["ocId"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  344. if dataSource.getIndexMetadata(ocId: metadata.ocId) != nil {
  345. reloadDataSource()
  346. }
  347. }
  348. }
  349. @objc func downloadStartFile(_ notification: NSNotification) {
  350. if let userInfo = notification.userInfo as NSDictionary?, let ocId = userInfo["ocId"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  351. if let row = dataSource.reloadMetadata(ocId: metadata.ocId) {
  352. let indexPath = IndexPath(row: row, section: 0)
  353. if indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section) {
  354. collectionView?.reloadItems(at: [indexPath])
  355. }
  356. }
  357. }
  358. }
  359. @objc func downloadedFile(_ notification: NSNotification) {
  360. guard let userInfo = notification.userInfo as NSDictionary?,
  361. let ocId = userInfo["ocId"] as? String,
  362. let _ = userInfo["errorCode"] as? Int,
  363. let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId),
  364. let row = dataSource.reloadMetadata(ocId: metadata.ocId)
  365. else { return }
  366. let indexPath = IndexPath(row: row, section: 0)
  367. if indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section) {
  368. collectionView?.reloadItems(at: [indexPath])
  369. }
  370. }
  371. @objc func downloadCancelFile(_ notification: NSNotification) {
  372. if let userInfo = notification.userInfo as NSDictionary?, let ocId = userInfo["ocId"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  373. if let row = dataSource.reloadMetadata(ocId: metadata.ocId) {
  374. let indexPath = IndexPath(row: row, section: 0)
  375. if indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section) {
  376. collectionView?.reloadItems(at: [indexPath])
  377. }
  378. }
  379. }
  380. }
  381. @objc func uploadStartFile(_ notification: NSNotification) {
  382. if let userInfo = notification.userInfo as NSDictionary?, let ocId = userInfo["ocId"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  383. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  384. dataSource.addMetadata(metadata)
  385. self.collectionView?.reloadData()
  386. }
  387. }
  388. }
  389. @objc func uploadedFile(_ notification: NSNotification) {
  390. 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) {
  391. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  392. dataSource.reloadMetadata(ocId: metadata.ocId, ocIdTemp: ocIdTemp)
  393. collectionView?.reloadData()
  394. }
  395. }
  396. }
  397. @objc func uploadCancelFile(_ notification: NSNotification) {
  398. 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 {
  399. if serverUrl == self.serverUrl && account == appDelegate.account {
  400. if let row = dataSource.deleteMetadata(ocId: ocId) {
  401. let indexPath = IndexPath(row: row, section: 0)
  402. collectionView?.performBatchUpdates({
  403. if indexPath.section < (collectionView?.numberOfSections ?? 0) && indexPath.row < (collectionView?.numberOfItems(inSection: indexPath.section) ?? 0) {
  404. collectionView?.deleteItems(at: [indexPath])
  405. }
  406. }, completion: { _ in
  407. self.collectionView?.reloadData()
  408. })
  409. } else {
  410. self.reloadDataSource()
  411. }
  412. }
  413. }
  414. }
  415. @objc func triggerProgressTask(_ notification: NSNotification) {
  416. 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 {
  417. let status = userInfo["status"] as? Int ?? NCGlobal.shared.metadataStatusNormal
  418. if let index = dataSource.getIndexMetadata(ocId: ocId) {
  419. if let cell = collectionView?.cellForItem(at: IndexPath(row: index, section: 0)) {
  420. if cell is NCListCell {
  421. let cell = cell as! NCListCell
  422. if progressNumber.floatValue == 1 {
  423. cell.progressView?.isHidden = true
  424. cell.progressView?.progress = .zero
  425. cell.setButtonMore(named: NCGlobal.shared.buttonMoreMore, image: NCBrandColor.cacheImages.buttonMore)
  426. if let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  427. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date) + " · " + CCUtility.transformedSize(metadata.size)
  428. } else {
  429. cell.labelInfo.text = ""
  430. }
  431. } else if progressNumber.floatValue > 0 {
  432. cell.progressView?.isHidden = false
  433. cell.progressView?.progress = progressNumber.floatValue
  434. cell.setButtonMore(named: NCGlobal.shared.buttonMoreStop, image: NCBrandColor.cacheImages.buttonStop)
  435. if status == NCGlobal.shared.metadataStatusInDownload {
  436. cell.labelInfo.text = CCUtility.transformedSize(totalBytesExpected) + " - ↓ " + CCUtility.transformedSize(totalBytes)
  437. } else if status == NCGlobal.shared.metadataStatusInUpload {
  438. cell.labelInfo.text = CCUtility.transformedSize(totalBytesExpected) + " - ↑ " + CCUtility.transformedSize(totalBytes)
  439. }
  440. }
  441. } else if cell is NCTransferCell {
  442. let cell = cell as! NCTransferCell
  443. if progressNumber.floatValue == 1 {
  444. cell.progressView?.isHidden = true
  445. cell.progressView?.progress = .zero
  446. cell.buttonMore.isHidden = true
  447. cell.labelInfo.text = ""
  448. } else if progressNumber.floatValue > 0 {
  449. cell.progressView?.isHidden = false
  450. cell.progressView?.progress = progressNumber.floatValue
  451. cell.setButtonMore(named: NCGlobal.shared.buttonMoreStop, image: NCBrandColor.cacheImages.buttonStop)
  452. if status == NCGlobal.shared.metadataStatusInDownload {
  453. cell.labelInfo.text = CCUtility.transformedSize(totalBytesExpected) + " - ↓ " + CCUtility.transformedSize(totalBytes)
  454. } else if status == NCGlobal.shared.metadataStatusInUpload {
  455. cell.labelInfo.text = CCUtility.transformedSize(totalBytesExpected) + " - ↑ " + CCUtility.transformedSize(totalBytes)
  456. }
  457. }
  458. } else if cell is NCGridCell {
  459. let cell = cell as! NCGridCell
  460. if progressNumber.floatValue == 1 {
  461. cell.progressView.isHidden = true
  462. cell.progressView.progress = .zero
  463. cell.setButtonMore(named: NCGlobal.shared.buttonMoreMore, image: NCBrandColor.cacheImages.buttonMore)
  464. } else if progressNumber.floatValue > 0 {
  465. cell.progressView.isHidden = false
  466. cell.progressView.progress = progressNumber.floatValue
  467. cell.setButtonMore(named: NCGlobal.shared.buttonMoreStop, image: NCBrandColor.cacheImages.buttonStop)
  468. }
  469. }
  470. }
  471. }
  472. }
  473. }
  474. // MARK: - Layout
  475. @objc func setNavigationItem() {
  476. self.setNavigationHeader()
  477. guard !isEditMode, layoutKey == NCGlobal.shared.layoutViewFiles else { return }
  478. // PROFILE BUTTON
  479. let activeAccount = NCManageDatabase.shared.getActiveAccount()
  480. let image = NCUtility.shared.loadUserImage(
  481. for: appDelegate.user,
  482. displayName: activeAccount?.displayName,
  483. userBaseUrl: appDelegate)
  484. let button = UIButton(type: .custom)
  485. button.setImage(image, for: .normal)
  486. if serverUrl == NCUtilityFileSystem.shared.getHomeServer(account: appDelegate.account) {
  487. var titleButton = " "
  488. if getNavigationTitle() == activeAccount?.alias {
  489. titleButton = ""
  490. } else {
  491. titleButton += activeAccount?.displayName ?? ""
  492. }
  493. button.setTitle(titleButton, for: .normal)
  494. button.setTitleColor(.systemBlue, for: .normal)
  495. }
  496. button.semanticContentAttribute = .forceLeftToRight
  497. button.sizeToFit()
  498. button.action(for: .touchUpInside) { _ in
  499. let accounts = NCManageDatabase.shared.getAllAccountOrderAlias()
  500. if accounts.count > 0 && !NCBrandOptions.shared.disable_multiaccount && !NCBrandOptions.shared.disable_manage_account {
  501. if let vcAccountRequest = UIStoryboard(name: "NCAccountRequest", bundle: nil).instantiateInitialViewController() as? NCAccountRequest {
  502. vcAccountRequest.activeAccount = NCManageDatabase.shared.getActiveAccount()
  503. vcAccountRequest.accounts = accounts
  504. vcAccountRequest.enableTimerProgress = false
  505. vcAccountRequest.enableAddAccount = true
  506. vcAccountRequest.delegate = self
  507. vcAccountRequest.dismissDidEnterBackground = true
  508. let screenHeighMax = UIScreen.main.bounds.height - (UIScreen.main.bounds.height/5)
  509. let numberCell = accounts.count + 1
  510. let height = min(CGFloat(numberCell * Int(vcAccountRequest.heightCell) + 45), screenHeighMax)
  511. let popup = NCPopupViewController(contentController: vcAccountRequest, popupWidth: 300, popupHeight: height)
  512. UIApplication.shared.keyWindow?.rootViewController?.present(popup, animated: true)
  513. }
  514. }
  515. }
  516. navigationItem.setLeftBarButton(UIBarButtonItem(customView: button), animated: true)
  517. navigationItem.leftItemsSupplementBackButton = true
  518. }
  519. func getNavigationTitle() -> String {
  520. let activeAccount = NCManageDatabase.shared.getActiveAccount()
  521. guard let userAlias = activeAccount?.alias, !userAlias.isEmpty else {
  522. return NCBrandOptions.shared.brand
  523. }
  524. return userAlias
  525. }
  526. // MARK: - BackgroundImageColor Delegate
  527. func colorPickerCancel() {
  528. changeTheming()
  529. }
  530. func colorPickerWillChange(color: UIColor) {
  531. collectionView.backgroundColor = color
  532. }
  533. func colorPickerDidChange(lightColor: String, darkColor: String) {
  534. NCManageDatabase.shared.setAccountColorFiles(lightColorBackground: lightColor, darkColorBackground: darkColor)
  535. changeTheming()
  536. }
  537. // MARK: - Empty
  538. func emptyDataSetView(_ view: NCEmptyView) {
  539. if isSearching {
  540. view.emptyImage.image = UIImage(named: "search")?.image(color: .gray, size: UIScreen.main.bounds.width)
  541. if isReloadDataSourceNetworkInProgress {
  542. view.emptyTitle.text = NSLocalizedString("_search_in_progress_", comment: "")
  543. } else {
  544. view.emptyTitle.text = NSLocalizedString("_search_no_record_found_", comment: "")
  545. }
  546. view.emptyDescription.text = NSLocalizedString("_search_instruction_", comment: "")
  547. } else if isReloadDataSourceNetworkInProgress {
  548. view.emptyImage.image = UIImage(named: "networkInProgress")?.image(color: .gray, size: UIScreen.main.bounds.width)
  549. view.emptyTitle.text = NSLocalizedString("_request_in_progress_", comment: "")
  550. view.emptyDescription.text = ""
  551. } else {
  552. if serverUrl == "" {
  553. view.emptyImage.image = emptyImage
  554. view.emptyTitle.text = NSLocalizedString(emptyTitle, comment: "")
  555. view.emptyDescription.text = NSLocalizedString(emptyDescription, comment: "")
  556. } else {
  557. view.emptyImage.image = UIImage(named: "folder")?.image(color: NCBrandColor.shared.brandElement, size: UIScreen.main.bounds.width)
  558. view.emptyTitle.text = NSLocalizedString("_files_no_files_", comment: "")
  559. view.emptyDescription.text = NSLocalizedString("_no_file_pull_down_", comment: "")
  560. }
  561. }
  562. }
  563. // MARK: - SEARCH
  564. func updateSearchResults(for searchController: UISearchController) {
  565. timerInputSearch?.invalidate()
  566. timerInputSearch = Timer.scheduledTimer(timeInterval: 1.5, target: self, selector: #selector(reloadDataSourceNetwork), userInfo: nil, repeats: false)
  567. literalSearch = searchController.searchBar.text
  568. collectionView?.reloadData()
  569. }
  570. func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
  571. isSearching = true
  572. metadatasSource.removeAll()
  573. reloadDataSource()
  574. }
  575. func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
  576. isSearching = false
  577. literalSearch = ""
  578. reloadDataSource()
  579. }
  580. // MARK: - TAP EVENT
  581. func accountRequestChangeAccount(account: String) {
  582. NCManageDatabase.shared.setAccountActive(account)
  583. if let activeAccount = NCManageDatabase.shared.getActiveAccount() {
  584. NCOperationQueue.shared.cancelAllQueue()
  585. NCNetworking.shared.cancelAllTask()
  586. appDelegate.settingAccount(activeAccount.account, urlBase: activeAccount.urlBase, user: activeAccount.user, userId: activeAccount.userId, password: CCUtility.getPassword(activeAccount.account))
  587. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterInitialize)
  588. }
  589. }
  590. func accountRequestAddAccount() {
  591. appDelegate.openLogin(viewController: self, selector: NCGlobal.shared.introLogin, openLoginWeb: false)
  592. }
  593. func tapSwitchHeader(sender: Any) {
  594. if collectionView.collectionViewLayout == gridLayout {
  595. // list layout
  596. header?.buttonSwitch.accessibilityLabel = NSLocalizedString("_grid_view_", comment: "")
  597. UIView.animate(withDuration: 0.0, animations: {
  598. self.collectionView.collectionViewLayout.invalidateLayout()
  599. self.collectionView.setCollectionViewLayout(self.listLayout, animated: false, completion: { _ in
  600. self.collectionView.reloadData()
  601. })
  602. })
  603. layoutForView?.layout = NCGlobal.shared.layoutList
  604. NCUtility.shared.setLayoutForView(key: layoutKey, serverUrl: serverUrl, layout: layoutForView?.layout)
  605. } else {
  606. // grid layout
  607. header?.buttonSwitch.accessibilityLabel = NSLocalizedString("_list_view_", comment: "")
  608. UIView.animate(withDuration: 0.0, animations: {
  609. self.collectionView.collectionViewLayout.invalidateLayout()
  610. self.collectionView.setCollectionViewLayout(self.gridLayout, animated: false, completion: { _ in
  611. self.collectionView.reloadData()
  612. })
  613. })
  614. layoutForView?.layout = NCGlobal.shared.layoutGrid
  615. NCUtility.shared.setLayoutForView(key: layoutKey, serverUrl: serverUrl, layout: layoutForView?.layout)
  616. }
  617. }
  618. func tapOrderHeader(sender: Any) {
  619. let sortMenu = NCSortMenu()
  620. sortMenu.toggleMenu(viewController: self, key: layoutKey, sortButton: sender as? UIButton, serverUrl: serverUrl)
  621. }
  622. func tapMoreHeader(sender: Any) { }
  623. func tapMoreListItem(with objectId: String, namedButtonMore: String, image: UIImage?, sender: Any) {
  624. tapMoreGridItem(with: objectId, namedButtonMore: namedButtonMore, image: image, sender: sender)
  625. }
  626. func tapShareListItem(with objectId: String, sender: Any) {
  627. if isEditMode { return }
  628. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(objectId) else { return }
  629. NCFunctionCenter.shared.openShare(viewController: self, metadata: metadata, indexPage: .sharing)
  630. }
  631. func tapMoreGridItem(with objectId: String, namedButtonMore: String, image: UIImage?, sender: Any) {
  632. if isEditMode { return }
  633. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(objectId) else { return }
  634. if namedButtonMore == NCGlobal.shared.buttonMoreMore || namedButtonMore == NCGlobal.shared.buttonMoreLock {
  635. toggleMenu(metadata: metadata, imageIcon: image)
  636. } else if namedButtonMore == NCGlobal.shared.buttonMoreStop {
  637. NCNetworking.shared.cancelTransferMetadata(metadata) { }
  638. }
  639. }
  640. func tapRichWorkspace(sender: Any) {
  641. if let navigationController = UIStoryboard(name: "NCViewerRichWorkspace", bundle: nil).instantiateInitialViewController() as? UINavigationController {
  642. if let viewerRichWorkspace = navigationController.topViewController as? NCViewerRichWorkspace {
  643. viewerRichWorkspace.richWorkspaceText = richWorkspaceText ?? ""
  644. viewerRichWorkspace.serverUrl = serverUrl
  645. navigationController.modalPresentationStyle = .fullScreen
  646. self.present(navigationController, animated: true, completion: nil)
  647. }
  648. }
  649. }
  650. func longPressListItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) {
  651. }
  652. func longPressGridItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) {
  653. }
  654. func longPressMoreListItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) {
  655. }
  656. func longPressMoreGridItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) {
  657. }
  658. @objc func longPressCollecationView(_ gestureRecognizer: UILongPressGestureRecognizer) {
  659. openMenuItems(with: nil, gestureRecognizer: gestureRecognizer)
  660. /*
  661. if #available(iOS 13.0, *) {
  662. let interaction = UIContextMenuInteraction(delegate: self)
  663. self.view.addInteraction(interaction)
  664. }
  665. */
  666. }
  667. @available(iOS 13.0, *)
  668. func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
  669. return UIContextMenuConfiguration(identifier: nil, previewProvider: {
  670. return nil
  671. }, actionProvider: { _ in
  672. // let share = UIAction(title: "Share Pupper", image: UIImage(systemName: "square.and.arrow.up")) { action in
  673. // }
  674. // return UIMenu(title: "Main Menu", children: [share])
  675. return nil
  676. })
  677. }
  678. func openMenuItems(with objectId: String?, gestureRecognizer: UILongPressGestureRecognizer) {
  679. if gestureRecognizer.state != .began { return }
  680. var listMenuItems: [UIMenuItem] = []
  681. let touchPoint = gestureRecognizer.location(in: collectionView)
  682. becomeFirstResponder()
  683. if serverUrl != "" {
  684. listMenuItems.append(UIMenuItem(title: NSLocalizedString("_paste_file_", comment: ""), action: #selector(pasteFilesMenu)))
  685. }
  686. if #available(iOS 13.0, *) {
  687. if !NCBrandOptions.shared.disable_background_color {
  688. listMenuItems.append(UIMenuItem(title: NSLocalizedString("_background_", comment: ""), action: #selector(backgroundFilesMenu)))
  689. }
  690. }
  691. if listMenuItems.count > 0 {
  692. UIMenuController.shared.menuItems = listMenuItems
  693. UIMenuController.shared.setTargetRect(CGRect(x: touchPoint.x, y: touchPoint.y, width: 0, height: 0), in: collectionView)
  694. UIMenuController.shared.setMenuVisible(true, animated: true)
  695. }
  696. }
  697. // MARK: - Menu Item
  698. override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
  699. if #selector(pasteFilesMenu) == action {
  700. if UIPasteboard.general.items.count > 0 {
  701. return true
  702. }
  703. }
  704. if #selector(backgroundFilesMenu) == action {
  705. return true
  706. }
  707. return false
  708. }
  709. @objc func pasteFilesMenu() {
  710. NCFunctionCenter.shared.pastePasteboard(serverUrl: serverUrl)
  711. }
  712. @objc func backgroundFilesMenu() {
  713. if let vcBackgroundImageColor = UIStoryboard(name: "NCBackgroundImageColor", bundle: nil).instantiateInitialViewController() as? NCBackgroundImageColor {
  714. vcBackgroundImageColor.delegate = self
  715. vcBackgroundImageColor.setupColor = collectionView.backgroundColor
  716. if let activeAccount = NCManageDatabase.shared.getActiveAccount() {
  717. vcBackgroundImageColor.lightColor = activeAccount.lightColorBackground
  718. vcBackgroundImageColor.darkColor = activeAccount.darkColorBackground
  719. }
  720. let popup = NCPopupViewController(contentController: vcBackgroundImageColor, popupWidth: vcBackgroundImageColor.width, popupHeight: vcBackgroundImageColor.height)
  721. popup.backgroundAlpha = 0
  722. self.present(popup, animated: true)
  723. }
  724. }
  725. // MARK: - DataSource + NC Endpoint
  726. @objc func reloadDataSource() {
  727. if appDelegate.account == "" { return }
  728. // Get richWorkspace Text
  729. let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, serverUrl))
  730. richWorkspaceText = directory?.richWorkspace
  731. // E2EE
  732. isEncryptedFolder = CCUtility.isFolderEncrypted(serverUrl, e2eEncrypted: metadataFolder?.e2eEncrypted ?? false, account: appDelegate.account, urlBase: appDelegate.urlBase)
  733. // get auto upload folder
  734. autoUploadFileName = NCManageDatabase.shared.getAccountAutoUploadFileName()
  735. autoUploadDirectory = NCManageDatabase.shared.getAccountAutoUploadDirectory(urlBase: appDelegate.urlBase, account: appDelegate.account)
  736. // get layout for view
  737. layoutForView = NCUtility.shared.getLayoutForView(key: layoutKey, serverUrl: serverUrl)
  738. }
  739. @objc func reloadDataSourceNetwork(forced: Bool = false) { }
  740. @objc func networkSearch() {
  741. guard !appDelegate.account.isEmpty, let literalSearch = literalSearch, !literalSearch.isEmpty
  742. else {
  743. DispatchQueue.main.async { self.refreshControl.endRefreshing() }
  744. return
  745. }
  746. let completionHandler: ([tableMetadata]?, Int, String) -> Void = { metadatas, errorCode, errorDescription in
  747. DispatchQueue.main.async {
  748. if self.searchController?.isActive == true, errorCode == 0, let metadatas = metadatas {
  749. self.metadatasSource = metadatas
  750. }
  751. self.refreshControl.endRefreshing()
  752. self.isReloadDataSourceNetworkInProgress = false
  753. self.reloadDataSource()
  754. }
  755. }
  756. isReloadDataSourceNetworkInProgress = true
  757. collectionView?.reloadData()
  758. let serverVersionMajor = NCManageDatabase.shared.getCapabilitiesServerInt(account: appDelegate.account, elements: NCElementsJSON.shared.capabilitiesVersionMajor)
  759. if serverVersionMajor >= NCGlobal.shared.nextcloudVersion20 {
  760. NCNetworking.shared.unifiedSearchFiles(urlBase: appDelegate, literal: literalSearch, update: { metadatas in
  761. guard let metadatas = metadatas else { return }
  762. self.metadatasSource = Array(metadatas)
  763. self.reloadDataSource()
  764. }, completion: completionHandler)
  765. } else {
  766. NCNetworking.shared.searchFiles(urlBase: appDelegate, literal: literalSearch, completion: completionHandler)
  767. }
  768. }
  769. @objc func networkReadFolder(forced: Bool, completion: @escaping(_ tableDirectory: tableDirectory?, _ metadatas: [tableMetadata]?, _ metadatasUpdate: [tableMetadata]?, _ metadatasDelete: [tableMetadata]?, _ errorCode: Int, _ errorDescription: String) -> Void) {
  770. var tableDirectory: tableDirectory?
  771. NCNetworking.shared.readFile(serverUrlFileName: serverUrl) { (account, metadataFolder, errorCode, errorDescription) in
  772. if errorCode == 0 {
  773. if let metadataFolder = metadataFolder {
  774. tableDirectory = NCManageDatabase.shared.setDirectory(richWorkspace: metadataFolder.richWorkspace, serverUrl: self.serverUrl, account: account)
  775. }
  776. if forced || tableDirectory?.etag != metadataFolder?.etag || metadataFolder?.e2eEncrypted ?? false {
  777. NCNetworking.shared.readFolder(serverUrl: self.serverUrl, account: self.appDelegate.account) { account, metadataFolder, metadatas, metadatasUpdate, _, metadatasDelete, errorCode, errorDescription in
  778. if errorCode == 0 {
  779. self.metadataFolder = metadataFolder
  780. // E2EE
  781. if let metadataFolder = metadataFolder {
  782. if metadataFolder.e2eEncrypted && CCUtility.isEnd(toEndEnabled: self.appDelegate.account) {
  783. NCCommunication.shared.getE2EEMetadata(fileId: metadataFolder.ocId, e2eToken: nil) { account, e2eMetadata, errorCode, errorDescription in
  784. if errorCode == 0 && e2eMetadata != nil {
  785. if !NCEndToEndMetadata.shared.decoderMetadata(e2eMetadata!, privateKey: CCUtility.getEndToEndPrivateKey(account), serverUrl: self.serverUrl, account: account, urlBase: self.appDelegate.urlBase) {
  786. NCContentPresenter.shared.messageNotification("_error_e2ee_", description: "_e2e_error_decode_metadata_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.errorDecodeMetadata)
  787. } else {
  788. self.reloadDataSource()
  789. }
  790. } else if errorCode != NCGlobal.shared.errorResourceNotFound {
  791. NCContentPresenter.shared.messageNotification("_error_e2ee_", description: "_e2e_error_decode_metadata_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.errorDecodeMetadata)
  792. }
  793. completion(tableDirectory, metadatas, metadatasUpdate, metadatasDelete, errorCode, errorDescription)
  794. }
  795. } else {
  796. completion(tableDirectory, metadatas, metadatasUpdate, metadatasDelete, errorCode, errorDescription)
  797. }
  798. } else {
  799. completion(tableDirectory, metadatas, metadatasUpdate, metadatasDelete, errorCode, errorDescription)
  800. }
  801. } else {
  802. completion(tableDirectory, nil, nil, nil, errorCode, errorDescription)
  803. }
  804. }
  805. } else {
  806. completion(tableDirectory, nil, nil, nil, 0, "")
  807. }
  808. } else {
  809. completion(nil, nil, nil, nil, errorCode, errorDescription)
  810. }
  811. }
  812. }
  813. // MARK: - Push metadata
  814. func pushMetadata(_ metadata: tableMetadata) {
  815. guard let serverUrlPush = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName) else { return }
  816. appDelegate.activeMetadata = metadata
  817. // FILES
  818. if layoutKey == NCGlobal.shared.layoutViewFiles && !pushed {
  819. if let viewController = appDelegate.listFilesVC[serverUrlPush] {
  820. if viewController.isViewLoaded {
  821. pushViewController(viewController: viewController)
  822. }
  823. } else {
  824. if let viewController: NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as? NCFiles {
  825. viewController.isRoot = false
  826. viewController.serverUrl = serverUrlPush
  827. viewController.titleCurrentFolder = metadata.fileNameView
  828. appDelegate.listFilesVC[serverUrlPush] = viewController
  829. pushViewController(viewController: viewController)
  830. }
  831. }
  832. }
  833. // FAVORITE
  834. if layoutKey == NCGlobal.shared.layoutViewFavorite && !pushed {
  835. if let viewController = appDelegate.listFavoriteVC[serverUrlPush] {
  836. if viewController.isViewLoaded {
  837. pushViewController(viewController: viewController)
  838. }
  839. } else {
  840. if let viewController: NCFavorite = UIStoryboard(name: "NCFavorite", bundle: nil).instantiateInitialViewController() as? NCFavorite {
  841. viewController.serverUrl = serverUrlPush
  842. viewController.titleCurrentFolder = metadata.fileNameView
  843. appDelegate.listFavoriteVC[serverUrlPush] = viewController
  844. pushViewController(viewController: viewController)
  845. }
  846. }
  847. }
  848. // OFFLINE
  849. if layoutKey == NCGlobal.shared.layoutViewOffline && !pushed {
  850. if let viewController = appDelegate.listOfflineVC[serverUrlPush] {
  851. if viewController.isViewLoaded {
  852. pushViewController(viewController: viewController)
  853. }
  854. } else {
  855. if let viewController: NCOffline = UIStoryboard(name: "NCOffline", bundle: nil).instantiateInitialViewController() as? NCOffline {
  856. viewController.serverUrl = serverUrlPush
  857. viewController.titleCurrentFolder = metadata.fileNameView
  858. appDelegate.listOfflineVC[serverUrlPush] = viewController
  859. pushViewController(viewController: viewController)
  860. }
  861. }
  862. }
  863. // RECENT ( for push use Files ... he he he )
  864. if layoutKey == NCGlobal.shared.layoutViewRecent && !pushed {
  865. if let viewController = appDelegate.listFilesVC[serverUrlPush] {
  866. if viewController.isViewLoaded {
  867. pushViewController(viewController: viewController)
  868. }
  869. } else {
  870. if let viewController: NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as? NCFiles {
  871. viewController.isRoot = false
  872. viewController.serverUrl = serverUrlPush
  873. viewController.titleCurrentFolder = metadata.fileNameView
  874. appDelegate.listFilesVC[serverUrlPush] = viewController
  875. pushViewController(viewController: viewController)
  876. }
  877. }
  878. }
  879. // VIEW IN FOLDER
  880. if layoutKey == NCGlobal.shared.layoutViewViewInFolder && !pushed {
  881. if let viewController: NCFileViewInFolder = UIStoryboard(name: "NCFileViewInFolder", bundle: nil).instantiateInitialViewController() as? NCFileViewInFolder {
  882. viewController.serverUrl = serverUrlPush
  883. viewController.titleCurrentFolder = metadata.fileNameView
  884. pushViewController(viewController: viewController)
  885. }
  886. }
  887. // SHARES ( for push use Files ... he he he )
  888. if layoutKey == NCGlobal.shared.layoutViewShares && !pushed {
  889. if let viewController = appDelegate.listFilesVC[serverUrlPush] {
  890. if viewController.isViewLoaded {
  891. pushViewController(viewController: viewController)
  892. }
  893. } else {
  894. if let viewController: NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as? NCFiles {
  895. viewController.isRoot = false
  896. viewController.serverUrl = serverUrlPush
  897. viewController.titleCurrentFolder = metadata.fileNameView
  898. appDelegate.listFilesVC[serverUrlPush] = viewController
  899. pushViewController(viewController: viewController)
  900. }
  901. }
  902. }
  903. }
  904. }
  905. // MARK: - Collection View
  906. extension NCCollectionViewCommon: UICollectionViewDelegate {
  907. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  908. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  909. appDelegate.activeMetadata = metadata
  910. if isEditMode {
  911. if let index = selectOcId.firstIndex(of: metadata.ocId) {
  912. selectOcId.remove(at: index)
  913. } else {
  914. selectOcId.append(metadata.ocId)
  915. }
  916. collectionView.reloadItems(at: [indexPath])
  917. self.navigationItem.title = NSLocalizedString("_selected_", comment: "") + " : \(selectOcId.count)" + " / \(dataSource.metadatas.count)"
  918. return
  919. }
  920. if metadata.e2eEncrypted && !CCUtility.isEnd(toEndEnabled: appDelegate.account) {
  921. NCContentPresenter.shared.messageNotification("_info_", description: "_e2e_goto_settings_for_enable_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info, errorCode: NCGlobal.shared.errorE2EENotEnabled)
  922. return
  923. }
  924. if metadata.directory {
  925. pushMetadata(metadata)
  926. } else if !(self is NCFileViewInFolder) {
  927. let imageIcon = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  928. if metadata.classFile == NCCommunicationCommon.typeClassFile.image.rawValue || metadata.classFile == NCCommunicationCommon.typeClassFile.video.rawValue || metadata.classFile == NCCommunicationCommon.typeClassFile.audio.rawValue {
  929. var metadatas: [tableMetadata] = []
  930. for metadata in dataSource.metadatas {
  931. if metadata.classFile == NCCommunicationCommon.typeClassFile.image.rawValue || metadata.classFile == NCCommunicationCommon.typeClassFile.video.rawValue || metadata.classFile == NCCommunicationCommon.typeClassFile.audio.rawValue {
  932. metadatas.append(metadata)
  933. }
  934. }
  935. NCViewer.shared.view(viewController: self, metadata: metadata, metadatas: metadatas, imageIcon: imageIcon)
  936. return
  937. }
  938. if CCUtility.fileProviderStorageExists(metadata) {
  939. NCViewer.shared.view(viewController: self, metadata: metadata, metadatas: [metadata], imageIcon: imageIcon)
  940. } else if NCCommunication.shared.isNetworkReachable() {
  941. NCNetworking.shared.download(metadata: metadata, selector: NCGlobal.shared.selectorLoadFileView) { _ in }
  942. } else {
  943. NCContentPresenter.shared.messageNotification("_info_", description: "_go_online_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info, errorCode: NCGlobal.shared.errorOffline)
  944. }
  945. }
  946. }
  947. func pushViewController(viewController: UIViewController) {
  948. if pushed { return }
  949. pushed = true
  950. navigationController?.pushViewController(viewController, animated: true)
  951. }
  952. @available(iOS 13.0, *)
  953. func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
  954. if isEditMode { return nil }
  955. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return nil }
  956. let identifier = indexPath as NSCopying
  957. var image: UIImage?
  958. let cell = collectionView.cellForItem(at: indexPath)
  959. if cell is NCListCell {
  960. image = (cell as! NCListCell).imageItem.image
  961. } else if cell is NCGridCell {
  962. image = (cell as! NCGridCell).imageItem.image
  963. }
  964. return UIContextMenuConfiguration(identifier: identifier, previewProvider: {
  965. return NCViewerProviderContextMenu(metadata: metadata, image: image)
  966. }, actionProvider: { _ in
  967. return NCFunctionCenter.shared.contextMenuConfiguration(ocId: metadata.ocId, viewController: self, enableDeleteLocal: true, enableViewInFolder: false, image: image)
  968. })
  969. }
  970. @available(iOS 13.0, *)
  971. func collectionView(_ collectionView: UICollectionView, willPerformPreviewActionForMenuWith configuration: UIContextMenuConfiguration, animator: UIContextMenuInteractionCommitAnimating) {
  972. animator.addCompletion {
  973. if let indexPath = configuration.identifier as? IndexPath {
  974. self.collectionView(collectionView, didSelectItemAt: indexPath)
  975. }
  976. }
  977. }
  978. }
  979. extension NCCollectionViewCommon: UICollectionViewDataSource {
  980. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  981. if kind == UICollectionView.elementKindSectionHeader {
  982. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeaderMenu", for: indexPath) as! NCSectionHeaderMenu
  983. self.header = header
  984. if collectionView.collectionViewLayout == gridLayout {
  985. header.buttonSwitch.setImage(UIImage(named: "switchList")!.image(color: NCBrandColor.shared.gray, size: 50), for: .normal)
  986. header.buttonSwitch.accessibilityLabel = NSLocalizedString("_list_view_", comment: "")
  987. } else {
  988. header.buttonSwitch.setImage(UIImage(named: "switchGrid")!.image(color: NCBrandColor.shared.gray, size: 50), for: .normal)
  989. header.buttonSwitch.accessibilityLabel = NSLocalizedString("_grid_view_", comment: "")
  990. }
  991. header.delegate = self
  992. header.setStatusButton(count: dataSource.metadatas.count)
  993. header.setTitleSorted(datasourceTitleButton: layoutForView?.titleButtonHeader ?? "")
  994. header.viewRichWorkspaceHeightConstraint.constant = headerRichWorkspaceHeight
  995. header.setRichWorkspaceText(richWorkspaceText: richWorkspaceText)
  996. return header
  997. } else {
  998. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  999. let info = dataSource.getFilesInformation()
  1000. footer.setTitleLabel(directories: info.directories, files: info.files, size: info.size )
  1001. return footer
  1002. }
  1003. }
  1004. func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  1005. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  1006. // Thumbnail
  1007. if !metadata.directory {
  1008. if metadata.name == "files" {
  1009. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  1010. (cell as! NCCellProtocol).filePreviewImageView?.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  1011. } else {
  1012. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, placeholder: true, cell: cell, view: collectionView)
  1013. }
  1014. } else {
  1015. // Unified search
  1016. switch metadata.iconName {
  1017. case let str where str.contains("contacts"):
  1018. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconContacts
  1019. case let str where str.contains("conversation"):
  1020. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconConversation
  1021. case let str where str.contains("calendar"):
  1022. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconCalendar
  1023. case let str where str.contains("deck"):
  1024. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconDeck
  1025. default:
  1026. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.file
  1027. }
  1028. }
  1029. }
  1030. // Avatar
  1031. if metadata.ownerId.count > 0,
  1032. metadata.ownerId != appDelegate.userId,
  1033. appDelegate.account == metadata.account,
  1034. let cell = cell as? NCCellProtocol {
  1035. let fileName = metadata.userBaseUrl + "-" + metadata.ownerId + ".png"
  1036. NCOperationQueue.shared.downloadAvatar(user: metadata.ownerId, dispalyName: metadata.ownerDisplayName, fileName: fileName, cell: cell, view: collectionView)
  1037. }
  1038. }
  1039. func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  1040. }
  1041. func numberOfSections(in collectionView: UICollectionView) -> Int {
  1042. return 1
  1043. }
  1044. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  1045. let numberItems = dataSource.numberOfItems()
  1046. emptyDataSet?.numberOfItemsInSection(numberItems, section: section)
  1047. return numberItems
  1048. }
  1049. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  1050. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else {
  1051. if layoutForView?.layout == NCGlobal.shared.layoutList {
  1052. return collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  1053. } else {
  1054. return collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  1055. }
  1056. }
  1057. var tableShare: tableShare?
  1058. var isShare = false
  1059. var isMounted = false
  1060. if metadataFolder != nil {
  1061. isShare = metadata.permissions.contains(NCGlobal.shared.permissionShared) && !metadataFolder!.permissions.contains(NCGlobal.shared.permissionShared)
  1062. isMounted = metadata.permissions.contains(NCGlobal.shared.permissionMounted) && !metadataFolder!.permissions.contains(NCGlobal.shared.permissionMounted)
  1063. }
  1064. if dataSource.metadataShare[metadata.ocId] != nil {
  1065. tableShare = dataSource.metadataShare[metadata.ocId]
  1066. }
  1067. //
  1068. // LAYOUT LIST
  1069. //
  1070. if layoutForView?.layout == NCGlobal.shared.layoutList {
  1071. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  1072. cell.delegate = self
  1073. cell.fileObjectId = metadata.ocId
  1074. cell.fileUser = metadata.ownerId
  1075. if isSearching {
  1076. if metadata.name == "files" {
  1077. cell.labelTitle.text = NCUtilityFileSystem.shared.getPath(metadata: metadata)
  1078. cell.labelTitle.lineBreakMode = .byTruncatingHead
  1079. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date) + " · " + CCUtility.transformedSize(metadata.size)
  1080. } else {
  1081. cell.labelTitle.text = metadata.fileName
  1082. cell.labelTitle.lineBreakMode = .byTruncatingTail
  1083. cell.labelInfo.text = metadata.subline
  1084. }
  1085. } else {
  1086. cell.labelTitle.text = metadata.fileNameView
  1087. cell.labelTitle.lineBreakMode = .byTruncatingMiddle
  1088. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date) + " · " + CCUtility.transformedSize(metadata.size)
  1089. }
  1090. cell.labelTitle.textColor = NCBrandColor.shared.label
  1091. cell.labelInfo.textColor = NCBrandColor.shared.systemGray
  1092. cell.imageSelect.image = nil
  1093. cell.imageStatus.image = nil
  1094. cell.imageLocal.image = nil
  1095. cell.imageFavorite.image = nil
  1096. cell.imageShared.image = nil
  1097. cell.imageMore.image = nil
  1098. cell.imageItem.image = nil
  1099. cell.imageItem.backgroundColor = nil
  1100. // Progress
  1101. var progress: Float = 0.0
  1102. var totalBytes: Int64 = 0
  1103. if let progressType = appDelegate.listProgress[metadata.ocId] {
  1104. progress = progressType.progress
  1105. totalBytes = progressType.totalBytes
  1106. }
  1107. if metadata.status == NCGlobal.shared.metadataStatusDownloading || metadata.status == NCGlobal.shared.metadataStatusUploading {
  1108. cell.progressView.isHidden = false
  1109. cell.progressView.progress = progress
  1110. } else {
  1111. cell.progressView.isHidden = true
  1112. cell.progressView.progress = 0.0
  1113. }
  1114. var a11yValues: [String] = []
  1115. if metadata.ownerId != appDelegate.userId, appDelegate.account == metadata.account {
  1116. a11yValues.append(NSLocalizedString("_shared_with_you_by_", comment: "") + " " + metadata.ownerDisplayName)
  1117. }
  1118. if metadata.directory {
  1119. if metadata.e2eEncrypted {
  1120. cell.imageItem.image = NCBrandColor.cacheImages.folderEncrypted
  1121. } else if isShare {
  1122. cell.imageItem.image = NCBrandColor.cacheImages.folderSharedWithMe
  1123. } else if tableShare != nil && tableShare?.shareType != 3 {
  1124. cell.imageItem.image = NCBrandColor.cacheImages.folderSharedWithMe
  1125. } else if tableShare != nil && tableShare?.shareType == 3 {
  1126. cell.imageItem.image = NCBrandColor.cacheImages.folderPublic
  1127. } else if metadata.mountType == "group" {
  1128. cell.imageItem.image = NCBrandColor.cacheImages.folderGroup
  1129. } else if isMounted {
  1130. cell.imageItem.image = NCBrandColor.cacheImages.folderExternal
  1131. } else if metadata.fileName == autoUploadFileName && metadata.serverUrl == autoUploadDirectory {
  1132. cell.imageItem.image = NCBrandColor.cacheImages.folderAutomaticUpload
  1133. } else {
  1134. cell.imageItem.image = NCBrandColor.cacheImages.folder
  1135. }
  1136. let lockServerUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!
  1137. let tableDirectory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, lockServerUrl))
  1138. // Local image: offline
  1139. if tableDirectory != nil && tableDirectory!.offline {
  1140. cell.imageLocal.image = NCBrandColor.cacheImages.offlineFlag
  1141. }
  1142. } else {
  1143. // image local
  1144. if dataSource.metadataOffLine.contains(metadata.ocId) {
  1145. a11yValues.append(NSLocalizedString("_offline_", comment: ""))
  1146. cell.imageLocal.image = NCBrandColor.cacheImages.offlineFlag
  1147. } else if CCUtility.fileProviderStorageExists(metadata) {
  1148. cell.imageLocal.image = NCBrandColor.cacheImages.local
  1149. }
  1150. }
  1151. // image Favorite
  1152. if metadata.favorite {
  1153. cell.imageFavorite.image = NCBrandColor.cacheImages.favorite
  1154. a11yValues.append(NSLocalizedString("_favorite_", comment: ""))
  1155. }
  1156. // Share image
  1157. if isShare {
  1158. cell.imageShared.image = NCBrandColor.cacheImages.shared
  1159. } else if tableShare != nil && tableShare?.shareType == 3 {
  1160. cell.imageShared.image = NCBrandColor.cacheImages.shareByLink
  1161. } else if tableShare != nil && tableShare?.shareType != 3 {
  1162. cell.imageShared.image = NCBrandColor.cacheImages.shared
  1163. } else {
  1164. cell.imageShared.image = NCBrandColor.cacheImages.canShare
  1165. }
  1166. if appDelegate.account != metadata.account {
  1167. cell.imageShared.image = NCBrandColor.cacheImages.shared
  1168. }
  1169. if metadata.status == NCGlobal.shared.metadataStatusInDownload || metadata.status == NCGlobal.shared.metadataStatusDownloading || metadata.status == NCGlobal.shared.metadataStatusInUpload || metadata.status == NCGlobal.shared.metadataStatusUploading {
  1170. cell.setButtonMore(named: NCGlobal.shared.buttonMoreStop, image: NCBrandColor.cacheImages.buttonStop)
  1171. } else if metadata.lock == true {
  1172. cell.setButtonMore(named: NCGlobal.shared.buttonMoreLock, image: NCBrandColor.cacheImages.buttonMoreLock)
  1173. a11yValues.append(String(format: NSLocalizedString("_locked_by_", comment: ""), metadata.lockOwnerDisplayName))
  1174. } else {
  1175. cell.setButtonMore(named: NCGlobal.shared.buttonMoreMore, image: NCBrandColor.cacheImages.buttonMore)
  1176. }
  1177. // Write status on Label Info
  1178. switch metadata.status {
  1179. case NCGlobal.shared.metadataStatusWaitDownload:
  1180. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_download_", comment: "")
  1181. break
  1182. case NCGlobal.shared.metadataStatusInDownload:
  1183. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_download_", comment: "")
  1184. break
  1185. case NCGlobal.shared.metadataStatusDownloading:
  1186. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - ↓ " + CCUtility.transformedSize(totalBytes)
  1187. break
  1188. case NCGlobal.shared.metadataStatusWaitUpload:
  1189. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_upload_", comment: "")
  1190. break
  1191. case NCGlobal.shared.metadataStatusInUpload:
  1192. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_upload_", comment: "")
  1193. break
  1194. case NCGlobal.shared.metadataStatusUploading:
  1195. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - ↑ " + CCUtility.transformedSize(totalBytes)
  1196. break
  1197. case NCGlobal.shared.metadataStatusUploadError:
  1198. if metadata.sessionError != "" {
  1199. cell.labelInfo.text = NSLocalizedString("_status_wait_upload_", comment: "") + " " + metadata.sessionError
  1200. } else {
  1201. cell.labelInfo.text = NSLocalizedString("_status_wait_upload_", comment: "")
  1202. }
  1203. break
  1204. default:
  1205. break
  1206. }
  1207. cell.accessibilityLabel = metadata.fileNameView + ", " + (cell.labelInfo.text ?? "")
  1208. // Live Photo
  1209. if metadata.livePhoto {
  1210. cell.imageStatus.image = NCBrandColor.cacheImages.livePhoto
  1211. a11yValues.append(NSLocalizedString("_upload_mov_livephoto_", comment: ""))
  1212. }
  1213. // E2EE
  1214. if metadata.e2eEncrypted || isEncryptedFolder {
  1215. cell.hideButtonShare(true)
  1216. } else {
  1217. cell.hideButtonShare(false)
  1218. }
  1219. // Remove last separator
  1220. if collectionView.numberOfItems(inSection: indexPath.section) == indexPath.row + 1 {
  1221. cell.separator.isHidden = true
  1222. } else {
  1223. cell.separator.isHidden = false
  1224. }
  1225. // Edit mode
  1226. if isEditMode {
  1227. cell.selectMode(true)
  1228. if selectOcId.contains(metadata.ocId) {
  1229. cell.selected(true)
  1230. a11yValues.append(NSLocalizedString("_selected_", comment: ""))
  1231. } else {
  1232. cell.selected(false)
  1233. }
  1234. } else {
  1235. cell.selectMode(false)
  1236. }
  1237. cell.accessibilityValue = a11yValues.joined(separator: ", ")
  1238. // Disable Share Button
  1239. if appDelegate.disableSharesView {
  1240. cell.hideButtonShare(true)
  1241. }
  1242. return cell
  1243. }
  1244. //
  1245. // LAYOUT GRID
  1246. //
  1247. if layoutForView?.layout == NCGlobal.shared.layoutGrid {
  1248. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  1249. cell.delegate = self
  1250. cell.fileObjectId = metadata.ocId
  1251. cell.fileUser = metadata.ownerId
  1252. cell.labelTitle.text = metadata.fileNameView
  1253. cell.labelTitle.textColor = NCBrandColor.shared.label
  1254. cell.imageSelect.image = nil
  1255. cell.imageStatus.image = nil
  1256. cell.imageLocal.image = nil
  1257. cell.imageFavorite.image = nil
  1258. cell.imageItem.image = nil
  1259. cell.imageItem.backgroundColor = nil
  1260. // Progress
  1261. var progress: Float = 0.0
  1262. if let progressType = appDelegate.listProgress[metadata.ocId] {
  1263. progress = progressType.progress
  1264. }
  1265. if metadata.status == NCGlobal.shared.metadataStatusDownloading || metadata.status == NCGlobal.shared.metadataStatusUploading {
  1266. cell.progressView.isHidden = false
  1267. cell.progressView.progress = progress
  1268. cell.accessibilityLabel = metadata.fileNameView + ", \(Int(progress * 100))%"
  1269. } else {
  1270. cell.progressView.isHidden = true
  1271. cell.progressView.progress = 0.0
  1272. cell.accessibilityLabel = metadata.fileNameView
  1273. }
  1274. var a11yValues: [String] = []
  1275. if metadata.ownerId != appDelegate.userId, appDelegate.account == metadata.account {
  1276. a11yValues.append(NSLocalizedString("_shared_with_you_by_", comment: "") + " " + metadata.ownerDisplayName)
  1277. }
  1278. if metadata.directory {
  1279. if metadata.e2eEncrypted {
  1280. cell.imageItem.image = NCBrandColor.cacheImages.folderEncrypted
  1281. } else if isShare {
  1282. cell.imageItem.image = NCBrandColor.cacheImages.folderSharedWithMe
  1283. } else if tableShare != nil && tableShare!.shareType != 3 {
  1284. cell.imageItem.image = NCBrandColor.cacheImages.folderSharedWithMe
  1285. } else if tableShare != nil && tableShare!.shareType == 3 {
  1286. cell.imageItem.image = NCBrandColor.cacheImages.folderPublic
  1287. } else if metadata.mountType == "group" {
  1288. cell.imageItem.image = NCBrandColor.cacheImages.folderGroup
  1289. } else if isMounted {
  1290. cell.imageItem.image = NCBrandColor.cacheImages.folderExternal
  1291. } else if metadata.fileName == autoUploadFileName && metadata.serverUrl == autoUploadDirectory {
  1292. cell.imageItem.image = NCBrandColor.cacheImages.folderAutomaticUpload
  1293. } else {
  1294. cell.imageItem.image = NCBrandColor.cacheImages.folder
  1295. }
  1296. let lockServerUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!
  1297. let tableDirectory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, lockServerUrl))
  1298. // Local image: offline
  1299. if tableDirectory != nil && tableDirectory!.offline {
  1300. cell.imageLocal.image = NCBrandColor.cacheImages.offlineFlag
  1301. }
  1302. } else {
  1303. // image Local
  1304. if dataSource.metadataOffLine.contains(metadata.ocId) {
  1305. cell.imageLocal.image = NCBrandColor.cacheImages.offlineFlag
  1306. a11yValues.append(NSLocalizedString("_offline_", comment: ""))
  1307. } else if CCUtility.fileProviderStorageExists(metadata) {
  1308. cell.imageLocal.image = NCBrandColor.cacheImages.local
  1309. }
  1310. }
  1311. // image Favorite
  1312. if metadata.favorite {
  1313. cell.imageFavorite.image = NCBrandColor.cacheImages.favorite
  1314. a11yValues.append(NSLocalizedString("_favorite_", comment: ""))
  1315. }
  1316. // Transfer
  1317. if metadata.status == NCGlobal.shared.metadataStatusInDownload || metadata.status == NCGlobal.shared.metadataStatusDownloading || metadata.status == NCGlobal.shared.metadataStatusInUpload || metadata.status == NCGlobal.shared.metadataStatusUploading {
  1318. cell.setButtonMore(named: NCGlobal.shared.buttonMoreStop, image: NCBrandColor.cacheImages.buttonStop)
  1319. } else if metadata.lock == true {
  1320. cell.setButtonMore(named: NCGlobal.shared.buttonMoreLock, image: NCBrandColor.cacheImages.buttonMoreLock)
  1321. a11yValues.append(String(format: NSLocalizedString("_locked_by_", comment: ""), metadata.lockOwnerDisplayName))
  1322. } else {
  1323. cell.setButtonMore(named: NCGlobal.shared.buttonMoreMore, image: NCBrandColor.cacheImages.buttonMore)
  1324. }
  1325. // Live Photo
  1326. if metadata.livePhoto {
  1327. cell.imageStatus.image = NCBrandColor.cacheImages.livePhoto
  1328. a11yValues.append(NSLocalizedString("_upload_mov_livephoto_", comment: ""))
  1329. }
  1330. // Edit mode
  1331. if isEditMode {
  1332. cell.selectMode(true)
  1333. if selectOcId.contains(metadata.ocId) {
  1334. cell.selected(true)
  1335. a11yValues.append(NSLocalizedString("_selected_", comment: ""))
  1336. } else {
  1337. cell.selected(false)
  1338. }
  1339. } else {
  1340. cell.selectMode(false)
  1341. }
  1342. cell.accessibilityValue = a11yValues.joined(separator: ", ")
  1343. return cell
  1344. }
  1345. return collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  1346. }
  1347. }
  1348. extension NCCollectionViewCommon: UICollectionViewDelegateFlowLayout {
  1349. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  1350. headerRichWorkspaceHeight = 0
  1351. if let richWorkspaceText = richWorkspaceText {
  1352. let trimmed = richWorkspaceText.trimmingCharacters(in: .whitespaces)
  1353. if trimmed.count > 0 && !isSearching {
  1354. headerRichWorkspaceHeight = UIScreen.main.bounds.size.height / 4
  1355. }
  1356. }
  1357. return CGSize(width: collectionView.frame.width, height: headerHeight + headerRichWorkspaceHeight)
  1358. }
  1359. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  1360. return CGSize(width: collectionView.frame.width, height: footerHeight)
  1361. }
  1362. }