NCCollectionViewCommon.swift 60 KB

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