NCCollectionViewCommon.swift 54 KB

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