NCTrash.swift 16 KB

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