NCCollectionViewCommon.swift 82 KB

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