NCTrash.swift 16 KB

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