NCTrash.swift 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779
  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 Sheeeeeeeeet
  25. class NCTrash: UIViewController, UIGestureRecognizerDelegate, NCTrashListCellDelegate, NCGridCellDelegate, NCTrashSectionHeaderMenuDelegate, DropdownMenuDelegate, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate {
  26. @IBOutlet fileprivate weak var collectionView: UICollectionView!
  27. var serverUrl = ""
  28. var titleCurrentFolder = NSLocalizedString("_trash_view_", comment: "")
  29. var scrollToFileID = ""
  30. var scrollToIndexPath: IndexPath?
  31. private let appDelegate = UIApplication.shared.delegate as! AppDelegate
  32. private var isEditMode = false
  33. private var selectFileID = [String]()
  34. private var datasource = [tableTrash]()
  35. private var typeLayout = ""
  36. private var datasourceSorted = ""
  37. private var datasourceAscending = true
  38. private var datasourceGroupBy = "none"
  39. private var datasourceDirectoryOnTop = false
  40. private var listLayout: NCListLayout!
  41. private var gridLayout: NCGridLayout!
  42. private var actionSheet: ActionSheet?
  43. private let highHeader: CGFloat = 50
  44. private let refreshControl = UIRefreshControl()
  45. override func viewDidLoad() {
  46. super.viewDidLoad()
  47. // Cell
  48. collectionView.register(UINib.init(nibName: "NCTrashListCell", bundle: nil), forCellWithReuseIdentifier: "listCell")
  49. collectionView.register(UINib.init(nibName: "NCGridCell", bundle: nil), forCellWithReuseIdentifier: "gridCell")
  50. // Header - Footer
  51. collectionView.register(UINib.init(nibName: "NCTrashSectionHeaderMenu", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeaderMenu")
  52. collectionView.register(UINib.init(nibName: "NCTrashSectionFooter", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "sectionFooter")
  53. collectionView.alwaysBounceVertical = true
  54. listLayout = NCListLayout()
  55. gridLayout = NCGridLayout()
  56. // Add Refresh Control
  57. collectionView.refreshControl = refreshControl
  58. // Configure Refresh Control
  59. refreshControl.tintColor = NCBrandColor.sharedInstance.brandText
  60. refreshControl.backgroundColor = NCBrandColor.sharedInstance.brand
  61. refreshControl.addTarget(self, action: #selector(loadListingTrash), for: .valueChanged)
  62. // empty Data Source
  63. self.collectionView.emptyDataSetDelegate = self;
  64. self.collectionView.emptyDataSetSource = self;
  65. }
  66. override func viewWillAppear(_ animated: Bool) {
  67. super.viewWillAppear(animated)
  68. // Color
  69. appDelegate.aspectNavigationControllerBar(self.navigationController?.navigationBar, online: appDelegate.reachability.isReachable(), hidden: false)
  70. appDelegate.aspectTabBar(self.tabBarController?.tabBar, hidden: false)
  71. self.navigationItem.title = titleCurrentFolder
  72. (typeLayout, datasourceSorted, datasourceAscending, datasourceGroupBy, datasourceDirectoryOnTop) = NCUtility.sharedInstance.getLayoutForView(key: k_layout_view_trash)
  73. if typeLayout == k_layout_list {
  74. collectionView.collectionViewLayout = listLayout
  75. } else {
  76. collectionView.collectionViewLayout = gridLayout
  77. }
  78. loadListingTrash()
  79. }
  80. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  81. super.viewWillTransition(to: size, with: coordinator)
  82. coordinator.animate(alongsideTransition: nil) { _ in
  83. self.collectionView.collectionViewLayout.invalidateLayout()
  84. self.actionSheet?.viewDidLayoutSubviews()
  85. }
  86. }
  87. // MARK: DZNEmpty
  88. func backgroundColor(forEmptyDataSet scrollView: UIScrollView) -> UIColor? {
  89. return NCBrandColor.sharedInstance.backgroundView
  90. }
  91. func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
  92. return CCGraphics.changeThemingColorImage(UIImage.init(named: "trash"), width: 300, height: 300, color: NCBrandColor.sharedInstance.graySoft)
  93. }
  94. func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
  95. let text = "\n"+NSLocalizedString("_trash_no_trash_", comment: "")
  96. let attributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 20), NSAttributedString.Key.foregroundColor: UIColor.lightGray]
  97. return NSAttributedString.init(string: text, attributes: attributes)
  98. }
  99. func description(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
  100. let text = "\n"+NSLocalizedString("_trash_no_trash_description_", comment: "")
  101. let attributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14), NSAttributedString.Key.foregroundColor: UIColor.lightGray]
  102. return NSAttributedString.init(string: text, attributes: attributes)
  103. }
  104. func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView) -> Bool {
  105. return true
  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. self.collectionView.setContentOffset(CGPoint(x:0,y:0), animated: false)
  116. })
  117. })
  118. typeLayout = k_layout_list
  119. NCUtility.sharedInstance.setLayoutForView(key: k_layout_view_trash, layout: typeLayout, sort: datasourceSorted, ascending: datasourceAscending, groupBy: datasourceGroupBy, directoryOnTop: datasourceDirectoryOnTop)
  120. } else {
  121. // grid layout
  122. UIView.animate(withDuration: 0.0, animations: {
  123. self.collectionView.collectionViewLayout.invalidateLayout()
  124. self.collectionView.setCollectionViewLayout(self.gridLayout, animated: false, completion: { (_) in
  125. self.collectionView.reloadData()
  126. self.collectionView.setContentOffset(CGPoint(x:0,y:0), animated: false)
  127. })
  128. })
  129. typeLayout = k_layout_grid
  130. NCUtility.sharedInstance.setLayoutForView(key: k_layout_view_trash, layout: typeLayout, sort: datasourceSorted, ascending: datasourceAscending, groupBy: datasourceGroupBy, directoryOnTop: datasourceDirectoryOnTop)
  131. }
  132. }
  133. func tapOrderHeaderMenu(sender: Any) {
  134. var menuView: DropdownMenu?
  135. var selectedRow = 0
  136. let item1 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "sortFileNameAZ"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_order_by_name_a_z_", comment: ""))
  137. let item2 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "sortFileNameZA"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_order_by_name_z_a_", comment: ""))
  138. let item3 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "sortDateMoreRecent"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_order_by_date_more_recent_", comment: ""))
  139. let item4 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "sortDateLessRecent"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_order_by_date_less_recent_", comment: ""))
  140. let item5 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "sortSmallest"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_order_by_size_smallest_", comment: ""))
  141. let item6 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "sortLargest"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_order_by_size_largest_", comment: ""))
  142. switch datasourceSorted {
  143. case "fileName":
  144. if datasourceAscending == true { item1.style = .highlight; selectedRow = 0 }
  145. if datasourceAscending == false { item2.style = .highlight; selectedRow = 1 }
  146. case "date":
  147. if datasourceAscending == false { item3.style = .highlight; selectedRow = 2 }
  148. if datasourceAscending == true { item4.style = .highlight; selectedRow = 3 }
  149. case "size":
  150. if datasourceAscending == true { item5.style = .highlight; selectedRow = 4 }
  151. if datasourceAscending == false { item6.style = .highlight; selectedRow = 5 }
  152. default:
  153. print("")
  154. }
  155. menuView = DropdownMenu(navigationController: self.navigationController!, items: [item1, item2, item3, item4, item5, item6], selectedRow: selectedRow)
  156. menuView?.token = "tapOrderHeaderMenu"
  157. menuView?.delegate = self
  158. menuView?.rowHeight = 45
  159. menuView?.highlightColor = NCBrandColor.sharedInstance.brand
  160. menuView?.tableView.alwaysBounceVertical = false
  161. menuView?.tableViewBackgroundColor = UIColor.white
  162. let header = (sender as? UIButton)?.superview as! NCTrashSectionHeaderMenu
  163. let headerRect = self.collectionView.convert(header.bounds, from: self.view)
  164. let menuOffsetY = headerRect.height - headerRect.origin.y - 2
  165. menuView?.topOffsetY = CGFloat(menuOffsetY)
  166. menuView?.showMenu()
  167. }
  168. func tapMoreHeaderMenu(sender: Any) {
  169. var menuView: DropdownMenu?
  170. if isEditMode {
  171. //let item0 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "checkedNo"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_cancel_", comment: ""))
  172. //let item1 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "restore"), multiplier: 1, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_trash_restore_selected_", comment: ""))
  173. let item2 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "trash"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_trash_delete_selected_", comment: ""))
  174. menuView = DropdownMenu(navigationController: self.navigationController!, items: [item2], selectedRow: -1)
  175. menuView?.token = "tapMoreHeaderMenuSelect"
  176. } else {
  177. //let item0 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "select"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_select_", comment: ""))
  178. //let item1 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "restore"), multiplier: 1, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_trash_restore_all_", comment: ""))
  179. let item2 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "trash"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_trash_delete_all_", comment: ""))
  180. menuView = DropdownMenu(navigationController: self.navigationController!, items: [item2], selectedRow: -1)
  181. menuView?.token = "tapMoreHeaderMenu"
  182. }
  183. menuView?.delegate = self
  184. menuView?.rowHeight = 45
  185. menuView?.highlightColor = NCBrandColor.sharedInstance.brand
  186. menuView?.tableView.alwaysBounceVertical = false
  187. menuView?.tableViewBackgroundColor = UIColor.white
  188. let header = (sender as? UIButton)?.superview as! NCTrashSectionHeaderMenu
  189. let headerRect = self.collectionView.convert(header.bounds, from: self.view)
  190. let menuOffsetY = headerRect.height - headerRect.origin.y - 2
  191. menuView?.topOffsetY = CGFloat(menuOffsetY)
  192. menuView?.showMenu()
  193. }
  194. func tapRestoreListItem(with fileID: String, sender: Any) {
  195. if !isEditMode {
  196. restoreItem(with: fileID)
  197. } else {
  198. let buttonPosition:CGPoint = (sender as! UIButton).convert(CGPoint.zero, to:collectionView)
  199. let indexPath = collectionView.indexPathForItem(at: buttonPosition)
  200. collectionView(self.collectionView, didSelectItemAt: indexPath!)
  201. }
  202. }
  203. func tapMoreListItem(with fileID: String, sender: Any) {
  204. if !isEditMode {
  205. var items = [ActionSheetItem]()
  206. items.append(ActionSheetDangerButton(title: NSLocalizedString("_delete_", comment: "")))
  207. items.append(ActionSheetCancelButton(title: NSLocalizedString("_cancel_", comment: "")))
  208. actionSheet = ActionSheet(items: items) { sheet, item in
  209. if item is ActionSheetDangerButton { self.deleteItem(with: fileID) }
  210. if item is ActionSheetCancelButton { print("Cancel buttons has the value `true`") }
  211. }
  212. guard let tableTrash = NCManageDatabase.sharedInstance.getTrashItem(fileID: fileID, account: appDelegate.activeAccount) else {
  213. return
  214. }
  215. let headerView = NCActionSheetHeader.sharedInstance.actionSheetHeader(isDirectory: tableTrash.directory, iconName: tableTrash.iconName, fileID: tableTrash.fileID, fileNameView: tableTrash.fileName, text: tableTrash.trashbinFileName)
  216. actionSheet?.headerView = headerView
  217. actionSheet?.headerView?.frame.size.height = 50
  218. actionSheet?.present(in: self, from: sender as! UIButton)
  219. } else {
  220. let buttonPosition:CGPoint = (sender as! UIButton).convert(CGPoint.zero, to:collectionView)
  221. let indexPath = collectionView.indexPathForItem(at: buttonPosition)
  222. collectionView(self.collectionView, didSelectItemAt: indexPath!)
  223. }
  224. }
  225. func tapMoreGridItem(with fileID: String, sender: Any) {
  226. if !isEditMode {
  227. var items = [ActionSheetItem]()
  228. let appearanceDelete = ActionSheetItemAppearance.init()
  229. appearanceDelete.textColor = UIColor.red
  230. items.append(ActionSheetItem(title: NSLocalizedString("_restore_", comment: ""), value: 0, image: CCGraphics.changeThemingColorImage(UIImage.init(named: "restore"), multiplier: 1, color: NCBrandColor.sharedInstance.icon)))
  231. let itemDelete = ActionSheetItem(title: NSLocalizedString("_delete_", comment: ""), value: 1, image: CCGraphics.changeThemingColorImage(UIImage.init(named: "trash"), multiplier: 2, color: UIColor.red))
  232. itemDelete.customAppearance = appearanceDelete
  233. items.append(itemDelete)
  234. items.append(ActionSheetCancelButton(title: NSLocalizedString("_cancel_", comment: "")))
  235. actionSheet = ActionSheet(items: items) { sheet, item in
  236. if item.value as? Int == 0 { self.restoreItem(with: fileID) }
  237. if item.value as? Int == 1 { self.deleteItem(with: fileID) }
  238. if item is ActionSheetCancelButton { print("Cancel buttons has the value `true`") }
  239. }
  240. guard let tableTrash = NCManageDatabase.sharedInstance.getTrashItem(fileID: fileID, account: appDelegate.activeAccount) else {
  241. return
  242. }
  243. let headerView = NCActionSheetHeader.sharedInstance.actionSheetHeader(isDirectory: tableTrash.directory, iconName: tableTrash.iconName, fileID: tableTrash.fileID, fileNameView: tableTrash.fileName, text: tableTrash.trashbinFileName)
  244. actionSheet?.headerView = headerView
  245. actionSheet?.headerView?.frame.size.height = 50
  246. actionSheet?.present(in: self, from: sender as! UIButton)
  247. } else {
  248. let buttonPosition:CGPoint = (sender as! UIButton).convert(CGPoint.zero, to:collectionView)
  249. let indexPath = collectionView.indexPathForItem(at: buttonPosition)
  250. collectionView(self.collectionView, didSelectItemAt: indexPath!)
  251. }
  252. }
  253. // MARK: DROP-DOWN-MENU
  254. func dropdownMenu(_ dropdownMenu: DropdownMenu, didSelectRowAt indexPath: IndexPath) {
  255. if dropdownMenu.token == "tapOrderHeaderMenu" {
  256. switch indexPath.row {
  257. case 0: datasourceSorted = "fileName"; datasourceAscending = true
  258. case 1: datasourceSorted = "fileName"; datasourceAscending = false
  259. case 2: datasourceSorted = "date"; datasourceAscending = false
  260. case 3: datasourceSorted = "date"; datasourceAscending = true
  261. case 4: datasourceSorted = "size"; datasourceAscending = true
  262. case 5: datasourceSorted = "size"; datasourceAscending = false
  263. default: print("")
  264. }
  265. NCUtility.sharedInstance.setLayoutForView(key: k_layout_view_trash, layout: typeLayout, sort: datasourceSorted, ascending: datasourceAscending, groupBy: datasourceGroupBy, directoryOnTop: datasourceDirectoryOnTop)
  266. loadDatasource()
  267. }
  268. if dropdownMenu.token == "tapMoreHeaderMenu" {
  269. /*
  270. // Select
  271. if indexPath.row == 0 {
  272. isEditMode = true
  273. collectionView.reloadData()
  274. }
  275. // Restore ALL
  276. if indexPath.row == 1 {
  277. for record: tableTrash in self.datasource {
  278. restoreItem(with: record.fileID)
  279. }
  280. }
  281. */
  282. // Empty Trash
  283. if indexPath.row == 0 {
  284. var items = [ActionSheetItem]()
  285. items.append(ActionSheetTitle(title: NSLocalizedString("_trash_delete_all_", comment: "")))
  286. items.append(ActionSheetDangerButton(title: NSLocalizedString("_ok_", comment: "")))
  287. items.append(ActionSheetCancelButton(title: NSLocalizedString("_cancel_", comment: "")))
  288. actionSheet = ActionSheet(items: items) { sheet, item in
  289. if item is ActionSheetDangerButton {
  290. self.emptyTrash()
  291. //for record: tableTrash in self.datasource {
  292. // self.deleteItem(with: record.fileID)
  293. //}
  294. }
  295. if item is ActionSheetCancelButton { return }
  296. }
  297. actionSheet?.present(in: self, from: self.view)
  298. }
  299. }
  300. if dropdownMenu.token == "tapMoreHeaderMenuSelect" {
  301. // Cancel
  302. if indexPath.row == 0 {
  303. isEditMode = false
  304. selectFileID.removeAll()
  305. collectionView.reloadData()
  306. }
  307. // Restore selected files
  308. if indexPath.row == 1 {
  309. for fileID in selectFileID {
  310. restoreItem(with: fileID)
  311. }
  312. isEditMode = false
  313. selectFileID.removeAll()
  314. collectionView.reloadData()
  315. }
  316. // Delete selected files
  317. if indexPath.row == 2 {
  318. var items = [ActionSheetItem]()
  319. items.append(ActionSheetTitle(title: NSLocalizedString("_trash_delete_selected_", comment: "")))
  320. items.append(ActionSheetDangerButton(title: NSLocalizedString("_delete_", comment: "")))
  321. items.append(ActionSheetCancelButton(title: NSLocalizedString("_cancel_", comment: "")))
  322. actionSheet = ActionSheet(items: items) { sheet, item in
  323. if item is ActionSheetDangerButton {
  324. for fileID in self.selectFileID {
  325. self.deleteItem(with: fileID)
  326. }
  327. self.isEditMode = false
  328. self.selectFileID.removeAll()
  329. self.collectionView.reloadData()
  330. }
  331. if item is ActionSheetCancelButton { return }
  332. }
  333. actionSheet?.present(in: self, from: self.view)
  334. }
  335. }
  336. }
  337. /*
  338. func dropdownMenuWillDismiss(_ dropdownMenu: DropdownMenu) {
  339. if dropdownMenu.token == "tapOrderHeaderMenu" {
  340. let trashHeader = collectionView.supplementaryView(forElementKind: UICollectionView.elementKindSectionHeader, at: IndexPath(row: 0, section: 0)) as! NCTrashHeaderMenu
  341. let title = String(trashHeader.buttonOrder.title(for: .normal)!.dropLast()) + "▽"
  342. trashHeader.buttonOrder.setTitle(title, for: .normal)
  343. }
  344. }
  345. func dropdownMenuWillShow(_ dropdownMenu: DropdownMenu) {
  346. if dropdownMenu.token == "tapOrderHeaderMenu" {
  347. let trashHeader = collectionView.supplementaryView(forElementKind: UICollectionView.elementKindSectionHeader, at: IndexPath(row: 0, section: 0)) as! NCTrashHeaderMenu
  348. let title = String(trashHeader.buttonOrder.title(for: .normal)!.dropLast()) + "△"
  349. trashHeader.buttonOrder.setTitle(title, for: .normal)
  350. }
  351. }
  352. */
  353. }
  354. // MARK: - Collection View
  355. extension NCTrash: UICollectionViewDelegate {
  356. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  357. let tableTrash = datasource[indexPath.item]
  358. if isEditMode {
  359. if let index = selectFileID.index(of: tableTrash.fileID) {
  360. selectFileID.remove(at: index)
  361. } else {
  362. selectFileID.append(tableTrash.fileID)
  363. }
  364. collectionView.reloadItems(at: [indexPath])
  365. return
  366. }
  367. if tableTrash.directory {
  368. let ncTrash:NCTrash = UIStoryboard(name: "NCTrash", bundle: nil).instantiateInitialViewController() as! NCTrash
  369. ncTrash.serverUrl = tableTrash.filePath + tableTrash.fileName
  370. ncTrash.titleCurrentFolder = tableTrash.trashbinFileName
  371. self.navigationController?.pushViewController(ncTrash, animated: true)
  372. }
  373. }
  374. }
  375. extension NCTrash: UICollectionViewDataSource {
  376. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  377. if kind == UICollectionView.elementKindSectionHeader {
  378. let trashHeader = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeaderMenu", for: indexPath) as! NCTrashSectionHeaderMenu
  379. if collectionView.collectionViewLayout == gridLayout {
  380. trashHeader.buttonSwitch.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "switchList"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), for: .normal)
  381. } else {
  382. trashHeader.buttonSwitch.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "switchGrid"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), for: .normal)
  383. }
  384. trashHeader.delegate = self
  385. trashHeader.setStatusButton(datasource: datasource)
  386. trashHeader.setTitleOrder(datasourceSorted: datasourceSorted, datasourceAscending: datasourceAscending)
  387. return trashHeader
  388. } else {
  389. let trashFooter = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCTrashSectionFooter
  390. trashFooter.setTitleLabelFooter(datasource: datasource)
  391. return trashFooter
  392. }
  393. }
  394. func numberOfSections(in collectionView: UICollectionView) -> Int {
  395. return 1
  396. }
  397. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  398. return datasource.count
  399. }
  400. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  401. let tableTrash = datasource[indexPath.item]
  402. var image: UIImage?
  403. if tableTrash.iconName.count > 0 {
  404. image = UIImage.init(named: tableTrash.iconName)
  405. } else {
  406. image = UIImage.init(named: "file")
  407. }
  408. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconFileID(tableTrash.fileID, fileNameView: tableTrash.fileName)) {
  409. image = UIImage.init(contentsOfFile: CCUtility.getDirectoryProviderStorageIconFileID(tableTrash.fileID, fileNameView: tableTrash.fileName))
  410. } else {
  411. if tableTrash.hasPreview == 1 && !CCUtility.fileProviderStorageIconExists(tableTrash.fileID, fileNameView: tableTrash.fileName) {
  412. downloadThumbnail(with: tableTrash, indexPath: indexPath)
  413. }
  414. }
  415. if collectionView.collectionViewLayout == listLayout {
  416. // LIST
  417. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCTrashListCell
  418. cell.delegate = self
  419. cell.fileID = tableTrash.fileID
  420. cell.indexPath = indexPath
  421. cell.labelTitle.text = tableTrash.trashbinFileName
  422. if tableTrash.directory {
  423. cell.imageItem.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder"), multiplier: 3, color: NCBrandColor.sharedInstance.brandElement)
  424. cell.labelInfo.text = CCUtility.dateDiff(tableTrash.date as Date)
  425. } else {
  426. cell.imageItem.image = image
  427. cell.labelInfo.text = CCUtility.dateDiff(tableTrash.date as Date) + ", " + CCUtility.transformedSize(tableTrash.size)
  428. }
  429. if isEditMode {
  430. cell.imageItemLeftConstraint.constant = 45
  431. cell.imageSelect.isHidden = false
  432. if selectFileID.contains(tableTrash.fileID) {
  433. cell.imageSelect.image = CCGraphics.scale(UIImage.init(named: "checkedYes"), to: CGSize(width: 50, height: 50), isAspectRation: true)
  434. cell.backgroundView = NCUtility.sharedInstance.cellBlurEffect(with: cell.bounds)
  435. } else {
  436. cell.imageSelect.image = CCGraphics.scale(UIImage.init(named: "checkedNo"), to: CGSize(width: 50, height: 50), isAspectRation: true)
  437. cell.backgroundView = nil
  438. }
  439. } else {
  440. cell.imageItemLeftConstraint.constant = 10
  441. cell.imageSelect.isHidden = true
  442. cell.backgroundView = nil
  443. }
  444. return cell
  445. } else {
  446. // GRID
  447. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  448. cell.delegate = self
  449. cell.fileID = tableTrash.fileID
  450. cell.indexPath = indexPath
  451. cell.labelTitle.text = tableTrash.trashbinFileName
  452. if tableTrash.directory {
  453. cell.imageItem.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder"), multiplier: 3, color: NCBrandColor.sharedInstance.brandElement)
  454. } else {
  455. cell.imageItem.image = image
  456. }
  457. if isEditMode {
  458. cell.imageSelect.isHidden = false
  459. if selectFileID.contains(tableTrash.fileID) {
  460. cell.imageSelect.image = CCGraphics.scale(UIImage.init(named: "checkedYes"), to: CGSize(width: 50, height: 50), isAspectRation: true)
  461. cell.backgroundView = NCUtility.sharedInstance.cellBlurEffect(with: cell.bounds)
  462. } else {
  463. cell.imageSelect.isHidden = true
  464. cell.backgroundView = nil
  465. }
  466. } else {
  467. cell.imageSelect.isHidden = true
  468. cell.backgroundView = nil
  469. }
  470. return cell
  471. }
  472. }
  473. }
  474. extension NCTrash: UICollectionViewDelegateFlowLayout {
  475. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  476. return CGSize(width: collectionView.frame.width, height: highHeader)
  477. }
  478. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  479. return CGSize(width: collectionView.frame.width, height: highHeader)
  480. }
  481. }
  482. // MARK: - NC API & Algorithm
  483. extension NCTrash {
  484. @objc func loadDatasource() {
  485. datasource.removeAll()
  486. var path = ""
  487. if serverUrl == "" {
  488. let userID = (appDelegate.activeUserID as NSString).addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlFragmentAllowed)
  489. path = k_dav + "/trashbin/" + userID! + "/trash/"
  490. } else {
  491. path = serverUrl
  492. }
  493. guard let tashItems = NCManageDatabase.sharedInstance.getTrash(filePath: path, sorted: datasourceSorted, ascending: datasourceAscending, account: appDelegate.activeAccount) else {
  494. return
  495. }
  496. datasource = tashItems
  497. reloadDataThenPerform {
  498. // GoTo FileID
  499. if self.scrollToFileID != "" {
  500. for item in 0...self.datasource.count-1 {
  501. if self.datasource[item].fileID.contains(self.scrollToFileID) {
  502. self.scrollToIndexPath = IndexPath(item: item, section: 0)
  503. self.collectionView.scrollToItem(at: self.scrollToIndexPath!, at: .top, animated: true)
  504. if let cell = self.collectionView.cellForItem(at: self.scrollToIndexPath!) as? NCTrashListCell {
  505. cell.backgroundColor = NCBrandColor.sharedInstance.brandElement
  506. UIView.animate(withDuration: 0.5, animations: {
  507. cell.backgroundColor = .white
  508. })
  509. }
  510. }
  511. }
  512. self.scrollToFileID = ""
  513. }
  514. }
  515. }
  516. @objc func loadListingTrash() {
  517. var path = ""
  518. if serverUrl == "" {
  519. let userID = (appDelegate.activeUserID as NSString).addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlFragmentAllowed)
  520. path = k_dav + "/trashbin/" + userID! + "/trash/"
  521. } else {
  522. path = serverUrl
  523. }
  524. OCNetworking.sharedManager().listingTrash(withAccount: appDelegate.activeAccount, path: path, serverUrl: appDelegate.activeUrl, completion: { (account, item, message, errorCode) in
  525. self.refreshControl.endRefreshing()
  526. if errorCode == 0 && account == self.appDelegate.activeAccount {
  527. NCManageDatabase.sharedInstance.deleteTrash(filePath: path, account: self.appDelegate.activeAccount)
  528. NCManageDatabase.sharedInstance.addTrashs(item as! [tableTrash])
  529. } else if errorCode == kOCErrorServerUnauthorized {
  530. self.appDelegate.openLoginView(self, delegate: self.appDelegate.activeMain, loginType: Int(k_login_Modify_Password), selector: Int(k_intro_login))
  531. } else if errorCode != 0 {
  532. self.appDelegate.messageNotification("_error_", description: message, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  533. } else {
  534. print("[LOG] It has been changed user during networking process, error.")
  535. }
  536. self.loadDatasource()
  537. })
  538. }
  539. func reloadDataThenPerform(_ closure: @escaping (() -> Void)) {
  540. CATransaction.begin()
  541. CATransaction.setCompletionBlock(closure)
  542. collectionView.reloadData()
  543. CATransaction.commit()
  544. }
  545. func restoreItem(with fileID: String) {
  546. guard let tableTrash = NCManageDatabase.sharedInstance.getTrashItem(fileID: fileID, account: appDelegate.activeAccount) else {
  547. return
  548. }
  549. let fileName = appDelegate.activeUrl + tableTrash.filePath + tableTrash.fileName
  550. let fileNameTo = appDelegate.activeUrl + k_dav + "/trashbin/" + appDelegate.activeUserID + "/restore/" + tableTrash.fileName
  551. OCNetworking.sharedManager().moveFileOrFolder(withAccount: appDelegate.activeAccount, fileName: fileName, fileNameTo: fileNameTo, completion: { (account, message, errorCode) in
  552. if errorCode == 0 && account == self.appDelegate.activeAccount {
  553. NCManageDatabase.sharedInstance.deleteTrash(fileID: fileID, account: account!)
  554. self.loadDatasource()
  555. } else if errorCode == kOCErrorServerUnauthorized {
  556. self.appDelegate.openLoginView(self, delegate: self.appDelegate.activeMain, loginType: Int(k_login_Modify_Password), selector: Int(k_intro_login))
  557. } else if errorCode != 0 {
  558. self.appDelegate.messageNotification("_error_", description: message, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  559. } else {
  560. print("[LOG] It has been changed user during networking process, error.")
  561. }
  562. })
  563. }
  564. func emptyTrash() {
  565. OCNetworking.sharedManager().emptyTrash(withAccount: appDelegate.activeAccount, completion: { (account, message, errorCode) in
  566. if errorCode == 0 && account == self.appDelegate.activeAccount {
  567. NCManageDatabase.sharedInstance.deleteTrash(fileID: nil, account: self.appDelegate.activeAccount)
  568. } else if errorCode == kOCErrorServerUnauthorized {
  569. self.appDelegate.openLoginView(self, delegate: self.appDelegate.activeMain, loginType: Int(k_login_Modify_Password), selector: Int(k_intro_login))
  570. } else if errorCode != 0 {
  571. self.appDelegate.messageNotification("_error_", description: message, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  572. } else {
  573. print("[LOG] It has been changed user during networking process, error.")
  574. }
  575. self.loadDatasource()
  576. })
  577. }
  578. func deleteItem(with fileID: String) {
  579. guard let tableTrash = NCManageDatabase.sharedInstance.getTrashItem(fileID: fileID, account: appDelegate.activeAccount) else {
  580. return
  581. }
  582. let path = appDelegate.activeUrl + tableTrash.filePath + tableTrash.fileName
  583. OCNetworking.sharedManager().deleteFileOrFolder(withAccount: appDelegate.activeAccount, path: path, completion: { (account, message, errorCode) in
  584. if errorCode == 0 && account == self.appDelegate.activeAccount {
  585. NCManageDatabase.sharedInstance.deleteTrash(fileID: fileID, account: account!)
  586. self.loadDatasource()
  587. } else if errorCode != 0 {
  588. self.appDelegate.messageNotification("_error_", description: message, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  589. } else {
  590. print("[LOG] It has been changed user during networking process, error.")
  591. }
  592. })
  593. }
  594. func downloadThumbnail(with tableTrash: tableTrash, indexPath: IndexPath) {
  595. OCNetworking.sharedManager().downloadPreviewTrash(withAccount: appDelegate.activeAccount, fileID: tableTrash.fileID, fileName: tableTrash.fileName, completion: { (account, image, message, errorCode) in
  596. if errorCode == 0 && account == self.appDelegate.activeAccount {
  597. if let cell = self.collectionView.cellForItem(at: indexPath) {
  598. if cell is NCTrashListCell {
  599. (cell as! NCTrashListCell).imageItem.image = image
  600. } else if cell is NCGridCell {
  601. (cell as! NCGridCell).imageItem.image = image
  602. }
  603. }
  604. }
  605. })
  606. }
  607. }