NCCollectionViewCommon.swift 82 KB

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