NCTrash.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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, NCSelectableNavigationView, NCTrashListCellDelegate, NCSectionHeaderMenuDelegate, 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. internal let appDelegate = (UIApplication.shared.delegate as? AppDelegate)!
  36. internal var isEditMode = false
  37. internal var selectOcId: [String] = []
  38. internal var selectIndexPath: [IndexPath] = []
  39. var datasource: [tableTrash] = []
  40. var layoutForView: NCDBLayoutForView?
  41. var listLayout: NCListLayout!
  42. var gridLayout: NCGridLayout!
  43. var layoutKey = NCGlobal.shared.layoutViewTrash
  44. private let refreshControl = UIRefreshControl()
  45. // MARK: - View Life Cycle
  46. override func viewDidLoad() {
  47. view.backgroundColor = .systemBackground
  48. self.navigationController?.navigationBar.prefersLargeTitles = true
  49. // Cell
  50. collectionView.register(UINib(nibName: "NCTrashListCell", bundle: nil), forCellWithReuseIdentifier: "listCell")
  51. collectionView.register(UINib(nibName: "NCGridCell", bundle: nil), forCellWithReuseIdentifier: "gridCell")
  52. // Header - Footer
  53. collectionView.register(UINib(nibName: "NCSectionHeaderMenu", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeaderMenu")
  54. collectionView.register(UINib(nibName: "NCSectionFooter", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "sectionFooter")
  55. collectionView.alwaysBounceVertical = true
  56. collectionView.backgroundColor = .systemBackground
  57. listLayout = NCListLayout()
  58. gridLayout = NCGridLayout()
  59. // Add Refresh Control
  60. collectionView.refreshControl = refreshControl
  61. refreshControl.tintColor = .gray
  62. refreshControl.addTarget(self, action: #selector(loadListingTrash), for: .valueChanged)
  63. // Empty
  64. emptyDataSet = NCEmptyDataSet(view: collectionView, offset: NCGlobal.shared.heightButtonsView, delegate: self)
  65. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSource), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadDataSource), object: nil)
  66. }
  67. override func viewWillAppear(_ animated: Bool) {
  68. appDelegate.activeViewController = self
  69. navigationController?.setFileAppreance()
  70. navigationItem.title = titleCurrentFolder
  71. layoutForView = NCManageDatabase.shared.getLayoutForView(account: appDelegate.account, key: NCGlobal.shared.layoutViewTrash, serverUrl: "")
  72. gridLayout.itemForLine = CGFloat(layoutForView?.itemForLine ?? 3)
  73. if layoutForView?.layout == NCGlobal.shared.layoutList {
  74. collectionView.collectionViewLayout = listLayout
  75. } else {
  76. collectionView.collectionViewLayout = gridLayout
  77. }
  78. setNavigationItem()
  79. reloadDataSource()
  80. }
  81. override func viewDidAppear(_ animated: Bool) {
  82. super.viewDidAppear(animated)
  83. loadListingTrash()
  84. }
  85. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  86. super.viewWillTransition(to: size, with: coordinator)
  87. coordinator.animate(alongsideTransition: nil) { _ in
  88. self.collectionView?.collectionViewLayout.invalidateLayout()
  89. }
  90. }
  91. // MARK: - Empty
  92. func emptyDataSetView(_ view: NCEmptyView) {
  93. view.emptyImage.image = UIImage(named: "trash")?.image(color: .gray, size: UIScreen.main.bounds.width)
  94. view.emptyTitle.text = NSLocalizedString("_trash_no_trash_", comment: "")
  95. view.emptyDescription.text = NSLocalizedString("_trash_no_trash_description_", comment: "")
  96. }
  97. // MARK: TAP EVENT
  98. func tapButtonSwitch(_ sender: Any) {
  99. if collectionView.collectionViewLayout == gridLayout {
  100. // list layout
  101. layoutForView?.layout = NCGlobal.shared.layoutList
  102. NCManageDatabase.shared.setLayoutForView(account: appDelegate.account, key: NCGlobal.shared.layoutViewTrash, serverUrl: "", layout: layoutForView?.layout)
  103. self.collectionView.reloadData()
  104. self.collectionView.collectionViewLayout.invalidateLayout()
  105. self.collectionView.setCollectionViewLayout(self.listLayout, animated: true)
  106. } else {
  107. // grid layout
  108. layoutForView?.layout = NCGlobal.shared.layoutGrid
  109. NCManageDatabase.shared.setLayoutForView(account: appDelegate.account, key: NCGlobal.shared.layoutViewTrash, serverUrl: "", layout: layoutForView?.layout)
  110. self.collectionView.reloadData()
  111. self.collectionView.collectionViewLayout.invalidateLayout()
  112. self.collectionView.setCollectionViewLayout(self.gridLayout, animated: true)
  113. }
  114. }
  115. func tapButtonOrder(_ sender: Any) {
  116. let sortMenu = NCSortMenu()
  117. sortMenu.toggleMenu(viewController: self, account: appDelegate.account, key: NCGlobal.shared.layoutViewTrash, sortButton: sender as? UIButton, serverUrl: "", hideDirectoryOnTop: true)
  118. }
  119. func tapButtonMore(_ sender: Any) {
  120. toggleMenuMoreHeader()
  121. }
  122. func tapRestoreListItem(with ocId: String, image: UIImage?, sender: Any) {
  123. if !isEditMode {
  124. restoreItem(with: ocId)
  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 tapMoreListItem(with objectId: String, image: UIImage?, sender: Any) {
  132. if !isEditMode {
  133. toggleMenuMore(with: objectId, image: image, isGridCell: false)
  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. } // else: undefined sender
  139. }
  140. func tapMoreGridItem(with objectId: String, namedButtonMore: String, image: UIImage?, sender: Any) {
  141. if !isEditMode {
  142. toggleMenuMore(with: objectId, image: image, isGridCell: true)
  143. } else if let button = sender as? UIView {
  144. let buttonPosition = button.convert(CGPoint.zero, to: collectionView)
  145. let indexPath = collectionView.indexPathForItem(at: buttonPosition)
  146. collectionView(self.collectionView, didSelectItemAt: indexPath!)
  147. }
  148. }
  149. func tapButton1(_ sender: Any) {
  150. if isEditMode {
  151. if selectOcId.isEmpty { return }
  152. self.selectOcId.forEach(self.restoreItem)
  153. self.tapSelect()
  154. } else {
  155. if datasource.isEmpty { return }
  156. datasource.forEach({ self.restoreItem(with: $0.fileId) })
  157. }
  158. }
  159. func tapButton2(_ sender: Any) {
  160. if isEditMode {
  161. if selectOcId.isEmpty { return }
  162. let alert = UIAlertController(title: NSLocalizedString("_trash_delete_selected_", comment: ""), message: "", preferredStyle: .alert)
  163. alert.addAction(UIAlertAction(title: NSLocalizedString("_delete_", comment: ""), style: .destructive, handler: { _ in
  164. self.selectOcId.forEach(self.deleteItem)
  165. self.tapSelect()
  166. }))
  167. alert.addAction(UIAlertAction(title: NSLocalizedString("_cancel_", comment: ""), style: .cancel, handler: { _ in }))
  168. self.present(alert, animated: true, completion: nil)
  169. } else {
  170. if datasource.isEmpty { return }
  171. let alert = UIAlertController(title: NSLocalizedString("_trash_delete_all_description_", comment: ""), message: "", preferredStyle: .alert)
  172. alert.addAction(UIAlertAction(title: NSLocalizedString("_trash_delete_all_", comment: ""), style: .destructive, handler: { _ in
  173. self.emptyTrash()
  174. }))
  175. alert.addAction(UIAlertAction(title: NSLocalizedString("_cancel_", comment: ""), style: .cancel))
  176. self.present(alert, animated: true, completion: nil)
  177. }
  178. }
  179. func longPressGridItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) { }
  180. func longPressMoreGridItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) { }
  181. // MARK: - DataSource
  182. @objc func reloadDataSource(isForced: Bool = true) {
  183. layoutForView = NCManageDatabase.shared.getLayoutForView(account: appDelegate.account, key: NCGlobal.shared.layoutViewTrash, serverUrl: "")
  184. datasource.removeAll()
  185. guard let trashPath = self.getTrashPath(), let tashItems = NCManageDatabase.shared.getTrash(filePath: trashPath, sort: layoutForView?.sort, ascending: layoutForView?.ascending, account: appDelegate.account) else {
  186. return
  187. }
  188. datasource = tashItems
  189. collectionView.reloadData()
  190. guard let blinkFileId = blinkFileId else { return }
  191. for itemIx in 0..<self.datasource.count where self.datasource[itemIx].fileId.contains(blinkFileId) {
  192. let indexPath = IndexPath(item: itemIx, section: 0)
  193. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
  194. UIView.animate(withDuration: 0.3) {
  195. self.collectionView.scrollToItem(at: indexPath, at: .centeredVertically, animated: false)
  196. } completion: { _ in
  197. guard let cell = self.collectionView.cellForItem(at: indexPath) else { return }
  198. cell.backgroundColor = .darkGray
  199. UIView.animate(withDuration: 2) {
  200. cell.backgroundColor = .clear
  201. self.blinkFileId = nil
  202. }
  203. }
  204. }
  205. }
  206. }
  207. func getTrashPath() -> String? {
  208. if self.trashPath.isEmpty {
  209. guard let userId = (appDelegate.userId as NSString).addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlFragmentAllowed) else { return nil }
  210. let trashPath = appDelegate.urlBase + "/" + NextcloudKit.shared.nkCommonInstance.dav + "/trashbin/" + userId + "/trash/"
  211. return trashPath
  212. } else {
  213. return self.trashPath
  214. }
  215. }
  216. }
  217. // MARK: - NC API & Algorithm
  218. extension NCTrash {
  219. @objc func loadListingTrash() {
  220. NextcloudKit.shared.listingTrash(showHiddenFiles: false) { account, items, _, error in
  221. DispatchQueue.main.async { self.refreshControl.endRefreshing() }
  222. guard error == .success, account == self.appDelegate.account, let trashPath = self.getTrashPath() else {
  223. NCContentPresenter.shared.showError(error: error)
  224. return
  225. }
  226. NCManageDatabase.shared.deleteTrash(filePath: trashPath, account: self.appDelegate.account)
  227. NCManageDatabase.shared.addTrash(account: account, items: items)
  228. self.reloadDataSource()
  229. }
  230. }
  231. func restoreItem(with fileId: String) {
  232. guard let tableTrash = NCManageDatabase.shared.getTrashItem(fileId: fileId, account: appDelegate.account) else { return }
  233. let fileNameFrom = tableTrash.filePath + tableTrash.fileName
  234. let fileNameTo = appDelegate.urlBase + "/" + NextcloudKit.shared.nkCommonInstance.dav + "/trashbin/" + appDelegate.userId + "/restore/" + tableTrash.fileName
  235. NextcloudKit.shared.moveFileOrFolder(serverUrlFileNameSource: fileNameFrom, serverUrlFileNameDestination: fileNameTo, overwrite: true) { account, error in
  236. guard error == .success, account == self.appDelegate.account else {
  237. NCContentPresenter.shared.showError(error: error)
  238. return
  239. }
  240. NCManageDatabase.shared.deleteTrash(fileId: fileId, account: account)
  241. self.reloadDataSource()
  242. }
  243. }
  244. func emptyTrash() {
  245. let serverUrlFileName = appDelegate.urlBase + "/" + NextcloudKit.shared.nkCommonInstance.dav + "/trashbin/" + appDelegate.userId + "/trash"
  246. NextcloudKit.shared.deleteFileOrFolder(serverUrlFileName: serverUrlFileName) { account, error in
  247. guard error == .success, account == self.appDelegate.account else {
  248. NCContentPresenter.shared.showError(error: error)
  249. return
  250. }
  251. NCManageDatabase.shared.deleteTrash(fileId: nil, account: self.appDelegate.account)
  252. self.reloadDataSource()
  253. }
  254. }
  255. func deleteItem(with fileId: String) {
  256. guard let tableTrash = NCManageDatabase.shared.getTrashItem(fileId: fileId, account: appDelegate.account) else { return }
  257. let serverUrlFileName = tableTrash.filePath + tableTrash.fileName
  258. NextcloudKit.shared.deleteFileOrFolder(serverUrlFileName: serverUrlFileName) { account, error in
  259. guard error == .success, account == self.appDelegate.account else {
  260. NCContentPresenter.shared.showError(error: error)
  261. return
  262. }
  263. NCManageDatabase.shared.deleteTrash(fileId: fileId, account: account)
  264. self.reloadDataSource()
  265. }
  266. }
  267. func downloadThumbnail(with tableTrash: tableTrash, indexPath: IndexPath) {
  268. let fileNamePreviewLocalPath = CCUtility.getDirectoryProviderStoragePreviewOcId(tableTrash.fileId, etag: tableTrash.fileName)!
  269. let fileNameIconLocalPath = CCUtility.getDirectoryProviderStorageIconOcId(tableTrash.fileId, etag: tableTrash.fileName)!
  270. NextcloudKit.shared.downloadPreview(
  271. fileNamePathOrFileId: tableTrash.fileId,
  272. fileNamePreviewLocalPath: fileNamePreviewLocalPath,
  273. widthPreview: NCGlobal.shared.sizePreview,
  274. heightPreview: NCGlobal.shared.sizePreview,
  275. fileNameIconLocalPath: fileNameIconLocalPath,
  276. sizeIcon: NCGlobal.shared.sizeIcon,
  277. etag: nil,
  278. endpointTrashbin: true) { account, _, imageIcon, _, _, error in
  279. guard error == .success, let imageIcon = imageIcon, account == self.appDelegate.account,
  280. let cell = self.collectionView.cellForItem(at: indexPath) else { return }
  281. if let cell = cell as? NCTrashListCell {
  282. cell.imageItem.image = imageIcon
  283. } else if let cell = cell as? NCGridCell {
  284. cell.imageItem.image = imageIcon
  285. } // else: undefined cell
  286. }
  287. }
  288. }