NCTrash.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. import UIKit
  24. import NCCommunication
  25. class NCTrash: NCCollectionViewCommon, NCTrashListCellDelegate, NCTrashSectionHeaderMenuDelegate {
  26. var trashPath = ""
  27. var blinkFileId: String?
  28. var datasource: [tableTrash] = []
  29. let highHeader: CGFloat = 50
  30. // MARK: - View Life Cycle
  31. override func viewDidLoad() {
  32. view.backgroundColor = NCBrandColor.shared.systemBackground
  33. self.navigationController?.navigationBar.prefersLargeTitles = true
  34. titleCurrentFolder = titleCurrentFolder.isEmpty ? NSLocalizedString("_trash_view_", comment: "") : titleCurrentFolder
  35. // Cell
  36. collectionView.register(UINib(nibName: "NCTrashListCell", bundle: nil), forCellWithReuseIdentifier: "listCell")
  37. collectionView.register(UINib(nibName: "NCGridCell", bundle: nil), forCellWithReuseIdentifier: "gridCell")
  38. // Header - Footer
  39. collectionView.register(UINib(nibName: "NCTrashSectionHeaderMenu", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeaderMenu")
  40. collectionView.register(UINib(nibName: "NCTrashSectionFooter", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "sectionFooter")
  41. collectionView.alwaysBounceVertical = true
  42. collectionView.backgroundColor = NCBrandColor.shared.systemBackground
  43. listLayout = NCListLayout()
  44. gridLayout = NCGridLayout()
  45. // Add Refresh Control
  46. collectionView.addSubview(refreshControl)
  47. refreshControl.tintColor = .gray
  48. refreshControl.addTarget(self, action: #selector(loadListingTrash), for: .valueChanged)
  49. // Empty
  50. emptyDataSet = NCEmptyDataSet(view: collectionView, offset: highHeader, delegate: self)
  51. NotificationCenter.default.addObserver(self, selector: #selector(changeTheming), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterChangeTheming), object: nil)
  52. NotificationCenter.default.addObserver(self, selector: #selector(reloadTrashDataSource), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadDataSource), object: nil)
  53. changeTheming()
  54. }
  55. override func viewWillAppear(_ animated: Bool) {
  56. appDelegate.activeViewController = self
  57. self.navigationItem.title = titleCurrentFolder
  58. layoutForView = NCUtility.shared.getLayoutForView(key: NCGlobal.shared.layoutViewTrash, serverUrl: "", sort: "date", ascending: false, titleButtonHeader: "_sorted_by_date_more_recent_")
  59. gridLayout.itemForLine = CGFloat(layoutForView?.itemForLine ?? 3)
  60. if layoutForView?.layout == NCGlobal.shared.layoutList {
  61. collectionView.collectionViewLayout = listLayout
  62. } else {
  63. collectionView.collectionViewLayout = gridLayout
  64. }
  65. if trashPath.isEmpty {
  66. guard let userId = (appDelegate.userId as NSString).addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlFragmentAllowed) else { return }
  67. trashPath = appDelegate.urlBase + "/" + NCUtilityFileSystem.shared.getWebDAV(account: appDelegate.account) + "/trashbin/" + userId + "/trash/"
  68. }
  69. setNavigationItem()
  70. reloadDataSource()
  71. }
  72. override func viewDidAppear(_ animated: Bool) {
  73. super.viewDidAppear(animated)
  74. loadListingTrash()
  75. }
  76. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  77. super.viewWillTransition(to: size, with: coordinator)
  78. coordinator.animate(alongsideTransition: nil) { _ in
  79. self.collectionView?.collectionViewLayout.invalidateLayout()
  80. }
  81. }
  82. @objc override func changeTheming() {
  83. collectionView.reloadData()
  84. }
  85. // MARK: - Empty
  86. override func emptyDataSetView(_ view: NCEmptyView) {
  87. view.emptyImage.image = UIImage(named: "trash")?.image(color: .gray, size: UIScreen.main.bounds.width)
  88. view.emptyTitle.text = NSLocalizedString("_trash_no_trash_", comment: "")
  89. view.emptyDescription.text = NSLocalizedString("_trash_no_trash_description_", comment: "")
  90. }
  91. // MARK: TAP EVENT
  92. func tapSwitchHeaderMenu(sender: Any) {
  93. if collectionView.collectionViewLayout == gridLayout {
  94. // list layout
  95. UIView.animate(withDuration: 0.0, animations: {
  96. self.collectionView.collectionViewLayout.invalidateLayout()
  97. self.collectionView.setCollectionViewLayout(self.listLayout, animated: false, completion: { _ in
  98. self.collectionView.reloadData()
  99. })
  100. })
  101. layoutForView?.layout = NCGlobal.shared.layoutList
  102. NCUtility.shared.setLayoutForView(key: NCGlobal.shared.layoutViewTrash, serverUrl: "", layout: layoutForView?.layout)
  103. } else {
  104. // grid layout
  105. UIView.animate(withDuration: 0.0, animations: {
  106. self.collectionView.collectionViewLayout.invalidateLayout()
  107. self.collectionView.setCollectionViewLayout(self.gridLayout, animated: false, completion: { _ in
  108. self.collectionView.reloadData()
  109. })
  110. })
  111. layoutForView?.layout = NCGlobal.shared.layoutGrid
  112. NCUtility.shared.setLayoutForView(key: NCGlobal.shared.layoutViewTrash, serverUrl: "", layout: layoutForView?.layout)
  113. }
  114. }
  115. func tapOrderHeaderMenu(sender: Any) {
  116. let sortMenu = NCSortMenu()
  117. sortMenu.toggleMenu(viewController: self, key: NCGlobal.shared.layoutViewTrash, sortButton: sender as? UIButton, serverUrl: "", hideDirectoryOnTop: true)
  118. }
  119. func tapMoreHeaderMenu(sender: Any) {
  120. toggleMenuMoreHeader()
  121. }
  122. func tapRestoreListItem(with ocId: String, image: UIImage?, sender: Any) {
  123. if !isEditMode {
  124. restoreItem(with: ocId)
  125. } else if let button = sender as? UIView {
  126. let buttonPosition = button.convert(CGPoint.zero, to: collectionView)
  127. let indexPath = collectionView.indexPathForItem(at: buttonPosition)
  128. collectionView(self.collectionView, didSelectItemAt: indexPath!)
  129. } // else: undefined sender
  130. }
  131. func tapMoreListItem(with objectId: String, image: UIImage?, sender: Any) {
  132. if !isEditMode {
  133. toggleMenuMoreList(with: objectId, image: image)
  134. } else if let button = sender as? UIView {
  135. let buttonPosition = button.convert(CGPoint.zero, to: collectionView)
  136. let indexPath = collectionView.indexPathForItem(at: buttonPosition)
  137. collectionView(self.collectionView, didSelectItemAt: indexPath!)
  138. } // else: undefined sender
  139. }
  140. override func tapMoreGridItem(with objectId: String, namedButtonMore: String, image: UIImage?, sender: Any) {
  141. if !isEditMode {
  142. toggleMenuMoreGrid(with: objectId, namedButtonMore: namedButtonMore, image: image)
  143. } else if let button = sender as? UIView {
  144. let buttonPosition = button.convert(CGPoint.zero, to: collectionView)
  145. let indexPath = collectionView.indexPathForItem(at: buttonPosition)
  146. collectionView(self.collectionView, didSelectItemAt: indexPath!)
  147. } // else: undefined sender
  148. }
  149. override func longPressGridItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) {
  150. }
  151. override func longPressMoreGridItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) {
  152. }
  153. override func collectionViewSelectAll() {
  154. selectOcId = datasource.map({ $0.fileId })
  155. navigationItem.title = NSLocalizedString("_selected_", comment: "") + " : \(selectOcId.count)" + " / \(datasource.count)"
  156. collectionView.reloadData()
  157. }
  158. @objc func reloadTrashDataSource() { self.reloadDataSource() }
  159. @objc override func reloadDataSource() {
  160. layoutForView = NCUtility.shared.getLayoutForView(key: NCGlobal.shared.layoutViewTrash, serverUrl: "")
  161. datasource.removeAll()
  162. guard let tashItems = NCManageDatabase.shared.getTrash(filePath: trashPath, sort: layoutForView?.sort, ascending: layoutForView?.ascending, account: appDelegate.account) else {
  163. return
  164. }
  165. datasource = tashItems
  166. collectionView.reloadData()
  167. guard let blinkFileId = blinkFileId else { return }
  168. for itemIx in 0..<self.datasource.count where self.datasource[itemIx].fileId.contains(blinkFileId) {
  169. let indexPath = IndexPath(item: itemIx, section: 0)
  170. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
  171. UIView.animate(withDuration: 0.3) {
  172. self.collectionView.scrollToItem(at: indexPath, at: .centeredVertically, animated: false)
  173. } completion: { _ in
  174. guard let cell = self.collectionView.cellForItem(at: indexPath) else { return }
  175. cell.backgroundColor = .darkGray
  176. UIView.animate(withDuration: 2) {
  177. cell.backgroundColor = .clear
  178. self.blinkFileId = nil
  179. }
  180. }
  181. }
  182. }
  183. }
  184. }
  185. // MARK: - NC API & Algorithm
  186. extension NCTrash {
  187. @objc func loadListingTrash() {
  188. NCCommunication.shared.listingTrash(showHiddenFiles: false, queue: NCCommunicationCommon.shared.backgroundQueue) { account, items, errorCode, errorDescription in
  189. if errorCode == 0 && account == self.appDelegate.account {
  190. NCManageDatabase.shared.deleteTrash(filePath: self.trashPath, account: self.appDelegate.account)
  191. NCManageDatabase.shared.addTrash(account: account, items: items)
  192. } else if errorCode != 0 {
  193. NCContentPresenter.shared.showError(description: errorDescription, errorCode: errorCode)
  194. } else {
  195. print("[LOG] It has been changed user during networking process, error.")
  196. }
  197. DispatchQueue.main.async {
  198. self.refreshControl.endRefreshing()
  199. self.reloadDataSource()
  200. }
  201. }
  202. }
  203. func restoreItem(with fileId: String) {
  204. guard let tableTrash = NCManageDatabase.shared.getTrashItem(fileId: fileId, account: appDelegate.account) else {
  205. return
  206. }
  207. let fileNameFrom = tableTrash.filePath + tableTrash.fileName
  208. let fileNameTo = appDelegate.urlBase + "/" + NCUtilityFileSystem.shared.getWebDAV(account: appDelegate.account) + "/trashbin/" + appDelegate.userId + "/restore/" + tableTrash.fileName
  209. NCCommunication.shared.moveFileOrFolder(serverUrlFileNameSource: fileNameFrom, serverUrlFileNameDestination: fileNameTo, overwrite: true) { account, errorCode, errorDescription in
  210. if errorCode == 0 && account == self.appDelegate.account {
  211. NCManageDatabase.shared.deleteTrash(fileId: fileId, account: account)
  212. self.reloadDataSource()
  213. } else if errorCode != 0 {
  214. NCContentPresenter.shared.showError(description: errorDescription, errorCode: errorCode)
  215. } else {
  216. print("[LOG] It has been changed user during networking process, error.")
  217. }
  218. }
  219. }
  220. func emptyTrash() {
  221. let serverUrlFileName = appDelegate.urlBase + "/" + NCUtilityFileSystem.shared.getWebDAV(account: appDelegate.account) + "/trashbin/" + appDelegate.userId + "/trash"
  222. NCCommunication.shared.deleteFileOrFolder(serverUrlFileName) { account, errorCode, errorDescription in
  223. if errorCode == 0 && account == self.appDelegate.account {
  224. NCManageDatabase.shared.deleteTrash(fileId: nil, account: self.appDelegate.account)
  225. } else if errorCode != 0 {
  226. NCContentPresenter.shared.showError(description: errorDescription, errorCode: errorCode)
  227. } else {
  228. print("[LOG] It has been changed user during networking process, error.")
  229. }
  230. self.reloadDataSource()
  231. }
  232. }
  233. func deleteItem(with fileId: String) {
  234. guard let tableTrash = NCManageDatabase.shared.getTrashItem(fileId: fileId, account: appDelegate.account) else {
  235. return
  236. }
  237. let serverUrlFileName = tableTrash.filePath + tableTrash.fileName
  238. NCCommunication.shared.deleteFileOrFolder(serverUrlFileName) { account, errorCode, errorDescription in
  239. if errorCode == 0 && account == self.appDelegate.account {
  240. NCManageDatabase.shared.deleteTrash(fileId: fileId, account: account)
  241. self.reloadDataSource()
  242. } else if errorCode != 0 {
  243. NCContentPresenter.shared.showError(description: errorDescription, errorCode: errorCode)
  244. } else {
  245. print("[LOG] It has been changed user during networking process, error.")
  246. }
  247. }
  248. }
  249. func downloadThumbnail(with tableTrash: tableTrash, indexPath: IndexPath) {
  250. let fileNamePreviewLocalPath = CCUtility.getDirectoryProviderStoragePreviewOcId(tableTrash.fileId, etag: tableTrash.fileName)!
  251. let fileNameIconLocalPath = CCUtility.getDirectoryProviderStorageIconOcId(tableTrash.fileId, etag: tableTrash.fileName)!
  252. NCCommunication.shared.downloadPreview(
  253. fileNamePathOrFileId: tableTrash.fileId,
  254. fileNamePreviewLocalPath: fileNamePreviewLocalPath,
  255. widthPreview: NCGlobal.shared.sizePreview,
  256. heightPreview: NCGlobal.shared.sizePreview,
  257. fileNameIconLocalPath: fileNameIconLocalPath,
  258. sizeIcon: NCGlobal.shared.sizeIcon,
  259. etag: nil,
  260. endpointTrashbin: true) { account, _, imageIcon, _, _, errorCode, _ in
  261. guard errorCode == 0, let imageIcon = imageIcon, account == self.appDelegate.account,
  262. let cell = self.collectionView.cellForItem(at: indexPath) else { return }
  263. if let cell = cell as? NCTrashListCell {
  264. cell.imageItem.image = imageIcon
  265. } else if let cell = cell as? NCGridCell {
  266. cell.imageItem.image = imageIcon
  267. } // else: undefined cell
  268. }
  269. }
  270. }