NCTrash.swift 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  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. import Foundation
  9. class NCTrash: UIViewController , UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UIGestureRecognizerDelegate, NCTrashListDelegate, NCTrashGridDelegate, NCTrashHeaderMenuDelegate, DropdownMenuDelegate, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate {
  10. @IBOutlet fileprivate weak var collectionView: UICollectionView!
  11. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  12. var path = ""
  13. var titleCurrentFolder = NSLocalizedString("_trash_view_", comment: "")
  14. var datasource = [tableTrash]()
  15. var datasourceSorted = CCUtility.getOrderSettings()
  16. var datasourceAscending = CCUtility.getAscendingSettings()
  17. var listLayout: ListLayout!
  18. var gridLayout: GridLayout!
  19. private let highHeader: CGFloat = 50
  20. private let refreshControl = UIRefreshControl()
  21. override func viewDidLoad() {
  22. super.viewDidLoad()
  23. collectionView.register(UINib.init(nibName: "NCTrashListCell", bundle: nil), forCellWithReuseIdentifier: "cell-list")
  24. collectionView.register(UINib.init(nibName: "NCTrashGridCell", bundle: nil), forCellWithReuseIdentifier: "cell-grid")
  25. collectionView.alwaysBounceVertical = true
  26. listLayout = ListLayout()
  27. gridLayout = GridLayout()
  28. if CCUtility.getLayoutTrash() == "list" {
  29. collectionView.collectionViewLayout = listLayout
  30. } else {
  31. collectionView.collectionViewLayout = gridLayout
  32. }
  33. // Add Refresh Control
  34. if #available(iOS 10.0, *) {
  35. collectionView.refreshControl = refreshControl
  36. } else {
  37. collectionView.addSubview(refreshControl)
  38. }
  39. // Configure Refresh Control
  40. refreshControl.tintColor = NCBrandColor.sharedInstance.brandText
  41. refreshControl.backgroundColor = NCBrandColor.sharedInstance.brand
  42. refreshControl.addTarget(self, action: #selector(loadListingTrash), for: .valueChanged)
  43. // empty Data Source
  44. self.collectionView.emptyDataSetDelegate = self;
  45. self.collectionView.emptyDataSetSource = self;
  46. }
  47. override func viewWillAppear(_ animated: Bool) {
  48. super.viewWillAppear(animated)
  49. self.navigationItem.title = titleCurrentFolder
  50. if path == "" {
  51. let userID = (appDelegate.activeUserID as NSString).addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlFragmentAllowed)
  52. path = k_dav + "/trashbin/" + userID! + "/trash/"
  53. }
  54. guard let datasource = NCManageDatabase.sharedInstance.getTrash(filePath: path, sorted: datasourceSorted!, ascending: datasourceAscending) else {
  55. return
  56. }
  57. self.datasource = datasource
  58. collectionView.reloadData()
  59. loadListingTrash()
  60. }
  61. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  62. super.viewWillTransition(to: size, with: coordinator)
  63. coordinator.animate(alongsideTransition: nil) { _ in
  64. self.collectionView.collectionViewLayout.invalidateLayout()
  65. }
  66. }
  67. // MARK: DZNEmpty Delegate
  68. func backgroundColor(forEmptyDataSet scrollView: UIScrollView) -> UIColor? {
  69. return NCBrandColor.sharedInstance.backgroundView
  70. }
  71. func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
  72. return CCGraphics.changeThemingColorImage(UIImage.init(named: "trashNoFiles"), multiplier: 2, color: NCBrandColor.sharedInstance.graySoft)
  73. }
  74. func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
  75. let text = "\n"+NSLocalizedString("_trash_no_trash_", comment: "")
  76. let attributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 20), NSAttributedString.Key.foregroundColor: UIColor.lightGray]
  77. return NSAttributedString.init(string: text, attributes: attributes)
  78. }
  79. func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView) -> Bool {
  80. return true
  81. }
  82. // MARK: TAP EVENT
  83. func tapRestoreItem(with fileID: String, sender: Any) {
  84. restoreItem(with: fileID)
  85. }
  86. func tapMoreItem(with fileID: String, sender: Any) {
  87. var items = [ActionSheetItem]()
  88. items.append(ActionSheetTitle(title: NSLocalizedString("_delete_selected_files_", comment: "")))
  89. items.append(ActionSheetDangerButton(title: NSLocalizedString("_delete_", comment: "")))
  90. items.append(ActionSheetCancelButton(title: NSLocalizedString("_cancel_", comment: "")))
  91. let actionSheet = ActionSheet(items: items) { sheet, item in
  92. if item is ActionSheetDangerButton { self.deleteItem(with: fileID) }
  93. if item is ActionSheetCancelButton { print("Cancel buttons has the value `true`") }
  94. }
  95. actionSheet.present(in: self, from: sender as! UIButton)
  96. }
  97. func tapSwitchHeaderMenu(sender: Any) {
  98. if collectionView.collectionViewLayout == gridLayout {
  99. // list layout
  100. UIView.animate(withDuration: 0.0, animations: {
  101. self.collectionView.collectionViewLayout.invalidateLayout()
  102. self.collectionView.setCollectionViewLayout(self.listLayout, animated: false, completion: { (_) in
  103. self.collectionView.reloadData()
  104. })
  105. })
  106. CCUtility.setLayoutTrash("list")
  107. } else {
  108. // grid layout
  109. UIView.animate(withDuration: 0.0, animations: {
  110. self.collectionView.collectionViewLayout.invalidateLayout()
  111. self.collectionView.setCollectionViewLayout(self.gridLayout, animated: false, completion: { (_) in
  112. self.collectionView.reloadData()
  113. })
  114. })
  115. CCUtility.setLayoutTrash("grid")
  116. }
  117. }
  118. func tapMoreHeaderMenu(sender: Any) {
  119. var menuView: DropdownMenu?
  120. let item1 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "restore"), multiplier: 1, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_trash_restore_all_", comment: ""))
  121. let item2 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "trash"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_trash_delete_all_", comment: ""))
  122. menuView = DropdownMenu(navigationController: self.navigationController!, items: [item1, item2], selectedRow: -1)
  123. menuView?.delegate = self
  124. menuView?.rowHeight = 50
  125. menuView?.tableView.alwaysBounceVertical = false
  126. menuView?.topOffsetY = CGFloat(highHeader-2)
  127. menuView?.showMenu()
  128. }
  129. func tapOrderHeaderMenu(sender: Any) {
  130. }
  131. func dropdownMenu(_ dropdownMenu: DropdownMenu, didSelectRowAt indexPath: IndexPath) {
  132. if indexPath.row == 0 {
  133. for record: tableTrash in self.datasource {
  134. restoreItem(with: record.fileID)
  135. }
  136. }
  137. if indexPath.row == 1 {
  138. var items = [ActionSheetItem]()
  139. items.append(ActionSheetTitle(title: NSLocalizedString("_trash_delete_all_", comment: "")))
  140. items.append(ActionSheetDangerButton(title: NSLocalizedString("_delete_", comment: "")))
  141. items.append(ActionSheetCancelButton(title: NSLocalizedString("_cancel_", comment: "")))
  142. let actionSheet = ActionSheet(items: items) { sheet, item in
  143. if item is ActionSheetDangerButton {
  144. for record: tableTrash in self.datasource {
  145. self.deleteItem(with: record.fileID)
  146. }
  147. }
  148. if item is ActionSheetCancelButton { return }
  149. }
  150. actionSheet.present(in: self, from: self.view)
  151. }
  152. }
  153. // MARK: NC API
  154. @objc func loadListingTrash() {
  155. let ocNetworking = OCnetworking.init(delegate: self, metadataNet: nil, withUser: appDelegate.activeUser, withUserID: appDelegate.activeUserID, withPassword: appDelegate.activePassword, withUrl: appDelegate.activeUrl)
  156. ocNetworking?.listingTrash(appDelegate.activeUrl, path:path, account: appDelegate.activeAccount, success: { (item) in
  157. self.refreshControl.endRefreshing()
  158. NCManageDatabase.sharedInstance.deleteTrash(filePath: self.path)
  159. NCManageDatabase.sharedInstance.addTrashs(item as! [tableTrash])
  160. let results = NCManageDatabase.sharedInstance.getTrash(filePath: self.path, sorted: self.datasourceSorted!, ascending: self.datasourceAscending)
  161. if (results != nil) {
  162. self.datasource = results!
  163. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  164. self.collectionView.reloadData()
  165. }
  166. }
  167. }, failure: { (message, errorCode) in
  168. self.refreshControl.endRefreshing()
  169. print("error " + message!)
  170. })
  171. }
  172. func restoreItem(with fileID: String) {
  173. guard let tableTrash = NCManageDatabase.sharedInstance.getTrashItem(fileID: fileID) else {
  174. return
  175. }
  176. let ocNetworking = OCnetworking.init(delegate: self, metadataNet: nil, withUser: appDelegate.activeUser, withUserID: appDelegate.activeUserID, withPassword: appDelegate.activePassword, withUrl: appDelegate.activeUrl)
  177. let fileName = appDelegate.activeUrl + tableTrash.filePath + tableTrash.fileName
  178. let fileNameTo = appDelegate.activeUrl + k_dav + "/trashbin/" + appDelegate.activeUserID + "/restore/" + tableTrash.fileName
  179. ocNetworking?.moveFileOrFolder(fileName, fileNameTo: fileNameTo, success: {
  180. NCManageDatabase.sharedInstance.deleteTrash(fileID: fileID)
  181. guard let datasource = NCManageDatabase.sharedInstance.getTrash(filePath: self.path, sorted: self.datasourceSorted!, ascending: self.datasourceAscending) else {
  182. return
  183. }
  184. self.datasource = datasource
  185. self.collectionView.reloadData()
  186. }, failure: { (message, errorCode) in
  187. self.appDelegate.messageNotification("_error_", description: message, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  188. })
  189. }
  190. func deleteItem(with fileID: String) {
  191. guard let tableTrash = NCManageDatabase.sharedInstance.getTrashItem(fileID: fileID) else {
  192. return
  193. }
  194. let ocNetworking = OCnetworking.init(delegate: self, metadataNet: nil, withUser: appDelegate.activeUser, withUserID: appDelegate.activeUserID, withPassword: appDelegate.activePassword, withUrl: appDelegate.activeUrl)
  195. let path = appDelegate.activeUrl + tableTrash.filePath + tableTrash.fileName
  196. ocNetworking?.deleteFileOrFolder(path, completion: { (message, errorCode) in
  197. if errorCode == 0 {
  198. NCManageDatabase.sharedInstance.deleteTrash(fileID: fileID)
  199. guard let datasource = NCManageDatabase.sharedInstance.getTrash(filePath: self.path, sorted: self.datasourceSorted!, ascending: self.datasourceAscending) else {
  200. return
  201. }
  202. self.datasource = datasource
  203. self.collectionView.reloadData()
  204. } else {
  205. self.appDelegate.messageNotification("_error_", description: message, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  206. }
  207. })
  208. }
  209. func downloadThumbnail(with tableTrash: tableTrash, indexPath: IndexPath) {
  210. let ocNetworking = OCnetworking.init(delegate: self, metadataNet: nil, withUser: appDelegate.activeUser, withUserID: appDelegate.activeUserID, withPassword: appDelegate.activePassword, withUrl: appDelegate.activeUrl)
  211. ocNetworking?.downloadPreviewTrash(withFileID: tableTrash.fileID, fileName: tableTrash.fileName, completion: { (message, errorCode) in
  212. if errorCode == 0 && CCUtility.fileProviderStorageIconExists(tableTrash.fileID, fileNameView: tableTrash.fileName) {
  213. self.collectionView.reloadItems(at: [indexPath])
  214. }
  215. })
  216. }
  217. // MARK: COLLECTIONVIEW METHODS
  218. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  219. if kind == UICollectionView.elementKindSectionHeader {
  220. let trashHeader = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "headerMenu", for: indexPath) as! NCTrashHeaderMenu
  221. if collectionView.collectionViewLayout == gridLayout {
  222. trashHeader.buttonSwitch.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "switchList"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), for: .normal)
  223. } else {
  224. trashHeader.buttonSwitch.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "switchGrid"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), for: .normal)
  225. }
  226. trashHeader.delegate = self
  227. if self.datasource.count == 0 {
  228. trashHeader.buttonSwitch.isEnabled = false
  229. trashHeader.buttonMore.isEnabled = false
  230. } else {
  231. trashHeader.buttonSwitch.isEnabled = true
  232. trashHeader.buttonMore.isEnabled = true
  233. }
  234. return trashHeader
  235. } else {
  236. let trashFooter = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "footerMenu", for: indexPath) as! NCTrashFooterMenu
  237. trashFooter.labelFooter.textColor = NCBrandColor.sharedInstance.icon
  238. var folders: Int = 0, foldersText = ""
  239. var files: Int = 0, filesText = ""
  240. var size: Double = 0
  241. for record: tableTrash in self.datasource {
  242. if record.directory {
  243. folders += 1
  244. } else {
  245. files += 1
  246. size = size + record.size
  247. }
  248. }
  249. if folders > 1 {
  250. foldersText = "\(folders) " + NSLocalizedString("_folders_", comment: "")
  251. } else if folders == 1 {
  252. foldersText = "1 " + NSLocalizedString("_folder_", comment: "")
  253. }
  254. if files > 1 {
  255. filesText = "\(files) " + NSLocalizedString("_files_", comment: "") + " " + CCUtility.transformedSize(size)
  256. } else if files == 1 {
  257. filesText = "1 " + NSLocalizedString("_file_", comment: "") + " " + CCUtility.transformedSize(size)
  258. }
  259. if foldersText == "" {
  260. trashFooter.labelFooter.text = filesText
  261. } else if filesText == "" {
  262. trashFooter.labelFooter.text = foldersText
  263. } else {
  264. trashFooter.labelFooter.text = foldersText + ", " + filesText
  265. }
  266. return trashFooter
  267. }
  268. }
  269. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  270. return CGSize(width: collectionView.frame.width, height: highHeader)
  271. }
  272. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  273. return CGSize(width: collectionView.frame.width, height: highHeader)
  274. }
  275. func numberOfSections(in collectionView: UICollectionView) -> Int {
  276. return 1
  277. }
  278. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  279. return datasource.count
  280. }
  281. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  282. let tableTrash = datasource[indexPath.item]
  283. var image: UIImage?
  284. if tableTrash.iconName.count > 0 {
  285. image = UIImage.init(named: tableTrash.iconName)
  286. } else {
  287. image = UIImage.init(named: "file")
  288. }
  289. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconFileID(tableTrash.fileID, fileNameView: tableTrash.fileName)) {
  290. image = UIImage.init(contentsOfFile: CCUtility.getDirectoryProviderStorageIconFileID(tableTrash.fileID, fileNameView: tableTrash.fileName))
  291. } else {
  292. if tableTrash.thumbnailExists && !CCUtility.fileProviderStorageIconExists(tableTrash.fileID, fileNameView: tableTrash.fileName) {
  293. downloadThumbnail(with: tableTrash, indexPath: indexPath)
  294. }
  295. }
  296. if collectionView.collectionViewLayout == listLayout {
  297. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell-list", for: indexPath) as! NCTrashListCell
  298. cell.delegate = self
  299. cell.fileID = tableTrash.fileID
  300. cell.indexPath = indexPath
  301. cell.labelTitle.text = tableTrash.trashbinFileName
  302. if tableTrash.directory {
  303. cell.imageItem.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder"), multiplier: 3, color: NCBrandColor.sharedInstance.brandElement)
  304. cell.labelInfo.text = CCUtility.dateDiff(tableTrash.date as Date)
  305. } else {
  306. cell.imageItem.image = image
  307. cell.labelInfo.text = CCUtility.dateDiff(tableTrash.date as Date) + " " + CCUtility.transformedSize(tableTrash.size)
  308. }
  309. // last record: hidden separator
  310. if indexPath.row == datasource.count - 1 {
  311. cell.separator.isHidden = true
  312. }
  313. return cell
  314. } else {
  315. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell-grid", for: indexPath) as! NCTrashGridCell
  316. cell.delegate = self
  317. cell.fileID = tableTrash.fileID
  318. cell.indexPath = indexPath
  319. cell.labelTitle.text = tableTrash.trashbinFileName
  320. if tableTrash.directory {
  321. cell.imageItem.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder"), multiplier: 3, color: NCBrandColor.sharedInstance.brandElement)
  322. } else {
  323. cell.imageItem.image = image
  324. }
  325. return cell
  326. }
  327. }
  328. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  329. let tableTrash = datasource[indexPath.item]
  330. if tableTrash.directory {
  331. let ncTrash:NCTrash = UIStoryboard(name: "NCTrash", bundle: nil).instantiateInitialViewController() as! NCTrash
  332. ncTrash.path = tableTrash.filePath + tableTrash.fileName
  333. ncTrash.titleCurrentFolder = tableTrash.trashbinFileName
  334. self.navigationController?.pushViewController(ncTrash, animated: true)
  335. }
  336. }
  337. }
  338. class ListLayout: UICollectionViewFlowLayout {
  339. let itemHeight: CGFloat = 60
  340. override init() {
  341. super.init()
  342. self.scrollDirection = .vertical
  343. self.sectionInset = UIEdgeInsets(top: 10, left: 0, bottom: 10, right: 0)
  344. }
  345. required init?(coder aDecoder: NSCoder) {
  346. fatalError("init(coder:) has not been implemented")
  347. }
  348. override var itemSize: CGSize {
  349. get {
  350. if let collectionView = collectionView {
  351. let itemWidth: CGFloat = collectionView.frame.width
  352. return CGSize(width: itemWidth, height: self.itemHeight)
  353. }
  354. // Default fallback
  355. return CGSize(width: 100, height: 100)
  356. }
  357. set {
  358. super.itemSize = newValue
  359. }
  360. }
  361. override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
  362. return proposedContentOffset
  363. }
  364. }
  365. class GridLayout: UICollectionViewFlowLayout {
  366. let numberOfColumns: Int = 5
  367. let itemHeightWithoutImage: CGFloat = 34
  368. override init() {
  369. super.init()
  370. minimumInteritemSpacing = 10
  371. self.scrollDirection = .vertical
  372. self.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
  373. }
  374. required init?(coder aDecoder: NSCoder) {
  375. fatalError("init(coder:) has not been implemented")
  376. }
  377. override var itemSize: CGSize {
  378. get {
  379. if let collectionView = collectionView {
  380. let itemWidth: CGFloat = (collectionView.frame.width/CGFloat(self.numberOfColumns)) - self.minimumInteritemSpacing
  381. let itemHeight: CGFloat = itemWidth + itemHeightWithoutImage
  382. return CGSize(width: itemWidth, height: itemHeight)
  383. }
  384. // Default fallback
  385. return CGSize(width: 100, height: 100)
  386. }
  387. set {
  388. super.itemSize = newValue
  389. }
  390. }
  391. override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
  392. return proposedContentOffset
  393. }
  394. }