NCTrash.swift 16 KB

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