NCTrash.swift 22 KB

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