NCTransfers.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. //
  2. // NCTransfers.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 17/09/2020.
  6. // Copyright © 2018 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  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. import NCCommunication
  25. class NCTransfers: NCCollectionViewCommon, NCTransferCellDelegate {
  26. var metadataTemp: tableMetadata?
  27. required init?(coder aDecoder: NSCoder) {
  28. super.init(coder: aDecoder)
  29. appDelegate.activeTransfers = self
  30. titleCurrentFolder = NSLocalizedString("_transfers_", comment: "")
  31. layoutKey = k_layout_view_transfers
  32. enableSearchBar = false
  33. DZNimage = CCGraphics.changeThemingColorImage(UIImage.init(named: "load"), width: 300, height: 300, color: .gray)
  34. DZNtitle = "_no_transfer_"
  35. DZNdescription = "_no_transfer_sub_"
  36. }
  37. override func viewWillAppear(_ animated: Bool) {
  38. appDelegate.activeViewController = self
  39. collectionView?.collectionViewLayout = listLayout
  40. self.navigationItem.title = titleCurrentFolder
  41. setNavigationItem()
  42. reloadDataSource()
  43. }
  44. override func setNavigationItem() {
  45. self.navigationItem.rightBarButtonItem = nil
  46. self.navigationItem.leftBarButtonItem = nil
  47. }
  48. // MARK: - NotificationCenter
  49. override func downloadStartFile(_ notification: NSNotification) {
  50. if self.view?.window == nil { return }
  51. reloadDataSource()
  52. }
  53. override func downloadedFile(_ notification: NSNotification) {
  54. if self.view?.window == nil { return }
  55. reloadDataSource()
  56. }
  57. override func downloadCancelFile(_ notification: NSNotification) {
  58. if self.view?.window == nil { return }
  59. reloadDataSource()
  60. }
  61. override func uploadStartFile(_ notification: NSNotification) {
  62. if self.view?.window == nil { return }
  63. if let userInfo = notification.userInfo as NSDictionary? {
  64. if let metadata = userInfo["metadata"] as? tableMetadata {
  65. if let row = dataSource.addMetadata(metadata) {
  66. let indexPath = IndexPath(row: row, section: 0)
  67. collectionView?.performBatchUpdates({
  68. collectionView?.insertItems(at: [indexPath])
  69. }, completion: { (_) in
  70. self.reloadDataSource()
  71. })
  72. }
  73. }
  74. }
  75. }
  76. override func uploadedFile(_ notification: NSNotification) {
  77. if self.view?.window == nil { return }
  78. if let userInfo = notification.userInfo as NSDictionary? {
  79. if let metadata = userInfo["metadata"] as? tableMetadata, let ocIdTemp = userInfo["ocIdTemp"] as? String, let errorCode = userInfo["errorCode"] as? Int {
  80. if errorCode == 0 {
  81. if let row = dataSource.deleteMetadata(ocId: metadata.ocId) {
  82. let indexPath = IndexPath(row: row, section: 0)
  83. collectionView?.performBatchUpdates({
  84. collectionView?.deleteItems(at: [indexPath])
  85. }, completion: { (_) in
  86. self.collectionView?.reloadData()
  87. })
  88. } else {
  89. reloadDataSource()
  90. }
  91. } else if errorCode != NSURLErrorCancelled {
  92. if let row = dataSource.reloadMetadata(ocId: metadata.ocId, ocIdTemp: ocIdTemp) {
  93. let indexPath = IndexPath(row: row, section: 0)
  94. collectionView?.performBatchUpdates({
  95. collectionView?.reloadItems(at: [indexPath])
  96. }, completion: { (_) in
  97. self.collectionView?.reloadData()
  98. })
  99. } else {
  100. reloadDataSource()
  101. }
  102. }
  103. }
  104. }
  105. }
  106. override func uploadCancelFile(_ notification: NSNotification) {
  107. if self.view?.window == nil { return }
  108. if let userInfo = notification.userInfo as NSDictionary? {
  109. if let metadata = userInfo["metadata"] as? tableMetadata {
  110. if let row = dataSource.deleteMetadata(ocId: metadata.ocId) {
  111. let indexPath = IndexPath(row: row, section: 0)
  112. collectionView?.performBatchUpdates({
  113. collectionView?.deleteItems(at: [indexPath])
  114. }, completion: { (_) in
  115. self.collectionView?.reloadData()
  116. })
  117. } else {
  118. self.reloadDataSource()
  119. }
  120. }
  121. }
  122. }
  123. // MARK: TAP EVENT
  124. override func longPressMoreListItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) {
  125. let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .alert)
  126. alertController.addAction(UIAlertAction(title: NSLocalizedString("_cancel_", comment: ""), style: .cancel, handler: nil))
  127. alertController.addAction(UIAlertAction(title: NSLocalizedString("_cancel_all_task_", comment: ""), style: .default, handler: { action in
  128. NCNetworking.shared.cancelAllTransfer(account: self.appDelegate.account) {
  129. self.reloadDataSource()
  130. }
  131. }))
  132. self.present(alertController, animated: true, completion: nil)
  133. }
  134. override func longPressListItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) {
  135. if let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(objectId) {
  136. metadataTemp = metadata
  137. let touchPoint = gestureRecognizer.location(in: collectionView)
  138. becomeFirstResponder()
  139. let startTaskItem = UIMenuItem.init(title: NSLocalizedString("_force_start_", comment: ""), action: #selector(startTask(_:)))
  140. UIMenuController.shared.menuItems = [startTaskItem]
  141. UIMenuController.shared.setTargetRect(CGRect(x: touchPoint.x, y: touchPoint.y, width: 0, height: 0), in: collectionView)
  142. UIMenuController.shared.setMenuVisible(true, animated: true)
  143. }
  144. }
  145. override func longPressCollecationView(_ gestureRecognizer: UILongPressGestureRecognizer) { }
  146. @objc func startTask(_ notification: Any) {
  147. guard let metadata = metadataTemp else { return }
  148. metadata.status = Int(k_metadataStatusInUpload)
  149. metadata.session = NCCommunicationCommon.shared.sessionIdentifierUpload
  150. NCManageDatabase.sharedInstance.addMetadata(metadata)
  151. NCNetworking.shared.upload(metadata: metadata) { (_, _) in }
  152. }
  153. override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
  154. if action != #selector(startTask(_:)) { return false }
  155. guard let metadata = metadataTemp else { return false }
  156. if metadata.e2eEncrypted { return false }
  157. if metadata.status == k_metadataStatusWaitUpload || metadata.status == k_metadataStatusInUpload || metadata.status == k_metadataStatusUploading {
  158. return true
  159. }
  160. return false
  161. }
  162. // MARK: - Collection View
  163. override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  164. // nothing
  165. }
  166. override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  167. return CGSize(width: collectionView.frame.width, height: 0)
  168. }
  169. override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  170. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else {
  171. return UICollectionViewCell()
  172. }
  173. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "transferCell", for: indexPath) as! NCTransferCell
  174. cell.delegate = self
  175. cell.objectId = metadata.ocId
  176. cell.indexPath = indexPath
  177. cell.labelTitle.text = metadata.fileNameView
  178. cell.labelTitle.textColor = NCBrandColor.sharedInstance.textView
  179. cell.separator.backgroundColor = NCBrandColor.sharedInstance.separator
  180. cell.setButtonMore(named: k_buttonMoreStop, image: NCCollectionCommon.images.cellButtonStop)
  181. cell.imageItem.image = nil
  182. cell.imageItem.backgroundColor = nil
  183. cell.progressView.progress = 0.0
  184. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  185. cell.imageItem.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  186. } else {
  187. if metadata.hasPreview {
  188. cell.imageItem.backgroundColor = .lightGray
  189. } else {
  190. if metadata.iconName.count > 0 {
  191. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  192. } else {
  193. cell.imageItem.image = NCCollectionCommon.images.cellFileImage
  194. }
  195. }
  196. }
  197. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date) + " · " + CCUtility.transformedSize(metadata.size)
  198. // Transfer
  199. var progress: Float = 0.0
  200. var totalBytes: Double = 0.0
  201. let progressArray = appDelegate.listProgressMetadata.object(forKey: metadata.ocId) as? NSArray
  202. if progressArray != nil && progressArray?.count == 3 {
  203. progress = progressArray?.object(at: 0) as? Float ?? 0
  204. totalBytes = progressArray?.object(at: 1) as? Double ?? 0
  205. }
  206. if metadata.status == k_metadataStatusInDownload || metadata.status == k_metadataStatusDownloading || metadata.status >= k_metadataStatusTypeUpload {
  207. cell.progressView.isHidden = false
  208. } else {
  209. cell.progressView.isHidden = true
  210. cell.progressView.progress = progress
  211. }
  212. // Write status on Label Info
  213. switch metadata.status {
  214. case Int(k_metadataStatusWaitDownload):
  215. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_download_", comment: "")
  216. break
  217. case Int(k_metadataStatusInDownload):
  218. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_download_", comment: "")
  219. break
  220. case Int(k_metadataStatusDownloading):
  221. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - ↓ " + CCUtility.transformedSize(totalBytes)
  222. break
  223. case Int(k_metadataStatusWaitUpload):
  224. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_upload_", comment: "")
  225. break
  226. case Int(k_metadataStatusInUpload):
  227. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_upload_", comment: "")
  228. break
  229. case Int(k_metadataStatusUploading):
  230. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - ↑ " + CCUtility.transformedSize(totalBytes)
  231. break
  232. default:
  233. break
  234. }
  235. // Remove last separator
  236. if collectionView.numberOfItems(inSection: indexPath.section) == indexPath.row + 1 {
  237. cell.separator.isHidden = true
  238. } else {
  239. cell.separator.isHidden = false
  240. }
  241. return cell
  242. }
  243. // MARK: - DataSource + NC Endpoint
  244. override func reloadDataSource() {
  245. super.reloadDataSource()
  246. metadatasSource = NCManageDatabase.sharedInstance.getAdvancedMetadatas(predicate: NSPredicate(format: "(session CONTAINS 'upload') OR (session CONTAINS 'download')"), page: 1, limit: 100, sorted: "sessionTaskIdentifier", ascending: false)
  247. self.dataSource = NCDataSource.init(metadatasSource: metadatasSource)
  248. refreshControl.endRefreshing()
  249. collectionView.reloadData()
  250. }
  251. override func reloadDataSourceNetwork(forced: Bool = false) {
  252. super.reloadDataSourceNetwork(forced: forced)
  253. reloadDataSource()
  254. }
  255. }