NCTrash.swift 40 KB

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