NCCollectionViewCommon.swift 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498
  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, UIAdaptivePresentationControllerDelegate, NCEmptyDataSetDelegate, UIContextMenuInteractionDelegate {
  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 emptyDataSet: NCEmptyDataSet?
  31. internal var serverUrl: String = ""
  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 sort: String = ""
  42. internal var ascending: Bool = true
  43. internal var directoryOnTop: Bool = true
  44. internal var groupBy = ""
  45. internal var titleButton = ""
  46. internal var itemForLine = 0
  47. private var autoUploadFileName = ""
  48. private var autoUploadDirectory = ""
  49. internal var listLayout: NCListLayout!
  50. internal var gridLayout: NCGridLayout!
  51. private let headerHeight: CGFloat = 50
  52. private var headerRichWorkspaceHeight: CGFloat = 0
  53. private let footerHeight: CGFloat = 100
  54. private var timerInputSearch: Timer?
  55. internal var literalSearch: String?
  56. internal var isSearching: Bool = false
  57. internal var isReloadDataSourceNetworkInProgress: Bool = false
  58. var selectedIndexPath: IndexPath!
  59. // DECLARE
  60. internal var layoutKey = ""
  61. internal var titleCurrentFolder = ""
  62. internal var enableSearchBar: Bool = false
  63. internal var emptyImage: UIImage?
  64. internal var emptyTitle: String = ""
  65. internal var emptyDescription: String = ""
  66. required init?(coder aDecoder: NSCoder) {
  67. super.init(coder: aDecoder)
  68. }
  69. override func viewDidLoad() {
  70. super.viewDidLoad()
  71. self.navigationController?.presentationController?.delegate = self
  72. if enableSearchBar {
  73. searchController = UISearchController(searchResultsController: nil)
  74. searchController?.searchResultsUpdater = self
  75. searchController?.obscuresBackgroundDuringPresentation = false
  76. searchController?.delegate = self
  77. searchController?.searchBar.delegate = self
  78. navigationItem.searchController = searchController
  79. navigationItem.hidesSearchBarWhenScrolling = false
  80. }
  81. // Cell
  82. collectionView.register(UINib.init(nibName: "NCListCell", bundle: nil), forCellWithReuseIdentifier: "listCell")
  83. collectionView.register(UINib.init(nibName: "NCGridCell", bundle: nil), forCellWithReuseIdentifier: "gridCell")
  84. collectionView.register(UINib.init(nibName: "NCTransferCell", bundle: nil), forCellWithReuseIdentifier: "transferCell")
  85. // Header
  86. collectionView.register(UINib.init(nibName: "NCSectionHeaderMenu", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeaderMenu")
  87. // Footer
  88. collectionView.register(UINib.init(nibName: "NCSectionFooter", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "sectionFooter")
  89. collectionView.alwaysBounceVertical = true
  90. listLayout = NCListLayout()
  91. gridLayout = NCGridLayout()
  92. // Refresh Control
  93. collectionView.addSubview(refreshControl)
  94. refreshControl.tintColor = .gray
  95. refreshControl.addTarget(self, action: #selector(reloadDataSourceNetworkRefreshControl), for: .valueChanged)
  96. // Empty
  97. emptyDataSet = NCEmptyDataSet.init(view: collectionView, offset: 0, delegate: self)
  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: NCGlobal.shared.notificationCenterInitializeMain), object: nil)
  106. NotificationCenter.default.addObserver(self, selector: #selector(changeTheming), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterChangeTheming), object: nil)
  107. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSource(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadDataSource), object: nil)
  108. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSourceNetworkForced(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadDataSourceNetworkForced), object: nil)
  109. NotificationCenter.default.addObserver(self, selector: #selector(changeStatusFolderE2EE(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterChangeStatusFolderE2EE), object: nil)
  110. NotificationCenter.default.addObserver(self, selector: #selector(closeRichWorkspaceWebView), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCloseRichWorkspaceWebView), object: nil)
  111. NotificationCenter.default.addObserver(self, selector: #selector(deleteFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDeleteFile), object: nil)
  112. NotificationCenter.default.addObserver(self, selector: #selector(moveFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMoveFile), object: nil)
  113. NotificationCenter.default.addObserver(self, selector: #selector(copyFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCopyFile), object: nil)
  114. NotificationCenter.default.addObserver(self, selector: #selector(renameFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterRenameFile), object: nil)
  115. NotificationCenter.default.addObserver(self, selector: #selector(createFolder(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCreateFolder), object: nil)
  116. NotificationCenter.default.addObserver(self, selector: #selector(favoriteFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterFavoriteFile), object: nil)
  117. NotificationCenter.default.addObserver(self, selector: #selector(downloadStartFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadStartFile), object: nil)
  118. NotificationCenter.default.addObserver(self, selector: #selector(downloadedFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadedFile), object: nil)
  119. NotificationCenter.default.addObserver(self, selector: #selector(downloadCancelFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadCancelFile), object: nil)
  120. NotificationCenter.default.addObserver(self, selector: #selector(uploadStartFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadStartFile), object: nil)
  121. NotificationCenter.default.addObserver(self, selector: #selector(uploadedFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedFile), object: nil)
  122. NotificationCenter.default.addObserver(self, selector: #selector(uploadCancelFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadCancelFile), object: nil)
  123. NotificationCenter.default.addObserver(self, selector: #selector(triggerProgressTask(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterProgressTask), object:nil)
  124. changeTheming()
  125. }
  126. override func viewWillAppear(_ animated: Bool) {
  127. super.viewWillAppear(animated)
  128. appDelegate.activeViewController = self
  129. if serverUrl == "" {
  130. appDelegate.activeServerUrl = NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate.urlBase, account: appDelegate.account)
  131. } else {
  132. appDelegate.activeServerUrl = serverUrl
  133. }
  134. (layout, sort, ascending, groupBy, directoryOnTop, titleButton, itemForLine) = NCUtility.shared.getLayoutForView(key: layoutKey, serverUrl: serverUrl)
  135. gridLayout.itemForLine = CGFloat(itemForLine)
  136. if layout == NCGlobal.shared.layoutList {
  137. collectionView?.collectionViewLayout = listLayout
  138. } else {
  139. collectionView?.collectionViewLayout = gridLayout
  140. }
  141. navigationController?.navigationBar.prefersLargeTitles = true
  142. navigationController?.setNavigationBarHidden(false, animated: true)
  143. setNavigationItem()
  144. reloadDataSource()
  145. }
  146. override func viewDidAppear(_ animated: Bool) {
  147. super.viewDidAppear(animated)
  148. reloadDataSourceNetwork()
  149. }
  150. func presentationControllerDidDismiss( _ presentationController: UIPresentationController) {
  151. let viewController = presentationController.presentedViewController
  152. if viewController is NCViewerRichWorkspaceWebView {
  153. closeRichWorkspaceWebView()
  154. } else if viewController is UINavigationController {
  155. if (viewController as! UINavigationController).topViewController is NCFileViewInFolder {
  156. appDelegate.activeFileViewInFolder = nil
  157. }
  158. }
  159. }
  160. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  161. super.viewWillTransition(to: size, with: coordinator)
  162. coordinator.animate(alongsideTransition: nil) { _ in
  163. self.collectionView?.collectionViewLayout.invalidateLayout()
  164. }
  165. }
  166. override var canBecomeFirstResponder: Bool {
  167. return true
  168. }
  169. func setNavigationItem() {
  170. if isEditMode {
  171. navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage.init(named: "navigationMore"), style: .plain, target: self, action:#selector(tapSelectMenu(sender:)))
  172. navigationItem.leftBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_cancel_", comment: ""), style: .plain, target: self, action: #selector(tapSelect(sender:)))
  173. navigationItem.title = NSLocalizedString("_selected_", comment: "") + " : \(selectOcId.count)" + " / \(dataSource.metadatas.count)"
  174. } else {
  175. navigationItem.rightBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_select_", comment: ""), style: UIBarButtonItem.Style.plain, target: self, action: #selector(tapSelect(sender:)))
  176. navigationItem.leftBarButtonItem = nil
  177. navigationItem.title = titleCurrentFolder
  178. }
  179. }
  180. // MARK: - NotificationCenter
  181. @objc func initializeMain() {
  182. if appDelegate.account == "" { return }
  183. if searchController?.isActive ?? false {
  184. searchController?.isActive = false
  185. }
  186. // set active serverUrl
  187. if self.view?.window != nil {
  188. if serverUrl == "" {
  189. appDelegate.activeServerUrl = NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate.urlBase, account: appDelegate.account)
  190. } else {
  191. appDelegate.activeServerUrl = serverUrl
  192. }
  193. }
  194. self.navigationController?.popToRootViewController(animated: false)
  195. appDelegate.listFilesVC.removeAll()
  196. appDelegate.listFavoriteVC.removeAll()
  197. appDelegate.listOfflineVC.removeAll()
  198. reloadDataSource()
  199. }
  200. @objc func changeTheming() {
  201. view.backgroundColor = NCBrandColor.shared.backgroundView
  202. collectionView.backgroundColor = NCBrandColor.shared.backgroundView
  203. collectionView.reloadData()
  204. }
  205. @objc func reloadDataSource(_ notification: NSNotification) {
  206. if self.view?.window == nil { return }
  207. reloadDataSource()
  208. }
  209. @objc func reloadDataSourceNetworkForced(_ notification: NSNotification) {
  210. if self.view?.window == nil { return }
  211. if let userInfo = notification.userInfo as NSDictionary? {
  212. if let serverUrl = userInfo["serverUrl"] as? String {
  213. if serverUrl == self.serverUrl {
  214. reloadDataSourceNetwork(forced: true)
  215. }
  216. }
  217. } else {
  218. reloadDataSourceNetwork(forced: true)
  219. }
  220. }
  221. @objc func changeStatusFolderE2EE(_ notification: NSNotification) {
  222. if self.view?.window == nil { return }
  223. reloadDataSource()
  224. }
  225. @objc func closeRichWorkspaceWebView() {
  226. if self.view?.window == nil { return }
  227. reloadDataSourceNetwork()
  228. }
  229. @objc func deleteFile(_ notification: NSNotification) {
  230. if self.view?.window == nil { return }
  231. if let userInfo = notification.userInfo as NSDictionary? {
  232. if let ocId = userInfo["ocId"] as? String, let fileNameView = userInfo["fileNameView"] as? String, let onlyLocal = userInfo["onlyLocal"] as? Bool {
  233. if onlyLocal {
  234. reloadDataSource()
  235. } else if fileNameView.lowercased() == NCGlobal.shared.fileNameRichWorkspace.lowercased() {
  236. reloadDataSourceNetwork(forced: true)
  237. } else {
  238. if let row = dataSource.deleteMetadata(ocId: ocId) {
  239. let indexPath = IndexPath(row: row, section: 0)
  240. collectionView?.performBatchUpdates({
  241. collectionView?.deleteItems(at: [indexPath])
  242. }, completion: { (_) in
  243. self.collectionView?.reloadData()
  244. })
  245. }
  246. }
  247. }
  248. }
  249. }
  250. @objc func moveFile(_ notification: NSNotification) {
  251. if self.view?.window == nil { return }
  252. if let userInfo = notification.userInfo as NSDictionary? {
  253. if let ocId = userInfo["ocId"] as? String, let serverUrlFrom = userInfo["serverUrlFrom"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  254. // DEL
  255. if serverUrlFrom == serverUrl && metadata.account == appDelegate.account {
  256. if let row = dataSource.deleteMetadata(ocId: ocId) {
  257. let indexPath = IndexPath(row: row, section: 0)
  258. collectionView?.performBatchUpdates({
  259. collectionView?.deleteItems(at: [indexPath])
  260. }, completion: { (_) in
  261. self.collectionView?.reloadData()
  262. })
  263. }
  264. // ADD
  265. } else if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  266. if let row = dataSource.addMetadata(metadata) {
  267. let indexPath = IndexPath(row: row, section: 0)
  268. collectionView?.performBatchUpdates({
  269. collectionView?.insertItems(at: [indexPath])
  270. }, completion: { (_) in
  271. self.collectionView?.reloadData()
  272. })
  273. }
  274. }
  275. }
  276. }
  277. }
  278. @objc func copyFile(_ notification: NSNotification) {
  279. if self.view?.window == nil { return }
  280. if let userInfo = notification.userInfo as NSDictionary? {
  281. if let serverUrlTo = userInfo["serverUrlTo"] as? String {
  282. if serverUrlTo == self.serverUrl {
  283. reloadDataSource()
  284. }
  285. }
  286. }
  287. }
  288. @objc func renameFile(_ notification: NSNotification) {
  289. if self.view?.window == nil { return }
  290. reloadDataSource()
  291. }
  292. @objc func createFolder(_ notification: NSNotification) {
  293. if self.view?.window == nil { return }
  294. if let userInfo = notification.userInfo as NSDictionary? {
  295. if let ocId = userInfo["ocId"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  296. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  297. if let row = dataSource.addMetadata(metadata) {
  298. let indexPath = IndexPath(row: row, section: 0)
  299. collectionView?.performBatchUpdates({
  300. collectionView?.insertItems(at: [indexPath])
  301. }, completion: { (_) in
  302. self.collectionView?.reloadData()
  303. })
  304. }
  305. }
  306. }
  307. } else {
  308. reloadDataSourceNetwork()
  309. }
  310. }
  311. @objc func favoriteFile(_ notification: NSNotification) {
  312. if self.view?.window == nil { return }
  313. if let userInfo = notification.userInfo as NSDictionary? {
  314. if let ocId = userInfo["ocId"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  315. if dataSource.getIndexMetadata(ocId: metadata.ocId) != nil {
  316. reloadDataSource()
  317. }
  318. }
  319. }
  320. }
  321. @objc func downloadStartFile(_ notification: NSNotification) {
  322. if self.view?.window == nil { return }
  323. if let userInfo = notification.userInfo as NSDictionary? {
  324. if let ocId = userInfo["ocId"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  325. if let row = dataSource.reloadMetadata(ocId: metadata.ocId) {
  326. let indexPath = IndexPath(row: row, section: 0)
  327. if indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section) {
  328. collectionView?.reloadItems(at: [indexPath])
  329. }
  330. }
  331. }
  332. }
  333. }
  334. @objc func downloadedFile(_ notification: NSNotification) {
  335. if self.view?.window == nil { return }
  336. if let userInfo = notification.userInfo as NSDictionary? {
  337. if let ocId = userInfo["ocId"] as? String, let _ = userInfo["errorCode"] as? Int, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  338. if let row = dataSource.reloadMetadata(ocId: metadata.ocId) {
  339. let indexPath = IndexPath(row: row, section: 0)
  340. if indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section) {
  341. collectionView?.reloadItems(at: [indexPath])
  342. }
  343. }
  344. }
  345. }
  346. }
  347. @objc func downloadCancelFile(_ notification: NSNotification) {
  348. if self.view?.window == nil { return }
  349. if let userInfo = notification.userInfo as NSDictionary? {
  350. if let ocId = userInfo["ocId"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  351. if let row = dataSource.reloadMetadata(ocId: metadata.ocId) {
  352. let indexPath = IndexPath(row: row, section: 0)
  353. if indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section) {
  354. collectionView?.reloadItems(at: [indexPath])
  355. }
  356. }
  357. }
  358. }
  359. }
  360. @objc func uploadStartFile(_ notification: NSNotification) {
  361. if self.view?.window == nil { return }
  362. if let userInfo = notification.userInfo as NSDictionary? {
  363. if let ocId = userInfo["ocId"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  364. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  365. dataSource.addMetadata(metadata)
  366. self.collectionView?.reloadData()
  367. }
  368. }
  369. }
  370. }
  371. @objc func uploadedFile(_ notification: NSNotification) {
  372. if self.view?.window == nil { return }
  373. if let userInfo = notification.userInfo as NSDictionary? {
  374. if let ocId = userInfo["ocId"] as? String, let ocIdTemp = userInfo["ocIdTemp"] as? String, let _ = userInfo["errorCode"] as? Int, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  375. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  376. dataSource.reloadMetadata(ocId: metadata.ocId, ocIdTemp: ocIdTemp)
  377. collectionView?.reloadData()
  378. }
  379. }
  380. }
  381. }
  382. @objc func uploadCancelFile(_ notification: NSNotification) {
  383. if self.view?.window == nil { return }
  384. if let userInfo = notification.userInfo as NSDictionary? {
  385. if let ocId = userInfo["ocId"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  386. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  387. if let row = dataSource.deleteMetadata(ocId: metadata.ocId) {
  388. let indexPath = IndexPath(row: row, section: 0)
  389. collectionView?.performBatchUpdates({
  390. collectionView?.deleteItems(at: [indexPath])
  391. }, completion: { (_) in
  392. self.collectionView?.reloadData()
  393. })
  394. } else {
  395. self.reloadDataSource()
  396. }
  397. }
  398. }
  399. }
  400. }
  401. @objc func triggerProgressTask(_ notification: NSNotification) {
  402. if self.view?.window == nil { return }
  403. if let userInfo = notification.userInfo as NSDictionary? {
  404. if let ocId = userInfo["ocId"] as? String {
  405. let _ = userInfo["account"] as? String ?? ""
  406. let _ = userInfo["serverUrl"] as? String ?? ""
  407. let progressNumber = userInfo["progress"] as? NSNumber ?? 0
  408. let progress = progressNumber.floatValue
  409. let status = userInfo["status"] as? Int ?? NCGlobal.shared.metadataStatusNormal
  410. let totalBytes = userInfo["totalBytes"] as? Int64 ?? 0
  411. let totalBytesExpected = userInfo["totalBytesExpected"] as? Int64 ?? 0
  412. let progressType = NCGlobal.progressType(progress: progress, totalBytes: totalBytes, totalBytesExpected: totalBytesExpected)
  413. appDelegate.listProgress[ocId] = progressType
  414. if let index = dataSource.getIndexMetadata(ocId: ocId) {
  415. if let cell = collectionView?.cellForItem(at: IndexPath(row: index, section: 0)) {
  416. if cell is NCListCell {
  417. let cell = cell as! NCListCell
  418. if progress > 0 {
  419. cell.progressView?.isHidden = false
  420. cell.progressView?.progress = progress
  421. cell.setButtonMore(named: NCGlobal.shared.buttonMoreStop, image: NCCollectionCommon.images.cellButtonStop)
  422. if status == NCGlobal.shared.metadataStatusInDownload {
  423. cell.labelInfo.text = CCUtility.transformedSize(totalBytesExpected) + " - ↓ " + CCUtility.transformedSize(totalBytes)
  424. } else if status == NCGlobal.shared.metadataStatusInUpload {
  425. cell.labelInfo.text = CCUtility.transformedSize(totalBytesExpected) + " - ↑ " + CCUtility.transformedSize(totalBytes)
  426. }
  427. }
  428. } else if cell is NCTransferCell {
  429. let cell = cell as! NCTransferCell
  430. if progress > 0 {
  431. cell.progressView?.isHidden = false
  432. cell.progressView?.progress = progress
  433. cell.setButtonMore(named: NCGlobal.shared.buttonMoreStop, image: NCCollectionCommon.images.cellButtonStop)
  434. if status == NCGlobal.shared.metadataStatusInDownload {
  435. cell.labelInfo.text = CCUtility.transformedSize(totalBytesExpected) + " - ↓ " + CCUtility.transformedSize(totalBytes)
  436. } else if status == NCGlobal.shared.metadataStatusInUpload {
  437. cell.labelInfo.text = CCUtility.transformedSize(totalBytesExpected) + " - ↑ " + CCUtility.transformedSize(totalBytes)
  438. }
  439. }
  440. } else if cell is NCGridCell {
  441. let cell = cell as! NCGridCell
  442. if progress > 0 {
  443. cell.progressView.isHidden = false
  444. cell.progressView.progress = progress
  445. cell.setButtonMore(named: NCGlobal.shared.buttonMoreStop, image: NCCollectionCommon.images.cellButtonStop)
  446. }
  447. }
  448. }
  449. }
  450. }
  451. }
  452. }
  453. // MARK: - Empty
  454. func emptyDataSetView(_ view: NCEmptyView) {
  455. if searchController?.isActive ?? false {
  456. view.emptyImage.image = UIImage.init(named: "search")?.image(color: .gray, size: UIScreen.main.bounds.width)
  457. if isReloadDataSourceNetworkInProgress {
  458. view.emptyTitle.text = NSLocalizedString("_search_in_progress_", comment: "")
  459. } else {
  460. view.emptyTitle.text = NSLocalizedString("_search_no_record_found_", comment: "")
  461. }
  462. view.emptyDescription.text = NSLocalizedString("_search_instruction_", comment: "")
  463. } else if isReloadDataSourceNetworkInProgress {
  464. view.emptyImage.image = UIImage.init(named: "networkInProgress")?.image(color: .gray, size: UIScreen.main.bounds.width)
  465. view.emptyTitle.text = NSLocalizedString("_request_in_progress_", comment: "")
  466. view.emptyDescription.text = ""
  467. } else {
  468. if serverUrl == "" {
  469. view.emptyImage.image = emptyImage
  470. view.emptyTitle.text = NSLocalizedString(emptyTitle, comment: "")
  471. view.emptyDescription.text = NSLocalizedString(emptyDescription, comment: "")
  472. } else {
  473. view.emptyImage.image = UIImage.init(named: "folder")?.image(color: NCBrandColor.shared.brandElement, size: UIScreen.main.bounds.width)
  474. view.emptyTitle.text = NSLocalizedString("_files_no_files_", comment: "")
  475. view.emptyDescription.text = NSLocalizedString("_no_file_pull_down_", comment: "")
  476. }
  477. }
  478. }
  479. // MARK: - SEARCH
  480. func updateSearchResults(for searchController: UISearchController) {
  481. timerInputSearch?.invalidate()
  482. timerInputSearch = Timer.scheduledTimer(timeInterval: 1.5, target: self, selector: #selector(reloadDataSourceNetwork), userInfo: nil, repeats: false)
  483. literalSearch = searchController.searchBar.text
  484. collectionView?.reloadData()
  485. }
  486. func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
  487. isSearching = true
  488. metadatasSource.removeAll()
  489. reloadDataSource()
  490. }
  491. func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
  492. isSearching = false
  493. literalSearch = ""
  494. reloadDataSource()
  495. }
  496. // MARK: - TAP EVENT
  497. @objc func tapSelect(sender: Any) {
  498. isEditMode = !isEditMode
  499. selectOcId.removeAll()
  500. setNavigationItem()
  501. self.collectionView.reloadData()
  502. }
  503. func tapSwitchHeader(sender: Any) {
  504. if collectionView.collectionViewLayout == gridLayout {
  505. // list layout
  506. UIView.animate(withDuration: 0.0, animations: {
  507. self.collectionView.collectionViewLayout.invalidateLayout()
  508. self.collectionView.setCollectionViewLayout(self.listLayout, animated: false, completion: { (_) in
  509. self.collectionView.reloadData()
  510. })
  511. })
  512. layout = NCGlobal.shared.layoutList
  513. NCUtility.shared.setLayoutForView(key: layoutKey, serverUrl: serverUrl, layout: layout)
  514. } else {
  515. // grid layout
  516. UIView.animate(withDuration: 0.0, animations: {
  517. self.collectionView.collectionViewLayout.invalidateLayout()
  518. self.collectionView.setCollectionViewLayout(self.gridLayout, animated: false, completion: { (_) in
  519. self.collectionView.reloadData()
  520. })
  521. })
  522. layout = NCGlobal.shared.layoutGrid
  523. NCUtility.shared.setLayoutForView(key: layoutKey, serverUrl: serverUrl, layout: layout)
  524. }
  525. }
  526. func tapOrderHeader(sender: Any) {
  527. let sortMenu = NCSortMenu()
  528. sortMenu.toggleMenu(viewController: self, key: layoutKey, sortButton: sender as? UIButton, serverUrl: serverUrl)
  529. }
  530. @objc func tapSelectMenu(sender: Any) {
  531. guard let tabBarController = self.tabBarController else { return }
  532. toggleMoreSelect(viewController: tabBarController, selectOcId: selectOcId)
  533. }
  534. func tapMoreHeader(sender: Any) { }
  535. func tapMoreListItem(with objectId: String, namedButtonMore: String, image: UIImage?, sender: Any) {
  536. tapMoreGridItem(with: objectId, namedButtonMore: namedButtonMore, image: image, sender: sender)
  537. }
  538. func tapShareListItem(with objectId: String, sender: Any) {
  539. if isEditMode { return }
  540. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(objectId) else { return }
  541. NCNetworkingNotificationCenter.shared.openShare(ViewController: self, metadata: metadata, indexPage: 2)
  542. }
  543. func tapMoreGridItem(with objectId: String, namedButtonMore: String, image: UIImage?, sender: Any) {
  544. if isEditMode { return }
  545. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(objectId) else { return }
  546. if namedButtonMore == NCGlobal.shared.buttonMoreMore {
  547. toggleMoreMenu(viewController: self, metadata: metadata, image: image)
  548. } else if namedButtonMore == NCGlobal.shared.buttonMoreStop {
  549. NCNetworking.shared.cancelTransferMetadata(metadata) { }
  550. }
  551. }
  552. func tapRichWorkspace(sender: Any) {
  553. if let navigationController = UIStoryboard(name: "NCViewerRichWorkspace", bundle: nil).instantiateInitialViewController() as? UINavigationController {
  554. if let viewerRichWorkspace = navigationController.topViewController as? NCViewerRichWorkspace {
  555. viewerRichWorkspace.richWorkspaceText = richWorkspaceText ?? ""
  556. viewerRichWorkspace.serverUrl = serverUrl
  557. navigationController.modalPresentationStyle = .fullScreen
  558. self.present(navigationController, animated: true, completion: nil)
  559. }
  560. }
  561. }
  562. func longPressListItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) {
  563. }
  564. func longPressGridItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) {
  565. }
  566. func longPressMoreListItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) {
  567. }
  568. func longPressMoreGridItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) {
  569. }
  570. @objc func longPressCollecationView(_ gestureRecognizer: UILongPressGestureRecognizer) {
  571. openMenuItems(with: nil, gestureRecognizer: gestureRecognizer)
  572. /*
  573. if #available(iOS 13.0, *) {
  574. let interaction = UIContextMenuInteraction(delegate: self)
  575. self.view.addInteraction(interaction)
  576. }
  577. */
  578. }
  579. @available(iOS 13.0, *)
  580. func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
  581. return UIContextMenuConfiguration(identifier: nil, previewProvider: {
  582. return nil
  583. }, actionProvider: { suggestedActions in
  584. //let share = UIAction(title: "Share Pupper", image: UIImage(systemName: "square.and.arrow.up")) { action in
  585. //}
  586. //return UIMenu(title: "Main Menu", children: [share])
  587. return nil
  588. })
  589. }
  590. func openMenuItems(with objectId: String?, gestureRecognizer: UILongPressGestureRecognizer) {
  591. if gestureRecognizer.state != .began { return }
  592. if serverUrl == "" { return }
  593. if let metadata = NCManageDatabase.shared.getMetadataFromOcId(objectId) {
  594. metadataTouch = metadata
  595. } else {
  596. metadataTouch = nil
  597. }
  598. var listMenuItems: [UIMenuItem] = []
  599. let touchPoint = gestureRecognizer.location(in: collectionView)
  600. becomeFirstResponder()
  601. listMenuItems.append(UIMenuItem.init(title: NSLocalizedString("_paste_file_", comment: ""), action: #selector(pasteFilesMenu)))
  602. if listMenuItems.count > 0 {
  603. UIMenuController.shared.menuItems = listMenuItems
  604. UIMenuController.shared.setTargetRect(CGRect(x: touchPoint.x, y: touchPoint.y, width: 0, height: 0), in: collectionView)
  605. UIMenuController.shared.setMenuVisible(true, animated: true)
  606. }
  607. }
  608. // MARK: - Menu Item
  609. override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
  610. if (#selector(pasteFilesMenu) == action) {
  611. if UIPasteboard.general.items.count > 0 {
  612. return true
  613. }
  614. }
  615. return false
  616. }
  617. @objc func pasteFilesMenu() {
  618. NCCollectionCommon.shared.pastePasteboard(serverUrl: serverUrl)
  619. }
  620. // MARK: - DataSource + NC Endpoint
  621. @objc func reloadDataSource() {
  622. if appDelegate.account == "" { return }
  623. // Get richWorkspace Text
  624. let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, serverUrl))
  625. richWorkspaceText = directory?.richWorkspace
  626. // E2EE
  627. isEncryptedFolder = CCUtility.isFolderEncrypted(serverUrl, e2eEncrypted: metadataFolder?.e2eEncrypted ?? false, account: appDelegate.account, urlBase: appDelegate.urlBase)
  628. // get auto upload folder
  629. autoUploadFileName = NCManageDatabase.shared.getAccountAutoUploadFileName()
  630. autoUploadDirectory = NCManageDatabase.shared.getAccountAutoUploadDirectory(urlBase: appDelegate.urlBase, account: appDelegate.account)
  631. // get layout for view
  632. (layout, sort, ascending, groupBy, directoryOnTop, titleButton, itemForLine) = NCUtility.shared.getLayoutForView(key: layoutKey, serverUrl: serverUrl)
  633. }
  634. @objc func reloadDataSourceNetwork(forced: Bool = false) { }
  635. @objc func reloadDataSourceNetworkRefreshControl() {
  636. reloadDataSourceNetwork(forced: true)
  637. }
  638. @objc func networkSearch() {
  639. if appDelegate.account == "" { return }
  640. if literalSearch?.count ?? 0 > 1 {
  641. isReloadDataSourceNetworkInProgress = true
  642. collectionView?.reloadData()
  643. NCNetworking.shared.searchFiles(urlBase: appDelegate.urlBase, user: appDelegate.user, literal: literalSearch!) { (account, metadatas, errorCode, errorDescription) in
  644. if self.searchController?.isActive ?? false && errorCode == 0 {
  645. self.metadatasSource = metadatas!
  646. }
  647. self.refreshControl.endRefreshing()
  648. self.isReloadDataSourceNetworkInProgress = false
  649. self.reloadDataSource()
  650. }
  651. } else {
  652. self.refreshControl.endRefreshing()
  653. }
  654. }
  655. @objc func networkReadFolder(forced: Bool, completion: @escaping(_ metadatas: [tableMetadata]?, _ metadatasUpdate: [tableMetadata]?, _ errorCode: Int, _ errorDescription: String)->()) {
  656. NCNetworking.shared.readFile(serverUrlFileName: serverUrl, account: appDelegate.account) { (account, metadata, errorCode, errorDescription) in
  657. if errorCode == 0 {
  658. let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", self.appDelegate.account, self.serverUrl))
  659. if forced || directory?.etag != metadata?.etag || directory?.e2eEncrypted ?? false {
  660. NCNetworking.shared.readFolder(serverUrl: self.serverUrl, account: self.appDelegate.account) { (account, metadataFolder, metadatas, metadatasUpdate, metadatasLocalUpdate, errorCode, errorDescription) in
  661. if errorCode == 0 {
  662. self.metadataFolder = metadataFolder
  663. // E2EE
  664. if let metadataFolder = metadataFolder {
  665. if metadataFolder.e2eEncrypted && CCUtility.isEnd(toEndEnabled: self.appDelegate.account) {
  666. NCCommunication.shared.getE2EEMetadata(fileId: metadataFolder.ocId, e2eToken: nil) { (account, e2eMetadata, errorCode, errorDescription) in
  667. if errorCode == 0 && e2eMetadata != nil {
  668. if !NCEndToEndMetadata.shared.decoderMetadata(e2eMetadata!, privateKey: CCUtility.getEndToEndPrivateKey(account), serverUrl: self.serverUrl, account: account, urlBase: self.appDelegate.urlBase) {
  669. NCContentPresenter.shared.messageNotification("_error_e2ee_", description: "_e2e_error_decode_metadata_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.ErrorDecodeMetadata, forced: true)
  670. } else {
  671. self.reloadDataSource()
  672. }
  673. } else if errorCode != NCGlobal.shared.ErrorResourceNotFound {
  674. NCContentPresenter.shared.messageNotification("_error_e2ee_", description: "_e2e_error_decode_metadata_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.ErrorDecodeMetadata, forced: true)
  675. }
  676. completion(metadatas, metadatasUpdate, errorCode, errorDescription)
  677. }
  678. } else {
  679. completion(metadatas, metadatasUpdate, errorCode, errorDescription)
  680. }
  681. } else {
  682. completion(metadatas, metadatasUpdate, errorCode, errorDescription)
  683. }
  684. } else {
  685. completion(nil, nil, errorCode, errorDescription)
  686. }
  687. }
  688. } else {
  689. completion(nil, nil, 0, "")
  690. }
  691. } else {
  692. completion(nil, nil, errorCode, errorDescription)
  693. }
  694. }
  695. }
  696. }
  697. // MARK: - Collection View
  698. extension NCCollectionViewCommon: UICollectionViewDelegate {
  699. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  700. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  701. metadataTouch = metadata
  702. selectedIndexPath = indexPath
  703. if isEditMode {
  704. if let index = selectOcId.firstIndex(of: metadata.ocId) {
  705. selectOcId.remove(at: index)
  706. } else {
  707. selectOcId.append(metadata.ocId)
  708. }
  709. collectionView.reloadItems(at: [indexPath])
  710. self.navigationItem.title = NSLocalizedString("_selected_", comment: "") + " : \(selectOcId.count)" + " / \(dataSource.metadatas.count)"
  711. return
  712. }
  713. if metadata.e2eEncrypted && !CCUtility.isEnd(toEndEnabled: appDelegate.account) {
  714. NCContentPresenter.shared.messageNotification("_info_", description: "_e2e_goto_settings_for_enable_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info, errorCode: NCGlobal.shared.ErrorE2EENotEnabled, forced: true)
  715. return
  716. }
  717. if metadata.directory {
  718. guard let serverUrlPush = CCUtility.stringAppendServerUrl(metadataTouch!.serverUrl, addFileName: metadataTouch!.fileName) else { return }
  719. // FILES
  720. if layoutKey == NCGlobal.shared.layoutViewFiles {
  721. if let viewController = appDelegate.listFilesVC[serverUrlPush] {
  722. if viewController.isViewLoaded {
  723. self.navigationController?.pushViewController(viewController, animated: true)
  724. }
  725. } else {
  726. let vcFiles:NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as! NCFiles
  727. vcFiles.isRoot = false
  728. vcFiles.serverUrl = serverUrlPush
  729. vcFiles.titleCurrentFolder = metadataTouch!.fileNameView
  730. appDelegate.listFilesVC[serverUrlPush] = vcFiles
  731. self.navigationController?.pushViewController(vcFiles, animated: true)
  732. }
  733. }
  734. // FAVORITE
  735. if layoutKey == NCGlobal.shared.layoutViewFavorite {
  736. if let viewController = appDelegate.listFavoriteVC[serverUrlPush] {
  737. if viewController.isViewLoaded {
  738. self.navigationController?.pushViewController(viewController, animated: true)
  739. }
  740. } else {
  741. let vcFavorite:NCFavorite = UIStoryboard(name: "NCFavorite", bundle: nil).instantiateInitialViewController() as! NCFavorite
  742. vcFavorite.serverUrl = serverUrlPush
  743. vcFavorite.titleCurrentFolder = metadataTouch!.fileNameView
  744. appDelegate.listFavoriteVC[serverUrlPush] = vcFavorite
  745. self.navigationController?.pushViewController(vcFavorite, animated: true)
  746. }
  747. }
  748. // OFFLINE
  749. if layoutKey == NCGlobal.shared.layoutViewOffline {
  750. if let viewController = appDelegate.listOfflineVC[serverUrlPush] {
  751. if viewController.isViewLoaded {
  752. self.navigationController?.pushViewController(viewController, animated: true)
  753. }
  754. } else {
  755. let vcOffline:NCOffline = UIStoryboard(name: "NCOffline", bundle: nil).instantiateInitialViewController() as! NCOffline
  756. vcOffline.serverUrl = serverUrlPush
  757. vcOffline.titleCurrentFolder = metadataTouch!.fileNameView
  758. appDelegate.listOfflineVC[serverUrlPush] = vcOffline
  759. self.navigationController?.pushViewController(vcOffline, animated: true)
  760. }
  761. }
  762. // RECENT ( for push use Files ... he he he )
  763. if layoutKey == NCGlobal.shared.layoutViewRecent {
  764. if let viewController = appDelegate.listFilesVC[serverUrlPush] {
  765. if viewController.isViewLoaded {
  766. self.navigationController?.pushViewController(viewController, animated: true)
  767. }
  768. } else {
  769. let vcFiles:NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as! NCFiles
  770. vcFiles.isRoot = false
  771. vcFiles.serverUrl = serverUrlPush
  772. vcFiles.titleCurrentFolder = metadataTouch!.fileNameView
  773. appDelegate.listFilesVC[serverUrlPush] = vcFiles
  774. self.navigationController?.pushViewController(vcFiles, animated: true)
  775. }
  776. }
  777. //VIEW IN FOLDER
  778. if layoutKey == NCGlobal.shared.layoutViewViewInFolder {
  779. let vcFileViewInFolder:NCFileViewInFolder = UIStoryboard(name: "NCFileViewInFolder", bundle: nil).instantiateInitialViewController() as! NCFileViewInFolder
  780. vcFileViewInFolder.serverUrl = serverUrlPush
  781. vcFileViewInFolder.titleCurrentFolder = metadataTouch!.fileNameView
  782. self.navigationController?.pushViewController(vcFileViewInFolder, animated: true)
  783. }
  784. // SHARES ( for push use Files ... he he he )
  785. if layoutKey == NCGlobal.shared.layoutViewShares {
  786. if let viewController = appDelegate.listFilesVC[serverUrlPush] {
  787. if viewController.isViewLoaded {
  788. self.navigationController?.pushViewController(viewController, animated: true)
  789. }
  790. } else {
  791. let vcFiles:NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as! NCFiles
  792. vcFiles.isRoot = false
  793. vcFiles.serverUrl = serverUrlPush
  794. vcFiles.titleCurrentFolder = metadataTouch!.fileNameView
  795. appDelegate.listFilesVC[serverUrlPush] = vcFiles
  796. self.navigationController?.pushViewController(vcFiles, animated: true)
  797. }
  798. }
  799. } else {
  800. guard let metadataTouch = metadataTouch else { return }
  801. if metadata.typeFile == NCGlobal.shared.metadataTypeFileImage || metadata.typeFile == NCGlobal.shared.metadataTypeFileVideo || metadata.typeFile == NCGlobal.shared.metadataTypeFileAudio {
  802. var metadatas: [tableMetadata] = []
  803. for metadata in dataSource.metadatas {
  804. if metadata.typeFile == NCGlobal.shared.metadataTypeFileImage || metadata.typeFile == NCGlobal.shared.metadataTypeFileVideo || metadata.typeFile == NCGlobal.shared.metadataTypeFileAudio {
  805. metadatas.append(metadata)
  806. }
  807. }
  808. NCViewer.shared.view(viewController: self, metadata: metadataTouch, metadatas: metadatas)
  809. return
  810. }
  811. if CCUtility.fileProviderStorageExists(metadataTouch.ocId, fileNameView: metadataTouch.fileNameView) {
  812. NCViewer.shared.view(viewController: self, metadata: metadataTouch, metadatas: [metadataTouch])
  813. } else if NCCommunication.shared.isNetworkReachable() {
  814. NCNetworking.shared.download(metadata: metadataTouch, selector: NCGlobal.shared.selectorLoadFileView) { (_) in }
  815. } else {
  816. NCContentPresenter.shared.messageNotification("_info_", description: "_go_online_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info, errorCode: NCGlobal.shared.ErrorOffline, forced: true)
  817. }
  818. }
  819. }
  820. func collectionViewSelectAll() {
  821. selectOcId.removeAll()
  822. for metadata in metadatasSource {
  823. selectOcId.append(metadata.ocId)
  824. }
  825. collectionView.reloadData()
  826. }
  827. @available(iOS 13.0, *)
  828. func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
  829. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return nil }
  830. metadataTouch = metadata
  831. let identifier = indexPath as NSCopying
  832. return UIContextMenuConfiguration(identifier: identifier, previewProvider: {
  833. return NCViewerProviderContextMenu(metadata: metadata)
  834. }, actionProvider: { suggestedActions in
  835. return NCCollectionCommon.shared.contextMenuConfiguration(metadata: metadata, viewController: self, enableDeleteLocal: true, enableViewInFolder: false)
  836. })
  837. }
  838. @available(iOS 13.0, *)
  839. func collectionView(_ collectionView: UICollectionView, willPerformPreviewActionForMenuWith configuration: UIContextMenuConfiguration, animator: UIContextMenuInteractionCommitAnimating) {
  840. animator.addCompletion {
  841. if let indexPath = configuration.identifier as? IndexPath {
  842. self.collectionView(collectionView, didSelectItemAt: indexPath)
  843. }
  844. }
  845. }
  846. }
  847. extension NCCollectionViewCommon: UICollectionViewDataSource {
  848. func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  849. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  850. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, urlBase: appDelegate.urlBase, view: collectionView, indexPath: indexPath)
  851. }
  852. func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  853. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  854. NCOperationQueue.shared.cancelDownloadThumbnail(metadata: metadata)
  855. }
  856. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  857. if kind == UICollectionView.elementKindSectionHeader {
  858. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeaderMenu", for: indexPath) as! NCSectionHeaderMenu
  859. if collectionView.collectionViewLayout == gridLayout {
  860. header.buttonSwitch.setImage(UIImage.init(named: "switchList")!.image(color: NCBrandColor.shared.icon, size: 50), for: .normal)
  861. } else {
  862. header.buttonSwitch.setImage(UIImage.init(named: "switchGrid")!.image(color: NCBrandColor.shared.icon, size: 50), for: .normal)
  863. }
  864. header.delegate = self
  865. header.setStatusButton(count: dataSource.metadatas.count)
  866. header.setTitleSorted(datasourceTitleButton: titleButton)
  867. header.viewRichWorkspaceHeightConstraint.constant = headerRichWorkspaceHeight
  868. header.setRichWorkspaceText(richWorkspaceText: richWorkspaceText)
  869. return header
  870. } else {
  871. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  872. let info = dataSource.getFilesInformation()
  873. footer.setTitleLabel(directories: info.directories, files: info.files, size: info.size )
  874. return footer
  875. }
  876. }
  877. func numberOfSections(in collectionView: UICollectionView) -> Int {
  878. return 1
  879. }
  880. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  881. let numberItems = dataSource.numberOfItems()
  882. emptyDataSet?.numberOfItemsInSection(numberItems, section: section)
  883. return numberItems
  884. }
  885. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  886. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else {
  887. if layout == NCGlobal.shared.layoutList {
  888. return collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  889. } else {
  890. return collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  891. }
  892. }
  893. var tableShare: tableShare?
  894. var isShare = false
  895. var isMounted = false
  896. if metadataFolder != nil {
  897. isShare = metadata.permissions.contains(NCGlobal.shared.permissionShared) && !metadataFolder!.permissions.contains(NCGlobal.shared.permissionShared)
  898. isMounted = metadata.permissions.contains(NCGlobal.shared.permissionMounted) && !metadataFolder!.permissions.contains(NCGlobal.shared.permissionMounted)
  899. }
  900. if dataSource.metadataShare[metadata.ocId] != nil {
  901. tableShare = dataSource.metadataShare[metadata.ocId]
  902. }
  903. //
  904. // LAYOUT LIST
  905. //
  906. if layout == NCGlobal.shared.layoutList {
  907. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  908. cell.delegate = self
  909. cell.objectId = metadata.ocId
  910. cell.indexPath = indexPath
  911. cell.labelTitle.text = metadata.fileNameView
  912. cell.labelTitle.textColor = NCBrandColor.shared.textView
  913. cell.separator.backgroundColor = NCBrandColor.shared.separator
  914. cell.imageSelect.image = nil
  915. cell.imageStatus.image = nil
  916. cell.imageLocal.image = nil
  917. cell.imageFavorite.image = nil
  918. cell.imageShared.image = nil
  919. cell.imageShared.clearLayerMask()
  920. cell.imageMore.image = nil
  921. cell.imageItem.image = nil
  922. cell.imageItem.backgroundColor = nil
  923. cell.progressView.progress = 0.0
  924. if metadata.directory {
  925. if metadata.e2eEncrypted {
  926. cell.imageItem.image = NCCollectionCommon.images.cellFolderEncryptedImage
  927. } else if isShare {
  928. cell.imageItem.image = NCCollectionCommon.images.cellFolderSharedWithMeImage
  929. } else if (tableShare != nil && tableShare?.shareType != 3) {
  930. cell.imageItem.image = NCCollectionCommon.images.cellFolderSharedWithMeImage
  931. } else if (tableShare != nil && tableShare?.shareType == 3) {
  932. cell.imageItem.image = NCCollectionCommon.images.cellFolderPublicImage
  933. } else if metadata.mountType == "group" {
  934. cell.imageItem.image = NCCollectionCommon.images.cellFolderGroupImage
  935. } else if isMounted {
  936. cell.imageItem.image = NCCollectionCommon.images.cellFolderExternalImage
  937. } else if metadata.fileName == autoUploadFileName && metadata.serverUrl == autoUploadDirectory {
  938. cell.imageItem.image = NCCollectionCommon.images.cellFolderAutomaticUploadImage
  939. } else {
  940. cell.imageItem.image = NCCollectionCommon.images.cellFolderImage
  941. }
  942. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date)
  943. let lockServerUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!
  944. let tableDirectory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, lockServerUrl))
  945. // Local image: offline
  946. if tableDirectory != nil && tableDirectory!.offline {
  947. cell.imageLocal.image = NCCollectionCommon.images.cellOfflineFlag
  948. }
  949. } else {
  950. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  951. cell.imageItem.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  952. } else {
  953. if metadata.hasPreview {
  954. cell.imageItem.backgroundColor = .lightGray
  955. } else {
  956. if metadata.iconName.count > 0 {
  957. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  958. } else {
  959. cell.imageItem.image = NCCollectionCommon.images.cellFileImage
  960. }
  961. }
  962. }
  963. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date) + " · " + CCUtility.transformedSize(metadata.size)
  964. // image local
  965. if dataSource.metadataOffLine.contains(metadata.ocId) {
  966. cell.imageLocal.image = NCCollectionCommon.images.cellOfflineFlag
  967. } else if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  968. cell.imageLocal.image = NCCollectionCommon.images.cellLocal
  969. }
  970. }
  971. // image Favorite
  972. if metadata.favorite {
  973. cell.imageFavorite.image = NCCollectionCommon.images.cellFavouriteImage
  974. }
  975. // Share image
  976. if (isShare) {
  977. cell.imageShared.image = NCCollectionCommon.images.cellSharedImage
  978. } else if (tableShare != nil && tableShare?.shareType == 3) {
  979. cell.imageShared.image = NCCollectionCommon.images.cellShareByLinkImage
  980. } else if (tableShare != nil && tableShare?.shareType != 3) {
  981. cell.imageShared.image = NCCollectionCommon.images.cellSharedImage
  982. } else {
  983. cell.imageShared.image = NCCollectionCommon.images.cellCanShareImage
  984. }
  985. if metadata.ownerId.count > 0 && metadata.ownerId != appDelegate.userId {
  986. var fileNameUser = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.user, urlBase: appDelegate.urlBase) + "-" + metadata.ownerId
  987. fileNameUser = fileNameUser + ".png"
  988. if FileManager.default.fileExists(atPath: fileNameUser) {
  989. cell.imageShared.avatar()
  990. cell.imageShared.image = UIImage(contentsOfFile: fileNameUser)
  991. } else {
  992. NCCommunication.shared.downloadAvatar(userId: metadata.ownerId, fileNameLocalPath: fileNameUser, size: NCGlobal.shared.avatarSize) { (account, data, errorCode, errorMessage) in
  993. if errorCode == 0 && account == self.appDelegate.account {
  994. cell.imageShared.avatar()
  995. cell.imageShared.image = UIImage(contentsOfFile: fileNameUser)
  996. }
  997. }
  998. }
  999. }
  1000. // Transfer
  1001. var progress: Float = 0.0
  1002. var totalBytes: Int64 = 0
  1003. if let progressType = appDelegate.listProgress[metadata.ocId] {
  1004. progress = progressType.progress
  1005. totalBytes = progressType.totalBytes
  1006. }
  1007. if metadata.status == NCGlobal.shared.metadataStatusInDownload || metadata.status == NCGlobal.shared.metadataStatusDownloading || metadata.status >= NCGlobal.shared.metadataStatusTypeUpload {
  1008. cell.progressView.isHidden = false
  1009. cell.setButtonMore(named: NCGlobal.shared.buttonMoreStop, image: NCCollectionCommon.images.cellButtonStop)
  1010. } else {
  1011. cell.progressView.isHidden = true
  1012. cell.progressView.progress = progress
  1013. cell.setButtonMore(named: NCGlobal.shared.buttonMoreMore, image: NCCollectionCommon.images.cellButtonMore)
  1014. }
  1015. // Write status on Label Info
  1016. switch metadata.status {
  1017. case NCGlobal.shared.metadataStatusWaitDownload:
  1018. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_download_", comment: "")
  1019. break
  1020. case NCGlobal.shared.metadataStatusInDownload:
  1021. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_download_", comment: "")
  1022. break
  1023. case NCGlobal.shared.metadataStatusDownloading:
  1024. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - ↓ " + CCUtility.transformedSize(totalBytes)
  1025. break
  1026. case NCGlobal.shared.metadataStatusWaitUpload:
  1027. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_upload_", comment: "")
  1028. break
  1029. case NCGlobal.shared.metadataStatusInUpload:
  1030. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_upload_", comment: "")
  1031. break
  1032. case NCGlobal.shared.metadataStatusUploading:
  1033. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - ↑ " + CCUtility.transformedSize(totalBytes)
  1034. break
  1035. default:
  1036. break
  1037. }
  1038. // Live Photo
  1039. if metadata.livePhoto {
  1040. cell.imageStatus.image = NCCollectionCommon.images.cellLivePhotoImage
  1041. }
  1042. // E2EE
  1043. if metadata.e2eEncrypted || isEncryptedFolder {
  1044. cell.hideButtonShare(true)
  1045. } else {
  1046. cell.hideButtonShare(false)
  1047. }
  1048. // Remove last separator
  1049. if collectionView.numberOfItems(inSection: indexPath.section) == indexPath.row + 1 {
  1050. cell.separator.isHidden = true
  1051. } else {
  1052. cell.separator.isHidden = false
  1053. }
  1054. // Edit mode
  1055. if isEditMode {
  1056. cell.selectMode(true)
  1057. if selectOcId.contains(metadata.ocId) {
  1058. cell.selected(true)
  1059. } else {
  1060. cell.selected(false)
  1061. }
  1062. } else {
  1063. cell.selectMode(false)
  1064. }
  1065. // Disable Share Button
  1066. if appDelegate.disableSharesView {
  1067. cell.hideButtonShare(true)
  1068. }
  1069. return cell
  1070. }
  1071. //
  1072. // LAYOUT GRID
  1073. //
  1074. if layout == NCGlobal.shared.layoutGrid {
  1075. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  1076. cell.delegate = self
  1077. cell.objectId = metadata.ocId
  1078. cell.indexPath = indexPath
  1079. cell.labelTitle.text = metadata.fileNameView
  1080. cell.labelTitle.textColor = NCBrandColor.shared.textView
  1081. cell.imageSelect.image = nil
  1082. cell.imageStatus.image = nil
  1083. cell.imageLocal.image = nil
  1084. cell.imageFavorite.image = nil
  1085. cell.imageItem.image = nil
  1086. cell.imageItem.backgroundColor = nil
  1087. cell.progressView.progress = 0.0
  1088. if metadata.directory {
  1089. if metadata.e2eEncrypted {
  1090. cell.imageItem.image = NCCollectionCommon.images.cellFolderEncryptedImage
  1091. } else if isShare {
  1092. cell.imageItem.image = NCCollectionCommon.images.cellFolderSharedWithMeImage
  1093. } else if (tableShare != nil && tableShare!.shareType != 3) {
  1094. cell.imageItem.image = NCCollectionCommon.images.cellFolderSharedWithMeImage
  1095. } else if (tableShare != nil && tableShare!.shareType == 3) {
  1096. cell.imageItem.image = NCCollectionCommon.images.cellFolderPublicImage
  1097. } else if metadata.mountType == "group" {
  1098. cell.imageItem.image = NCCollectionCommon.images.cellFolderGroupImage
  1099. } else if isMounted {
  1100. cell.imageItem.image = NCCollectionCommon.images.cellFolderExternalImage
  1101. } else if metadata.fileName == autoUploadFileName && metadata.serverUrl == autoUploadDirectory {
  1102. cell.imageItem.image = NCCollectionCommon.images.cellFolderAutomaticUploadImage
  1103. } else {
  1104. cell.imageItem.image = NCCollectionCommon.images.cellFolderImage
  1105. }
  1106. let lockServerUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!
  1107. let tableDirectory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, lockServerUrl))
  1108. // Local image: offline
  1109. if tableDirectory != nil && tableDirectory!.offline {
  1110. cell.imageLocal.image = NCCollectionCommon.images.cellOfflineFlag
  1111. }
  1112. } else {
  1113. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  1114. cell.imageItem.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  1115. } else {
  1116. if metadata.hasPreview {
  1117. cell.imageItem.backgroundColor = .lightGray
  1118. } else {
  1119. if metadata.iconName.count > 0 {
  1120. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  1121. } else {
  1122. cell.imageItem.image = NCCollectionCommon.images.cellFileImage
  1123. }
  1124. }
  1125. }
  1126. // image Local
  1127. if dataSource.metadataOffLine.contains(metadata.ocId) {
  1128. cell.imageLocal.image = NCCollectionCommon.images.cellOfflineFlag
  1129. } else if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  1130. cell.imageLocal.image = NCCollectionCommon.images.cellLocal
  1131. }
  1132. }
  1133. // image Favorite
  1134. if metadata.favorite {
  1135. cell.imageFavorite.image = NCCollectionCommon.images.cellFavouriteImage
  1136. }
  1137. // Transfer
  1138. if metadata.status == NCGlobal.shared.metadataStatusInDownload || metadata.status == NCGlobal.shared.metadataStatusDownloading || metadata.status >= NCGlobal.shared.metadataStatusTypeUpload {
  1139. cell.progressView.isHidden = false
  1140. cell.setButtonMore(named: NCGlobal.shared.buttonMoreStop, image: NCCollectionCommon.images.cellButtonStop)
  1141. } else {
  1142. cell.progressView.isHidden = true
  1143. cell.progressView.progress = 0.0
  1144. cell.setButtonMore(named: NCGlobal.shared.buttonMoreMore, image: NCCollectionCommon.images.cellButtonMore)
  1145. }
  1146. // Live Photo
  1147. if metadata.livePhoto {
  1148. cell.imageStatus.image = NCCollectionCommon.images.cellLivePhotoImage
  1149. }
  1150. // Edit mode
  1151. if isEditMode {
  1152. cell.selectMode(true)
  1153. if selectOcId.contains(metadata.ocId) {
  1154. cell.selected(true)
  1155. } else {
  1156. cell.selected(false)
  1157. }
  1158. } else {
  1159. cell.selectMode(false)
  1160. }
  1161. return cell
  1162. }
  1163. return collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  1164. }
  1165. }
  1166. extension NCCollectionViewCommon: UICollectionViewDelegateFlowLayout {
  1167. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  1168. headerRichWorkspaceHeight = 0
  1169. if let richWorkspaceText = richWorkspaceText {
  1170. let trimmed = richWorkspaceText.trimmingCharacters(in: .whitespaces)
  1171. if trimmed.count > 0 && !isSearching {
  1172. headerRichWorkspaceHeight = UIScreen.main.bounds.size.height / 4
  1173. }
  1174. }
  1175. return CGSize(width: collectionView.frame.width, height: headerHeight + headerRichWorkspaceHeight)
  1176. }
  1177. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  1178. return CGSize(width: collectionView.frame.width, height: footerHeight)
  1179. }
  1180. }