NCTrash.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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, NCTrashSectionHeaderMenuDelegate, NCEmptyDataSetDelegate {
  29. var selectableDataSource: [RealmSwiftObject] { datasource }
  30. @IBOutlet weak var collectionView: UICollectionView!
  31. var trashPath = ""
  32. var titleCurrentFolder = NSLocalizedString("_trash_view_", comment: "")
  33. var blinkFileId: String?
  34. var emptyDataSet: NCEmptyDataSet?
  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. let highHeader: CGFloat = 50
  43. private let refreshControl = UIRefreshControl()
  44. // MARK: - View Life Cycle
  45. override func viewDidLoad() {
  46. view.backgroundColor = NCBrandColor.shared.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: "NCTrashSectionHeaderMenu", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeaderMenu")
  53. collectionView.register(UINib(nibName: "NCTrashSectionFooter", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "sectionFooter")
  54. collectionView.alwaysBounceVertical = true
  55. collectionView.backgroundColor = NCBrandColor.shared.systemBackground
  56. listLayout = NCListLayout()
  57. gridLayout = NCGridLayout()
  58. // Add Refresh Control
  59. collectionView.addSubview(refreshControl)
  60. refreshControl.tintColor = .gray
  61. refreshControl.addTarget(self, action: #selector(loadListingTrash), for: .valueChanged)
  62. // Empty
  63. emptyDataSet = NCEmptyDataSet(view: collectionView, offset: highHeader, delegate: self)
  64. NotificationCenter.default.addObserver(self, selector: #selector(changeTheming), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterChangeTheming), object: nil)
  65. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSource), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadDataSource), object: nil)
  66. changeTheming()
  67. }
  68. override func viewWillAppear(_ animated: Bool) {
  69. appDelegate.activeViewController = self
  70. self.navigationItem.title = titleCurrentFolder
  71. layoutForView = NCUtility.shared.getLayoutForView(key: NCGlobal.shared.layoutViewTrash, serverUrl: "", sort: "date", ascending: false, titleButtonHeader: "_sorted_by_date_more_recent_")
  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. if trashPath.isEmpty {
  79. guard let userId = (appDelegate.userId as NSString).addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlFragmentAllowed) else { return }
  80. trashPath = appDelegate.urlBase + "/" + NCUtilityFileSystem.shared.getWebDAV(account: appDelegate.account) + "/trashbin/" + userId + "/trash/"
  81. }
  82. setNavigationItem()
  83. reloadDataSource()
  84. }
  85. override func viewDidAppear(_ animated: Bool) {
  86. super.viewDidAppear(animated)
  87. loadListingTrash()
  88. }
  89. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  90. super.viewWillTransition(to: size, with: coordinator)
  91. coordinator.animate(alongsideTransition: nil) { _ in
  92. self.collectionView?.collectionViewLayout.invalidateLayout()
  93. }
  94. }
  95. @objc func changeTheming() {
  96. collectionView.reloadData()
  97. }
  98. // MARK: - Empty
  99. func emptyDataSetView(_ view: NCEmptyView) {
  100. view.emptyImage.image = UIImage(named: "trash")?.image(color: .gray, size: UIScreen.main.bounds.width)
  101. view.emptyTitle.text = NSLocalizedString("_trash_no_trash_", comment: "")
  102. view.emptyDescription.text = NSLocalizedString("_trash_no_trash_description_", comment: "")
  103. }
  104. // MARK: TAP EVENT
  105. func tapSwitchHeaderMenu(sender: Any) {
  106. if collectionView.collectionViewLayout == gridLayout {
  107. // list layout
  108. UIView.animate(withDuration: 0.0, animations: {
  109. self.collectionView.collectionViewLayout.invalidateLayout()
  110. self.collectionView.setCollectionViewLayout(self.listLayout, animated: false, completion: { _ in
  111. self.collectionView.reloadData()
  112. })
  113. })
  114. layoutForView?.layout = NCGlobal.shared.layoutList
  115. NCUtility.shared.setLayoutForView(key: NCGlobal.shared.layoutViewTrash, serverUrl: "", layout: layoutForView?.layout)
  116. } else {
  117. // grid layout
  118. UIView.animate(withDuration: 0.0, animations: {
  119. self.collectionView.collectionViewLayout.invalidateLayout()
  120. self.collectionView.setCollectionViewLayout(self.gridLayout, animated: false, completion: { _ in
  121. self.collectionView.reloadData()
  122. })
  123. })
  124. layoutForView?.layout = NCGlobal.shared.layoutGrid
  125. NCUtility.shared.setLayoutForView(key: NCGlobal.shared.layoutViewTrash, serverUrl: "", layout: layoutForView?.layout)
  126. }
  127. }
  128. func tapOrderHeaderMenu(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 tapMoreHeaderMenu(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. toggleMenuMoreList(with: objectId, image: image)
  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. toggleMenuMoreGrid(with: objectId, namedButtonMore: namedButtonMore, image: image)
  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. } // else: undefined sender
  161. }
  162. func longPressGridItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) { }
  163. func longPressMoreGridItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) { }
  164. @objc func reloadDataSource() {
  165. layoutForView = NCUtility.shared.getLayoutForView(key: NCGlobal.shared.layoutViewTrash, serverUrl: "")
  166. datasource.removeAll()
  167. guard let tashItems = NCManageDatabase.shared.getTrash(filePath: trashPath, sort: layoutForView?.sort, ascending: layoutForView?.ascending, account: appDelegate.account) else {
  168. return
  169. }
  170. datasource = tashItems
  171. collectionView.reloadData()
  172. guard let blinkFileId = blinkFileId else { return }
  173. for itemIx in 0..<self.datasource.count where self.datasource[itemIx].fileId.contains(blinkFileId) {
  174. let indexPath = IndexPath(item: itemIx, section: 0)
  175. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
  176. UIView.animate(withDuration: 0.3) {
  177. self.collectionView.scrollToItem(at: indexPath, at: .centeredVertically, animated: false)
  178. } completion: { _ in
  179. guard let cell = self.collectionView.cellForItem(at: indexPath) else { return }
  180. cell.backgroundColor = .darkGray
  181. UIView.animate(withDuration: 2) {
  182. cell.backgroundColor = .clear
  183. self.blinkFileId = nil
  184. }
  185. }
  186. }
  187. }
  188. }
  189. }
  190. // MARK: - NC API & Algorithm
  191. extension NCTrash {
  192. @objc func loadListingTrash() {
  193. NCCommunication.shared.listingTrash(showHiddenFiles: false, queue: NCCommunicationCommon.shared.backgroundQueue) { account, items, errorCode, errorDescription in
  194. if errorCode == 0 && account == self.appDelegate.account {
  195. NCManageDatabase.shared.deleteTrash(filePath: self.trashPath, account: self.appDelegate.account)
  196. NCManageDatabase.shared.addTrash(account: account, items: items)
  197. } else if errorCode != 0 {
  198. NCContentPresenter.shared.showError(description: errorDescription, errorCode: errorCode)
  199. } else {
  200. print("[LOG] It has been changed user during networking process, error.")
  201. }
  202. DispatchQueue.main.async {
  203. self.refreshControl.endRefreshing()
  204. self.reloadDataSource()
  205. }
  206. }
  207. }
  208. func restoreItem(with fileId: String) {
  209. guard let tableTrash = NCManageDatabase.shared.getTrashItem(fileId: fileId, account: appDelegate.account) else {
  210. return
  211. }
  212. let fileNameFrom = tableTrash.filePath + tableTrash.fileName
  213. let fileNameTo = appDelegate.urlBase + "/" + NCUtilityFileSystem.shared.getWebDAV(account: appDelegate.account) + "/trashbin/" + appDelegate.userId + "/restore/" + tableTrash.fileName
  214. NCCommunication.shared.moveFileOrFolder(serverUrlFileNameSource: fileNameFrom, serverUrlFileNameDestination: fileNameTo, overwrite: true) { account, errorCode, errorDescription in
  215. if errorCode == 0 && account == self.appDelegate.account {
  216. NCManageDatabase.shared.deleteTrash(fileId: fileId, account: account)
  217. self.reloadDataSource()
  218. } else if errorCode != 0 {
  219. NCContentPresenter.shared.showError(description: errorDescription, errorCode: errorCode)
  220. } else {
  221. print("[LOG] It has been changed user during networking process, error.")
  222. }
  223. }
  224. }
  225. func emptyTrash() {
  226. let serverUrlFileName = appDelegate.urlBase + "/" + NCUtilityFileSystem.shared.getWebDAV(account: appDelegate.account) + "/trashbin/" + appDelegate.userId + "/trash"
  227. NCCommunication.shared.deleteFileOrFolder(serverUrlFileName) { account, errorCode, errorDescription in
  228. if errorCode == 0 && account == self.appDelegate.account {
  229. NCManageDatabase.shared.deleteTrash(fileId: nil, account: self.appDelegate.account)
  230. } else if errorCode != 0 {
  231. NCContentPresenter.shared.showError(description: errorDescription, errorCode: errorCode)
  232. } else {
  233. print("[LOG] It has been changed user during networking process, error.")
  234. }
  235. self.reloadDataSource()
  236. }
  237. }
  238. func deleteItem(with fileId: String) {
  239. guard let tableTrash = NCManageDatabase.shared.getTrashItem(fileId: fileId, account: appDelegate.account) else {
  240. return
  241. }
  242. let serverUrlFileName = tableTrash.filePath + tableTrash.fileName
  243. NCCommunication.shared.deleteFileOrFolder(serverUrlFileName) { account, errorCode, errorDescription in
  244. if errorCode == 0 && account == self.appDelegate.account {
  245. NCManageDatabase.shared.deleteTrash(fileId: fileId, account: account)
  246. self.reloadDataSource()
  247. } else if errorCode != 0 {
  248. NCContentPresenter.shared.showError(description: errorDescription, errorCode: errorCode)
  249. } else {
  250. print("[LOG] It has been changed user during networking process, error.")
  251. }
  252. }
  253. }
  254. func downloadThumbnail(with tableTrash: tableTrash, indexPath: IndexPath) {
  255. let fileNamePreviewLocalPath = CCUtility.getDirectoryProviderStoragePreviewOcId(tableTrash.fileId, etag: tableTrash.fileName)!
  256. let fileNameIconLocalPath = CCUtility.getDirectoryProviderStorageIconOcId(tableTrash.fileId, etag: tableTrash.fileName)!
  257. NCCommunication.shared.downloadPreview(
  258. fileNamePathOrFileId: tableTrash.fileId,
  259. fileNamePreviewLocalPath: fileNamePreviewLocalPath,
  260. widthPreview: NCGlobal.shared.sizePreview,
  261. heightPreview: NCGlobal.shared.sizePreview,
  262. fileNameIconLocalPath: fileNameIconLocalPath,
  263. sizeIcon: NCGlobal.shared.sizeIcon,
  264. etag: nil,
  265. endpointTrashbin: true) { account, _, imageIcon, _, _, errorCode, _ in
  266. guard errorCode == 0, let imageIcon = imageIcon, account == self.appDelegate.account,
  267. let cell = self.collectionView.cellForItem(at: indexPath) else { return }
  268. if let cell = cell as? NCTrashListCell {
  269. cell.imageItem.image = imageIcon
  270. } else if let cell = cell as? NCGridCell {
  271. cell.imageItem.image = imageIcon
  272. } // else: undefined cell
  273. }
  274. }
  275. }