NCCollectionViewCommon.swift 82 KB

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