NCTrash.swift 17 KB

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