NCCollectionViewCommon.swift 76 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612
  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, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate {
  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 serverUrl: String = ""
  31. internal var isEncryptedFolder = false
  32. internal var isEditMode = false
  33. internal var selectOcId: [String] = []
  34. internal var metadatasSource: [tableMetadata] = []
  35. internal var metadataFolder: tableMetadata?
  36. internal var metadataTouch: tableMetadata?
  37. internal var dataSource = NCDataSource()
  38. internal var richWorkspaceText: String?
  39. internal var layout = ""
  40. internal var groupBy = ""
  41. internal var titleButton = ""
  42. internal var itemForLine = 0
  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 = 50
  50. private var timerInputSearch: Timer?
  51. internal var literalSearch: String?
  52. internal var isSearching: Bool = false
  53. internal var isReloadDataSourceNetworkInProgress: Bool = false
  54. // DECLARE
  55. internal var layoutKey = ""
  56. internal var titleCurrentFolder = ""
  57. internal var enableSearchBar: Bool = false
  58. internal var DZNimage: UIImage?
  59. internal var DZNtitle: String = ""
  60. internal var DZNdescription: String = ""
  61. required init?(coder aDecoder: NSCoder) {
  62. super.init(coder: aDecoder)
  63. }
  64. override func viewDidLoad() {
  65. super.viewDidLoad()
  66. self.navigationController?.navigationBar.prefersLargeTitles = true
  67. if enableSearchBar {
  68. searchController = UISearchController(searchResultsController: nil)
  69. searchController?.searchResultsUpdater = self
  70. searchController?.dimsBackgroundDuringPresentation = false
  71. searchController?.delegate = self
  72. searchController?.searchBar.delegate = self
  73. navigationItem.searchController = searchController
  74. navigationItem.hidesSearchBarWhenScrolling = false
  75. }
  76. // Cell
  77. collectionView.register(UINib.init(nibName: "NCListCell", bundle: nil), forCellWithReuseIdentifier: "listCell")
  78. collectionView.register(UINib.init(nibName: "NCGridCell", bundle: nil), forCellWithReuseIdentifier: "gridCell")
  79. // Header
  80. collectionView.register(UINib.init(nibName: "NCSectionHeaderMenu", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeaderMenu")
  81. // Footer
  82. collectionView.register(UINib.init(nibName: "NCSectionFooter", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "sectionFooter")
  83. collectionView.alwaysBounceVertical = true
  84. listLayout = NCListLayout()
  85. gridLayout = NCGridLayout()
  86. // Refresh Control
  87. collectionView.addSubview(refreshControl)
  88. refreshControl.tintColor = .gray
  89. refreshControl.addTarget(self, action: #selector(reloadDataSourceNetworkRefreshControl), for: .valueChanged)
  90. // empty Data Source
  91. self.collectionView.emptyDataSetDelegate = self
  92. self.collectionView.emptyDataSetSource = self
  93. // 3D Touch peek and pop
  94. if traitCollection.forceTouchCapability == .available {
  95. registerForPreviewing(with: self, sourceView: view)
  96. }
  97. // Long Press on CollectionView
  98. let longPressedGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPressCollecationView(_:)))
  99. longPressedGesture.minimumPressDuration = 0.5
  100. longPressedGesture.delegate = self
  101. longPressedGesture.delaysTouchesBegan = true
  102. collectionView.addGestureRecognizer(longPressedGesture)
  103. // Notification
  104. NotificationCenter.default.addObserver(self, selector: #selector(initializeMain), name: NSNotification.Name(rawValue: k_notificationCenter_initializeMain), object: nil)
  105. NotificationCenter.default.addObserver(self, selector: #selector(changeTheming), name: NSNotification.Name(rawValue: k_notificationCenter_changeTheming), object: nil)
  106. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSource(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_reloadDataSource), object: nil)
  107. NotificationCenter.default.addObserver(self, selector: #selector(changeStatusFolderE2EE(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_changeStatusFolderE2EE), object: nil)
  108. NotificationCenter.default.addObserver(self, selector: #selector(deleteFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_deleteFile), object: nil)
  109. NotificationCenter.default.addObserver(self, selector: #selector(moveFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_moveFile), object: nil)
  110. NotificationCenter.default.addObserver(self, selector: #selector(copyFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_copyFile), object: nil)
  111. NotificationCenter.default.addObserver(self, selector: #selector(renameFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_renameFile), object: nil)
  112. NotificationCenter.default.addObserver(self, selector: #selector(createFolder(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_createFolder), object: nil)
  113. NotificationCenter.default.addObserver(self, selector: #selector(favoriteFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_favoriteFile), object: nil)
  114. NotificationCenter.default.addObserver(self, selector: #selector(downloadStartFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_downloadStartFile), object: nil)
  115. NotificationCenter.default.addObserver(self, selector: #selector(downloadedFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_downloadedFile), object: nil)
  116. NotificationCenter.default.addObserver(self, selector: #selector(downloadCancelFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_downloadCancelFile), object: nil)
  117. NotificationCenter.default.addObserver(self, selector: #selector(uploadStartFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_uploadStartFile), object: nil)
  118. NotificationCenter.default.addObserver(self, selector: #selector(uploadedFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_uploadedFile), object: nil)
  119. NotificationCenter.default.addObserver(self, selector: #selector(uploadCancelFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_uploadCancelFile), object: nil)
  120. NotificationCenter.default.addObserver(self, selector: #selector(triggerProgressTask(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_progressTask), object:nil)
  121. changeTheming()
  122. }
  123. override func viewWillAppear(_ animated: Bool) {
  124. super.viewWillAppear(animated)
  125. if serverUrl == "" {
  126. appDelegate.activeServerUrl = NCUtility.shared.getHomeServer(urlBase: appDelegate.urlBase, account: appDelegate.account)
  127. } else {
  128. appDelegate.activeServerUrl = serverUrl
  129. }
  130. appDelegate.activeViewController = self
  131. self.navigationItem.title = titleCurrentFolder
  132. (layout, _, _, groupBy, _, titleButton, itemForLine) = NCUtility.shared.getLayoutForView(key: layoutKey, serverUrl: serverUrl)
  133. gridLayout.itemForLine = CGFloat(itemForLine)
  134. if layout == k_layout_list {
  135. collectionView?.collectionViewLayout = listLayout
  136. } else {
  137. collectionView?.collectionViewLayout = gridLayout
  138. }
  139. setNavigationItem()
  140. reloadDataSource()
  141. }
  142. override func viewDidAppear(_ animated: Bool) {
  143. super.viewDidAppear(animated)
  144. reloadDataSourceNetwork()
  145. }
  146. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  147. super.viewWillTransition(to: size, with: coordinator)
  148. coordinator.animate(alongsideTransition: nil) { _ in
  149. self.collectionView?.collectionViewLayout.invalidateLayout()
  150. }
  151. }
  152. override var canBecomeFirstResponder: Bool {
  153. return true
  154. }
  155. func setNavigationItem() {
  156. if isEditMode {
  157. self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage.init(named: "navigationMore"), style: .plain, target: self, action:#selector(tapSelectMenu(sender:)))
  158. self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_cancel_", comment: ""), style: .plain, target: self, action: #selector(tapSelect(sender:)))
  159. self.navigationItem.title = NSLocalizedString("_selected_", comment: "") + " : \(selectOcId.count)" + " / \(dataSource.metadatas.count)"
  160. } else {
  161. self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_select_", comment: ""), style: UIBarButtonItem.Style.plain, target: self, action: #selector(tapSelect(sender:)))
  162. self.navigationItem.leftBarButtonItem = nil
  163. self.navigationItem.title = titleCurrentFolder
  164. }
  165. }
  166. // MARK: - NotificationCenter
  167. @objc func initializeMain() {
  168. if appDelegate.account.count == 0 { return }
  169. if searchController?.isActive ?? false {
  170. searchController?.isActive = false
  171. }
  172. // set active serverUrl
  173. if self.view?.window != nil {
  174. if serverUrl == "" {
  175. appDelegate.activeServerUrl = NCUtility.shared.getHomeServer(urlBase: appDelegate.urlBase, account: appDelegate.account)
  176. } else {
  177. appDelegate.activeServerUrl = serverUrl
  178. }
  179. }
  180. self.navigationController?.popToRootViewController(animated: false)
  181. appDelegate.listFilesVC.removeAllObjects()
  182. appDelegate.listFavoriteVC.removeAllObjects()
  183. appDelegate.listOfflineVC.removeAllObjects()
  184. reloadDataSource()
  185. }
  186. @objc func changeTheming() {
  187. appDelegate.changeTheming(self, tableView: nil, collectionView: collectionView, form: false)
  188. }
  189. @objc func reloadDataSource(_ notification: NSNotification) {
  190. if self.view?.window == nil { return }
  191. reloadDataSource()
  192. }
  193. @objc func changeStatusFolderE2EE(_ notification: NSNotification) {
  194. if self.view?.window == nil { return }
  195. reloadDataSource()
  196. }
  197. @objc func deleteFile(_ notification: NSNotification) {
  198. if self.view?.window == nil { return }
  199. if let userInfo = notification.userInfo as NSDictionary? {
  200. if let metadata = userInfo["metadata"] as? tableMetadata, let onlyLocal = userInfo["onlyLocal"] as? Bool {
  201. if onlyLocal {
  202. if let row = dataSource.reloadMetadata(ocId: metadata.ocId) {
  203. let indexPath = IndexPath(row: row, section: 0)
  204. collectionView?.reloadItems(at: [indexPath])
  205. }
  206. } else {
  207. if let row = dataSource.deleteMetadata(ocId: metadata.ocId) {
  208. let indexPath = IndexPath(row: row, section: 0)
  209. collectionView?.performBatchUpdates({
  210. collectionView?.deleteItems(at: [indexPath])
  211. }, completion: { (_) in
  212. self.collectionView?.reloadData()
  213. })
  214. }
  215. }
  216. }
  217. }
  218. }
  219. @objc func moveFile(_ notification: NSNotification) {
  220. if self.view?.window == nil { return }
  221. if let userInfo = notification.userInfo as NSDictionary? {
  222. if let metadata = userInfo["metadata"] as? tableMetadata, let metadataNew = userInfo["metadataNew"] as? tableMetadata {
  223. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  224. if let row = dataSource.deleteMetadata(ocId: metadata.ocId) {
  225. let indexPath = IndexPath(row: row, section: 0)
  226. collectionView?.performBatchUpdates({
  227. collectionView?.deleteItems(at: [indexPath])
  228. }, completion: { (_) in
  229. self.collectionView?.reloadData()
  230. })
  231. }
  232. } else if metadataNew.serverUrl == serverUrl && metadata.account == appDelegate.account {
  233. if let row = dataSource.addMetadata(metadataNew) {
  234. let indexPath = IndexPath(row: row, section: 0)
  235. collectionView?.performBatchUpdates({
  236. collectionView?.insertItems(at: [indexPath])
  237. }, completion: { (_) in
  238. self.collectionView?.reloadData()
  239. })
  240. }
  241. }
  242. }
  243. }
  244. }
  245. @objc func copyFile(_ notification: NSNotification) {
  246. if self.view?.window == nil { return }
  247. if let userInfo = notification.userInfo as NSDictionary? {
  248. if let serverUrlTo = userInfo["serverUrlTo"] as? String {
  249. if serverUrlTo == self.serverUrl {
  250. self.reloadDataSource()
  251. }
  252. }
  253. }
  254. }
  255. @objc func renameFile(_ notification: NSNotification) {
  256. if self.view?.window == nil { return }
  257. if let userInfo = notification.userInfo as NSDictionary? {
  258. if let metadata = userInfo["metadata"] as? tableMetadata {
  259. if let row = dataSource.reloadMetadata(ocId: metadata.ocId) {
  260. let indexPath = IndexPath(row: row, section: 0)
  261. collectionView?.performBatchUpdates({
  262. collectionView?.reloadItems(at: [indexPath])
  263. }, completion: { (_) in
  264. self.collectionView?.reloadData()
  265. })
  266. }
  267. }
  268. }
  269. }
  270. @objc func createFolder(_ notification: NSNotification) {
  271. if self.view?.window == nil { return }
  272. if let userInfo = notification.userInfo as NSDictionary? {
  273. if let metadata = userInfo["metadata"] as? tableMetadata {
  274. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  275. if let row = dataSource.addMetadata(metadata) {
  276. let indexPath = IndexPath(row: row, section: 0)
  277. collectionView?.performBatchUpdates({
  278. collectionView?.insertItems(at: [indexPath])
  279. }, completion: { (_) in
  280. self.collectionView?.reloadData()
  281. })
  282. }
  283. }
  284. }
  285. } else {
  286. self.reloadDataSourceNetwork()
  287. }
  288. }
  289. @objc func favoriteFile(_ notification: NSNotification) {
  290. if self.view?.window == nil { return }
  291. if let userInfo = notification.userInfo as NSDictionary? {
  292. if let metadata = userInfo["metadata"] as? tableMetadata {
  293. if dataSource.getIndexMetadata(ocId: metadata.ocId) != nil {
  294. self.reloadDataSource()
  295. }
  296. }
  297. }
  298. }
  299. @objc func downloadStartFile(_ notification: NSNotification) {
  300. if self.view?.window == nil { return }
  301. if let userInfo = notification.userInfo as NSDictionary? {
  302. if let metadata = userInfo["metadata"] as? tableMetadata {
  303. if let row = dataSource.reloadMetadata(ocId: metadata.ocId) {
  304. let indexPath = IndexPath(row: row, section: 0)
  305. collectionView?.reloadItems(at: [indexPath])
  306. }
  307. }
  308. }
  309. }
  310. @objc func downloadedFile(_ notification: NSNotification) {
  311. if self.view?.window == nil { return }
  312. if let userInfo = notification.userInfo as NSDictionary? {
  313. if let metadata = userInfo["metadata"] as? tableMetadata, let _ = userInfo["errorCode"] as? Int {
  314. if let row = dataSource.reloadMetadata(ocId: metadata.ocId) {
  315. let indexPath = IndexPath(row: row, section: 0)
  316. collectionView?.reloadItems(at: [indexPath])
  317. }
  318. }
  319. }
  320. }
  321. @objc func downloadCancelFile(_ notification: NSNotification) {
  322. if self.view?.window == nil { return }
  323. if let userInfo = notification.userInfo as NSDictionary? {
  324. if let metadata = userInfo["metadata"] as? tableMetadata {
  325. if let row = dataSource.reloadMetadata(ocId: metadata.ocId) {
  326. let indexPath = IndexPath(row: row, section: 0)
  327. collectionView?.reloadItems(at: [indexPath])
  328. }
  329. }
  330. }
  331. }
  332. @objc func uploadStartFile(_ notification: NSNotification) {
  333. if self.view?.window == nil { return }
  334. if let userInfo = notification.userInfo as NSDictionary? {
  335. if let metadata = userInfo["metadata"] as? tableMetadata {
  336. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  337. if let row = dataSource.addMetadata(metadata) {
  338. let indexPath = IndexPath(row: row, section: 0)
  339. collectionView?.performBatchUpdates({
  340. collectionView?.insertItems(at: [indexPath])
  341. }, completion: { (_) in
  342. self.collectionView?.reloadData()
  343. })
  344. }
  345. }
  346. }
  347. }
  348. }
  349. @objc func uploadedFile(_ notification: NSNotification) {
  350. if self.view?.window == nil { return }
  351. if let userInfo = notification.userInfo as NSDictionary? {
  352. if let metadata = userInfo["metadata"] as? tableMetadata, let ocIdTemp = userInfo["ocIdTemp"] as? String, let _ = userInfo["errorCode"] as? Int {
  353. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  354. dataSource.reloadMetadata(ocId: metadata.ocId, ocIdTemp: ocIdTemp)
  355. collectionView?.reloadData()
  356. }
  357. }
  358. }
  359. }
  360. @objc func uploadCancelFile(_ notification: NSNotification) {
  361. if self.view?.window == nil { return }
  362. if let userInfo = notification.userInfo as NSDictionary? {
  363. if let metadata = userInfo["metadata"] as? tableMetadata {
  364. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  365. if let row = dataSource.deleteMetadata(ocId: metadata.ocId) {
  366. let indexPath = IndexPath(row: row, section: 0)
  367. collectionView?.performBatchUpdates({
  368. collectionView?.deleteItems(at: [indexPath])
  369. }, completion: { (_) in
  370. self.collectionView?.reloadData()
  371. })
  372. } else {
  373. self.reloadDataSource()
  374. }
  375. }
  376. }
  377. }
  378. }
  379. @objc func triggerProgressTask(_ notification: NSNotification) {
  380. if self.view?.window == nil { return }
  381. if let userInfo = notification.userInfo as NSDictionary? {
  382. if let ocId = userInfo["ocId"] as? String {
  383. let _ = userInfo["account"] as? String ?? ""
  384. let _ = userInfo["serverUrl"] as? String ?? ""
  385. let progressNumber = userInfo["progress"] as? NSNumber ?? 0
  386. let progress = progressNumber.floatValue
  387. let status = userInfo["status"] as? Int ?? Int(k_metadataStatusNormal)
  388. let totalBytes = userInfo["totalBytes"] as? Double ?? 0
  389. let totalBytesExpected = userInfo["totalBytesExpected"] as? Double ?? 0
  390. appDelegate.listProgressMetadata.setObject([progress as NSNumber, totalBytes as NSNumber, totalBytesExpected as NSNumber], forKey: userInfo["ocId"] as? NSString ?? "")
  391. if let index = dataSource.getIndexMetadata(ocId: ocId) {
  392. if let cell = collectionView?.cellForItem(at: IndexPath(row: index, section: 0)) {
  393. if cell is NCListCell {
  394. let cell = cell as! NCListCell
  395. if progress > 0 {
  396. cell.progressView?.isHidden = false
  397. cell.progressView?.progress = progress
  398. cell.setButtonMore(named: k_buttonMoreStop, image: NCCollectionCommon.images.cellButtonStop)
  399. if status == k_metadataStatusInDownload {
  400. cell.labelInfo.text = CCUtility.transformedSize(totalBytesExpected) + " - ↓ " + CCUtility.transformedSize(totalBytes)
  401. } else if status == k_metadataStatusInUpload {
  402. cell.labelInfo.text = CCUtility.transformedSize(totalBytesExpected) + " - ↑ " + CCUtility.transformedSize(totalBytes)
  403. }
  404. }
  405. } else if cell is NCGridCell {
  406. let cell = cell as! NCGridCell
  407. if progress > 0 {
  408. cell.progressView.isHidden = false
  409. cell.progressView.progress = progress
  410. cell.setButtonMore(named: k_buttonMoreStop, image: NCCollectionCommon.images.cellButtonStop)
  411. }
  412. }
  413. }
  414. }
  415. }
  416. }
  417. }
  418. // MARK: - DZNEmpty
  419. func backgroundColor(forEmptyDataSet scrollView: UIScrollView) -> UIColor? {
  420. return NCBrandColor.sharedInstance.backgroundView
  421. }
  422. func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
  423. if searchController?.isActive ?? false {
  424. return CCGraphics.changeThemingColorImage(UIImage.init(named: "search"), width: 300, height: 300, color: .gray)
  425. }
  426. if isReloadDataSourceNetworkInProgress {
  427. return CCGraphics.changeThemingColorImage(UIImage.init(named: "networkInProgress"), width: 300, height: 300, color: .gray)
  428. }
  429. return DZNimage
  430. }
  431. func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
  432. var text = "\n"+NSLocalizedString(DZNtitle, comment: "")
  433. if isReloadDataSourceNetworkInProgress {
  434. text = "\n"+NSLocalizedString("_request_in_progress_", comment: "")
  435. }
  436. if searchController?.isActive ?? false {
  437. if isReloadDataSourceNetworkInProgress {
  438. text = "\n"+NSLocalizedString("_search_in_progress_", comment: "")
  439. } else {
  440. text = "\n"+NSLocalizedString("_search_no_record_found_", comment: "")
  441. }
  442. }
  443. let attributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 20), NSAttributedString.Key.foregroundColor: UIColor.gray]
  444. return NSAttributedString.init(string: text, attributes: attributes)
  445. }
  446. func description(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
  447. var text = "\n"+NSLocalizedString(DZNdescription, comment: "")
  448. if isReloadDataSourceNetworkInProgress {
  449. text = ""
  450. }
  451. if searchController?.isActive ?? false {
  452. text = "\n"+NSLocalizedString("_search_instruction_", comment: "")
  453. }
  454. let attributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14), NSAttributedString.Key.foregroundColor: UIColor.lightGray]
  455. return NSAttributedString.init(string: text, attributes: attributes)
  456. }
  457. func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView) -> Bool {
  458. return true
  459. }
  460. // MARK: - SEARCH
  461. func updateSearchResults(for searchController: UISearchController) {
  462. timerInputSearch?.invalidate()
  463. timerInputSearch = Timer.scheduledTimer(timeInterval: 1.5, target: self, selector: #selector(reloadDataSourceNetwork), userInfo: nil, repeats: false)
  464. literalSearch = searchController.searchBar.text
  465. collectionView?.reloadData()
  466. }
  467. func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
  468. isSearching = true
  469. metadatasSource.removeAll()
  470. reloadDataSource()
  471. }
  472. func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
  473. isSearching = false
  474. literalSearch = ""
  475. reloadDataSource()
  476. }
  477. // MARK: - TAP EVENT
  478. @objc func tapSelect(sender: Any) {
  479. isEditMode = !isEditMode
  480. selectOcId.removeAll()
  481. setNavigationItem()
  482. self.collectionView.reloadData()
  483. }
  484. func tapSwitchHeader(sender: Any) {
  485. if collectionView.collectionViewLayout == gridLayout {
  486. // list layout
  487. UIView.animate(withDuration: 0.0, animations: {
  488. self.collectionView.collectionViewLayout.invalidateLayout()
  489. self.collectionView.setCollectionViewLayout(self.listLayout, animated: false, completion: { (_) in
  490. self.collectionView.reloadData()
  491. self.collectionView.setContentOffset(CGPoint(x:0,y:0), animated: false)
  492. })
  493. })
  494. layout = k_layout_list
  495. NCUtility.shared.setLayoutForView(key: layoutKey, serverUrl: serverUrl, layout: layout)
  496. } else {
  497. // grid layout
  498. UIView.animate(withDuration: 0.0, animations: {
  499. self.collectionView.collectionViewLayout.invalidateLayout()
  500. self.collectionView.setCollectionViewLayout(self.gridLayout, animated: false, completion: { (_) in
  501. self.collectionView.reloadData()
  502. self.collectionView.setContentOffset(CGPoint(x:0,y:0), animated: false)
  503. })
  504. })
  505. layout = k_layout_grid
  506. NCUtility.shared.setLayoutForView(key: layoutKey, serverUrl: serverUrl, layout: layout)
  507. }
  508. }
  509. func tapOrderHeader(sender: Any) {
  510. let sortMenu = NCSortMenu()
  511. sortMenu.toggleMenu(viewController: self, key: layoutKey, sortButton: sender as? UIButton, serverUrl: serverUrl)
  512. }
  513. @objc func tapSelectMenu(sender: Any) {
  514. guard let tabBarController = self.tabBarController else { return }
  515. toggleMoreSelect(viewController: tabBarController, selectOcId: selectOcId)
  516. }
  517. func tapMoreHeader(sender: Any) { }
  518. func tapMoreListItem(with objectId: String, namedButtonMore: String, sender: Any) {
  519. tapMoreGridItem(with: objectId, namedButtonMore: namedButtonMore, sender: sender)
  520. }
  521. func tapShareListItem(with objectId: String, sender: Any) {
  522. guard let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(objectId) else { return }
  523. NCNetworkingNotificationCenter.shared.openShare(ViewController: self, metadata: metadata, indexPage: 2)
  524. }
  525. func tapMoreGridItem(with objectId: String, namedButtonMore: String, sender: Any) {
  526. guard let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(objectId) else { return }
  527. if namedButtonMore == k_buttonMoreMore {
  528. toggleMoreMenu(viewController: self, metadata: metadata)
  529. } else if namedButtonMore == k_buttonMoreStop {
  530. NCNetworking.shared.cancelTransferMetadata(metadata) { }
  531. }
  532. }
  533. func tapRichWorkspace(sender: Any) {
  534. if let navigationController = UIStoryboard(name: "NCViewerRichWorkspace", bundle: nil).instantiateInitialViewController() as? UINavigationController {
  535. if let viewerRichWorkspace = navigationController.topViewController as? NCViewerRichWorkspace {
  536. viewerRichWorkspace.richWorkspaceText = richWorkspaceText ?? ""
  537. viewerRichWorkspace.serverUrl = serverUrl
  538. navigationController.modalPresentationStyle = .fullScreen
  539. self.present(navigationController, animated: true, completion: nil)
  540. }
  541. }
  542. }
  543. func longPressListItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) {
  544. if let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(objectId) {
  545. metadataTouch = metadata
  546. longPressCollecationView(gestureRecognizer)
  547. }
  548. }
  549. func longPressGridItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) {
  550. if let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(objectId) {
  551. metadataTouch = metadata
  552. longPressCollecationView(gestureRecognizer)
  553. }
  554. }
  555. func longPressMoreListItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) {
  556. }
  557. func longPressMoreGridItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) {
  558. }
  559. @objc func longPressCollecationView(_ gestureRecognizer: UILongPressGestureRecognizer) {
  560. if gestureRecognizer.state != .began { return }
  561. if serverUrl == "" { return }
  562. var listMenuItems: [UIMenuItem] = []
  563. let touchPoint = gestureRecognizer.location(in: collectionView)
  564. becomeFirstResponder()
  565. if metadataTouch != nil {
  566. listMenuItems.append(UIMenuItem.init(title: NSLocalizedString("_copy_file_", comment: ""), action: #selector(copyFileMenu(_:))))
  567. }
  568. listMenuItems.append(UIMenuItem.init(title: NSLocalizedString("_paste_file_", comment: ""), action: #selector(pasteFilesMenu(_:))))
  569. if metadataTouch != nil {
  570. listMenuItems.append(UIMenuItem.init(title: NSLocalizedString("_open_quicklook_", comment: ""), action: #selector(openQuickLookMenu(_:))))
  571. if !NCBrandOptions.sharedInstance.disable_openin_file {
  572. listMenuItems.append(UIMenuItem.init(title: NSLocalizedString("_open_in_", comment: ""), action: #selector(openInMenu(_:))))
  573. }
  574. }
  575. if listMenuItems.count > 0 {
  576. UIMenuController.shared.menuItems = listMenuItems
  577. UIMenuController.shared.setTargetRect(CGRect(x: touchPoint.x, y: touchPoint.y, width: 0, height: 0), in: collectionView)
  578. UIMenuController.shared.setMenuVisible(true, animated: true)
  579. }
  580. }
  581. // MARK: - Menu Item
  582. override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
  583. if (#selector(pasteFilesMenu(_:)) == action) {
  584. if UIPasteboard.general.items.count > 0 {
  585. return true
  586. }
  587. }
  588. if (#selector(openQuickLookMenu(_:)) == action || #selector(openInMenu(_:)) == action || #selector(copyFileMenu(_:)) == action) {
  589. guard let metadata = metadataTouch else { return false }
  590. if !metadata.directory && metadata.status == k_metadataStatusNormal {
  591. return true
  592. }
  593. }
  594. return false
  595. }
  596. @objc func copyFileMenu(_ notification: Any) {
  597. var metadatas: [tableMetadata] = []
  598. var items = [[String : Any]]()
  599. if isEditMode {
  600. for ocId in selectOcId {
  601. if let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(ocId) {
  602. metadatas.append(metadata)
  603. }
  604. }
  605. } else {
  606. guard let metadata = metadataTouch else { return }
  607. metadatas.append(metadata)
  608. }
  609. for metadata in metadatas {
  610. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  611. do {
  612. let etagPasteboard = try NSKeyedArchiver.archivedData(withRootObject: metadata.ocId, requiringSecureCoding: false)
  613. items.append([k_metadataKeyedUnarchiver:etagPasteboard])
  614. } catch {
  615. print("error")
  616. }
  617. } else {
  618. NCNetworking.shared.download(metadata: metadata, selector: selectorLoadCopy, setFavorite: false) { (_) in }
  619. }
  620. }
  621. UIPasteboard.general.setItems(items, options: [:])
  622. if isEditMode {
  623. tapSelect(sender: self)
  624. }
  625. }
  626. @objc func pasteFilesMenu(_ notification: Any) {
  627. var listData: [String] = []
  628. for item in UIPasteboard.general.items {
  629. for object in item {
  630. let contentType = object.key
  631. let data = object.value
  632. if contentType == k_metadataKeyedUnarchiver {
  633. do {
  634. if let ocId = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data as! Data) as? String{
  635. uploadPasteOcId(ocId)
  636. }
  637. } catch {
  638. print("error")
  639. }
  640. continue
  641. }
  642. if data is String {
  643. if listData.contains(data as! String) {
  644. continue
  645. } else {
  646. listData.append(data as! String)
  647. }
  648. }
  649. let type = NCCommunicationCommon.shared.convertUTItoResultType(fileUTI: contentType as CFString)
  650. if type.resultTypeFile != NCCommunicationCommon.typeFile.unknow.rawValue && type.resultExtension != "" {
  651. uploadPasteFile(fileName: type.resultFilename, ext: type.resultExtension, contentType: contentType, data: data)
  652. }
  653. }
  654. }
  655. }
  656. private func uploadPasteFile(fileName: String, ext: String, contentType: String, data: Any) {
  657. do {
  658. let fileNameView = fileName + "_" + CCUtility.getIncrementalNumber() + "." + ext
  659. let ocId = UUID().uuidString
  660. let filePath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView)!
  661. if data is UIImage {
  662. try (data as? UIImage)?.jpegData(compressionQuality: 1)?.write(to: URL(fileURLWithPath: filePath))
  663. } else if data is Data {
  664. try (data as? Data)?.write(to: URL(fileURLWithPath: filePath))
  665. } else if data is String {
  666. try (data as? String)?.write(to: URL(fileURLWithPath: filePath), atomically: true, encoding: .utf8)
  667. } else {
  668. return
  669. }
  670. let metadataForUpload = NCManageDatabase.sharedInstance.createMetadata(account: appDelegate.account, fileName: fileNameView, ocId: ocId, serverUrl: serverUrl, urlBase: appDelegate.urlBase, url: "", contentType: contentType, livePhoto: false)
  671. metadataForUpload.session = NCNetworking.shared.sessionIdentifierBackground
  672. metadataForUpload.sessionSelector = selectorUploadFile
  673. metadataForUpload.size = Double(NCUtilityFileSystem.shared.getFileSize(filePath: filePath))
  674. metadataForUpload.status = Int(k_metadataStatusWaitUpload)
  675. NCManageDatabase.sharedInstance.addMetadata(metadataForUpload)
  676. } catch { }
  677. }
  678. private func uploadPasteOcId(_ ocId: String) {
  679. if let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(ocId) {
  680. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  681. let fileNameView = NCUtility.shared.createFileName(metadata.fileNameView, serverUrl: serverUrl, account: appDelegate.account)
  682. let ocId = NSUUID().uuidString
  683. CCUtility.copyFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView), toPath: CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView))
  684. let metadataForUpload = NCManageDatabase.sharedInstance.createMetadata(account: appDelegate.account, fileName: fileNameView, ocId: ocId, serverUrl: serverUrl, urlBase: appDelegate.urlBase, url: "", contentType: "", livePhoto: false)
  685. metadataForUpload.session = NCNetworking.shared.sessionIdentifierBackground
  686. metadataForUpload.sessionSelector = selectorUploadFile
  687. metadataForUpload.size = metadata.size
  688. metadataForUpload.status = Int(k_metadataStatusWaitUpload)
  689. NCManageDatabase.sharedInstance.addMetadata(metadataForUpload)
  690. }
  691. }
  692. }
  693. @objc func openQuickLookMenu(_ notification: Any) {
  694. guard let metadata = metadataTouch else { return }
  695. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  696. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_downloadedFile, userInfo: ["metadata": metadata, "selector": selectorLoadFileQuickLook, "errorCode": 0, "errorDescription": "" ])
  697. } else {
  698. NCNetworking.shared.download(metadata: metadata, selector: selectorLoadFileQuickLook) { (_) in }
  699. }
  700. }
  701. @objc func openInMenu(_ notification: Any) {
  702. guard let metadata = metadataTouch else { return }
  703. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  704. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_downloadedFile, userInfo: ["metadata": metadata, "selector": selectorOpenIn, "errorCode": 0, "errorDescription": "" ])
  705. } else {
  706. NCNetworking.shared.download(metadata: metadata, selector: selectorOpenIn) { (_) in }
  707. }
  708. }
  709. // MARK: - SEGUE
  710. @objc func segue(metadata: tableMetadata) {
  711. self.metadataTouch = metadata
  712. performSegue(withIdentifier: "segueDetail", sender: self)
  713. }
  714. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  715. let photoDataSource: NSMutableArray = []
  716. for metadata in (dataSource.metadatas) {
  717. if metadata.typeFile == k_metadataTypeFile_image || metadata.typeFile == k_metadataTypeFile_video {
  718. photoDataSource.add(metadata)
  719. }
  720. }
  721. if let segueNavigationController = segue.destination as? UINavigationController {
  722. if let segueViewController = segueNavigationController.topViewController as? NCDetailViewController {
  723. segueViewController.metadata = metadataTouch
  724. segueViewController.layoutKey = layoutKey
  725. }
  726. }
  727. }
  728. // MARK: - DataSource + NC Endpoint
  729. @objc func reloadDataSource() {
  730. if appDelegate.account.count == 0 { return }
  731. let directory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, serverUrl))
  732. richWorkspaceText = directory?.richWorkspace
  733. // E2EE
  734. isEncryptedFolder = CCUtility.isFolderEncrypted(serverUrl, e2eEncrypted: metadataFolder?.e2eEncrypted ?? false, account: appDelegate.account, urlBase: appDelegate.urlBase)
  735. // get auto upload folder
  736. autoUploadFileName = NCManageDatabase.sharedInstance.getAccountAutoUploadFileName()
  737. autoUploadDirectory = NCManageDatabase.sharedInstance.getAccountAutoUploadDirectory(urlBase: appDelegate.urlBase, account: appDelegate.account)
  738. }
  739. @objc func reloadDataSourceNetwork(forced: Bool = false) { }
  740. @objc func reloadDataSourceNetworkRefreshControl() {
  741. reloadDataSourceNetwork(forced: true)
  742. }
  743. @objc func networkSearch() {
  744. if appDelegate.account.count == 0 { return }
  745. if literalSearch?.count ?? 0 > 1 {
  746. isReloadDataSourceNetworkInProgress = true
  747. collectionView?.reloadData()
  748. NCNetworking.shared.searchFiles(urlBase: appDelegate.urlBase, user: appDelegate.user, literal: literalSearch!) { (account, metadatas, errorCode, errorDescription) in
  749. if self.searchController?.isActive ?? false && errorCode == 0 {
  750. self.metadatasSource = metadatas!
  751. }
  752. self.refreshControl.endRefreshing()
  753. self.isReloadDataSourceNetworkInProgress = false
  754. self.reloadDataSource()
  755. }
  756. } else {
  757. self.refreshControl.endRefreshing()
  758. }
  759. }
  760. @objc func networkReadFolder(forced: Bool, completion: @escaping(_ metadatas: [tableMetadata]?, _ metadatasUpdate: [tableMetadata]?, _ errorCode: Int, _ errorDescription: String)->()) {
  761. NCNetworking.shared.readFile(serverUrlFileName: serverUrl, account: appDelegate.account) { (account, metadata, errorCode, errorDescription) in
  762. if errorCode == 0 {
  763. let directory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", self.appDelegate.account, self.serverUrl))
  764. if forced || directory?.etag != metadata?.etag || directory?.e2eEncrypted ?? false {
  765. NCNetworking.shared.readFolder(serverUrl: self.serverUrl, account: self.appDelegate.account) { (account, metadataFolder, metadatas, metadatasUpdate, metadatasLocalUpdate, errorCode, errorDescription) in
  766. if errorCode == 0 {
  767. self.metadataFolder = metadataFolder
  768. // E2EE
  769. if let metadataFolder = metadataFolder {
  770. if metadataFolder.e2eEncrypted && CCUtility.isEnd(toEndEnabled: self.appDelegate.account) {
  771. NCCommunication.shared.getE2EEMetadata(fileId: metadataFolder.ocId, e2eToken: nil) { (account, e2eMetadata, errorCode, errorDescription) in
  772. if errorCode == 0 && e2eMetadata != nil {
  773. if !NCEndToEndMetadata.sharedInstance.decoderMetadata(e2eMetadata!, privateKey: CCUtility.getEndToEndPrivateKey(account), serverUrl: self.serverUrl, account: account, urlBase: self.appDelegate.urlBase) {
  774. NCContentPresenter.shared.messageNotification("_error_e2ee_", description: "_e2e_error_decode_metadata_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: Int(k_CCErrorDecodeMetadata), forced: true)
  775. } else {
  776. self.reloadDataSource()
  777. }
  778. } else if errorCode != 404 {
  779. NCContentPresenter.shared.messageNotification("_error_e2ee_", description: "_e2e_error_decode_metadata_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: Int(k_CCErrorDecodeMetadata), forced: true)
  780. }
  781. completion(metadatas, metadatasUpdate, errorCode, errorDescription)
  782. }
  783. } else {
  784. completion(metadatas, metadatasUpdate, errorCode, errorDescription)
  785. }
  786. } else {
  787. completion(metadatas, metadatasUpdate, errorCode, errorDescription)
  788. }
  789. } else {
  790. completion(nil, nil, errorCode, errorDescription)
  791. }
  792. }
  793. } else {
  794. completion(nil, nil, 0, "")
  795. }
  796. } else {
  797. completion(nil, nil, errorCode, errorDescription)
  798. }
  799. }
  800. }
  801. }
  802. // MARK: - 3D Touch peek and pop
  803. extension NCCollectionViewCommon: UIViewControllerPreviewingDelegate {
  804. func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
  805. guard let point = collectionView?.convert(location, from: collectionView?.superview) else { return nil }
  806. guard let indexPath = collectionView?.indexPathForItem(at: point) else { return nil }
  807. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return nil }
  808. guard let viewController = UIStoryboard(name: "CCPeekPop", bundle: nil).instantiateViewController(withIdentifier: "PeekPopImagePreview") as? CCPeekPop else { return nil }
  809. viewController.metadata = metadata
  810. if layout == k_layout_grid {
  811. guard let cell = collectionView?.cellForItem(at: indexPath) as? NCGridCell else { return nil }
  812. previewingContext.sourceRect = cell.frame
  813. viewController.imageFile = cell.imageItem.image
  814. } else {
  815. guard let cell = collectionView?.cellForItem(at: indexPath) as? NCListCell else { return nil }
  816. previewingContext.sourceRect = cell.frame
  817. viewController.imageFile = cell.imageItem.image
  818. }
  819. viewController.showOpenIn = true
  820. viewController.showOpenQuickLook = NCUtility.shared.isQuickLookDisplayable(metadata: metadata)
  821. viewController.showShare = false
  822. return viewController
  823. }
  824. func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
  825. guard let indexPath = collectionView?.indexPathForItem(at: previewingContext.sourceRect.origin) else { return }
  826. collectionView(collectionView, didSelectItemAt: indexPath)
  827. }
  828. }
  829. // MARK: - Collection View
  830. extension NCCollectionViewCommon: UICollectionViewDelegate {
  831. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  832. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  833. metadataTouch = metadata
  834. if isEditMode {
  835. if let index = selectOcId.firstIndex(of: metadata.ocId) {
  836. selectOcId.remove(at: index)
  837. } else {
  838. selectOcId.append(metadata.ocId)
  839. }
  840. collectionView.reloadItems(at: [indexPath])
  841. self.navigationItem.title = NSLocalizedString("_selected_", comment: "") + " : \(selectOcId.count)" + " / \(dataSource.metadatas.count)"
  842. return
  843. }
  844. if metadata.e2eEncrypted && !CCUtility.isEnd(toEndEnabled: appDelegate.account) {
  845. NCContentPresenter.shared.messageNotification("_info_", description: "_e2e_goto_settings_for_enable_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.info, errorCode: Int(k_CCErrorE2EENotEnabled), forced: true)
  846. return
  847. }
  848. if metadata.directory {
  849. guard let serverUrlPush = CCUtility.stringAppendServerUrl(metadataTouch!.serverUrl, addFileName: metadataTouch!.fileName) else { return }
  850. // FILES
  851. if layoutKey == k_layout_view_files {
  852. if let viewController = appDelegate.listFilesVC.value(forKey: serverUrlPush) {
  853. guard let vcFiles = (viewController as? NCFiles) else { return }
  854. if vcFiles.isViewLoaded {
  855. self.navigationController?.pushViewController(vcFiles, animated: true)
  856. }
  857. } else {
  858. let vcFiles:NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as! NCFiles
  859. vcFiles.isRoot = false
  860. vcFiles.serverUrl = serverUrlPush
  861. vcFiles.titleCurrentFolder = metadataTouch!.fileNameView
  862. appDelegate.listFilesVC.setValue(vcFiles, forKey: serverUrlPush)
  863. self.navigationController?.pushViewController(vcFiles, animated: true)
  864. }
  865. }
  866. // FAVORITE
  867. if layoutKey == k_layout_view_favorite {
  868. if let viewController = appDelegate.listFavoriteVC.value(forKey: serverUrlPush) {
  869. guard let vcFavorite = (viewController as? NCFavorite) else { return }
  870. if vcFavorite.isViewLoaded {
  871. self.navigationController?.pushViewController(vcFavorite, animated: true)
  872. }
  873. } else {
  874. let vcFavorite:NCFavorite = UIStoryboard(name: "NCFavorite", bundle: nil).instantiateInitialViewController() as! NCFavorite
  875. vcFavorite.serverUrl = serverUrlPush
  876. vcFavorite.titleCurrentFolder = metadataTouch!.fileNameView
  877. appDelegate.listFavoriteVC.setValue(vcFavorite, forKey: serverUrlPush)
  878. self.navigationController?.pushViewController(vcFavorite, animated: true)
  879. }
  880. }
  881. // OFFLINE
  882. if layoutKey == k_layout_view_offline {
  883. if let viewController = appDelegate.listOfflineVC.value(forKey: serverUrlPush) {
  884. guard let vcOffline = (viewController as? NCOffline) else { return }
  885. if vcOffline.isViewLoaded {
  886. self.navigationController?.pushViewController(vcOffline, animated: true)
  887. }
  888. } else {
  889. let vcOffline:NCOffline = UIStoryboard(name: "NCOffline", bundle: nil).instantiateInitialViewController() as! NCOffline
  890. vcOffline.serverUrl = serverUrlPush
  891. vcOffline.titleCurrentFolder = metadataTouch!.fileNameView
  892. appDelegate.listOfflineVC.setValue(vcOffline, forKey: serverUrlPush)
  893. self.navigationController?.pushViewController(vcOffline, animated: true)
  894. }
  895. }
  896. // RECENT ( for push use Files ... he he he )
  897. if layoutKey == k_layout_view_recent {
  898. if let viewController = appDelegate.listFilesVC.value(forKey: serverUrlPush) {
  899. guard let vcFiles = (viewController as? NCFiles) else { return }
  900. if vcFiles.isViewLoaded {
  901. self.navigationController?.pushViewController(vcFiles, animated: true)
  902. }
  903. } else {
  904. let vcFiles:NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as! NCFiles
  905. vcFiles.isRoot = false
  906. vcFiles.serverUrl = serverUrlPush
  907. vcFiles.titleCurrentFolder = metadataTouch!.fileNameView
  908. appDelegate.listFilesVC.setValue(vcFiles, forKey: serverUrlPush)
  909. self.navigationController?.pushViewController(vcFiles, animated: true)
  910. }
  911. }
  912. if layoutKey == k_layout_view_viewInFolder {
  913. let vcFileViewInFolder:NCFileViewInFolder = UIStoryboard(name: "NCFileViewInFolder", bundle: nil).instantiateInitialViewController() as! NCFileViewInFolder
  914. vcFileViewInFolder.serverUrl = serverUrlPush
  915. vcFileViewInFolder.titleCurrentFolder = metadataTouch!.fileNameView
  916. self.navigationController?.pushViewController(vcFileViewInFolder, animated: true)
  917. }
  918. } else {
  919. if metadata.typeFile == k_metadataTypeFile_document && NCUtility.shared.isDirectEditing(account: metadata.account, contentType: metadata.contentType) != nil {
  920. if NCCommunication.shared.isNetworkReachable() {
  921. performSegue(withIdentifier: "segueDetail", sender: self)
  922. } else {
  923. NCContentPresenter.shared.messageNotification("_info_", description: "_go_online_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.info, errorCode: Int(k_CCErrorOffline), forced: true)
  924. }
  925. return
  926. }
  927. if metadata.typeFile == k_metadataTypeFile_document && NCUtility.shared.isRichDocument(metadata) {
  928. if NCCommunication.shared.isNetworkReachable() {
  929. performSegue(withIdentifier: "segueDetail", sender: self)
  930. } else {
  931. NCContentPresenter.shared.messageNotification("_info_", description: "_go_online_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.info, errorCode: Int(k_CCErrorOffline), forced: true)
  932. }
  933. return
  934. }
  935. if CCUtility.fileProviderStorageExists(metadataTouch?.ocId, fileNameView: metadataTouch?.fileNameView) {
  936. performSegue(withIdentifier: "segueDetail", sender: self)
  937. } else {
  938. NCNetworking.shared.download(metadata: metadataTouch!, selector: selectorLoadFileView) { (_) in }
  939. }
  940. }
  941. }
  942. func collectionViewSelectAll() {
  943. selectOcId.removeAll()
  944. for metadata in metadatasSource {
  945. selectOcId.append(metadata.ocId)
  946. }
  947. collectionView.reloadData()
  948. }
  949. }
  950. extension NCCollectionViewCommon: UICollectionViewDataSource {
  951. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  952. if kind == UICollectionView.elementKindSectionHeader {
  953. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeaderMenu", for: indexPath) as! NCSectionHeaderMenu
  954. if collectionView.collectionViewLayout == gridLayout {
  955. header.buttonSwitch.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "switchList"), width: 100, height: 100, color: NCBrandColor.sharedInstance.icon), for: .normal)
  956. } else {
  957. header.buttonSwitch.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "switchGrid"), width: 100, height: 100, color: NCBrandColor.sharedInstance.icon), for: .normal)
  958. }
  959. header.delegate = self
  960. header.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  961. header.separator.backgroundColor = NCBrandColor.sharedInstance.separator
  962. header.setStatusButton(count: dataSource.metadatas.count)
  963. header.setTitleSorted(datasourceTitleButton: titleButton)
  964. header.viewRichWorkspaceHeightConstraint.constant = headerRichWorkspaceHeight
  965. header.setRichWorkspaceText(richWorkspaceText: richWorkspaceText)
  966. return header
  967. } else {
  968. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  969. let info = dataSource.getFilesInformation()
  970. footer.setTitleLabel(directories: info.directories, files: info.files, size: info.size )
  971. return footer
  972. }
  973. }
  974. func numberOfSections(in collectionView: UICollectionView) -> Int {
  975. return 1
  976. }
  977. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  978. return dataSource.numberOfItems()
  979. }
  980. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  981. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else {
  982. return UICollectionViewCell()
  983. }
  984. var tableShare: tableShare?
  985. var isShare = false
  986. var isMounted = false
  987. // Download preview
  988. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, urlBase: appDelegate.urlBase, view: collectionView, indexPath: indexPath)
  989. if metadataFolder != nil {
  990. isShare = metadata.permissions.contains(k_permission_shared) && !metadataFolder!.permissions.contains(k_permission_shared)
  991. isMounted = metadata.permissions.contains(k_permission_mounted) && !metadataFolder!.permissions.contains(k_permission_mounted)
  992. }
  993. if dataSource.metadataShare[metadata.ocId] != nil {
  994. tableShare = dataSource.metadataShare[metadata.ocId]
  995. }
  996. // LAYOUT LIST
  997. if layout == k_layout_list {
  998. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  999. cell.delegate = self
  1000. cell.objectId = metadata.ocId
  1001. cell.indexPath = indexPath
  1002. cell.labelTitle.text = metadata.fileNameView
  1003. cell.labelTitle.textColor = NCBrandColor.sharedInstance.textView
  1004. cell.separator.backgroundColor = NCBrandColor.sharedInstance.separator
  1005. cell.imageSelect.image = nil
  1006. cell.imageStatus.image = nil
  1007. cell.imageLocal.image = nil
  1008. cell.imageFavorite.image = nil
  1009. cell.imageShared.image = nil
  1010. cell.imageMore.image = nil
  1011. cell.imageItem.image = nil
  1012. cell.imageItem.backgroundColor = nil
  1013. cell.progressView.progress = 0.0
  1014. if metadata.directory {
  1015. if metadata.e2eEncrypted {
  1016. cell.imageItem.image = NCCollectionCommon.images.cellFolderEncryptedImage
  1017. } else if isShare {
  1018. cell.imageItem.image = NCCollectionCommon.images.cellFolderSharedWithMeImage
  1019. } else if (tableShare != nil && tableShare?.shareType != 3) {
  1020. cell.imageItem.image = NCCollectionCommon.images.cellFolderSharedWithMeImage
  1021. } else if (tableShare != nil && tableShare?.shareType == 3) {
  1022. cell.imageItem.image = NCCollectionCommon.images.cellFolderPublicImage
  1023. } else if metadata.mountType == "group" {
  1024. cell.imageItem.image = NCCollectionCommon.images.cellFolderGroupImage
  1025. } else if isMounted {
  1026. cell.imageItem.image = NCCollectionCommon.images.cellFolderExternalImage
  1027. } else if metadata.fileName == autoUploadFileName && metadata.serverUrl == autoUploadDirectory {
  1028. cell.imageItem.image = NCCollectionCommon.images.cellFolderAutomaticUploadImage
  1029. } else {
  1030. cell.imageItem.image = NCCollectionCommon.images.cellFolderImage
  1031. }
  1032. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date)
  1033. let lockServerUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!
  1034. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, lockServerUrl))
  1035. // Local image: offline
  1036. if tableDirectory != nil && tableDirectory!.offline {
  1037. cell.imageLocal.image = NCCollectionCommon.images.cellOfflineFlag
  1038. }
  1039. } else {
  1040. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  1041. cell.imageItem.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  1042. } else {
  1043. if metadata.hasPreview {
  1044. cell.imageItem.backgroundColor = .lightGray
  1045. } else {
  1046. if metadata.iconName.count > 0 {
  1047. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  1048. } else {
  1049. cell.imageItem.image = NCCollectionCommon.images.cellFileImage
  1050. }
  1051. }
  1052. }
  1053. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date) + " · " + CCUtility.transformedSize(metadata.size)
  1054. // image local
  1055. if dataSource.metadataLocalImage[metadata.ocId] == "offlineFlag" {
  1056. cell.imageLocal.image = NCCollectionCommon.images.cellOfflineFlag
  1057. } else if dataSource.metadataLocalImage[metadata.ocId] == "local" {
  1058. cell.imageLocal.image = NCCollectionCommon.images.cellLocal
  1059. }
  1060. }
  1061. // image Favorite
  1062. if metadata.favorite {
  1063. cell.imageFavorite.image = NCCollectionCommon.images.cellFavouriteImage
  1064. }
  1065. // Share image
  1066. if (isShare) {
  1067. cell.imageShared.image = NCCollectionCommon.images.cellSharedImage
  1068. } else if (tableShare != nil && tableShare?.shareType == 3) {
  1069. cell.imageShared.image = NCCollectionCommon.images.cellShareByLinkImage
  1070. } else if (tableShare != nil && tableShare?.shareType != 3) {
  1071. cell.imageShared.image = NCCollectionCommon.images.cellSharedImage
  1072. } else {
  1073. cell.imageShared.image = NCCollectionCommon.images.cellCanShareImage
  1074. }
  1075. if metadata.ownerId.count > 0 && metadata.ownerId != appDelegate.userID {
  1076. // Load avatar
  1077. let fileNameSource = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.user, urlBase: appDelegate.urlBase) + "-" + metadata.ownerId + ".png"
  1078. let fileNameSourceAvatar = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.user, urlBase: appDelegate.urlBase) + "-avatar-" + metadata.ownerId + ".png"
  1079. if FileManager.default.fileExists(atPath: fileNameSourceAvatar) {
  1080. cell.imageShared.image = UIImage(contentsOfFile: fileNameSourceAvatar)
  1081. } else if FileManager.default.fileExists(atPath: fileNameSource) {
  1082. cell.imageShared.image = NCUtility.shared.createAvatar(fileNameSource: fileNameSource, fileNameSourceAvatar: fileNameSourceAvatar)
  1083. } else {
  1084. NCCommunication.shared.downloadAvatar(userID: metadata.ownerId, fileNameLocalPath: fileNameSource, size: Int(k_avatar_size)) { (account, data, errorCode, errorMessage) in
  1085. if errorCode == 0 && account == self.appDelegate.account {
  1086. cell.imageShared.image = NCUtility.shared.createAvatar(fileNameSource: fileNameSource, fileNameSourceAvatar: fileNameSourceAvatar)
  1087. }
  1088. }
  1089. }
  1090. }
  1091. if isEditMode {
  1092. cell.imageItemLeftConstraint.constant = 45
  1093. cell.imageSelect.isHidden = false
  1094. if selectOcId.contains(metadata.ocId) {
  1095. cell.imageSelect.image = NCCollectionCommon.images.cellCheckedYes
  1096. cell.backgroundView = NCUtility.shared.cellBlurEffect(with: cell.bounds)
  1097. } else {
  1098. cell.imageSelect.image = NCCollectionCommon.images.cellCheckedNo
  1099. cell.backgroundView = nil
  1100. }
  1101. } else {
  1102. cell.imageItemLeftConstraint.constant = 10
  1103. cell.imageSelect.isHidden = true
  1104. cell.backgroundView = nil
  1105. }
  1106. // Transfer
  1107. var progress: Float = 0.0
  1108. var totalBytes: Double = 0.0
  1109. let progressArray = appDelegate.listProgressMetadata.object(forKey: metadata.ocId) as? NSArray
  1110. if progressArray != nil && progressArray?.count == 3 {
  1111. progress = progressArray?.object(at: 0) as? Float ?? 0
  1112. totalBytes = progressArray?.object(at: 1) as? Double ?? 0
  1113. }
  1114. if metadata.status == k_metadataStatusInDownload || metadata.status == k_metadataStatusDownloading || metadata.status >= k_metadataStatusTypeUpload {
  1115. cell.progressView.isHidden = false
  1116. cell.setButtonMore(named: k_buttonMoreStop, image: NCCollectionCommon.images.cellButtonStop)
  1117. } else {
  1118. cell.progressView.isHidden = true
  1119. cell.progressView.progress = progress
  1120. cell.setButtonMore(named: k_buttonMoreMore, image: NCCollectionCommon.images.cellButtonMore)
  1121. }
  1122. // Write status on Label Info
  1123. switch metadata.status {
  1124. case Int(k_metadataStatusWaitDownload):
  1125. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_download_", comment: "")
  1126. break
  1127. case Int(k_metadataStatusInDownload):
  1128. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_download_", comment: "")
  1129. break
  1130. case Int(k_metadataStatusDownloading):
  1131. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - ↓ " + CCUtility.transformedSize(totalBytes)
  1132. break
  1133. case Int(k_metadataStatusWaitUpload):
  1134. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_upload_", comment: "")
  1135. break
  1136. case Int(k_metadataStatusInUpload):
  1137. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_upload_", comment: "")
  1138. break
  1139. case Int(k_metadataStatusUploading):
  1140. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - ↑ " + CCUtility.transformedSize(totalBytes)
  1141. break
  1142. default:
  1143. break
  1144. }
  1145. // Live Photo
  1146. if metadata.livePhoto {
  1147. cell.imageStatus.image = NCCollectionCommon.images.cellLivePhotoImage
  1148. }
  1149. // E2EE
  1150. if metadata.e2eEncrypted || isEncryptedFolder {
  1151. cell.hideButtonShare(true)
  1152. } else {
  1153. cell.hideButtonShare(false)
  1154. }
  1155. // Remove last separator
  1156. if collectionView.numberOfItems(inSection: indexPath.section) == indexPath.row + 1 {
  1157. cell.separator.isHidden = true
  1158. } else {
  1159. cell.separator.isHidden = false
  1160. }
  1161. return cell
  1162. }
  1163. // LAYOUT GRID
  1164. if layout == k_layout_grid {
  1165. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  1166. cell.delegate = self
  1167. cell.objectId = metadata.ocId
  1168. cell.indexPath = indexPath
  1169. cell.labelTitle.text = metadata.fileNameView
  1170. cell.labelTitle.textColor = NCBrandColor.sharedInstance.textView
  1171. cell.imageSelect.image = nil
  1172. cell.imageStatus.image = nil
  1173. cell.imageLocal.image = nil
  1174. cell.imageFavorite.image = nil
  1175. cell.imageItem.image = nil
  1176. cell.imageItem.backgroundColor = nil
  1177. cell.progressView.progress = 0.0
  1178. if metadata.directory {
  1179. if metadata.e2eEncrypted {
  1180. cell.imageItem.image = NCCollectionCommon.images.cellFolderEncryptedImage
  1181. } else if isShare {
  1182. cell.imageItem.image = NCCollectionCommon.images.cellFolderSharedWithMeImage
  1183. } else if (tableShare != nil && tableShare!.shareType != 3) {
  1184. cell.imageItem.image = NCCollectionCommon.images.cellFolderSharedWithMeImage
  1185. } else if (tableShare != nil && tableShare!.shareType == 3) {
  1186. cell.imageItem.image = NCCollectionCommon.images.cellFolderPublicImage
  1187. } else if metadata.mountType == "group" {
  1188. cell.imageItem.image = NCCollectionCommon.images.cellFolderGroupImage
  1189. } else if isMounted {
  1190. cell.imageItem.image = NCCollectionCommon.images.cellFolderExternalImage
  1191. } else if metadata.fileName == autoUploadFileName && metadata.serverUrl == autoUploadDirectory {
  1192. cell.imageItem.image = NCCollectionCommon.images.cellFolderAutomaticUploadImage
  1193. } else {
  1194. cell.imageItem.image = NCCollectionCommon.images.cellFolderImage
  1195. }
  1196. let lockServerUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!
  1197. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, lockServerUrl))
  1198. // Local image: offline
  1199. if tableDirectory != nil && tableDirectory!.offline {
  1200. cell.imageLocal.image = NCCollectionCommon.images.cellOfflineFlag
  1201. }
  1202. } else {
  1203. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  1204. cell.imageItem.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  1205. } else {
  1206. if metadata.hasPreview {
  1207. cell.imageItem.backgroundColor = .lightGray
  1208. } else {
  1209. if metadata.iconName.count > 0 {
  1210. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  1211. } else {
  1212. cell.imageItem.image = NCCollectionCommon.images.cellFileImage
  1213. }
  1214. }
  1215. }
  1216. // image Local
  1217. if dataSource.metadataLocalImage[metadata.ocId] == "offlineFlag" {
  1218. cell.imageLocal.image = NCCollectionCommon.images.cellOfflineFlag
  1219. } else if dataSource.metadataLocalImage[metadata.ocId] == "local" {
  1220. cell.imageLocal.image = NCCollectionCommon.images.cellLocal
  1221. }
  1222. }
  1223. // image Favorite
  1224. if metadata.favorite {
  1225. cell.imageFavorite.image = NCCollectionCommon.images.cellFavouriteImage
  1226. }
  1227. if isEditMode {
  1228. cell.imageSelect.isHidden = false
  1229. if selectOcId.contains(metadata.ocId) {
  1230. cell.imageSelect.image = NCCollectionCommon.images.cellCheckedYes
  1231. cell.backgroundView = NCUtility.shared.cellBlurEffect(with: cell.bounds)
  1232. } else {
  1233. cell.imageSelect.image = NCCollectionCommon.images.cellCheckedNo
  1234. cell.backgroundView = nil
  1235. }
  1236. } else {
  1237. cell.imageSelect.isHidden = true
  1238. cell.backgroundView = nil
  1239. }
  1240. // Transfer
  1241. if metadata.status == k_metadataStatusInDownload || metadata.status == k_metadataStatusDownloading || metadata.status >= k_metadataStatusTypeUpload {
  1242. cell.progressView.isHidden = false
  1243. cell.setButtonMore(named: k_buttonMoreStop, image: NCCollectionCommon.images.cellButtonStop)
  1244. } else {
  1245. cell.progressView.isHidden = true
  1246. cell.progressView.progress = 0.0
  1247. cell.setButtonMore(named: k_buttonMoreMore, image: NCCollectionCommon.images.cellButtonMore)
  1248. }
  1249. // Live Photo
  1250. if metadata.livePhoto {
  1251. cell.imageStatus.image = NCCollectionCommon.images.cellLivePhotoImage
  1252. }
  1253. return cell
  1254. }
  1255. return UICollectionViewCell()
  1256. }
  1257. }
  1258. extension NCCollectionViewCommon: UICollectionViewDelegateFlowLayout {
  1259. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  1260. headerRichWorkspaceHeight = 0
  1261. if let richWorkspaceText = richWorkspaceText {
  1262. let trimmed = richWorkspaceText.trimmingCharacters(in: .whitespaces)
  1263. if trimmed.count > 0 {
  1264. headerRichWorkspaceHeight = UIScreen.main.bounds.size.height / 4
  1265. }
  1266. }
  1267. return CGSize(width: collectionView.frame.width, height: headerHeight + headerRichWorkspaceHeight)
  1268. }
  1269. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  1270. return CGSize(width: collectionView.frame.width, height: footerHeight)
  1271. }
  1272. }