NCCollectionViewCommon.swift 79 KB

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