NCCollectionViewCommon.swift 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204
  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. internal let refreshControl = UIRefreshControl()
  28. internal var searchController: UISearchController?
  29. @objc var serverUrl: String = ""
  30. @objc var isRoot: Bool = true
  31. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  32. internal var isEncryptedFolder = false
  33. internal var isEditMode = false
  34. internal var selectOcId: [String] = []
  35. internal var metadatasSource: [tableMetadata] = []
  36. internal var metadataFolder: tableMetadata?
  37. internal var metadataTouch: tableMetadata?
  38. internal var dataSource: NCDataSource?
  39. internal var richWorkspaceText: String?
  40. internal var layout = ""
  41. internal var groupBy = ""
  42. internal var titleButton = ""
  43. internal var itemForLine = 0
  44. private var autoUploadFileName = ""
  45. private var autoUploadDirectory = ""
  46. private var listLayout: NCListLayout!
  47. private var gridLayout: NCGridLayout!
  48. private let headerHeight: CGFloat = 50
  49. private var headerRichWorkspaceHeight: CGFloat = 0
  50. private let footerHeight: CGFloat = 50
  51. private var timerInputSearch: Timer?
  52. internal var literalSearch: String?
  53. internal var isSearching: Bool = false
  54. internal var isReloadDataSourceNetworkInProgress: Bool = false
  55. // DECLARE
  56. internal var layoutKey = ""
  57. internal var titleCurrentFolder = ""
  58. internal var enableSearchBar: Bool = false
  59. internal var DZNimage: UIImage?
  60. internal var DZNtitle: String = ""
  61. internal var DZNdescription: String = ""
  62. required init?(coder aDecoder: NSCoder) {
  63. super.init(coder: aDecoder)
  64. }
  65. override func viewDidLoad() {
  66. super.viewDidLoad()
  67. self.navigationController?.navigationBar.prefersLargeTitles = true
  68. if enableSearchBar {
  69. searchController = UISearchController(searchResultsController: nil)
  70. searchController?.searchResultsUpdater = self
  71. searchController?.dimsBackgroundDuringPresentation = false
  72. searchController?.delegate = self
  73. searchController?.searchBar.delegate = self
  74. navigationItem.searchController = searchController
  75. navigationItem.hidesSearchBarWhenScrolling = false
  76. }
  77. // Cell
  78. collectionView.register(UINib.init(nibName: "NCListCell", bundle: nil), forCellWithReuseIdentifier: "listCell")
  79. collectionView.register(UINib.init(nibName: "NCGridCell", bundle: nil), forCellWithReuseIdentifier: "gridCell")
  80. // Header
  81. collectionView.register(UINib.init(nibName: "NCSectionHeaderMenu", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeaderMenu")
  82. // Footer
  83. collectionView.register(UINib.init(nibName: "NCSectionFooter", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "sectionFooter")
  84. collectionView.alwaysBounceVertical = true
  85. listLayout = NCListLayout()
  86. gridLayout = NCGridLayout()
  87. // Refresh Control
  88. collectionView.addSubview(refreshControl)
  89. refreshControl.tintColor = NCBrandColor.sharedInstance.brandText
  90. refreshControl.backgroundColor = NCBrandColor.sharedInstance.brandElement
  91. refreshControl.addTarget(self, action: #selector(reloadDataSourceNetworkRefreshControl), for: .valueChanged)
  92. // empty Data Source
  93. self.collectionView.emptyDataSetDelegate = self
  94. self.collectionView.emptyDataSetSource = self
  95. // 3D Touch peek and pop
  96. if traitCollection.forceTouchCapability == .available {
  97. registerForPreviewing(with: self, sourceView: view)
  98. }
  99. // Long Press on CollectionView
  100. let longPressedGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPressCollecationView(_:)))
  101. longPressedGesture.minimumPressDuration = 0.5
  102. longPressedGesture.delegate = self
  103. longPressedGesture.delaysTouchesBegan = true
  104. collectionView.addGestureRecognizer(longPressedGesture)
  105. // Notification
  106. NotificationCenter.default.addObserver(self, selector: #selector(initializeMain), name: NSNotification.Name(rawValue: k_notificationCenter_initializeMain), object: nil)
  107. NotificationCenter.default.addObserver(self, selector: #selector(changeTheming), name: NSNotification.Name(rawValue: k_notificationCenter_changeTheming), object: nil)
  108. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSource(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_reloadDataSource), object: nil)
  109. NotificationCenter.default.addObserver(self, selector: #selector(changeStatusFolderE2EE(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_changeStatusFolderE2EE), object: nil)
  110. NotificationCenter.default.addObserver(self, selector: #selector(deleteFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_deleteFile), object: nil)
  111. NotificationCenter.default.addObserver(self, selector: #selector(moveFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_moveFile), object: nil)
  112. NotificationCenter.default.addObserver(self, selector: #selector(copyFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_copyFile), object: nil)
  113. NotificationCenter.default.addObserver(self, selector: #selector(renameFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_renameFile), object: nil)
  114. NotificationCenter.default.addObserver(self, selector: #selector(createFolder(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_createFolder), object: nil)
  115. NotificationCenter.default.addObserver(self, selector: #selector(favoriteFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_favoriteFile), object: nil)
  116. NotificationCenter.default.addObserver(self, selector: #selector(downloadStartFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_downloadStartFile), object: nil)
  117. NotificationCenter.default.addObserver(self, selector: #selector(downloadedFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_downloadedFile), object: nil)
  118. NotificationCenter.default.addObserver(self, selector: #selector(downloadCancelFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_downloadCancelFile), object: nil)
  119. NotificationCenter.default.addObserver(self, selector: #selector(uploadStartFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_uploadStartFile), object: nil)
  120. NotificationCenter.default.addObserver(self, selector: #selector(uploadedFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_uploadedFile), object: nil)
  121. NotificationCenter.default.addObserver(self, selector: #selector(uploadCancelFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_uploadCancelFile), object: nil)
  122. NotificationCenter.default.addObserver(self, selector: #selector(triggerProgressTask(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_progressTask), object:nil)
  123. changeTheming()
  124. }
  125. override func viewWillAppear(_ animated: Bool) {
  126. super.viewWillAppear(animated)
  127. appDelegate.activeViewController = self
  128. self.navigationItem.title = titleCurrentFolder
  129. (layout, _, _, groupBy, _, titleButton, itemForLine) = NCUtility.shared.getLayoutForView(key: layoutKey)
  130. gridLayout.itemForLine = CGFloat(itemForLine)
  131. if layout == k_layout_list {
  132. collectionView?.collectionViewLayout = listLayout
  133. } else {
  134. collectionView?.collectionViewLayout = gridLayout
  135. }
  136. setNavigationItem()
  137. reloadDataSource()
  138. }
  139. override func viewDidAppear(_ animated: Bool) {
  140. super.viewDidAppear(animated)
  141. reloadDataSourceNetwork()
  142. }
  143. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  144. super.viewWillTransition(to: size, with: coordinator)
  145. coordinator.animate(alongsideTransition: nil) { _ in
  146. self.collectionView?.collectionViewLayout.invalidateLayout()
  147. }
  148. }
  149. override var canBecomeFirstResponder: Bool {
  150. return true
  151. }
  152. func setNavigationItem() {
  153. if isEditMode {
  154. self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage.init(named: "navigationMore"), style: .plain, target: self, action:#selector(tapSelectMenu(sender:)))
  155. self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_cancel_", comment: ""), style: .plain, target: self, action: #selector(tapSelect(sender:)))
  156. } else {
  157. self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_select_", comment: ""), style: UIBarButtonItem.Style.plain, target: self, action: #selector(tapSelect(sender:)))
  158. self.navigationItem.leftBarButtonItem = nil
  159. }
  160. }
  161. // MARK: - NotificationCenter
  162. @objc func initializeMain() {
  163. if isRoot {
  164. print("root")
  165. }
  166. if searchController?.isActive ?? false {
  167. searchController?.isActive = false
  168. }
  169. self.navigationController?.popToRootViewController(animated: false)
  170. appDelegate.listFilesVC.removeAllObjects()
  171. appDelegate.listFavoriteVC.removeAllObjects()
  172. appDelegate.listOfflineVC.removeAllObjects()
  173. reloadDataSource()
  174. }
  175. @objc func changeTheming() {
  176. appDelegate.changeTheming(self, tableView: nil, collectionView: collectionView, form: false)
  177. }
  178. @objc func changeStatusFolderE2EE(_ notification: NSNotification) {
  179. if self.view?.window == nil { return }
  180. reloadDataSource()
  181. }
  182. @objc func deleteFile(_ notification: NSNotification) {
  183. if self.view?.window == nil { return }
  184. if let userInfo = notification.userInfo as NSDictionary? {
  185. if let metadata = userInfo["metadata"] as? tableMetadata, let onlyLocal = userInfo["onlyLocal"] as? Bool {
  186. if onlyLocal {
  187. if let row = dataSource?.reloadMetadata(ocId: metadata.ocId) {
  188. let indexPath = IndexPath(row: row, section: 0)
  189. collectionView?.reloadItems(at: [indexPath])
  190. }
  191. } else {
  192. if let row = dataSource?.deleteMetadata(ocId: metadata.ocId) {
  193. let indexPath = IndexPath(row: row, section: 0)
  194. collectionView?.performBatchUpdates({
  195. collectionView?.deleteItems(at: [indexPath])
  196. }, completion: { (_) in
  197. self.collectionView?.reloadData()
  198. })
  199. }
  200. }
  201. }
  202. }
  203. }
  204. @objc func moveFile(_ notification: NSNotification) {
  205. if self.view?.window == nil { return }
  206. if let userInfo = notification.userInfo as NSDictionary? {
  207. if let metadata = userInfo["metadata"] as? tableMetadata, let metadataNew = userInfo["metadataNew"] as? tableMetadata {
  208. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  209. if let row = dataSource?.deleteMetadata(ocId: metadata.ocId) {
  210. let indexPath = IndexPath(row: row, section: 0)
  211. collectionView?.performBatchUpdates({
  212. collectionView?.deleteItems(at: [indexPath])
  213. }, completion: { (_) in
  214. self.collectionView?.reloadData()
  215. })
  216. }
  217. } else if metadataNew.serverUrl == serverUrl && metadata.account == appDelegate.account {
  218. if let row = dataSource?.addMetadata(metadataNew) {
  219. let indexPath = IndexPath(row: row, section: 0)
  220. collectionView?.performBatchUpdates({
  221. collectionView?.insertItems(at: [indexPath])
  222. }, completion: { (_) in
  223. self.collectionView?.reloadData()
  224. })
  225. }
  226. }
  227. }
  228. }
  229. }
  230. @objc func copyFile(_ notification: NSNotification) {
  231. if self.view?.window == nil { return }
  232. if let userInfo = notification.userInfo as NSDictionary? {
  233. if let serverUrlTo = userInfo["serverUrlTo"] as? String {
  234. if serverUrlTo == self.serverUrl {
  235. self.reloadDataSource()
  236. }
  237. }
  238. }
  239. }
  240. @objc func renameFile(_ notification: NSNotification) {
  241. if self.view?.window == nil { return }
  242. if let userInfo = notification.userInfo as NSDictionary? {
  243. if let metadata = userInfo["metadata"] as? tableMetadata {
  244. if let row = dataSource?.reloadMetadata(ocId: metadata.ocId) {
  245. let indexPath = IndexPath(row: row, section: 0)
  246. collectionView?.performBatchUpdates({
  247. collectionView?.reloadItems(at: [indexPath])
  248. }, completion: { (_) in
  249. self.collectionView?.reloadData()
  250. })
  251. }
  252. }
  253. }
  254. }
  255. @objc func createFolder(_ 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 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. } else {
  271. self.reloadDataSourceNetwork()
  272. }
  273. }
  274. @objc func favoriteFile(_ notification: NSNotification) {
  275. if self.view?.window == nil { return }
  276. if let userInfo = notification.userInfo as NSDictionary? {
  277. if let metadata = userInfo["metadata"] as? tableMetadata {
  278. if dataSource?.getIndexMetadata(ocId: metadata.ocId) != nil {
  279. self.reloadDataSource()
  280. }
  281. }
  282. }
  283. }
  284. @objc func downloadStartFile(_ notification: NSNotification) {
  285. if self.view?.window == nil { return }
  286. if let userInfo = notification.userInfo as NSDictionary? {
  287. if let metadata = userInfo["metadata"] as? tableMetadata {
  288. if let row = dataSource?.reloadMetadata(ocId: metadata.ocId) {
  289. let indexPath = IndexPath(row: row, section: 0)
  290. collectionView?.reloadItems(at: [indexPath])
  291. }
  292. }
  293. }
  294. }
  295. @objc func downloadedFile(_ notification: NSNotification) {
  296. if self.view?.window == nil { return }
  297. if let userInfo = notification.userInfo as NSDictionary? {
  298. if let metadata = userInfo["metadata"] as? tableMetadata, let _ = userInfo["errorCode"] as? Int {
  299. if let row = dataSource?.reloadMetadata(ocId: metadata.ocId) {
  300. let indexPath = IndexPath(row: row, section: 0)
  301. collectionView?.reloadItems(at: [indexPath])
  302. }
  303. }
  304. }
  305. }
  306. @objc func downloadCancelFile(_ notification: NSNotification) {
  307. if self.view?.window == nil { return }
  308. if let userInfo = notification.userInfo as NSDictionary? {
  309. if let metadata = userInfo["metadata"] as? tableMetadata {
  310. if let row = dataSource?.reloadMetadata(ocId: metadata.ocId) {
  311. let indexPath = IndexPath(row: row, section: 0)
  312. collectionView?.reloadItems(at: [indexPath])
  313. }
  314. }
  315. }
  316. }
  317. @objc func uploadStartFile(_ notification: NSNotification) {
  318. if self.view?.window == nil { return }
  319. if let userInfo = notification.userInfo as NSDictionary? {
  320. if let metadata = userInfo["metadata"] as? tableMetadata {
  321. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  322. if let row = dataSource?.addMetadata(metadata) {
  323. let indexPath = IndexPath(row: row, section: 0)
  324. collectionView?.performBatchUpdates({
  325. collectionView?.insertItems(at: [indexPath])
  326. }, completion: { (_) in
  327. self.collectionView?.reloadData()
  328. })
  329. }
  330. }
  331. }
  332. }
  333. }
  334. @objc func uploadedFile(_ notification: NSNotification) {
  335. if self.view?.window == nil { return }
  336. if let userInfo = notification.userInfo as NSDictionary? {
  337. if let metadata = userInfo["metadata"] as? tableMetadata, let ocIdTemp = userInfo["ocIdTemp"] as? String, let _ = userInfo["errorCode"] as? Int {
  338. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  339. dataSource?.reloadMetadata(ocId: metadata.ocId, ocIdTemp: ocIdTemp)
  340. collectionView?.reloadData()
  341. }
  342. }
  343. }
  344. }
  345. @objc func uploadCancelFile(_ notification: NSNotification) {
  346. if self.view?.window == nil { return }
  347. if let userInfo = notification.userInfo as NSDictionary? {
  348. if let metadata = userInfo["metadata"] as? tableMetadata {
  349. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  350. if let row = dataSource?.deleteMetadata(ocId: metadata.ocId) {
  351. let indexPath = IndexPath(row: row, section: 0)
  352. collectionView?.performBatchUpdates({
  353. collectionView?.deleteItems(at: [indexPath])
  354. }, completion: { (_) in
  355. self.collectionView?.reloadData()
  356. })
  357. } else {
  358. self.reloadDataSource()
  359. }
  360. }
  361. }
  362. }
  363. }
  364. @objc func triggerProgressTask(_ notification: NSNotification) {
  365. if self.view?.window == nil { return }
  366. if let userInfo = notification.userInfo as NSDictionary? {
  367. if let ocId = userInfo["ocId"] as? String {
  368. let _ = userInfo["account"] as? String ?? ""
  369. let _ = userInfo["serverUrl"] as? String ?? ""
  370. let progressNumber = userInfo["progress"] as? NSNumber ?? 0
  371. let progress = progressNumber.floatValue
  372. let status = userInfo["status"] as? Int ?? Int(k_metadataStatusNormal)
  373. let totalBytes = userInfo["totalBytes"] as? Double ?? 0
  374. let totalBytesExpected = userInfo["totalBytesExpected"] as? Double ?? 0
  375. appDelegate.listProgressMetadata.setObject([progress as NSNumber, totalBytes as NSNumber, totalBytesExpected as NSNumber], forKey: userInfo["ocId"] as? NSString ?? "")
  376. if let index = dataSource?.getIndexMetadata(ocId: ocId) {
  377. if let cell = collectionView?.cellForItem(at: IndexPath(row: index, section: 0)) {
  378. if cell is NCListCell {
  379. let cell = cell as! NCListCell
  380. if progress > 0 {
  381. cell.progressView?.isHidden = false
  382. cell.progressView?.progress = progress
  383. cell.setButtonMore(named: "stop")
  384. if status == k_metadataStatusInDownload {
  385. cell.labelInfo.text = CCUtility.transformedSize(totalBytesExpected) + " - ↓ " + CCUtility.transformedSize(totalBytes)
  386. } else if status == k_metadataStatusInUpload {
  387. cell.labelInfo.text = CCUtility.transformedSize(totalBytesExpected) + " - ↑ " + CCUtility.transformedSize(totalBytes)
  388. }
  389. }
  390. } else if cell is NCGridCell {
  391. let cell = cell as! NCGridCell
  392. if progress > 0 {
  393. cell.progressView.isHidden = false
  394. cell.progressView.progress = progress
  395. cell.setButtonMore(named: "stop")
  396. }
  397. }
  398. }
  399. }
  400. }
  401. }
  402. }
  403. // MARK: - DZNEmpty
  404. func backgroundColor(forEmptyDataSet scrollView: UIScrollView) -> UIColor? {
  405. return NCBrandColor.sharedInstance.backgroundView
  406. }
  407. func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
  408. if searchController?.isActive ?? false {
  409. return CCGraphics.changeThemingColorImage(UIImage.init(named: "search"), width: 300, height: 300, color: .gray)
  410. }
  411. return DZNimage
  412. }
  413. func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
  414. var text = "\n"+NSLocalizedString(DZNtitle, comment: "")
  415. if searchController?.isActive ?? false {
  416. if isReloadDataSourceNetworkInProgress {
  417. text = "\n"+NSLocalizedString("_search_in_progress_", comment: "")
  418. } else {
  419. text = "\n"+NSLocalizedString("_search_no_record_found_", comment: "")
  420. }
  421. }
  422. let attributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 20), NSAttributedString.Key.foregroundColor: UIColor.gray]
  423. return NSAttributedString.init(string: text, attributes: attributes)
  424. }
  425. func description(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
  426. var text = "\n"+NSLocalizedString(DZNdescription, comment: "")
  427. if searchController?.isActive ?? false {
  428. text = "\n"+NSLocalizedString("_search_instruction_", comment: "")
  429. }
  430. let attributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14), NSAttributedString.Key.foregroundColor: UIColor.lightGray]
  431. return NSAttributedString.init(string: text, attributes: attributes)
  432. }
  433. func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView) -> Bool {
  434. return true
  435. }
  436. // MARK: - SEARCH
  437. func updateSearchResults(for searchController: UISearchController) {
  438. timerInputSearch?.invalidate()
  439. timerInputSearch = Timer.scheduledTimer(timeInterval: 1.5, target: self, selector: #selector(reloadDataSourceNetwork), userInfo: nil, repeats: false)
  440. literalSearch = searchController.searchBar.text
  441. collectionView?.reloadData()
  442. }
  443. func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
  444. isSearching = true
  445. metadatasSource.removeAll()
  446. reloadDataSource()
  447. }
  448. func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
  449. isSearching = false
  450. literalSearch = ""
  451. reloadDataSource()
  452. }
  453. // MARK: - TAP EVENT
  454. @objc func tapSelect(sender: Any) {
  455. isEditMode = !isEditMode
  456. selectOcId.removeAll()
  457. setNavigationItem()
  458. self.collectionView.reloadData()
  459. }
  460. func tapSwitchHeader(sender: Any) {
  461. if collectionView.collectionViewLayout == gridLayout {
  462. // list layout
  463. UIView.animate(withDuration: 0.0, animations: {
  464. self.collectionView.collectionViewLayout.invalidateLayout()
  465. self.collectionView.setCollectionViewLayout(self.listLayout, animated: false, completion: { (_) in
  466. self.collectionView.reloadData()
  467. self.collectionView.setContentOffset(CGPoint(x:0,y:0), animated: false)
  468. })
  469. })
  470. layout = k_layout_list
  471. NCUtility.shared.setLayoutForView(key: layoutKey, layout: layout)
  472. } else {
  473. // grid layout
  474. UIView.animate(withDuration: 0.0, animations: {
  475. self.collectionView.collectionViewLayout.invalidateLayout()
  476. self.collectionView.setCollectionViewLayout(self.gridLayout, animated: false, completion: { (_) in
  477. self.collectionView.reloadData()
  478. self.collectionView.setContentOffset(CGPoint(x:0,y:0), animated: false)
  479. })
  480. })
  481. layout = k_layout_grid
  482. NCUtility.shared.setLayoutForView(key: layoutKey, layout: layout)
  483. }
  484. }
  485. func tapOrderHeader(sender: Any) {
  486. let sortMenu = NCSortMenu()
  487. sortMenu.toggleMenu(viewController: self, key: layoutKey, sortButton: sender as? UIButton, serverUrl: serverUrl)
  488. }
  489. @objc func tapSelectMenu(sender: Any) {
  490. guard let tabBarController = self.tabBarController else { return }
  491. toggleMoreSelect(viewController: tabBarController, selectOcId: selectOcId)
  492. }
  493. func tapMoreHeader(sender: Any) { }
  494. func tapMoreListItem(with objectId: String, namedButtonMore: String, sender: Any) {
  495. tapMoreGridItem(with: objectId, namedButtonMore: namedButtonMore, sender: sender)
  496. }
  497. func tapShareListItem(with objectId: String, sender: Any) {
  498. guard let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(objectId) else { return }
  499. NCMainCommon.shared.openShare(ViewController: self, metadata: metadata, indexPage: 2)
  500. }
  501. func tapMoreGridItem(with objectId: String, namedButtonMore: String, sender: Any) {
  502. guard let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(objectId) else { return }
  503. guard let tabBarController = self.tabBarController else { return }
  504. if namedButtonMore == "more" {
  505. toggleMoreMenu(viewController: tabBarController, metadata: metadata)
  506. } else if namedButtonMore == "stop" {
  507. NCNetworking.shared.cancelTransferMetadata(metadata) { }
  508. }
  509. }
  510. func tapRichWorkspace(sender: Any) {
  511. if let navigationController = UIStoryboard(name: "NCViewerRichWorkspace", bundle: nil).instantiateInitialViewController() as? UINavigationController {
  512. if let viewerRichWorkspace = navigationController.topViewController as? NCViewerRichWorkspace {
  513. viewerRichWorkspace.richWorkspaceText = richWorkspaceText ?? ""
  514. viewerRichWorkspace.serverUrl = serverUrl
  515. navigationController.modalPresentationStyle = .fullScreen
  516. self.present(navigationController, animated: true, completion: nil)
  517. }
  518. }
  519. }
  520. func longPressListItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) {
  521. if let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(objectId) {
  522. metadataTouch = metadata
  523. longPressCollecationView(gestureRecognizer)
  524. }
  525. }
  526. func longPressGridItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) {
  527. if let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(objectId) {
  528. metadataTouch = metadata
  529. longPressCollecationView(gestureRecognizer)
  530. }
  531. }
  532. func longPressMoreListItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) {
  533. }
  534. func longPressMoreGridItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) {
  535. }
  536. @objc func longPressCollecationView(_ gestureRecognizer: UILongPressGestureRecognizer) {
  537. if gestureRecognizer.state != .began { return }
  538. if serverUrl == "" { return }
  539. var listMenuItems: [UIMenuItem] = []
  540. let touchPoint = gestureRecognizer.location(in: collectionView)
  541. becomeFirstResponder()
  542. if metadataTouch != nil {
  543. listMenuItems.append(UIMenuItem.init(title: NSLocalizedString("_copy_file_", comment: ""), action: #selector(copyFileMenu(_:))))
  544. }
  545. listMenuItems.append(UIMenuItem.init(title: NSLocalizedString("_paste_file_", comment: ""), action: #selector(pasteFilesMenu(_:))))
  546. if metadataTouch != nil {
  547. listMenuItems.append(UIMenuItem.init(title: NSLocalizedString("_open_quicklook_", comment: ""), action: #selector(openQuickLookMenu(_:))))
  548. if !NCBrandOptions.sharedInstance.disable_openin_file {
  549. listMenuItems.append(UIMenuItem.init(title: NSLocalizedString("_open_in_", comment: ""), action: #selector(openInMenu(_:))))
  550. }
  551. }
  552. if listMenuItems.count > 0 {
  553. UIMenuController.shared.menuItems = listMenuItems
  554. UIMenuController.shared.setTargetRect(CGRect(x: touchPoint.x, y: touchPoint.y, width: 0, height: 0), in: collectionView)
  555. UIMenuController.shared.setMenuVisible(true, animated: true)
  556. }
  557. }
  558. // MARK: - Menu Item
  559. override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
  560. if (#selector(pasteFilesMenu(_:)) == action) {
  561. if UIPasteboard.general.items.count > 0 {
  562. return true
  563. }
  564. }
  565. if (#selector(openQuickLookMenu(_:)) == action || #selector(openInMenu(_:)) == action || #selector(copyFileMenu(_:)) == action) {
  566. guard let metadata = metadataTouch else { return false }
  567. if !metadata.directory && metadata.status == k_metadataStatusNormal {
  568. return true
  569. }
  570. }
  571. return false
  572. }
  573. @objc func copyFileMenu(_ notification: Any) {
  574. var metadatas: [tableMetadata] = []
  575. var items = [[String : Any]]()
  576. if isEditMode {
  577. for ocId in selectOcId {
  578. if let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(ocId) {
  579. metadatas.append(metadata)
  580. }
  581. }
  582. } else {
  583. guard let metadata = metadataTouch else { return }
  584. metadatas.append(metadata)
  585. }
  586. for metadata in metadatas {
  587. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  588. do {
  589. let etagPasteboard = try NSKeyedArchiver.archivedData(withRootObject: metadata.ocId, requiringSecureCoding: false)
  590. items.append([k_metadataKeyedUnarchiver:etagPasteboard])
  591. } catch {
  592. print("error")
  593. }
  594. } else {
  595. NCNetworking.shared.download(metadata: metadata, selector: selectorLoadCopy, setFavorite: false) { (_) in }
  596. }
  597. }
  598. UIPasteboard.general.setItems(items, options: [:])
  599. if isEditMode {
  600. tapSelect(sender: self)
  601. }
  602. }
  603. @objc func pasteFilesMenu(_ notification: Any) {
  604. var listData: [String] = []
  605. for item in UIPasteboard.general.items {
  606. for object in item {
  607. let contentType = object.key
  608. let data = object.value
  609. if contentType == k_metadataKeyedUnarchiver {
  610. do {
  611. if let ocId = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data as! Data) as? String{
  612. uploadPasteOcId(ocId)
  613. }
  614. } catch {
  615. print("error")
  616. }
  617. continue
  618. }
  619. if data is String {
  620. if listData.contains(data as! String) {
  621. continue
  622. } else {
  623. listData.append(data as! String)
  624. }
  625. }
  626. let type = NCCommunicationCommon.shared.convertUTItoResultType(fileUTI: contentType as CFString)
  627. if type.resultTypeFile != NCCommunicationCommon.typeFile.unknow.rawValue && type.resultExtension != "" {
  628. uploadPasteFile(fileName: type.resultFilename, ext: type.resultExtension, contentType: contentType, data: data)
  629. }
  630. }
  631. }
  632. }
  633. private func uploadPasteFile(fileName: String, ext: String, contentType: String, data: Any) {
  634. do {
  635. let fileNameView = fileName + "_" + CCUtility.getIncrementalNumber() + "." + ext
  636. let ocId = UUID().uuidString
  637. let filePath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView)!
  638. if data is UIImage {
  639. try (data as? UIImage)?.jpegData(compressionQuality: 1)?.write(to: URL(fileURLWithPath: filePath))
  640. } else if data is Data {
  641. try (data as? Data)?.write(to: URL(fileURLWithPath: filePath))
  642. } else if data is String {
  643. try (data as? String)?.write(to: URL(fileURLWithPath: filePath), atomically: true, encoding: .utf8)
  644. } else {
  645. return
  646. }
  647. let metadataForUpload = NCManageDatabase.sharedInstance.createMetadata(account: appDelegate.account, fileName: fileNameView, ocId: ocId, serverUrl: serverUrl, urlBase: appDelegate.urlBase, url: "", contentType: contentType, livePhoto: false)
  648. metadataForUpload.session = NCNetworking.shared.sessionIdentifierBackground
  649. metadataForUpload.sessionSelector = selectorUploadFile
  650. metadataForUpload.size = Double(NCUtilityFileSystem.shared.getFileSize(filePath: filePath))
  651. metadataForUpload.status = Int(k_metadataStatusWaitUpload)
  652. NCManageDatabase.sharedInstance.addMetadata(metadataForUpload)
  653. } catch { }
  654. }
  655. private func uploadPasteOcId(_ ocId: String) {
  656. if let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(ocId) {
  657. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  658. let fileNameView = NCUtility.shared.createFileName(metadata.fileNameView, serverUrl: serverUrl, account: appDelegate.account)
  659. let ocId = NSUUID().uuidString
  660. CCUtility.copyFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView), toPath: CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView))
  661. let metadataForUpload = NCManageDatabase.sharedInstance.createMetadata(account: appDelegate.account, fileName: fileNameView, ocId: ocId, serverUrl: serverUrl, urlBase: appDelegate.urlBase, url: "", contentType: "", livePhoto: false)
  662. metadataForUpload.session = NCNetworking.shared.sessionIdentifierBackground
  663. metadataForUpload.sessionSelector = selectorUploadFile
  664. metadataForUpload.size = metadata.size
  665. metadataForUpload.status = Int(k_metadataStatusWaitUpload)
  666. NCManageDatabase.sharedInstance.addMetadata(metadataForUpload)
  667. }
  668. }
  669. }
  670. @objc func openQuickLookMenu(_ notification: Any) {
  671. guard let metadata = metadataTouch else { return }
  672. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  673. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_downloadedFile, userInfo: ["metadata": metadata, "selector": selectorLoadFileQuickLook, "errorCode": 0, "errorDescription": "" ])
  674. } else {
  675. NCNetworking.shared.download(metadata: metadata, selector: selectorLoadFileQuickLook) { (_) in }
  676. }
  677. }
  678. @objc func openInMenu(_ notification: Any) {
  679. guard let metadata = metadataTouch else { return }
  680. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  681. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_downloadedFile, userInfo: ["metadata": metadata, "selector": selectorOpenIn, "errorCode": 0, "errorDescription": "" ])
  682. } else {
  683. NCNetworking.shared.download(metadata: metadata, selector: selectorOpenIn) { (_) in }
  684. }
  685. }
  686. // MARK: - SEGUE
  687. @objc func segue(metadata: tableMetadata) {
  688. self.metadataTouch = metadata
  689. performSegue(withIdentifier: "segueDetail", sender: self)
  690. }
  691. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  692. let photoDataSource: NSMutableArray = []
  693. for metadata in (dataSource?.metadatas ?? [tableMetadata]()) {
  694. if metadata.typeFile == k_metadataTypeFile_image || metadata.typeFile == k_metadataTypeFile_video {
  695. photoDataSource.add(metadata)
  696. }
  697. }
  698. if let segueNavigationController = segue.destination as? UINavigationController {
  699. if let segueViewController = segueNavigationController.topViewController as? NCDetailViewController {
  700. segueViewController.metadata = metadataTouch
  701. }
  702. }
  703. }
  704. // MARK: - DataSource + NC Endpoint
  705. @objc func reloadDataSource() {
  706. if appDelegate.account.count == 0 { return }
  707. let directory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, serverUrl))
  708. richWorkspaceText = directory?.richWorkspace
  709. // E2EE
  710. isEncryptedFolder = CCUtility.isFolderEncrypted(serverUrl, e2eEncrypted: metadataFolder?.e2eEncrypted ?? false, account: appDelegate.account, urlBase: appDelegate.urlBase)
  711. // get auto upload folder
  712. autoUploadFileName = NCManageDatabase.sharedInstance.getAccountAutoUploadFileName()
  713. autoUploadDirectory = NCManageDatabase.sharedInstance.getAccountAutoUploadDirectory(urlBase: appDelegate.urlBase, account: appDelegate.account)
  714. }
  715. @objc func reloadDataSource(_ notification: NSNotification) { }
  716. @objc func reloadDataSourceNetwork(forced: Bool = false) { }
  717. @objc func reloadDataSourceNetworkRefreshControl() {
  718. reloadDataSourceNetwork(forced: true)
  719. }
  720. @objc func networkSearch() {
  721. if appDelegate.account.count == 0 { return }
  722. if literalSearch?.count ?? 0 > 1 {
  723. isReloadDataSourceNetworkInProgress = true
  724. collectionView?.reloadData()
  725. NCNetworking.shared.searchFiles(urlBase: appDelegate.urlBase, user: appDelegate.user, literal: literalSearch!) { (account, metadatas, errorCode, errorDescription) in
  726. if self.searchController?.isActive ?? false && errorCode == 0 {
  727. self.metadatasSource = metadatas!
  728. }
  729. self.isReloadDataSourceNetworkInProgress = false
  730. self.reloadDataSource()
  731. }
  732. }
  733. }
  734. @objc func networkReadFolder(forced: Bool, completion: @escaping(_ metadatas: [tableMetadata]?, _ errorCode: Int, _ errorDescription: String)->()) {
  735. NCNetworking.shared.readFile(serverUrlFileName: serverUrl, account: appDelegate.account) { (account, metadata, errorCode, errorDescription) in
  736. if errorCode == 0 {
  737. let directory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", self.appDelegate.account, self.serverUrl))
  738. if forced || directory?.etag != metadata?.etag {
  739. NCNetworking.shared.readFolder(serverUrl: self.serverUrl, account: self.appDelegate.account) { (account, metadataFolder, metadatas, metadatasUpdate, metadatasLocalUpdate, errorCode, errorDescription) in
  740. if errorCode == 0 {
  741. self.metadataFolder = metadataFolder
  742. }
  743. completion(metadatas, errorCode, errorDescription)
  744. }
  745. } else {
  746. completion(nil, 0, "")
  747. }
  748. } else {
  749. completion(nil, errorCode, errorDescription)
  750. }
  751. }
  752. }
  753. }
  754. // MARK: - 3D Touch peek and pop
  755. extension NCCollectionViewCommon: UIViewControllerPreviewingDelegate {
  756. func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
  757. guard let point = collectionView?.convert(location, from: collectionView?.superview) else { return nil }
  758. guard let indexPath = collectionView?.indexPathForItem(at: point) else { return nil }
  759. guard let metadata = dataSource?.cellForItemAt(indexPath: indexPath) else { return nil }
  760. guard let viewController = UIStoryboard(name: "CCPeekPop", bundle: nil).instantiateViewController(withIdentifier: "PeekPopImagePreview") as? CCPeekPop else { return nil }
  761. viewController.metadata = metadata
  762. if layout == k_layout_grid {
  763. guard let cell = collectionView?.cellForItem(at: indexPath) as? NCGridCell else { return nil }
  764. previewingContext.sourceRect = cell.frame
  765. viewController.imageFile = cell.imageItem.image
  766. } else {
  767. guard let cell = collectionView?.cellForItem(at: indexPath) as? NCListCell else { return nil }
  768. previewingContext.sourceRect = cell.frame
  769. viewController.imageFile = cell.imageItem.image
  770. }
  771. viewController.showOpenIn = true
  772. viewController.showOpenQuickLook = NCUtility.shared.isQuickLookDisplayable(metadata: metadata)
  773. viewController.showShare = false
  774. return viewController
  775. }
  776. func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
  777. guard let indexPath = collectionView?.indexPathForItem(at: previewingContext.sourceRect.origin) else { return }
  778. collectionView(collectionView, didSelectItemAt: indexPath)
  779. }
  780. }
  781. // MARK: - Collection View
  782. extension NCCollectionViewCommon: UICollectionViewDelegate {
  783. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  784. guard let metadata = dataSource?.cellForItemAt(indexPath: indexPath) else { return }
  785. metadataTouch = metadata
  786. if isEditMode {
  787. if let index = selectOcId.firstIndex(of: metadata.ocId) {
  788. selectOcId.remove(at: index)
  789. } else {
  790. selectOcId.append(metadata.ocId)
  791. }
  792. collectionView.reloadItems(at: [indexPath])
  793. return
  794. }
  795. if metadata.e2eEncrypted && !CCUtility.isEnd(toEndEnabled: appDelegate.account) {
  796. NCContentPresenter.shared.messageNotification("_info_", description: "_e2e_goto_settings_for_enable_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.info, errorCode: Int(k_CCErrorE2EENotEnabled), forced: true)
  797. return
  798. }
  799. if metadata.directory {
  800. guard let serverUrlPush = CCUtility.stringAppendServerUrl(metadataTouch!.serverUrl, addFileName: metadataTouch!.fileName) else { return }
  801. // FILES
  802. if layoutKey == k_layout_view_files {
  803. if let viewController = appDelegate.listFilesVC.value(forKey: serverUrlPush) {
  804. guard let vcFiles = (viewController as? NCFiles) else { return }
  805. if vcFiles.isViewLoaded {
  806. self.navigationController?.pushViewController(vcFiles, animated: true)
  807. }
  808. } else {
  809. let vcFiles:NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as! NCFiles
  810. vcFiles.isRoot = false
  811. vcFiles.serverUrl = serverUrlPush
  812. vcFiles.titleCurrentFolder = metadataTouch!.fileNameView
  813. appDelegate.listFilesVC.setValue(vcFiles, forKey: serverUrlPush)
  814. self.navigationController?.pushViewController(vcFiles, animated: true)
  815. }
  816. }
  817. // FAVORITE
  818. if layoutKey == k_layout_view_favorite {
  819. if let viewController = appDelegate.listFavoriteVC.value(forKey: serverUrlPush) {
  820. guard let vcFavorite = (viewController as? NCFavorite) else { return }
  821. if vcFavorite.isViewLoaded {
  822. self.navigationController?.pushViewController(vcFavorite, animated: true)
  823. }
  824. } else {
  825. let vcFavorite:NCFavorite = UIStoryboard(name: "NCFavorite", bundle: nil).instantiateInitialViewController() as! NCFavorite
  826. vcFavorite.isRoot = false
  827. vcFavorite.serverUrl = serverUrlPush
  828. vcFavorite.titleCurrentFolder = metadataTouch!.fileNameView
  829. appDelegate.listFavoriteVC.setValue(vcFavorite, forKey: serverUrlPush)
  830. self.navigationController?.pushViewController(vcFavorite, animated: true)
  831. }
  832. }
  833. // OFFLINE
  834. if layoutKey == k_layout_view_offline {
  835. if let viewController = appDelegate.listOfflineVC.value(forKey: serverUrlPush) {
  836. guard let vcOffline = (viewController as? NCOffline) else { return }
  837. if vcOffline.isViewLoaded {
  838. self.navigationController?.pushViewController(vcOffline, animated: true)
  839. }
  840. } else {
  841. let vcOffline:NCOffline = UIStoryboard(name: "NCOffline", bundle: nil).instantiateInitialViewController() as! NCOffline
  842. vcOffline.isRoot = false
  843. vcOffline.serverUrl = serverUrlPush
  844. vcOffline.titleCurrentFolder = metadataTouch!.fileNameView
  845. appDelegate.listOfflineVC.setValue(vcOffline, forKey: serverUrlPush)
  846. self.navigationController?.pushViewController(vcOffline, animated: true)
  847. }
  848. }
  849. } else {
  850. if metadata.typeFile == k_metadataTypeFile_document && NCUtility.shared.isDirectEditing(account: metadata.account, contentType: metadata.contentType) != nil {
  851. if NCCommunication.shared.isNetworkReachable() {
  852. performSegue(withIdentifier: "segueDetail", sender: self)
  853. } else {
  854. NCContentPresenter.shared.messageNotification("_info_", description: "_go_online_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.info, errorCode: Int(k_CCErrorOffline), forced: true)
  855. }
  856. return
  857. }
  858. if metadata.typeFile == k_metadataTypeFile_document && NCUtility.shared.isRichDocument(metadata) {
  859. if NCCommunication.shared.isNetworkReachable() {
  860. performSegue(withIdentifier: "segueDetail", sender: self)
  861. } else {
  862. NCContentPresenter.shared.messageNotification("_info_", description: "_go_online_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.info, errorCode: Int(k_CCErrorOffline), forced: true)
  863. }
  864. return
  865. }
  866. if CCUtility.fileProviderStorageExists(metadataTouch?.ocId, fileNameView: metadataTouch?.fileNameView) {
  867. performSegue(withIdentifier: "segueDetail", sender: self)
  868. } else {
  869. NCNetworking.shared.download(metadata: metadataTouch!, selector: selectorLoadFileView) { (_) in }
  870. }
  871. }
  872. }
  873. func collectionViewSelectAll() {
  874. selectOcId.removeAll()
  875. for metadata in metadatasSource {
  876. selectOcId.append(metadata.ocId)
  877. }
  878. collectionView.reloadData()
  879. }
  880. }
  881. extension NCCollectionViewCommon: UICollectionViewDataSource {
  882. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  883. if kind == UICollectionView.elementKindSectionHeader {
  884. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeaderMenu", for: indexPath) as! NCSectionHeaderMenu
  885. if collectionView.collectionViewLayout == gridLayout {
  886. header.buttonSwitch.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "switchList"), width: 100, height: 100, color: NCBrandColor.sharedInstance.icon), for: .normal)
  887. } else {
  888. header.buttonSwitch.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "switchGrid"), width: 100, height: 100, color: NCBrandColor.sharedInstance.icon), for: .normal)
  889. }
  890. header.delegate = self
  891. header.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  892. header.separator.backgroundColor = NCBrandColor.sharedInstance.separator
  893. header.setStatusButton(count: dataSource?.metadatas.count ?? 0)
  894. header.setTitleSorted(datasourceTitleButton: titleButton)
  895. header.viewRichWorkspaceHeightConstraint.constant = headerRichWorkspaceHeight
  896. header.setRichWorkspaceText(richWorkspaceText: richWorkspaceText)
  897. return header
  898. } else {
  899. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  900. let info = dataSource?.getFilesInformation()
  901. footer.setTitleLabel(directories: info?.directories ?? 0, files: info?.files ?? 0, size: info?.size ?? 0)
  902. return footer
  903. }
  904. }
  905. func numberOfSections(in collectionView: UICollectionView) -> Int {
  906. return 1
  907. }
  908. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  909. return dataSource?.numberOfItems() ?? 0
  910. }
  911. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  912. let cell: UICollectionViewCell
  913. guard let metadata = dataSource?.cellForItemAt(indexPath: indexPath) else {
  914. return collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  915. }
  916. if layout == k_layout_grid {
  917. cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  918. } else {
  919. cell = collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  920. }
  921. let shares = NCManageDatabase.sharedInstance.getTableShares(account: metadata.account, serverUrl: metadata.serverUrl, fileName: metadata.fileName)
  922. NCCollectionCommon.shared.cellForItemAt(indexPath: indexPath, collectionView: collectionView, cell: cell, metadata: metadata, metadataFolder: metadataFolder, serverUrl: metadata.serverUrl, isEditMode: isEditMode, isEncryptedFolder: isEncryptedFolder, selectocId: selectOcId, autoUploadFileName: autoUploadFileName, autoUploadDirectory: autoUploadDirectory, hideButtonMore: false, downloadThumbnail: true, shares: shares, source: self, dataSource: dataSource)
  923. return cell
  924. }
  925. }
  926. extension NCCollectionViewCommon: UICollectionViewDelegateFlowLayout {
  927. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  928. if richWorkspaceText?.count ?? 0 == 0 {
  929. headerRichWorkspaceHeight = 0
  930. } else {
  931. headerRichWorkspaceHeight = UIScreen.main.bounds.size.height / 4
  932. }
  933. return CGSize(width: collectionView.frame.width, height: headerHeight + headerRichWorkspaceHeight)
  934. }
  935. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  936. return CGSize(width: collectionView.frame.width, height: footerHeight)
  937. }
  938. }