NCTrash.swift 40 KB

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