NCCollectionViewCommon.swift 78 KB

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