NCTrash.swift 18 KB

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