NCTrash.swift 37 KB

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