NCTrash.swift 37 KB

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