NCTrash.swift 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  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 Foundation
  24. import NCCommunication
  25. class NCTrash: UIViewController, UIGestureRecognizerDelegate, NCTrashListCellDelegate, NCGridCellDelegate, NCTrashSectionHeaderMenuDelegate, NCEmptyDataSetDelegate {
  26. @IBOutlet weak var collectionView: UICollectionView!
  27. var trashPath = ""
  28. var titleCurrentFolder = NSLocalizedString("_trash_view_", comment: "")
  29. var blinkFileId: String?
  30. var emptyDataSet: NCEmptyDataSet?
  31. internal let appDelegate = UIApplication.shared.delegate as! AppDelegate
  32. internal var isEditMode = false
  33. internal var selectOcId: [String] = []
  34. private var datasource: [tableTrash] = []
  35. private var sort: String = ""
  36. private var ascending: Bool = true
  37. private var directoryOnTop: Bool = true
  38. private var layout = ""
  39. private var groupBy = "none"
  40. private var titleButton = ""
  41. private var itemForLine = 0
  42. private var listLayout: NCListLayout!
  43. private var gridLayout: NCGridLayout!
  44. private let highHeader: CGFloat = 50
  45. private let refreshControl = UIRefreshControl()
  46. required init?(coder aDecoder: NSCoder) {
  47. super.init(coder: aDecoder)
  48. appDelegate.activeTrash = self
  49. }
  50. override func viewDidLoad() {
  51. super.viewDidLoad()
  52. self.navigationController?.navigationBar.prefersLargeTitles = true
  53. // Cell
  54. collectionView.register(UINib.init(nibName: "NCTrashListCell", bundle: nil), forCellWithReuseIdentifier: "listCell")
  55. collectionView.register(UINib.init(nibName: "NCGridCell", bundle: nil), forCellWithReuseIdentifier: "gridCell")
  56. // Header - Footer
  57. collectionView.register(UINib.init(nibName: "NCTrashSectionHeaderMenu", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeaderMenu")
  58. collectionView.register(UINib.init(nibName: "NCTrashSectionFooter", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "sectionFooter")
  59. collectionView.alwaysBounceVertical = true
  60. listLayout = NCListLayout()
  61. gridLayout = NCGridLayout()
  62. // Add Refresh Control
  63. collectionView.addSubview(refreshControl)
  64. refreshControl.tintColor = .gray
  65. refreshControl.addTarget(self, action: #selector(loadListingTrash), for: .valueChanged)
  66. // Empty
  67. emptyDataSet = NCEmptyDataSet.init(view: collectionView, offset: -50, delegate: self)
  68. NotificationCenter.default.addObserver(self, selector: #selector(changeTheming), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterChangeTheming), object: nil)
  69. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSource), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadDataSource), object: nil)
  70. changeTheming()
  71. }
  72. override func viewWillAppear(_ animated: Bool) {
  73. super.viewWillAppear(animated)
  74. appDelegate.activeViewController = self
  75. self.navigationItem.title = titleCurrentFolder
  76. (layout, sort, ascending, groupBy, directoryOnTop, titleButton, itemForLine) = NCUtility.shared.getLayoutForView(key: NCGlobal.shared.layoutViewTrash, serverUrl: "")
  77. gridLayout.itemForLine = CGFloat(itemForLine)
  78. if layout == NCGlobal.shared.layoutList {
  79. collectionView.collectionViewLayout = listLayout
  80. } else {
  81. collectionView.collectionViewLayout = gridLayout
  82. }
  83. if trashPath == "" {
  84. guard let userId = (appDelegate.userId as NSString).addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlFragmentAllowed) else { return }
  85. trashPath = appDelegate.urlBase + "/" + NCUtilityFileSystem.shared.getDAV() + "/trashbin/" + userId + "/trash/"
  86. }
  87. reloadDataSource()
  88. }
  89. override func viewDidAppear(_ animated: Bool) {
  90. super.viewDidAppear(animated)
  91. loadListingTrash()
  92. }
  93. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  94. super.viewWillTransition(to: size, with: coordinator)
  95. coordinator.animate(alongsideTransition: nil) { _ in
  96. self.collectionView?.collectionViewLayout.invalidateLayout()
  97. }
  98. }
  99. @objc func changeTheming() {
  100. view.backgroundColor = NCBrandColor.shared.backgroundView
  101. collectionView.backgroundColor = NCBrandColor.shared.backgroundView
  102. collectionView.reloadData()
  103. }
  104. // MARK: - Empty
  105. func emptyDataSetView(_ view: NCEmptyView) {
  106. view.emptyImage.image = UIImage.init(named: "trash")?.image(color: .gray, size: UIScreen.main.bounds.width)
  107. view.emptyTitle.text = NSLocalizedString("_trash_no_trash_", comment: "")
  108. view.emptyDescription.text = NSLocalizedString("_trash_no_trash_description_", comment: "")
  109. }
  110. // MARK: TAP EVENT
  111. func tapSwitchHeaderMenu(sender: Any) {
  112. if collectionView.collectionViewLayout == gridLayout {
  113. // list layout
  114. UIView.animate(withDuration: 0.0, animations: {
  115. self.collectionView.collectionViewLayout.invalidateLayout()
  116. self.collectionView.setCollectionViewLayout(self.listLayout, animated: false, completion: { (_) in
  117. self.collectionView.reloadData()
  118. })
  119. })
  120. layout = NCGlobal.shared.layoutList
  121. NCUtility.shared.setLayoutForView(key: NCGlobal.shared.layoutViewTrash, serverUrl: "", layout: layout)
  122. } else {
  123. // grid layout
  124. UIView.animate(withDuration: 0.0, animations: {
  125. self.collectionView.collectionViewLayout.invalidateLayout()
  126. self.collectionView.setCollectionViewLayout(self.gridLayout, animated: false, completion: { (_) in
  127. self.collectionView.reloadData()
  128. })
  129. })
  130. layout = NCGlobal.shared.layoutGrid
  131. NCUtility.shared.setLayoutForView(key: NCGlobal.shared.layoutViewTrash, serverUrl: "", layout: layout)
  132. }
  133. }
  134. func tapOrderHeaderMenu(sender: Any) {
  135. let sortMenu = NCSortMenu()
  136. sortMenu.toggleMenu(viewController: self, key: NCGlobal.shared.layoutViewTrash, sortButton: sender as? UIButton, serverUrl: "", hideDirectoryOnTop: true)
  137. }
  138. func tapMoreHeaderMenu(sender: Any) {
  139. toggleMenuMoreHeader()
  140. }
  141. func tapRestoreListItem(with ocId: String, image: UIImage?, sender: Any) {
  142. if !isEditMode {
  143. restoreItem(with: ocId)
  144. } else {
  145. let buttonPosition:CGPoint = (sender as! UIButton).convert(CGPoint.zero, to:collectionView)
  146. let indexPath = collectionView.indexPathForItem(at: buttonPosition)
  147. collectionView(self.collectionView, didSelectItemAt: indexPath!)
  148. }
  149. }
  150. func tapMoreListItem(with objectId: String, image: UIImage?, sender: Any) {
  151. if !isEditMode {
  152. toggleMenuMoreList(with: objectId, image: image)
  153. } else {
  154. let buttonPosition: CGPoint = (sender as! UIButton).convert(CGPoint.zero, to: collectionView)
  155. let indexPath = collectionView.indexPathForItem(at: buttonPosition)
  156. collectionView(self.collectionView, didSelectItemAt: indexPath!)
  157. }
  158. }
  159. func tapMoreGridItem(with objectId: String, namedButtonMore: String, image: UIImage?, sender: Any) {
  160. if !isEditMode {
  161. toggleMenuMoreGrid(with: objectId, namedButtonMore: namedButtonMore, image: image)
  162. } else {
  163. let buttonPosition: CGPoint = (sender as! UIButton).convert(CGPoint.zero, to: collectionView)
  164. let indexPath = collectionView.indexPathForItem(at: buttonPosition)
  165. collectionView(self.collectionView, didSelectItemAt: indexPath!)
  166. }
  167. }
  168. func longPressGridItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) {
  169. }
  170. func longPressMoreGridItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) {
  171. }
  172. }
  173. // MARK: - Collection View
  174. extension NCTrash: UICollectionViewDelegate {
  175. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  176. let tableTrash = datasource[indexPath.item]
  177. if isEditMode {
  178. if let index = selectOcId.firstIndex(of: tableTrash.fileId) {
  179. selectOcId.remove(at: index)
  180. } else {
  181. selectOcId.append(tableTrash.fileId)
  182. }
  183. collectionView.reloadItems(at: [indexPath])
  184. return
  185. }
  186. if tableTrash.directory {
  187. let ncTrash:NCTrash = UIStoryboard(name: "NCTrash", bundle: nil).instantiateInitialViewController() as! NCTrash
  188. ncTrash.trashPath = tableTrash.filePath + tableTrash.fileName
  189. ncTrash.titleCurrentFolder = tableTrash.trashbinFileName
  190. self.navigationController?.pushViewController(ncTrash, animated: true)
  191. }
  192. }
  193. }
  194. extension NCTrash: UICollectionViewDataSource {
  195. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  196. if kind == UICollectionView.elementKindSectionHeader {
  197. let trashHeader = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeaderMenu", for: indexPath) as! NCTrashSectionHeaderMenu
  198. if collectionView.collectionViewLayout == gridLayout {
  199. trashHeader.buttonSwitch.setImage(UIImage.init(named: "switchList")?.image(color: NCBrandColor.shared.icon, size: 25), for: .normal)
  200. } else {
  201. trashHeader.buttonSwitch.setImage(UIImage.init(named: "switchGrid")?.image(color: NCBrandColor.shared.icon, size: 25), for: .normal)
  202. }
  203. trashHeader.delegate = self
  204. trashHeader.backgroundColor = NCBrandColor.shared.backgroundView
  205. trashHeader.separator.backgroundColor = NCBrandColor.shared.separator
  206. trashHeader.setStatusButton(datasource: datasource)
  207. trashHeader.setTitleSorted(datasourceTitleButton: titleButton)
  208. return trashHeader
  209. } else {
  210. let trashFooter = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCTrashSectionFooter
  211. trashFooter.setTitleLabelFooter(datasource: datasource)
  212. return trashFooter
  213. }
  214. }
  215. func numberOfSections(in collectionView: UICollectionView) -> Int {
  216. return 1
  217. }
  218. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  219. emptyDataSet?.numberOfItemsInSection(datasource.count, section: section)
  220. return datasource.count
  221. }
  222. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  223. let tableTrash = datasource[indexPath.item]
  224. var image: UIImage?
  225. if tableTrash.iconName.count > 0 {
  226. image = UIImage.init(named: tableTrash.iconName)
  227. } else {
  228. image = UIImage.init(named: "file")
  229. }
  230. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(tableTrash.fileId, etag: tableTrash.fileName)) {
  231. image = UIImage.init(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(tableTrash.fileId, etag: tableTrash.fileName))
  232. } else {
  233. if tableTrash.hasPreview && !CCUtility.fileProviderStoragePreviewIconExists(tableTrash.fileId, etag: tableTrash.fileName) {
  234. downloadThumbnail(with: tableTrash, indexPath: indexPath)
  235. }
  236. }
  237. if collectionView.collectionViewLayout == listLayout {
  238. // LIST
  239. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCTrashListCell
  240. cell.delegate = self
  241. cell.objectId = tableTrash.fileId
  242. cell.indexPath = indexPath
  243. cell.labelTitle.text = tableTrash.trashbinFileName
  244. cell.labelTitle.textColor = NCBrandColor.shared.textView
  245. cell.separator.backgroundColor = NCBrandColor.shared.separator
  246. if tableTrash.directory {
  247. cell.imageItem.image = NCCollectionCommon.images.folder
  248. cell.labelInfo.text = CCUtility.dateDiff(tableTrash.date as Date)
  249. } else {
  250. cell.imageItem.image = image
  251. cell.labelInfo.text = CCUtility.dateDiff(tableTrash.date as Date) + ", " + CCUtility.transformedSize(tableTrash.size)
  252. }
  253. if isEditMode {
  254. cell.selectMode(true)
  255. if selectOcId.contains(tableTrash.fileId) {
  256. cell.selected(true)
  257. } else {
  258. cell.selected(false)
  259. }
  260. } else {
  261. cell.selectMode(false)
  262. }
  263. return cell
  264. } else {
  265. // GRID
  266. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  267. cell.delegate = self
  268. cell.objectId = tableTrash.fileId
  269. cell.indexPath = indexPath
  270. cell.labelTitle.text = tableTrash.trashbinFileName
  271. cell.labelTitle.textColor = NCBrandColor.shared.textView
  272. if tableTrash.directory {
  273. cell.imageItem.image = NCCollectionCommon.images.folder
  274. } else {
  275. cell.imageItem.image = image
  276. }
  277. if isEditMode {
  278. cell.imageSelect.isHidden = false
  279. if selectOcId.contains(tableTrash.fileId) {
  280. cell.selected(true)
  281. } else {
  282. cell.selected(false)
  283. }
  284. } else {
  285. cell.imageSelect.isHidden = true
  286. cell.backgroundView = nil
  287. }
  288. return cell
  289. }
  290. }
  291. }
  292. extension NCTrash: UICollectionViewDelegateFlowLayout {
  293. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  294. return CGSize(width: collectionView.frame.width, height: highHeader)
  295. }
  296. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  297. return CGSize(width: collectionView.frame.width, height: highHeader)
  298. }
  299. }
  300. // MARK: - NC API & Algorithm
  301. extension NCTrash {
  302. @objc func reloadDataSource() {
  303. (layout, sort, ascending, groupBy, directoryOnTop, titleButton, itemForLine) = NCUtility.shared.getLayoutForView(key: NCGlobal.shared.layoutViewTrash, serverUrl: "")
  304. datasource.removeAll()
  305. guard let tashItems = NCManageDatabase.shared.getTrash(filePath: trashPath, sort: sort, ascending: ascending, account: appDelegate.account) else {
  306. return
  307. }
  308. datasource = tashItems
  309. collectionView.reloadData()
  310. if self.blinkFileId != nil {
  311. for item in 0...self.datasource.count-1 {
  312. if self.datasource[item].fileId.contains(self.blinkFileId!) {
  313. let indexPath = IndexPath(item: item, section: 0)
  314. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
  315. UIView.animate(withDuration: 0.3) {
  316. self.collectionView.scrollToItem(at:indexPath, at: .centeredVertically, animated: false)
  317. } completion: { (_) in
  318. if let cell = self.collectionView.cellForItem(at: indexPath) {
  319. cell.backgroundColor = .darkGray
  320. UIView.animate(withDuration: 2) {
  321. cell.backgroundColor = .clear
  322. self.blinkFileId = nil
  323. }
  324. }
  325. }
  326. }
  327. }
  328. }
  329. }
  330. }
  331. @objc func loadListingTrash() {
  332. NCCommunication.shared.listingTrash(showHiddenFiles: false) { (account, items, errorCode, errorDescription) in
  333. self.refreshControl.endRefreshing()
  334. if errorCode == 0 && account == self.appDelegate.account {
  335. NCManageDatabase.shared.deleteTrash(filePath: self.trashPath, account: self.appDelegate.account)
  336. NCManageDatabase.shared.addTrash(account: account, items: items)
  337. } else if errorCode != 0 {
  338. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
  339. } else {
  340. print("[LOG] It has been changed user during networking process, error.")
  341. }
  342. self.reloadDataSource()
  343. }
  344. }
  345. func restoreItem(with fileId: String) {
  346. guard let tableTrash = NCManageDatabase.shared.getTrashItem(fileId: fileId, account: appDelegate.account) else {
  347. return
  348. }
  349. let fileNameFrom = tableTrash.filePath + tableTrash.fileName
  350. let fileNameTo = appDelegate.urlBase + "/" + NCUtilityFileSystem.shared.getDAV() + "/trashbin/" + appDelegate.userId + "/restore/" + tableTrash.fileName
  351. NCCommunication.shared.moveFileOrFolder(serverUrlFileNameSource: fileNameFrom, serverUrlFileNameDestination: fileNameTo, overwrite: true) { (account, errorCode, errorDescription) in
  352. if errorCode == 0 && account == self.appDelegate.account {
  353. NCManageDatabase.shared.deleteTrash(fileId: fileId, account: account)
  354. self.reloadDataSource()
  355. } else if errorCode != 0 {
  356. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
  357. } else {
  358. print("[LOG] It has been changed user during networking process, error.")
  359. }
  360. }
  361. }
  362. func emptyTrash() {
  363. let serverUrlFileName = appDelegate.urlBase + "/" + NCUtilityFileSystem.shared.getDAV() + "/trashbin/" + appDelegate.userId + "/trash"
  364. NCCommunication.shared.deleteFileOrFolder(serverUrlFileName) { (account, errorCode, errorDescription) in
  365. if errorCode == 0 && account == self.appDelegate.account {
  366. NCManageDatabase.shared.deleteTrash(fileId: nil, account: self.appDelegate.account)
  367. } else if errorCode != 0 {
  368. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
  369. } else {
  370. print("[LOG] It has been changed user during networking process, error.")
  371. }
  372. self.reloadDataSource()
  373. }
  374. }
  375. func deleteItem(with fileId: String) {
  376. guard let tableTrash = NCManageDatabase.shared.getTrashItem(fileId: fileId, account: appDelegate.account) else {
  377. return
  378. }
  379. let serverUrlFileName = tableTrash.filePath + tableTrash.fileName
  380. NCCommunication.shared.deleteFileOrFolder(serverUrlFileName) { (account, errorCode, errorDescription) in
  381. if errorCode == 0 && account == self.appDelegate.account {
  382. NCManageDatabase.shared.deleteTrash(fileId: fileId, account: account)
  383. self.reloadDataSource()
  384. } else if errorCode != 0 {
  385. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
  386. } else {
  387. print("[LOG] It has been changed user during networking process, error.")
  388. }
  389. }
  390. }
  391. func downloadThumbnail(with tableTrash: tableTrash, indexPath: IndexPath) {
  392. let fileNamePreviewLocalPath = CCUtility.getDirectoryProviderStoragePreviewOcId(tableTrash.fileId, etag: tableTrash.fileName)!
  393. let fileNameIconLocalPath = CCUtility.getDirectoryProviderStorageIconOcId(tableTrash.fileId, etag: tableTrash.fileName)!
  394. NCCommunication.shared.downloadPreview(fileNamePathOrFileId: tableTrash.fileId, fileNamePreviewLocalPath: fileNamePreviewLocalPath, widthPreview: NCGlobal.shared.sizePreview, heightPreview: NCGlobal.shared.sizePreview, fileNameIconLocalPath: fileNameIconLocalPath, sizeIcon: NCGlobal.shared.sizeIcon, endpointTrashbin: true) { (account, imagePreview, imageIcon, errorCode, errorDescription) in
  395. if errorCode == 0 && imageIcon != nil && account == self.appDelegate.account {
  396. if let cell = self.collectionView.cellForItem(at: indexPath) {
  397. if cell is NCTrashListCell {
  398. (cell as! NCTrashListCell).imageItem.image = imageIcon
  399. } else if cell is NCGridCell {
  400. (cell as! NCGridCell).imageItem.image = imageIcon
  401. }
  402. }
  403. }
  404. }
  405. }
  406. }