NCTrash.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. //
  2. // NCTrash.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 02/10/2018.
  6. // Copyright © 2018 Marino Faggiana. All rights reserved.
  7. // Copyright © 2022 Henrik Storch. All rights reserved.
  8. //
  9. // Author Henrik Storch <henrik.storch@nextcloud.com>
  10. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  11. //
  12. // This program is free software: you can redistribute it and/or modify
  13. // it under the terms of the GNU General Public License as published by
  14. // the Free Software Foundation, either version 3 of the License, or
  15. // (at your option) any later version.
  16. //
  17. // This program is distributed in the hope that it will be useful,
  18. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. // GNU General Public License for more details.
  21. //
  22. // You should have received a copy of the GNU General Public License
  23. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  24. //
  25. import Realm
  26. import UIKit
  27. import NextcloudKit
  28. class NCTrash: UIViewController, NCTrashListCellDelegate, NCEmptyDataSetDelegate, NCGridCellDelegate {
  29. @IBOutlet weak var collectionView: UICollectionView!
  30. var trashPath = ""
  31. var titleCurrentFolder = NSLocalizedString("_trash_view_", comment: "")
  32. var blinkFileId: String?
  33. var emptyDataSet: NCEmptyDataSet?
  34. var selectableDataSource: [RealmSwiftObject] { datasource }
  35. var dataSourceTask: URLSessionTask?
  36. let appDelegate = (UIApplication.shared.delegate as? AppDelegate)!
  37. let utilityFileSystem = NCUtilityFileSystem()
  38. let utility = NCUtility()
  39. var isEditMode = false
  40. var selectOcId: [String] = []
  41. var selectIndexPath: [IndexPath] = []
  42. var tabBarSelect: NCSelectableViewTabBar?
  43. var datasource: [tableTrash] = []
  44. var layoutForView: NCDBLayoutForView?
  45. var listLayout: NCListLayout!
  46. var gridLayout: NCGridLayout!
  47. var layoutKey = NCGlobal.shared.layoutViewTrash
  48. private let refreshControl = UIRefreshControl()
  49. // MARK: - View Life Cycle
  50. override func viewDidLoad() {
  51. super.viewDidLoad()
  52. tabBarSelect = NCTrashSelectTabBar(tabBarController: tabBarController, delegate: self)
  53. view.backgroundColor = .systemBackground
  54. self.navigationController?.navigationBar.prefersLargeTitles = true
  55. // Cell
  56. collectionView.register(UINib(nibName: "NCTrashListCell", bundle: nil), forCellWithReuseIdentifier: "listCell")
  57. collectionView.register(UINib(nibName: "NCGridCell", bundle: nil), forCellWithReuseIdentifier: "gridCell")
  58. // Footer
  59. collectionView.register(UINib(nibName: "NCSectionFooter", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "sectionFooter")
  60. collectionView.alwaysBounceVertical = true
  61. collectionView.backgroundColor = .systemBackground
  62. listLayout = NCListLayout()
  63. gridLayout = NCGridLayout()
  64. // Add Refresh Control
  65. collectionView.refreshControl = refreshControl
  66. refreshControl.tintColor = .gray
  67. refreshControl.addTarget(self, action: #selector(loadListingTrash), for: .valueChanged)
  68. // Empty
  69. emptyDataSet = NCEmptyDataSet(view: collectionView, offset: NCGlobal.shared.heightButtonsView, delegate: self)
  70. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSource), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadDataSource), object: nil)
  71. }
  72. override func viewWillAppear(_ animated: Bool) {
  73. appDelegate.activeViewController = self
  74. navigationController?.setNavigationBarAppearance()
  75. navigationItem.title = titleCurrentFolder
  76. layoutForView = NCManageDatabase.shared.getLayoutForView(account: appDelegate.account, key: NCGlobal.shared.layoutViewTrash, serverUrl: "")
  77. gridLayout.itemForLine = CGFloat(layoutForView?.itemForLine ?? 3)
  78. if layoutForView?.layout == NCGlobal.shared.layoutList {
  79. collectionView.collectionViewLayout = listLayout
  80. } else {
  81. collectionView.collectionViewLayout = gridLayout
  82. }
  83. setNavigationLeftItems()
  84. reloadDataSource()
  85. }
  86. override func viewDidAppear(_ animated: Bool) {
  87. super.viewDidAppear(animated)
  88. loadListingTrash()
  89. }
  90. override func viewWillDisappear(_ animated: Bool) {
  91. isEditMode = false
  92. setNavigationLeftItems()
  93. }
  94. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  95. super.viewWillTransition(to: size, with: coordinator)
  96. coordinator.animate(alongsideTransition: nil) { _ in
  97. self.collectionView?.collectionViewLayout.invalidateLayout()
  98. }
  99. }
  100. override func viewWillLayoutSubviews() {
  101. super.viewWillLayoutSubviews()
  102. if let frame = tabBarController?.tabBar.frame {
  103. (tabBarSelect as? NCTrashSelectTabBar)?.hostingController?.view.frame = frame
  104. }
  105. }
  106. // MARK: - Empty
  107. func emptyDataSetView(_ view: NCEmptyView) {
  108. view.emptyImage.image = UIImage(named: "trash")?.image(color: .gray, size: UIScreen.main.bounds.width)
  109. view.emptyTitle.text = NSLocalizedString("_trash_no_trash_", comment: "")
  110. view.emptyDescription.text = NSLocalizedString("_trash_no_trash_description_", comment: "")
  111. }
  112. // MARK: TAP EVENT
  113. func tapRestoreListItem(with ocId: String, image: UIImage?, sender: Any) {
  114. if !isEditMode {
  115. restoreItem(with: ocId)
  116. } else if let button = sender as? UIView {
  117. let buttonPosition = button.convert(CGPoint.zero, to: collectionView)
  118. let indexPath = collectionView.indexPathForItem(at: buttonPosition)
  119. collectionView(self.collectionView, didSelectItemAt: indexPath!)
  120. } // else: undefined sender
  121. }
  122. func tapMoreListItem(with objectId: String, image: UIImage?, sender: Any) {
  123. if !isEditMode {
  124. toggleMenuMore(with: objectId, image: image, isGridCell: false)
  125. } else if let button = sender as? UIView {
  126. let buttonPosition = button.convert(CGPoint.zero, to: collectionView)
  127. let indexPath = collectionView.indexPathForItem(at: buttonPosition)
  128. collectionView(self.collectionView, didSelectItemAt: indexPath!)
  129. } // else: undefined sender
  130. }
  131. func tapMoreGridItem(with objectId: String, namedButtonMore: String, image: UIImage?, sender: Any) {
  132. if !isEditMode {
  133. toggleMenuMore(with: objectId, image: image, isGridCell: true)
  134. } else if let button = sender as? UIView {
  135. let buttonPosition = button.convert(CGPoint.zero, to: collectionView)
  136. let indexPath = collectionView.indexPathForItem(at: buttonPosition)
  137. collectionView(self.collectionView, didSelectItemAt: indexPath!)
  138. }
  139. }
  140. func longPressGridItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) { }
  141. func longPressMoreGridItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) { }
  142. // MARK: - DataSource
  143. @objc func reloadDataSource(withQueryDB: Bool = true) {
  144. layoutForView = NCManageDatabase.shared.getLayoutForView(account: appDelegate.account, key: NCGlobal.shared.layoutViewTrash, serverUrl: "")
  145. datasource.removeAll()
  146. guard let trashPath = self.getTrashPath(), let tashItems = NCManageDatabase.shared.getTrash(filePath: trashPath, sort: layoutForView?.sort, ascending: layoutForView?.ascending, account: appDelegate.account) else {
  147. return
  148. }
  149. datasource = tashItems
  150. collectionView.reloadData()
  151. guard let blinkFileId = blinkFileId else { return }
  152. for itemIx in 0..<self.datasource.count where self.datasource[itemIx].fileId.contains(blinkFileId) {
  153. let indexPath = IndexPath(item: itemIx, section: 0)
  154. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
  155. UIView.animate(withDuration: 0.3) {
  156. self.collectionView.scrollToItem(at: indexPath, at: .centeredVertically, animated: false)
  157. } completion: { _ in
  158. guard let cell = self.collectionView.cellForItem(at: indexPath) else { return }
  159. cell.backgroundColor = .darkGray
  160. UIView.animate(withDuration: 2) {
  161. cell.backgroundColor = .clear
  162. self.blinkFileId = nil
  163. }
  164. }
  165. }
  166. }
  167. }
  168. func getTrashPath() -> String? {
  169. if self.trashPath.isEmpty {
  170. guard let userId = (appDelegate.userId as NSString).addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlFragmentAllowed) else { return nil }
  171. let trashPath = appDelegate.urlBase + "/" + NextcloudKit.shared.nkCommonInstance.dav + "/trashbin/" + userId + "/trash/"
  172. return trashPath
  173. } else {
  174. return self.trashPath
  175. }
  176. }
  177. }
  178. // MARK: - NC API & Algorithm
  179. extension NCTrash {
  180. @objc func loadListingTrash() {
  181. NextcloudKit.shared.listingTrash(showHiddenFiles: false) { task in
  182. self.dataSourceTask = task
  183. self.collectionView.reloadData()
  184. } completion: { account, items, _, error in
  185. DispatchQueue.main.async { self.refreshControl.endRefreshing() }
  186. guard error == .success, account == self.appDelegate.account, let trashPath = self.getTrashPath() else {
  187. NCContentPresenter().showError(error: error)
  188. return
  189. }
  190. NCManageDatabase.shared.deleteTrash(filePath: trashPath, account: self.appDelegate.account)
  191. NCManageDatabase.shared.addTrash(account: account, items: items)
  192. self.reloadDataSource()
  193. }
  194. }
  195. func restoreItem(with fileId: String) {
  196. guard let tableTrash = NCManageDatabase.shared.getTrashItem(fileId: fileId, account: appDelegate.account) else { return }
  197. let fileNameFrom = tableTrash.filePath + tableTrash.fileName
  198. let fileNameTo = appDelegate.urlBase + "/" + NextcloudKit.shared.nkCommonInstance.dav + "/trashbin/" + appDelegate.userId + "/restore/" + tableTrash.fileName
  199. NextcloudKit.shared.moveFileOrFolder(serverUrlFileNameSource: fileNameFrom, serverUrlFileNameDestination: fileNameTo, overwrite: true) { account, error in
  200. guard error == .success, account == self.appDelegate.account else {
  201. NCContentPresenter().showError(error: error)
  202. return
  203. }
  204. NCManageDatabase.shared.deleteTrash(fileId: fileId, account: account)
  205. self.reloadDataSource()
  206. }
  207. }
  208. func emptyTrash() {
  209. let serverUrlFileName = appDelegate.urlBase + "/" + NextcloudKit.shared.nkCommonInstance.dav + "/trashbin/" + appDelegate.userId + "/trash"
  210. NextcloudKit.shared.deleteFileOrFolder(serverUrlFileName: serverUrlFileName) { account, error in
  211. guard error == .success, account == self.appDelegate.account else {
  212. NCContentPresenter().showError(error: error)
  213. return
  214. }
  215. NCManageDatabase.shared.deleteTrash(fileId: nil, account: self.appDelegate.account)
  216. self.reloadDataSource()
  217. }
  218. }
  219. func deleteItem(with fileId: String) {
  220. guard let tableTrash = NCManageDatabase.shared.getTrashItem(fileId: fileId, account: appDelegate.account) else { return }
  221. let serverUrlFileName = tableTrash.filePath + tableTrash.fileName
  222. NextcloudKit.shared.deleteFileOrFolder(serverUrlFileName: serverUrlFileName) { account, error in
  223. guard error == .success, account == self.appDelegate.account else {
  224. NCContentPresenter().showError(error: error)
  225. return
  226. }
  227. NCManageDatabase.shared.deleteTrash(fileId: fileId, account: account)
  228. self.reloadDataSource()
  229. }
  230. }
  231. func downloadThumbnail(with tableTrash: tableTrash, indexPath: IndexPath) {
  232. let fileNamePreviewLocalPath = utilityFileSystem.getDirectoryProviderStoragePreviewOcId(tableTrash.fileId, etag: tableTrash.fileName)
  233. let fileNameIconLocalPath = utilityFileSystem.getDirectoryProviderStorageIconOcId(tableTrash.fileId, etag: tableTrash.fileName)
  234. NextcloudKit.shared.downloadPreview(fileNamePathOrFileId: tableTrash.fileId,
  235. fileNamePreviewLocalPath: fileNamePreviewLocalPath,
  236. widthPreview: NCGlobal.shared.sizePreview,
  237. heightPreview: NCGlobal.shared.sizePreview,
  238. fileNameIconLocalPath: fileNameIconLocalPath,
  239. sizeIcon: NCGlobal.shared.sizeIcon,
  240. etag: nil,
  241. endpointTrashbin: true) { account, _, imageIcon, _, _, error in
  242. guard error == .success, let imageIcon = imageIcon, account == self.appDelegate.account,
  243. let cell = self.collectionView.cellForItem(at: indexPath) else { return }
  244. if let cell = cell as? NCTrashListCell {
  245. cell.imageItem.image = imageIcon
  246. } else if let cell = cell as? NCGridCell {
  247. cell.imageItem.image = imageIcon
  248. } // else: undefined cell
  249. }
  250. }
  251. }
  252. extension NCTrash: NCSelectableNavigationView, NCTrashSelectTabBarDelegate {
  253. var serverUrl: String {
  254. ""
  255. }
  256. func setNavigationRightItems(enableMenu: Bool = false) {
  257. guard let tabBarSelect = tabBarSelect as? NCTrashSelectTabBar else { return }
  258. tabBarSelect.isSelectedEmpty = selectOcId.isEmpty
  259. if isEditMode {
  260. tabBarSelect.show()
  261. let select = UIBarButtonItem(title: NSLocalizedString("_cancel_", comment: ""), style: .done) { self.toggleSelect() }
  262. navigationItem.rightBarButtonItems = [select]
  263. } else {
  264. tabBarSelect.hide()
  265. let menu = UIMenu(children: createMenuActions())
  266. let menuButton = UIBarButtonItem(image: .init(systemName: "ellipsis.circle"), menu: menu)
  267. menuButton.isEnabled = true
  268. navigationItem.rightBarButtonItems = [menuButton]
  269. }
  270. }
  271. func onListSelected() {
  272. if layoutForView?.layout == NCGlobal.shared.layoutGrid {
  273. // list layout
  274. layoutForView?.layout = NCGlobal.shared.layoutList
  275. NCManageDatabase.shared.setLayoutForView(account: appDelegate.account, key: layoutKey, serverUrl: "", layout: layoutForView?.layout)
  276. self.collectionView.reloadData()
  277. self.collectionView.collectionViewLayout.invalidateLayout()
  278. self.collectionView.setCollectionViewLayout(self.listLayout, animated: true)
  279. }
  280. }
  281. func onGridSelected() {
  282. if layoutForView?.layout == NCGlobal.shared.layoutList {
  283. // grid layout
  284. layoutForView?.layout = NCGlobal.shared.layoutGrid
  285. NCManageDatabase.shared.setLayoutForView(account: appDelegate.account, key: layoutKey, serverUrl: "", layout: layoutForView?.layout)
  286. self.collectionView.reloadData()
  287. self.collectionView.collectionViewLayout.invalidateLayout()
  288. self.collectionView.setCollectionViewLayout(self.gridLayout, animated: true)
  289. }
  290. }
  291. func selectAll() {
  292. collectionViewSelectAll()
  293. }
  294. func recover() {
  295. self.selectOcId.forEach(restoreItem)
  296. self.toggleSelect()
  297. }
  298. func delete() {
  299. self.selectOcId.forEach(deleteItem)
  300. self.toggleSelect()
  301. }
  302. func createMenuActions() -> [UIMenuElement] {
  303. guard let layoutForView = NCManageDatabase.shared.getLayoutForView(account: appDelegate.account, key: layoutKey, serverUrl: serverUrl) else { return [] }
  304. let select = UIAction(title: NSLocalizedString("_select_", comment: ""), image: .init(systemName: "checkmark.circle"), attributes: selectableDataSource.isEmpty ? .disabled : []) { _ in self.toggleSelect() }
  305. let list = UIAction(title: NSLocalizedString("_list_", comment: ""), image: .init(systemName: "list.bullet"), state: layoutForView.layout == NCGlobal.shared.layoutList ? .on : .off) { _ in
  306. self.onListSelected()
  307. self.setNavigationRightItems()
  308. }
  309. let grid = UIAction(title: NSLocalizedString("_icons_", comment: ""), image: .init(systemName: "square.grid.2x2"), state: layoutForView.layout == NCGlobal.shared.layoutGrid ? .on : .off) { _ in
  310. self.onGridSelected()
  311. self.setNavigationRightItems()
  312. }
  313. let viewStyleSubmenu = UIMenu(title: "", options: .displayInline, children: [list, grid])
  314. return [select, viewStyleSubmenu]
  315. }
  316. }