NCCollectionViewCommon.swift 55 KB

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