NCTrash.swift 23 KB

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