NCCollectionViewCommon.swift 55 KB

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