NCTrash.swift 21 KB

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