NCOnDevice.swift 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861
  1. //
  2. // NCOnDevice.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 24/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 NCOnDevice: UIViewController ,UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UIGestureRecognizerDelegate, NCOnDeviceListCellDelegate, NCOnDeviceGridCellDelegate, NCOnDeviceHeaderMenuDelegate, 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("_on_device_", comment: "")
  29. var datasource = [tableTrash]()
  30. var datasourceSorted = ""
  31. var datasourceAscending = true
  32. var isEditMode = false
  33. var selectFileID = [String]()
  34. var listLayout: ListLayoutOnDevice!
  35. var gridLayout: GridLayoutOnDevice!
  36. private let highHeader: CGFloat = 50
  37. private let refreshControl = UIRefreshControl()
  38. override func viewDidLoad() {
  39. super.viewDidLoad()
  40. collectionView.register(UINib.init(nibName: "NCOnDeviceListCell", bundle: nil), forCellWithReuseIdentifier: "cell-list")
  41. collectionView.register(UINib.init(nibName: "NCOnDeviceGridCell", bundle: nil), forCellWithReuseIdentifier: "cell-grid")
  42. collectionView.alwaysBounceVertical = true
  43. listLayout = ListLayoutOnDevice()
  44. gridLayout = GridLayoutOnDevice()
  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: "filesNoFiles"), multiplier: 2, color: NCBrandColor.sharedInstance.graySoft)
  92. }
  93. func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
  94. let text = "\n"+NSLocalizedString("_files_no_files_", 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. /*
  99. func description(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
  100. let text = "\n"+NSLocalizedString("_no_file_pull_down_", comment: "")
  101. let attributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14), NSAttributedString.Key.foregroundColor: UIColor.lightGray]
  102. return NSAttributedString.init(string: text, attributes: attributes)
  103. }
  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! NCOnDeviceHeaderMenu
  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! NCOnDeviceHeaderMenu
  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. // MARK: NC API
  330. @objc func loadListingTrash() {
  331. let ocNetworking = OCnetworking.init(delegate: self, metadataNet: nil, withUser: appDelegate.activeUser, withUserID: appDelegate.activeUserID, withPassword: appDelegate.activePassword, withUrl: appDelegate.activeUrl)
  332. ocNetworking?.listingTrash(appDelegate.activeUrl, path:path, account: appDelegate.activeAccount, success: { (item) in
  333. self.refreshControl.endRefreshing()
  334. NCManageDatabase.sharedInstance.deleteTrash(filePath: self.path)
  335. NCManageDatabase.sharedInstance.addTrashs(item as! [tableTrash])
  336. let results = NCManageDatabase.sharedInstance.getTrash(filePath: self.path, sorted: self.datasourceSorted, ascending: self.datasourceAscending)
  337. if (results != nil) {
  338. self.datasource = results!
  339. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  340. self.collectionView.reloadData()
  341. }
  342. }
  343. }, failure: { (message, errorCode) in
  344. self.refreshControl.endRefreshing()
  345. print("error " + message!)
  346. })
  347. }
  348. func restoreItem(with fileID: String) {
  349. guard let tableTrash = NCManageDatabase.sharedInstance.getTrashItem(fileID: fileID) else {
  350. return
  351. }
  352. let ocNetworking = OCnetworking.init(delegate: self, metadataNet: nil, withUser: appDelegate.activeUser, withUserID: appDelegate.activeUserID, withPassword: appDelegate.activePassword, withUrl: appDelegate.activeUrl)
  353. let fileName = appDelegate.activeUrl + tableTrash.filePath + tableTrash.fileName
  354. let fileNameTo = appDelegate.activeUrl + k_dav + "/trashbin/" + appDelegate.activeUserID + "/restore/" + tableTrash.fileName
  355. ocNetworking?.moveFileOrFolder(fileName, fileNameTo: fileNameTo, success: {
  356. NCManageDatabase.sharedInstance.deleteTrash(fileID: fileID)
  357. guard let datasource = NCManageDatabase.sharedInstance.getTrash(filePath: self.path, sorted: self.datasourceSorted, ascending: self.datasourceAscending) else {
  358. return
  359. }
  360. self.datasource = datasource
  361. self.collectionView.reloadData()
  362. }, failure: { (message, errorCode) in
  363. self.appDelegate.messageNotification("_error_", description: message, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  364. })
  365. }
  366. func deleteItem(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 path = appDelegate.activeUrl + tableTrash.filePath + tableTrash.fileName
  372. ocNetworking?.deleteFileOrFolder(path, completion: { (message, errorCode) in
  373. if errorCode == 0 {
  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. } else {
  381. self.appDelegate.messageNotification("_error_", description: message, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  382. }
  383. })
  384. }
  385. func downloadThumbnail(with tableTrash: tableTrash, indexPath: IndexPath) {
  386. let ocNetworking = OCnetworking.init(delegate: self, metadataNet: nil, withUser: appDelegate.activeUser, withUserID: appDelegate.activeUserID, withPassword: appDelegate.activePassword, withUrl: appDelegate.activeUrl)
  387. ocNetworking?.downloadPreviewTrash(withFileID: tableTrash.fileID, fileName: tableTrash.fileName, completion: { (message, errorCode) in
  388. if errorCode == 0 && CCUtility.fileProviderStorageIconExists(tableTrash.fileID, fileNameView: tableTrash.fileName) {
  389. self.collectionView.reloadItems(at: [indexPath])
  390. }
  391. })
  392. }
  393. // MARK: COLLECTIONVIEW METHODS
  394. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  395. if kind == UICollectionView.elementKindSectionHeader {
  396. let onDeviceHeader = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "headerMenu", for: indexPath) as! NCOnDeviceHeaderMenu
  397. if collectionView.collectionViewLayout == gridLayout {
  398. onDeviceHeader.buttonSwitch.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "switchList"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), for: .normal)
  399. } else {
  400. onDeviceHeader.buttonSwitch.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "switchGrid"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), for: .normal)
  401. }
  402. onDeviceHeader.delegate = self
  403. if self.datasource.count == 0 {
  404. onDeviceHeader.buttonSwitch.isEnabled = false
  405. onDeviceHeader.buttonOrder.isEnabled = false
  406. onDeviceHeader.buttonMore.isEnabled = false
  407. } else {
  408. onDeviceHeader.buttonSwitch.isEnabled = true
  409. onDeviceHeader.buttonOrder.isEnabled = true
  410. onDeviceHeader.buttonMore.isEnabled = true
  411. }
  412. // Order (∨∧▽△)
  413. var title = ""
  414. switch datasourceSorted {
  415. case "fileName":
  416. if datasourceAscending == true { title = NSLocalizedString("_order_by_name_a_z_", comment: "") }
  417. if datasourceAscending == false { title = NSLocalizedString("_order_by_name_z_a_", comment: "") }
  418. case "date":
  419. if datasourceAscending == false { title = NSLocalizedString("_order_by_date_more_recent_", comment: "") }
  420. if datasourceAscending == true { title = NSLocalizedString("_order_by_date_less_recent_", comment: "") }
  421. case "size":
  422. if datasourceAscending == true { title = NSLocalizedString("_order_by_size_smallest_", comment: "") }
  423. if datasourceAscending == false { title = NSLocalizedString("_order_by_size_largest_", comment: "") }
  424. default:
  425. title = NSLocalizedString("_order_by_", comment: "") + " " + datasourceSorted
  426. }
  427. title = title + " ▽"
  428. let size = title.size(withAttributes:[.font: onDeviceHeader.buttonOrder.titleLabel?.font as Any])
  429. onDeviceHeader.buttonOrder.setTitle(title, for: .normal)
  430. onDeviceHeader.buttonOrderWidthConstraint.constant = size.width + 5
  431. return onDeviceHeader
  432. } else {
  433. let onDeviceFooter = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "footerMenu", for: indexPath) as! NCOnDeviceFooterMenu
  434. onDeviceFooter.labelFooter.textColor = NCBrandColor.sharedInstance.icon
  435. var folders: Int = 0, foldersText = ""
  436. var files: Int = 0, filesText = ""
  437. var size: Double = 0
  438. for record: tableTrash in self.datasource {
  439. if record.directory {
  440. folders += 1
  441. } else {
  442. files += 1
  443. size = size + record.size
  444. }
  445. }
  446. if folders > 1 {
  447. foldersText = "\(folders) " + NSLocalizedString("_folders_", comment: "")
  448. } else if folders == 1 {
  449. foldersText = "1 " + NSLocalizedString("_folder_", comment: "")
  450. }
  451. if files > 1 {
  452. filesText = "\(files) " + NSLocalizedString("_files_", comment: "") + " " + CCUtility.transformedSize(size)
  453. } else if files == 1 {
  454. filesText = "1 " + NSLocalizedString("_file_", comment: "") + " " + CCUtility.transformedSize(size)
  455. }
  456. if foldersText == "" {
  457. onDeviceFooter.labelFooter.text = filesText
  458. } else if filesText == "" {
  459. onDeviceFooter.labelFooter.text = foldersText
  460. } else {
  461. onDeviceFooter.labelFooter.text = foldersText + ", " + filesText
  462. }
  463. return onDeviceFooter
  464. }
  465. }
  466. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  467. return CGSize(width: collectionView.frame.width, height: highHeader)
  468. }
  469. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  470. return CGSize(width: collectionView.frame.width, height: highHeader)
  471. }
  472. func numberOfSections(in collectionView: UICollectionView) -> Int {
  473. return 1
  474. }
  475. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  476. return datasource.count
  477. }
  478. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  479. let tableTrash = datasource[indexPath.item]
  480. var image: UIImage?
  481. if tableTrash.iconName.count > 0 {
  482. image = UIImage.init(named: tableTrash.iconName)
  483. } else {
  484. image = UIImage.init(named: "file")
  485. }
  486. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconFileID(tableTrash.fileID, fileNameView: tableTrash.fileName)) {
  487. image = UIImage.init(contentsOfFile: CCUtility.getDirectoryProviderStorageIconFileID(tableTrash.fileID, fileNameView: tableTrash.fileName))
  488. } else {
  489. if tableTrash.thumbnailExists && !CCUtility.fileProviderStorageIconExists(tableTrash.fileID, fileNameView: tableTrash.fileName) {
  490. downloadThumbnail(with: tableTrash, indexPath: indexPath)
  491. }
  492. }
  493. if collectionView.collectionViewLayout == listLayout {
  494. // LIST
  495. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell-list", for: indexPath) as! NCOnDeviceListCell
  496. cell.delegate = self
  497. cell.fileID = tableTrash.fileID
  498. cell.indexPath = indexPath
  499. cell.labelTitle.text = tableTrash.trashbinFileName
  500. if tableTrash.directory {
  501. cell.imageItem.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder"), multiplier: 3, color: NCBrandColor.sharedInstance.brandElement)
  502. cell.labelInfo.text = CCUtility.dateDiff(tableTrash.date as Date)
  503. } else {
  504. cell.imageItem.image = image
  505. cell.labelInfo.text = CCUtility.dateDiff(tableTrash.date as Date) + " " + CCUtility.transformedSize(tableTrash.size)
  506. }
  507. if isEditMode {
  508. cell.imageItemLeftConstraint.constant = 45
  509. cell.imageSelect.isHidden = false
  510. if selectFileID.contains(tableTrash.fileID) {
  511. cell.imageSelect.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "checkedYes"), multiplier: 2, color: NCBrandColor.sharedInstance.brand)
  512. cell.backgroundView = cellBlurEffect(with: cell.bounds)
  513. } else {
  514. cell.imageSelect.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "checkedNo"), multiplier: 2, color: NCBrandColor.sharedInstance.optionItem)
  515. cell.backgroundView = nil
  516. }
  517. } else {
  518. cell.imageItemLeftConstraint.constant = 10
  519. cell.imageSelect.isHidden = true
  520. cell.backgroundView = nil
  521. }
  522. return cell
  523. } else {
  524. // GRID
  525. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell-grid", for: indexPath) as! NCOnDeviceGridCell
  526. cell.delegate = self
  527. cell.fileID = tableTrash.fileID
  528. cell.indexPath = indexPath
  529. cell.labelTitle.text = tableTrash.trashbinFileName
  530. if tableTrash.directory {
  531. cell.imageItem.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder"), multiplier: 3, color: NCBrandColor.sharedInstance.brandElement)
  532. } else {
  533. cell.imageItem.image = image
  534. }
  535. if isEditMode {
  536. cell.imageSelect.isHidden = false
  537. if selectFileID.contains(tableTrash.fileID) {
  538. cell.imageSelect.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "checkedYes"), multiplier: 2, color: UIColor.white)
  539. cell.backgroundView = cellBlurEffect(with: cell.bounds)
  540. } else {
  541. cell.imageSelect.isHidden = true
  542. cell.backgroundView = nil
  543. }
  544. } else {
  545. cell.imageSelect.isHidden = true
  546. cell.backgroundView = nil
  547. }
  548. return cell
  549. }
  550. }
  551. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  552. let tableTrash = datasource[indexPath.item]
  553. if isEditMode {
  554. if let index = selectFileID.index(of: tableTrash.fileID) {
  555. selectFileID.remove(at: index)
  556. } else {
  557. selectFileID.append(tableTrash.fileID)
  558. }
  559. collectionView.reloadItems(at: [indexPath])
  560. return
  561. }
  562. if tableTrash.directory {
  563. let ncTrash:NCTrash = UIStoryboard(name: "NCOnDevice", bundle: nil).instantiateInitialViewController() as! NCTrash
  564. ncTrash.path = tableTrash.filePath + tableTrash.fileName
  565. ncTrash.titleCurrentFolder = tableTrash.trashbinFileName
  566. self.navigationController?.pushViewController(ncTrash, animated: true)
  567. }
  568. }
  569. // MARK: UTILITY
  570. private func cellBlurEffect(with frame: CGRect) -> UIView {
  571. let blurEffect = UIBlurEffect(style: .extraLight)
  572. let blurEffectView = UIVisualEffectView(effect: blurEffect)
  573. blurEffectView.frame = frame
  574. blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
  575. blurEffectView.backgroundColor = NCBrandColor.sharedInstance.brand.withAlphaComponent(0.2)
  576. return blurEffectView
  577. }
  578. private func actionSheetHeader(with fileID: String) -> UIView? {
  579. var image: UIImage?
  580. guard let tableTrash = NCManageDatabase.sharedInstance.getTrashItem(fileID: fileID) else {
  581. return nil
  582. }
  583. // Header
  584. if tableTrash.directory {
  585. image = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder"), multiplier: 3, color: NCBrandColor.sharedInstance.brandElement)
  586. } else if tableTrash.iconName.count > 0 {
  587. image = UIImage.init(named: tableTrash.iconName)
  588. } else {
  589. image = UIImage.init(named: "file")
  590. }
  591. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconFileID(tableTrash.fileID, fileNameView: tableTrash.fileName)) {
  592. image = UIImage.init(contentsOfFile: CCUtility.getDirectoryProviderStorageIconFileID(tableTrash.fileID, fileNameView: tableTrash.fileName))
  593. }
  594. let headerView = UINib(nibName: "NCActionSheetHeaderView", bundle: nil).instantiate(withOwner: self, options: nil).first as! NCActionSheetHeaderView
  595. headerView.imageItem.image = image
  596. headerView.label.text = tableTrash.trashbinFileName
  597. headerView.label.textColor = NCBrandColor.sharedInstance.icon
  598. return headerView
  599. }
  600. }
  601. class ListLayoutOnDevice: UICollectionViewFlowLayout {
  602. let itemHeight: CGFloat = 60
  603. override init() {
  604. super.init()
  605. minimumInteritemSpacing = 0
  606. minimumLineSpacing = 1
  607. self.scrollDirection = .vertical
  608. self.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 10, right: 0)
  609. }
  610. required init?(coder aDecoder: NSCoder) {
  611. fatalError("init(coder:) has not been implemented")
  612. }
  613. override var itemSize: CGSize {
  614. get {
  615. if let collectionView = collectionView {
  616. let itemWidth: CGFloat = collectionView.frame.width
  617. return CGSize(width: itemWidth, height: self.itemHeight)
  618. }
  619. // Default fallback
  620. return CGSize(width: 100, height: 100)
  621. }
  622. set {
  623. super.itemSize = newValue
  624. }
  625. }
  626. override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
  627. return proposedContentOffset
  628. }
  629. }
  630. class GridLayoutOnDevice: UICollectionViewFlowLayout {
  631. let heightLabelPlusButton: CGFloat = 45
  632. let preferenceWidth: CGFloat = 110
  633. let marginLeftRight: CGFloat = 5
  634. override init() {
  635. super.init()
  636. minimumInteritemSpacing = 1
  637. minimumLineSpacing = 1
  638. self.scrollDirection = .vertical
  639. self.sectionInset = UIEdgeInsets(top: 10, left: marginLeftRight, bottom: 10, right: marginLeftRight)
  640. }
  641. required init?(coder aDecoder: NSCoder) {
  642. fatalError("init(coder:) has not been implemented")
  643. }
  644. override var itemSize: CGSize {
  645. get {
  646. if let collectionView = collectionView {
  647. let numItems: Int = Int(collectionView.frame.width / preferenceWidth)
  648. let itemWidth: CGFloat = (collectionView.frame.width - (marginLeftRight * 2) - CGFloat(numItems)) / CGFloat(numItems)
  649. let itemHeight: CGFloat = itemWidth + heightLabelPlusButton
  650. return CGSize(width: itemWidth, height: itemHeight)
  651. }
  652. // Default fallback
  653. return CGSize(width: 100, height: 100)
  654. }
  655. set {
  656. super.itemSize = newValue
  657. }
  658. }
  659. override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
  660. return proposedContentOffset
  661. }
  662. }