NCTrash.swift 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867
  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 <m.faggiana@twsweb.it>
  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. class NCTrash: UIViewController ,UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UIGestureRecognizerDelegate, NCTrashListDelegate, NCTrashGridDelegate, NCTrashHeaderMenuDelegate, DropdownMenuDelegate, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate {
  25. @IBOutlet fileprivate weak var collectionView: UICollectionView!
  26. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  27. var path = ""
  28. var titleCurrentFolder = NSLocalizedString("_trash_view_", comment: "")
  29. var datasource = [tableTrash]()
  30. var datasourceSorted = ""
  31. var datasourceAscending = true
  32. var isEditMode = false
  33. var selectFileID = [String]()
  34. var listLayout: ListLayout!
  35. var gridLayout: GridLayout!
  36. private let highHeader: CGFloat = 50
  37. private let refreshControl = UIRefreshControl()
  38. override func viewDidLoad() {
  39. super.viewDidLoad()
  40. collectionView.register(UINib.init(nibName: "NCTrashListCell", bundle: nil), forCellWithReuseIdentifier: "cell-list")
  41. collectionView.register(UINib.init(nibName: "NCTrashGridCell", bundle: nil), forCellWithReuseIdentifier: "cell-grid")
  42. collectionView.alwaysBounceVertical = true
  43. listLayout = ListLayout()
  44. gridLayout = GridLayout()
  45. if CCUtility.getLayoutTrash() == "list" {
  46. collectionView.collectionViewLayout = listLayout
  47. } else {
  48. collectionView.collectionViewLayout = gridLayout
  49. }
  50. // Add Refresh Control
  51. if #available(iOS 10.0, *) {
  52. collectionView.refreshControl = refreshControl
  53. } else {
  54. collectionView.addSubview(refreshControl)
  55. }
  56. // Configure Refresh Control
  57. refreshControl.tintColor = NCBrandColor.sharedInstance.brandText
  58. refreshControl.backgroundColor = NCBrandColor.sharedInstance.brand
  59. refreshControl.addTarget(self, action: #selector(loadListingTrash), for: .valueChanged)
  60. // empty Data Source
  61. self.collectionView.emptyDataSetDelegate = self;
  62. self.collectionView.emptyDataSetSource = self;
  63. }
  64. override func viewWillAppear(_ animated: Bool) {
  65. super.viewWillAppear(animated)
  66. self.navigationItem.title = titleCurrentFolder
  67. if path == "" {
  68. let userID = (appDelegate.activeUserID as NSString).addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlFragmentAllowed)
  69. path = k_dav + "/trashbin/" + userID! + "/trash/"
  70. }
  71. datasourceSorted = CCUtility.getOrderSettings()
  72. datasourceAscending = CCUtility.getAscendingSettings()
  73. guard let datasource = NCManageDatabase.sharedInstance.getTrash(filePath: path, sorted: datasourceSorted, ascending: datasourceAscending) else {
  74. return
  75. }
  76. self.datasource = datasource
  77. collectionView.reloadData()
  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. }
  85. }
  86. // MARK: DZNEmpty
  87. func backgroundColor(forEmptyDataSet scrollView: UIScrollView) -> UIColor? {
  88. return NCBrandColor.sharedInstance.backgroundView
  89. }
  90. func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
  91. return CCGraphics.changeThemingColorImage(UIImage.init(named: "trashNoFiles"), multiplier: 2, color: NCBrandColor.sharedInstance.graySoft)
  92. }
  93. func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
  94. let text = "\n"+NSLocalizedString("_trash_no_trash_", comment: "")
  95. let attributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 20), NSAttributedString.Key.foregroundColor: UIColor.lightGray]
  96. return NSAttributedString.init(string: text, attributes: attributes)
  97. }
  98. func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView) -> Bool {
  99. return true
  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. self.collectionView.setContentOffset(CGPoint(x:0,y:0), animated: false)
  110. })
  111. })
  112. CCUtility.setLayoutTrash("list")
  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. self.collectionView.setContentOffset(CGPoint(x:0,y:0), animated: false)
  120. })
  121. })
  122. CCUtility.setLayoutTrash("grid")
  123. }
  124. }
  125. func tapOrderHeaderMenu(sender: Any) {
  126. var menuView: DropdownMenu?
  127. var selectedRow = 0
  128. let item1 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "sortFileNameAZ"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_order_by_name_a_z_", comment: ""))
  129. let item2 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "sortFileNameZA"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_order_by_name_z_a_", comment: ""))
  130. let item3 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "sortDateMoreRecent"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_order_by_date_more_recent_", comment: ""))
  131. let item4 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "sortDateLessRecent"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_order_by_date_less_recent_", comment: ""))
  132. let item5 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "sortSmallest"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_order_by_size_smallest_", comment: ""))
  133. let item6 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "sortLargest"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_order_by_size_largest_", comment: ""))
  134. switch datasourceSorted {
  135. case "fileName":
  136. if datasourceAscending == true { item1.style = .highlight; selectedRow = 0 }
  137. if datasourceAscending == false { item2.style = .highlight; selectedRow = 1 }
  138. case "date":
  139. if datasourceAscending == false { item3.style = .highlight; selectedRow = 2 }
  140. if datasourceAscending == true { item4.style = .highlight; selectedRow = 3 }
  141. case "size":
  142. if datasourceAscending == true { item5.style = .highlight; selectedRow = 4 }
  143. if datasourceAscending == false { item6.style = .highlight; selectedRow = 5 }
  144. default:
  145. print("")
  146. }
  147. menuView = DropdownMenu(navigationController: self.navigationController!, items: [item1, item2, item3, item4, item5, item6], selectedRow: selectedRow)
  148. menuView?.token = "tapOrderHeaderMenu"
  149. menuView?.delegate = self
  150. menuView?.rowHeight = 50
  151. menuView?.highlightColor = NCBrandColor.sharedInstance.brand
  152. menuView?.tableView.alwaysBounceVertical = false
  153. let header = (sender as? UIButton)?.superview as! NCTrashHeaderMenu
  154. let headerRect = self.collectionView.convert(header.bounds, from: self.view)
  155. let menuOffsetY = headerRect.height - headerRect.origin.y - 2
  156. menuView?.topOffsetY = CGFloat(menuOffsetY)
  157. menuView?.showMenu()
  158. }
  159. func tapMoreHeaderMenu(sender: Any) {
  160. var menuView: DropdownMenu?
  161. if isEditMode {
  162. let item0 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "checkedNo"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_cancel_", comment: ""))
  163. let item1 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "restore"), multiplier: 1, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_trash_restore_selected_", comment: ""))
  164. let item2 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "trash"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_trash_delete_selected_", comment: ""))
  165. menuView = DropdownMenu(navigationController: self.navigationController!, items: [item0, item1, item2], selectedRow: -1)
  166. menuView?.token = "tapMoreHeaderMenuSelect"
  167. } else {
  168. let item0 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "select"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_select_", comment: ""))
  169. let item1 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "restore"), multiplier: 1, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_trash_restore_all_", comment: ""))
  170. let item2 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "trash"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_trash_delete_all_", comment: ""))
  171. menuView = DropdownMenu(navigationController: self.navigationController!, items: [item0, item1, item2], selectedRow: -1)
  172. menuView?.token = "tapMoreHeaderMenu"
  173. }
  174. menuView?.delegate = self
  175. menuView?.rowHeight = 50
  176. menuView?.tableView.alwaysBounceVertical = false
  177. let header = (sender as? UIButton)?.superview as! NCTrashHeaderMenu
  178. let headerRect = self.collectionView.convert(header.bounds, from: self.view)
  179. let menuOffsetY = headerRect.height - headerRect.origin.y - 2
  180. menuView?.topOffsetY = CGFloat(menuOffsetY)
  181. menuView?.showMenu()
  182. }
  183. func tapRestoreItem(with fileID: String, sender: Any) {
  184. if !isEditMode {
  185. restoreItem(with: fileID)
  186. } else {
  187. let buttonPosition:CGPoint = (sender as! UIButton).convert(CGPoint.zero, to:collectionView)
  188. let indexPath = collectionView.indexPathForItem(at: buttonPosition)
  189. collectionView(self.collectionView, didSelectItemAt: indexPath!)
  190. }
  191. }
  192. func tapMoreItem(with fileID: String, sender: Any) {
  193. if !isEditMode {
  194. var items = [ActionSheetItem]()
  195. items.append(ActionSheetDangerButton(title: NSLocalizedString("_delete_", comment: "")))
  196. items.append(ActionSheetCancelButton(title: NSLocalizedString("_cancel_", comment: "")))
  197. let actionSheet = ActionSheet(items: items) { sheet, item in
  198. if item is ActionSheetDangerButton { self.deleteItem(with: fileID) }
  199. if item is ActionSheetCancelButton { print("Cancel buttons has the value `true`") }
  200. }
  201. let headerView = actionSheetHeader(with: fileID)
  202. actionSheet.headerView = headerView
  203. actionSheet.headerView?.frame.size.height = 50
  204. actionSheet.present(in: self, from: sender as! UIButton)
  205. } else {
  206. let buttonPosition:CGPoint = (sender as! UIButton).convert(CGPoint.zero, to:collectionView)
  207. let indexPath = collectionView.indexPathForItem(at: buttonPosition)
  208. collectionView(self.collectionView, didSelectItemAt: indexPath!)
  209. }
  210. }
  211. func tapMoreGridItem(with fileID: String, sender: Any) {
  212. if !isEditMode {
  213. var items = [ActionSheetItem]()
  214. let appearanceDelete = ActionSheetItemAppearance.init()
  215. appearanceDelete.textColor = UIColor.red
  216. items.append(ActionSheetItem(title: NSLocalizedString("_restore_", comment: ""), value: 0, image: CCGraphics.changeThemingColorImage(UIImage.init(named: "restore"), multiplier: 1, color: NCBrandColor.sharedInstance.icon)))
  217. let itemDelete = ActionSheetItem(title: NSLocalizedString("_delete_", comment: ""), value: 1, image: CCGraphics.changeThemingColorImage(UIImage.init(named: "trash"), multiplier: 2, color: UIColor.red))
  218. itemDelete.customAppearance = appearanceDelete
  219. items.append(itemDelete)
  220. items.append(ActionSheetCancelButton(title: NSLocalizedString("_cancel_", comment: "")))
  221. let actionSheet = ActionSheet(items: items) { sheet, item in
  222. if item.value as? Int == 0 { self.restoreItem(with: fileID) }
  223. if item.value as? Int == 1 { self.deleteItem(with: fileID) }
  224. if item is ActionSheetCancelButton { print("Cancel buttons has the value `true`") }
  225. }
  226. let headerView = actionSheetHeader(with: fileID)
  227. actionSheet.headerView = headerView
  228. actionSheet.headerView?.frame.size.height = 50
  229. actionSheet.present(in: self, from: sender as! UIButton)
  230. } else {
  231. let buttonPosition:CGPoint = (sender as! UIButton).convert(CGPoint.zero, to:collectionView)
  232. let indexPath = collectionView.indexPathForItem(at: buttonPosition)
  233. collectionView(self.collectionView, didSelectItemAt: indexPath!)
  234. }
  235. }
  236. // MARK: DROP-DOWN-MENU
  237. func dropdownMenu(_ dropdownMenu: DropdownMenu, didSelectRowAt indexPath: IndexPath) {
  238. if dropdownMenu.token == "tapOrderHeaderMenu" {
  239. switch indexPath.row {
  240. case 0: CCUtility.setOrderSettings("fileName"); CCUtility.setAscendingSettings(true)
  241. case 1: CCUtility.setOrderSettings("fileName"); CCUtility.setAscendingSettings(false)
  242. case 2: CCUtility.setOrderSettings("date"); CCUtility.setAscendingSettings(false)
  243. case 3: CCUtility.setOrderSettings("date"); CCUtility.setAscendingSettings(true)
  244. case 4: CCUtility.setOrderSettings("size"); CCUtility.setAscendingSettings(true)
  245. case 5: CCUtility.setOrderSettings("size"); CCUtility.setAscendingSettings(false)
  246. default: print("")
  247. }
  248. datasourceSorted = CCUtility.getOrderSettings()
  249. datasourceAscending = CCUtility.getAscendingSettings()
  250. guard let datasource = NCManageDatabase.sharedInstance.getTrash(filePath: path, sorted: datasourceSorted, ascending: datasourceAscending) else {
  251. return
  252. }
  253. self.datasource = datasource
  254. collectionView.reloadData()
  255. }
  256. if dropdownMenu.token == "tapMoreHeaderMenu" {
  257. // Select
  258. if indexPath.row == 0 {
  259. isEditMode = true
  260. collectionView.reloadData()
  261. }
  262. // Restore ALL
  263. if indexPath.row == 1 {
  264. for record: tableTrash in self.datasource {
  265. restoreItem(with: record.fileID)
  266. }
  267. }
  268. // Delete ALL
  269. if indexPath.row == 2 {
  270. var items = [ActionSheetItem]()
  271. items.append(ActionSheetTitle(title: NSLocalizedString("_trash_delete_all_", comment: "")))
  272. items.append(ActionSheetDangerButton(title: NSLocalizedString("_delete_", comment: "")))
  273. items.append(ActionSheetCancelButton(title: NSLocalizedString("_cancel_", comment: "")))
  274. let actionSheet = ActionSheet(items: items) { sheet, item in
  275. if item is ActionSheetDangerButton {
  276. for record: tableTrash in self.datasource {
  277. self.deleteItem(with: record.fileID)
  278. }
  279. }
  280. if item is ActionSheetCancelButton { return }
  281. }
  282. actionSheet.present(in: self, from: self.view)
  283. }
  284. }
  285. if dropdownMenu.token == "tapMoreHeaderMenuSelect" {
  286. // Cancel
  287. if indexPath.row == 0 {
  288. isEditMode = false
  289. selectFileID.removeAll()
  290. collectionView.reloadData()
  291. }
  292. // Restore selected files
  293. if indexPath.row == 1 {
  294. for fileID in selectFileID {
  295. restoreItem(with: fileID)
  296. }
  297. isEditMode = false
  298. selectFileID.removeAll()
  299. collectionView.reloadData()
  300. }
  301. // Delete selected files
  302. if indexPath.row == 2 {
  303. var items = [ActionSheetItem]()
  304. items.append(ActionSheetTitle(title: NSLocalizedString("_trash_delete_selected_", comment: "")))
  305. items.append(ActionSheetDangerButton(title: NSLocalizedString("_delete_", comment: "")))
  306. items.append(ActionSheetCancelButton(title: NSLocalizedString("_cancel_", comment: "")))
  307. let actionSheet = ActionSheet(items: items) { sheet, item in
  308. if item is ActionSheetDangerButton {
  309. for fileID in self.selectFileID {
  310. self.deleteItem(with: fileID)
  311. }
  312. self.isEditMode = false
  313. self.selectFileID.removeAll()
  314. self.collectionView.reloadData()
  315. }
  316. if item is ActionSheetCancelButton { return }
  317. }
  318. actionSheet.present(in: self, from: self.view)
  319. }
  320. }
  321. }
  322. /*
  323. func dropdownMenuWillDismiss(_ dropdownMenu: DropdownMenu) {
  324. if dropdownMenu.token == "tapOrderHeaderMenu" {
  325. let trashHeader = collectionView.supplementaryView(forElementKind: UICollectionView.elementKindSectionHeader, at: IndexPath(row: 0, section: 0)) as! NCTrashHeaderMenu
  326. let title = String(trashHeader.buttonOrder.title(for: .normal)!.dropLast()) + "▽"
  327. trashHeader.buttonOrder.setTitle(title, for: .normal)
  328. }
  329. }
  330. func dropdownMenuWillShow(_ dropdownMenu: DropdownMenu) {
  331. if dropdownMenu.token == "tapOrderHeaderMenu" {
  332. let trashHeader = collectionView.supplementaryView(forElementKind: UICollectionView.elementKindSectionHeader, at: IndexPath(row: 0, section: 0)) as! NCTrashHeaderMenu
  333. let title = String(trashHeader.buttonOrder.title(for: .normal)!.dropLast()) + "△"
  334. trashHeader.buttonOrder.setTitle(title, for: .normal)
  335. }
  336. }
  337. */
  338. // MARK: NC API
  339. @objc func loadListingTrash() {
  340. let ocNetworking = OCnetworking.init(delegate: self, metadataNet: nil, withUser: appDelegate.activeUser, withUserID: appDelegate.activeUserID, withPassword: appDelegate.activePassword, withUrl: appDelegate.activeUrl)
  341. ocNetworking?.listingTrash(appDelegate.activeUrl, path:path, account: appDelegate.activeAccount, success: { (item) in
  342. self.refreshControl.endRefreshing()
  343. NCManageDatabase.sharedInstance.deleteTrash(filePath: self.path)
  344. NCManageDatabase.sharedInstance.addTrashs(item as! [tableTrash])
  345. let results = NCManageDatabase.sharedInstance.getTrash(filePath: self.path, sorted: self.datasourceSorted, ascending: self.datasourceAscending)
  346. if (results != nil) {
  347. self.datasource = results!
  348. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  349. self.collectionView.reloadData()
  350. }
  351. }
  352. }, failure: { (message, errorCode) in
  353. self.refreshControl.endRefreshing()
  354. print("error " + message!)
  355. })
  356. }
  357. func restoreItem(with fileID: String) {
  358. guard let tableTrash = NCManageDatabase.sharedInstance.getTrashItem(fileID: fileID) else {
  359. return
  360. }
  361. let ocNetworking = OCnetworking.init(delegate: self, metadataNet: nil, withUser: appDelegate.activeUser, withUserID: appDelegate.activeUserID, withPassword: appDelegate.activePassword, withUrl: appDelegate.activeUrl)
  362. let fileName = appDelegate.activeUrl + tableTrash.filePath + tableTrash.fileName
  363. let fileNameTo = appDelegate.activeUrl + k_dav + "/trashbin/" + appDelegate.activeUserID + "/restore/" + tableTrash.fileName
  364. ocNetworking?.moveFileOrFolder(fileName, fileNameTo: fileNameTo, success: {
  365. NCManageDatabase.sharedInstance.deleteTrash(fileID: fileID)
  366. guard let datasource = NCManageDatabase.sharedInstance.getTrash(filePath: self.path, sorted: self.datasourceSorted, ascending: self.datasourceAscending) else {
  367. return
  368. }
  369. self.datasource = datasource
  370. self.collectionView.reloadData()
  371. }, failure: { (message, errorCode) in
  372. self.appDelegate.messageNotification("_error_", description: message, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  373. })
  374. }
  375. func deleteItem(with fileID: String) {
  376. guard let tableTrash = NCManageDatabase.sharedInstance.getTrashItem(fileID: fileID) else {
  377. return
  378. }
  379. let ocNetworking = OCnetworking.init(delegate: self, metadataNet: nil, withUser: appDelegate.activeUser, withUserID: appDelegate.activeUserID, withPassword: appDelegate.activePassword, withUrl: appDelegate.activeUrl)
  380. let path = appDelegate.activeUrl + tableTrash.filePath + tableTrash.fileName
  381. ocNetworking?.deleteFileOrFolder(path, completion: { (message, errorCode) in
  382. if errorCode == 0 {
  383. NCManageDatabase.sharedInstance.deleteTrash(fileID: fileID)
  384. guard let datasource = NCManageDatabase.sharedInstance.getTrash(filePath: self.path, sorted: self.datasourceSorted, ascending: self.datasourceAscending) else {
  385. return
  386. }
  387. self.datasource = datasource
  388. self.collectionView.reloadData()
  389. } else {
  390. self.appDelegate.messageNotification("_error_", description: message, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  391. }
  392. })
  393. }
  394. func downloadThumbnail(with tableTrash: tableTrash, indexPath: IndexPath) {
  395. let ocNetworking = OCnetworking.init(delegate: self, metadataNet: nil, withUser: appDelegate.activeUser, withUserID: appDelegate.activeUserID, withPassword: appDelegate.activePassword, withUrl: appDelegate.activeUrl)
  396. ocNetworking?.downloadPreviewTrash(withFileID: tableTrash.fileID, fileName: tableTrash.fileName, completion: { (message, errorCode) in
  397. if errorCode == 0 && CCUtility.fileProviderStorageIconExists(tableTrash.fileID, fileNameView: tableTrash.fileName) {
  398. self.collectionView.reloadItems(at: [indexPath])
  399. }
  400. })
  401. }
  402. // MARK: COLLECTIONVIEW METHODS
  403. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  404. if kind == UICollectionView.elementKindSectionHeader {
  405. let trashHeader = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "headerMenu", for: indexPath) as! NCTrashHeaderMenu
  406. if collectionView.collectionViewLayout == gridLayout {
  407. trashHeader.buttonSwitch.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "switchList"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), for: .normal)
  408. } else {
  409. trashHeader.buttonSwitch.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "switchGrid"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), for: .normal)
  410. }
  411. trashHeader.delegate = self
  412. if self.datasource.count == 0 {
  413. trashHeader.buttonSwitch.isEnabled = false
  414. trashHeader.buttonOrder.isEnabled = false
  415. trashHeader.buttonMore.isEnabled = false
  416. } else {
  417. trashHeader.buttonSwitch.isEnabled = true
  418. trashHeader.buttonOrder.isEnabled = true
  419. trashHeader.buttonMore.isEnabled = true
  420. }
  421. // Order (∨∧▽△)
  422. var title = ""
  423. switch datasourceSorted {
  424. case "fileName":
  425. if datasourceAscending == true { title = NSLocalizedString("_order_by_name_a_z_", comment: "") }
  426. if datasourceAscending == false { title = NSLocalizedString("_order_by_name_z_a_", comment: "") }
  427. case "date":
  428. if datasourceAscending == false { title = NSLocalizedString("_order_by_date_more_recent_", comment: "") }
  429. if datasourceAscending == true { title = NSLocalizedString("_order_by_date_less_recent_", comment: "") }
  430. case "size":
  431. if datasourceAscending == true { title = NSLocalizedString("_order_by_size_smallest_", comment: "") }
  432. if datasourceAscending == false { title = NSLocalizedString("_order_by_size_largest_", comment: "") }
  433. default:
  434. title = NSLocalizedString("_order_by_", comment: "") + " " + datasourceSorted
  435. }
  436. title = title + " ▽"
  437. let size = title.size(withAttributes:[.font: trashHeader.buttonOrder.titleLabel?.font as Any])
  438. trashHeader.buttonOrder.setTitle(title, for: .normal)
  439. trashHeader.buttonOrderWidthConstraint.constant = size.width + 5
  440. return trashHeader
  441. } else {
  442. let trashFooter = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "footerMenu", for: indexPath) as! NCTrashFooterMenu
  443. trashFooter.labelFooter.textColor = NCBrandColor.sharedInstance.icon
  444. var folders: Int = 0, foldersText = ""
  445. var files: Int = 0, filesText = ""
  446. var size: Double = 0
  447. for record: tableTrash in self.datasource {
  448. if record.directory {
  449. folders += 1
  450. } else {
  451. files += 1
  452. size = size + record.size
  453. }
  454. }
  455. if folders > 1 {
  456. foldersText = "\(folders) " + NSLocalizedString("_folders_", comment: "")
  457. } else if folders == 1 {
  458. foldersText = "1 " + NSLocalizedString("_folder_", comment: "")
  459. }
  460. if files > 1 {
  461. filesText = "\(files) " + NSLocalizedString("_files_", comment: "") + " " + CCUtility.transformedSize(size)
  462. } else if files == 1 {
  463. filesText = "1 " + NSLocalizedString("_file_", comment: "") + " " + CCUtility.transformedSize(size)
  464. }
  465. if foldersText == "" {
  466. trashFooter.labelFooter.text = filesText
  467. } else if filesText == "" {
  468. trashFooter.labelFooter.text = foldersText
  469. } else {
  470. trashFooter.labelFooter.text = foldersText + ", " + filesText
  471. }
  472. return trashFooter
  473. }
  474. }
  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. func numberOfSections(in collectionView: UICollectionView) -> Int {
  482. return 1
  483. }
  484. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  485. return datasource.count
  486. }
  487. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  488. let tableTrash = datasource[indexPath.item]
  489. var image: UIImage?
  490. if tableTrash.iconName.count > 0 {
  491. image = UIImage.init(named: tableTrash.iconName)
  492. } else {
  493. image = UIImage.init(named: "file")
  494. }
  495. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconFileID(tableTrash.fileID, fileNameView: tableTrash.fileName)) {
  496. image = UIImage.init(contentsOfFile: CCUtility.getDirectoryProviderStorageIconFileID(tableTrash.fileID, fileNameView: tableTrash.fileName))
  497. } else {
  498. if tableTrash.thumbnailExists && !CCUtility.fileProviderStorageIconExists(tableTrash.fileID, fileNameView: tableTrash.fileName) {
  499. downloadThumbnail(with: tableTrash, indexPath: indexPath)
  500. }
  501. }
  502. if collectionView.collectionViewLayout == listLayout {
  503. // LIST
  504. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell-list", for: indexPath) as! NCTrashListCell
  505. cell.delegate = self
  506. cell.fileID = tableTrash.fileID
  507. cell.indexPath = indexPath
  508. cell.labelTitle.text = tableTrash.trashbinFileName
  509. if tableTrash.directory {
  510. cell.imageItem.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder"), multiplier: 3, color: NCBrandColor.sharedInstance.brandElement)
  511. cell.labelInfo.text = CCUtility.dateDiff(tableTrash.date as Date)
  512. } else {
  513. cell.imageItem.image = image
  514. cell.labelInfo.text = CCUtility.dateDiff(tableTrash.date as Date) + " " + CCUtility.transformedSize(tableTrash.size)
  515. }
  516. if isEditMode {
  517. cell.imageItemLeftConstraint.constant = 45
  518. cell.imageSelect.isHidden = false
  519. if selectFileID.contains(tableTrash.fileID) {
  520. cell.imageSelect.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "checkedYes"), multiplier: 2, color: NCBrandColor.sharedInstance.brand)
  521. cell.backgroundView = cellBlurEffect(with: cell.bounds)
  522. } else {
  523. cell.imageSelect.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "checkedNo"), multiplier: 2, color: NCBrandColor.sharedInstance.optionItem)
  524. cell.backgroundView = nil
  525. }
  526. } else {
  527. cell.imageItemLeftConstraint.constant = 10
  528. cell.imageSelect.isHidden = true
  529. cell.backgroundView = nil
  530. }
  531. return cell
  532. } else {
  533. // GRID
  534. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell-grid", for: indexPath) as! NCTrashGridCell
  535. cell.delegate = self
  536. cell.fileID = tableTrash.fileID
  537. cell.indexPath = indexPath
  538. cell.labelTitle.text = tableTrash.trashbinFileName
  539. if tableTrash.directory {
  540. cell.imageItem.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder"), multiplier: 3, color: NCBrandColor.sharedInstance.brandElement)
  541. } else {
  542. cell.imageItem.image = image
  543. }
  544. if isEditMode {
  545. cell.imageSelect.isHidden = false
  546. if selectFileID.contains(tableTrash.fileID) {
  547. cell.imageSelect.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "checkedYes"), multiplier: 2, color: UIColor.white)
  548. cell.backgroundView = cellBlurEffect(with: cell.bounds)
  549. } else {
  550. cell.imageSelect.isHidden = true
  551. cell.backgroundView = nil
  552. }
  553. } else {
  554. cell.imageSelect.isHidden = true
  555. cell.backgroundView = nil
  556. }
  557. return cell
  558. }
  559. }
  560. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  561. let tableTrash = datasource[indexPath.item]
  562. if isEditMode {
  563. if let index = selectFileID.index(of: tableTrash.fileID) {
  564. selectFileID.remove(at: index)
  565. } else {
  566. selectFileID.append(tableTrash.fileID)
  567. }
  568. collectionView.reloadItems(at: [indexPath])
  569. return
  570. }
  571. if tableTrash.directory {
  572. let ncTrash:NCTrash = UIStoryboard(name: "NCTrash", bundle: nil).instantiateInitialViewController() as! NCTrash
  573. ncTrash.path = tableTrash.filePath + tableTrash.fileName
  574. ncTrash.titleCurrentFolder = tableTrash.trashbinFileName
  575. self.navigationController?.pushViewController(ncTrash, animated: true)
  576. }
  577. }
  578. // MARK: UTILITY
  579. private func cellBlurEffect(with frame: CGRect) -> UIView {
  580. let blurEffect = UIBlurEffect(style: .extraLight)
  581. let blurEffectView = UIVisualEffectView(effect: blurEffect)
  582. blurEffectView.frame = frame
  583. blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
  584. blurEffectView.backgroundColor = NCBrandColor.sharedInstance.brand.withAlphaComponent(0.2)
  585. return blurEffectView
  586. }
  587. private func actionSheetHeader(with fileID: String) -> UIView? {
  588. var image: UIImage?
  589. guard let tableTrash = NCManageDatabase.sharedInstance.getTrashItem(fileID: fileID) else {
  590. return nil
  591. }
  592. // Header
  593. if tableTrash.iconName.count > 0 {
  594. image = UIImage.init(named: tableTrash.iconName)
  595. } else {
  596. image = UIImage.init(named: "file")
  597. }
  598. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconFileID(tableTrash.fileID, fileNameView: tableTrash.fileName)) {
  599. image = UIImage.init(contentsOfFile: CCUtility.getDirectoryProviderStorageIconFileID(tableTrash.fileID, fileNameView: tableTrash.fileName))
  600. }
  601. let headerView = UINib(nibName: "NCActionSheetHeaderView", bundle: nil).instantiate(withOwner: self, options: nil).first as! NCActionSheetHeaderView
  602. headerView.imageItem.image = image
  603. headerView.label.text = tableTrash.trashbinFileName
  604. headerView.label.textColor = NCBrandColor.sharedInstance.icon
  605. return headerView
  606. }
  607. }
  608. class ListLayout: UICollectionViewFlowLayout {
  609. let itemHeight: CGFloat = 60
  610. override init() {
  611. super.init()
  612. minimumInteritemSpacing = 0
  613. minimumLineSpacing = 1
  614. self.scrollDirection = .vertical
  615. self.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 10, right: 0)
  616. }
  617. required init?(coder aDecoder: NSCoder) {
  618. fatalError("init(coder:) has not been implemented")
  619. }
  620. override var itemSize: CGSize {
  621. get {
  622. if let collectionView = collectionView {
  623. let itemWidth: CGFloat = collectionView.frame.width
  624. return CGSize(width: itemWidth, height: self.itemHeight)
  625. }
  626. // Default fallback
  627. return CGSize(width: 100, height: 100)
  628. }
  629. set {
  630. super.itemSize = newValue
  631. }
  632. }
  633. override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
  634. return proposedContentOffset
  635. }
  636. }
  637. class GridLayout: UICollectionViewFlowLayout {
  638. let heightLabelPlusButton: CGFloat = 45
  639. override init() {
  640. super.init()
  641. minimumInteritemSpacing = 0
  642. minimumLineSpacing = 1
  643. self.scrollDirection = .vertical
  644. self.sectionInset = UIEdgeInsets(top: 10, left: 12, bottom: 10, right: 12)
  645. }
  646. required init?(coder aDecoder: NSCoder) {
  647. fatalError("init(coder:) has not been implemented")
  648. }
  649. override var itemSize: CGSize {
  650. get {
  651. if let collectionView = collectionView {
  652. let itemWidth: CGFloat = (collectionView.frame.width/CGFloat(collectionView.bounds.width / 90.0))
  653. let itemHeight: CGFloat = itemWidth + heightLabelPlusButton
  654. return CGSize(width: itemWidth, height: itemHeight)
  655. }
  656. // Default fallback
  657. return CGSize(width: 100, height: 100)
  658. }
  659. set {
  660. super.itemSize = newValue
  661. }
  662. }
  663. override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
  664. return proposedContentOffset
  665. }
  666. }