NCTrash.swift 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  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. private 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 == "" {
  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 {
  126. let buttonPosition: CGPoint = (sender as! UIButton).convert(CGPoint.zero, to: collectionView)
  127. let indexPath = collectionView.indexPathForItem(at: buttonPosition)
  128. collectionView(self.collectionView, didSelectItemAt: indexPath!)
  129. }
  130. }
  131. func tapMoreListItem(with objectId: String, image: UIImage?, sender: Any) {
  132. if !isEditMode {
  133. toggleMenuMoreList(with: objectId, image: image)
  134. } else {
  135. let buttonPosition: CGPoint = (sender as! UIButton).convert(CGPoint.zero, to: collectionView)
  136. let indexPath = collectionView.indexPathForItem(at: buttonPosition)
  137. collectionView(self.collectionView, didSelectItemAt: indexPath!)
  138. }
  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 {
  144. let buttonPosition: CGPoint = (sender as! UIButton).convert(CGPoint.zero, to: collectionView)
  145. let indexPath = collectionView.indexPathForItem(at: buttonPosition)
  146. collectionView(self.collectionView, didSelectItemAt: indexPath!)
  147. }
  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. if self.blinkFileId != nil {
  168. for item in 0...self.datasource.count-1 {
  169. if self.datasource[item].fileId.contains(self.blinkFileId!) {
  170. let indexPath = IndexPath(item: item, section: 0)
  171. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
  172. UIView.animate(withDuration: 0.3) {
  173. self.collectionView.scrollToItem(at: indexPath, at: .centeredVertically, animated: false)
  174. } completion: { _ in
  175. if let cell = self.collectionView.cellForItem(at: indexPath) {
  176. cell.backgroundColor = .darkGray
  177. UIView.animate(withDuration: 2) {
  178. cell.backgroundColor = .clear
  179. self.blinkFileId = nil
  180. }
  181. }
  182. }
  183. }
  184. }
  185. }
  186. }
  187. }
  188. }
  189. // MARK: - Collection View
  190. extension NCTrash {
  191. override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  192. let tableTrash = datasource[indexPath.item]
  193. guard !isEditMode else {
  194. if let index = selectOcId.firstIndex(of: tableTrash.fileId) {
  195. selectOcId.remove(at: index)
  196. } else {
  197. selectOcId.append(tableTrash.fileId)
  198. }
  199. collectionView.reloadItems(at: [indexPath])
  200. self.navigationItem.title = NSLocalizedString("_selected_", comment: "") + " : \(selectOcId.count)" + " / \(datasource.count)"
  201. return
  202. }
  203. if tableTrash.directory {
  204. let ncTrash: NCTrash = UIStoryboard(name: "NCTrash", bundle: nil).instantiateInitialViewController() as! NCTrash
  205. ncTrash.trashPath = tableTrash.filePath + tableTrash.fileName
  206. ncTrash.titleCurrentFolder = tableTrash.trashbinFileName
  207. self.navigationController?.pushViewController(ncTrash, animated: true)
  208. }
  209. }
  210. }
  211. extension NCTrash {
  212. override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  213. if kind == UICollectionView.elementKindSectionHeader {
  214. let trashHeader = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeaderMenu", for: indexPath) as! NCTrashSectionHeaderMenu
  215. if collectionView.collectionViewLayout == gridLayout {
  216. trashHeader.buttonSwitch.setImage(UIImage(named: "switchList")?.image(color: NCBrandColor.shared.gray, size: 25), for: .normal)
  217. } else {
  218. trashHeader.buttonSwitch.setImage(UIImage(named: "switchGrid")?.image(color: NCBrandColor.shared.gray, size: 25), for: .normal)
  219. }
  220. trashHeader.delegate = self
  221. trashHeader.backgroundColor = NCBrandColor.shared.systemBackground
  222. trashHeader.separator.backgroundColor = NCBrandColor.shared.separator
  223. trashHeader.setStatusButton(datasource: datasource)
  224. trashHeader.setTitleSorted(datasourceTitleButton: layoutForView?.titleButtonHeader ?? "")
  225. return trashHeader
  226. } else {
  227. let trashFooter = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCTrashSectionFooter
  228. trashFooter.setTitleLabelFooter(datasource: datasource)
  229. return trashFooter
  230. }
  231. }
  232. override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  233. emptyDataSet?.numberOfItemsInSection(datasource.count, section: section)
  234. return datasource.count
  235. }
  236. override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  237. let tableTrash = datasource[indexPath.item]
  238. var image: UIImage?
  239. if tableTrash.iconName.count > 0 {
  240. image = UIImage(named: tableTrash.iconName)
  241. } else {
  242. image = UIImage(named: "file")
  243. }
  244. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(tableTrash.fileId, etag: tableTrash.fileName)) {
  245. image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(tableTrash.fileId, etag: tableTrash.fileName))
  246. } else {
  247. if tableTrash.hasPreview && !CCUtility.fileProviderStoragePreviewIconExists(tableTrash.fileId, etag: tableTrash.fileName) {
  248. downloadThumbnail(with: tableTrash, indexPath: indexPath)
  249. }
  250. }
  251. if collectionView.collectionViewLayout == listLayout {
  252. // LIST
  253. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCTrashListCell
  254. cell.delegate = self
  255. cell.objectId = tableTrash.fileId
  256. cell.labelTitle.text = tableTrash.trashbinFileName
  257. cell.labelTitle.textColor = NCBrandColor.shared.label
  258. if tableTrash.directory {
  259. cell.imageItem.image = NCBrandColor.cacheImages.folder
  260. cell.labelInfo.text = CCUtility.dateDiff(tableTrash.date as Date)
  261. } else {
  262. cell.imageItem.image = image
  263. cell.labelInfo.text = CCUtility.dateDiff(tableTrash.date as Date) + ", " + CCUtility.transformedSize(tableTrash.size)
  264. }
  265. if isEditMode {
  266. cell.selectMode(true)
  267. if selectOcId.contains(tableTrash.fileId) {
  268. cell.selected(true)
  269. } else {
  270. cell.selected(false)
  271. }
  272. } else {
  273. cell.selectMode(false)
  274. }
  275. return cell
  276. } else {
  277. // GRID
  278. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  279. cell.delegate = self
  280. cell.fileObjectId = tableTrash.fileId
  281. cell.labelTitle.text = tableTrash.trashbinFileName
  282. cell.labelTitle.textColor = NCBrandColor.shared.label
  283. cell.setButtonMore(named: NCGlobal.shared.buttonMoreMore, image: NCBrandColor.cacheImages.buttonMore)
  284. if tableTrash.directory {
  285. cell.imageItem.image = NCBrandColor.cacheImages.folder
  286. } else {
  287. cell.imageItem.image = image
  288. }
  289. if isEditMode {
  290. cell.imageSelect.isHidden = false
  291. if selectOcId.contains(tableTrash.fileId) {
  292. cell.selected(true)
  293. } else {
  294. cell.selected(false)
  295. }
  296. } else {
  297. cell.imageSelect.isHidden = true
  298. cell.backgroundView = nil
  299. }
  300. return cell
  301. }
  302. }
  303. }
  304. extension NCTrash {
  305. override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  306. return CGSize(width: collectionView.frame.width, height: highHeader)
  307. }
  308. override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  309. return CGSize(width: collectionView.frame.width, height: highHeader)
  310. }
  311. }
  312. // MARK: - NC API & Algorithm
  313. extension NCTrash {
  314. @objc func loadListingTrash() {
  315. NCCommunication.shared.listingTrash(showHiddenFiles: false, queue: NCCommunicationCommon.shared.backgroundQueue) { account, items, errorCode, errorDescription in
  316. if errorCode == 0 && account == self.appDelegate.account {
  317. NCManageDatabase.shared.deleteTrash(filePath: self.trashPath, account: self.appDelegate.account)
  318. NCManageDatabase.shared.addTrash(account: account, items: items)
  319. } else if errorCode != 0 {
  320. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
  321. } else {
  322. print("[LOG] It has been changed user during networking process, error.")
  323. }
  324. DispatchQueue.main.async {
  325. self.refreshControl.endRefreshing()
  326. self.reloadDataSource()
  327. }
  328. }
  329. }
  330. func restoreItem(with fileId: String) {
  331. guard let tableTrash = NCManageDatabase.shared.getTrashItem(fileId: fileId, account: appDelegate.account) else {
  332. return
  333. }
  334. let fileNameFrom = tableTrash.filePath + tableTrash.fileName
  335. let fileNameTo = appDelegate.urlBase + "/" + NCUtilityFileSystem.shared.getWebDAV(account: appDelegate.account) + "/trashbin/" + appDelegate.userId + "/restore/" + tableTrash.fileName
  336. NCCommunication.shared.moveFileOrFolder(serverUrlFileNameSource: fileNameFrom, serverUrlFileNameDestination: fileNameTo, overwrite: true) { account, errorCode, errorDescription in
  337. if errorCode == 0 && account == self.appDelegate.account {
  338. NCManageDatabase.shared.deleteTrash(fileId: fileId, account: account)
  339. self.reloadDataSource()
  340. } else if errorCode != 0 {
  341. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
  342. } else {
  343. print("[LOG] It has been changed user during networking process, error.")
  344. }
  345. }
  346. }
  347. func emptyTrash() {
  348. let serverUrlFileName = appDelegate.urlBase + "/" + NCUtilityFileSystem.shared.getWebDAV(account: appDelegate.account) + "/trashbin/" + appDelegate.userId + "/trash"
  349. NCCommunication.shared.deleteFileOrFolder(serverUrlFileName) { account, errorCode, errorDescription in
  350. if errorCode == 0 && account == self.appDelegate.account {
  351. NCManageDatabase.shared.deleteTrash(fileId: nil, account: self.appDelegate.account)
  352. } else if errorCode != 0 {
  353. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
  354. } else {
  355. print("[LOG] It has been changed user during networking process, error.")
  356. }
  357. self.reloadDataSource()
  358. }
  359. }
  360. func deleteItem(with fileId: String) {
  361. guard let tableTrash = NCManageDatabase.shared.getTrashItem(fileId: fileId, account: appDelegate.account) else {
  362. return
  363. }
  364. let serverUrlFileName = tableTrash.filePath + tableTrash.fileName
  365. NCCommunication.shared.deleteFileOrFolder(serverUrlFileName) { account, errorCode, errorDescription in
  366. if errorCode == 0 && account == self.appDelegate.account {
  367. NCManageDatabase.shared.deleteTrash(fileId: fileId, account: account)
  368. self.reloadDataSource()
  369. } else if errorCode != 0 {
  370. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
  371. } else {
  372. print("[LOG] It has been changed user during networking process, error.")
  373. }
  374. }
  375. }
  376. func downloadThumbnail(with tableTrash: tableTrash, indexPath: IndexPath) {
  377. let fileNamePreviewLocalPath = CCUtility.getDirectoryProviderStoragePreviewOcId(tableTrash.fileId, etag: tableTrash.fileName)!
  378. let fileNameIconLocalPath = CCUtility.getDirectoryProviderStorageIconOcId(tableTrash.fileId, etag: tableTrash.fileName)!
  379. NCCommunication.shared.downloadPreview(fileNamePathOrFileId: tableTrash.fileId, fileNamePreviewLocalPath: fileNamePreviewLocalPath, widthPreview: NCGlobal.shared.sizePreview, heightPreview: NCGlobal.shared.sizePreview, fileNameIconLocalPath: fileNameIconLocalPath, sizeIcon: NCGlobal.shared.sizeIcon, etag: nil, endpointTrashbin: true) { account, _, imageIcon, _, _, errorCode, _ in
  380. if errorCode == 0 && imageIcon != nil && account == self.appDelegate.account {
  381. if let cell = self.collectionView.cellForItem(at: indexPath) {
  382. if cell is NCTrashListCell {
  383. (cell as! NCTrashListCell).imageItem.image = imageIcon
  384. } else if cell is NCGridCell {
  385. (cell as! NCGridCell).imageItem.image = imageIcon
  386. }
  387. }
  388. }
  389. }
  390. }
  391. }