NCTrash.swift 22 KB

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