NCTrash.swift 22 KB

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