NCCollectionViewCommon.swift 53 KB

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