NCCollectionViewCommon.swift 77 KB

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