NCOperationQueue.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. //
  2. // NCOperationQueue.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 03/06/2020.
  6. // Copyright © 2020 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 UIKit
  24. import Queuer
  25. import NextcloudKit
  26. import JGProgressHUD
  27. @objc class NCOperationQueue: NSObject {
  28. @objc public static let shared: NCOperationQueue = {
  29. let instance = NCOperationQueue()
  30. return instance
  31. }()
  32. let appDelegate = (UIApplication.shared.delegate as? AppDelegate)!
  33. // MARK: - Download file
  34. func download(metadata: tableMetadata, selector: String) {
  35. for case let operation as NCOperationDownload in appDelegate.downloadQueue.operations where operation.metadata.ocId == metadata.ocId { return }
  36. appDelegate.downloadQueue.addOperation(NCOperationDownload(metadata: metadata, selector: selector))
  37. }
  38. // MARK: - Download Thumbnail Activity
  39. func downloadThumbnailActivity(fileNamePathOrFileId: String, fileNamePreviewLocalPath: String, fileId: String, cell: NCActivityCollectionViewCell, collectionView: UICollectionView?) {
  40. cell.imageView?.image = UIImage(named: "file_photo")
  41. cell.fileId = fileId
  42. if !FileManager.default.fileExists(atPath: fileNamePreviewLocalPath) {
  43. for case let operation as NCOperationDownloadThumbnailActivity in appDelegate.downloadThumbnailActivityQueue.operations where operation.fileId == fileId {
  44. return
  45. }
  46. appDelegate.downloadThumbnailActivityQueue.addOperation(NCOperationDownloadThumbnailActivity(fileNamePathOrFileId: fileNamePathOrFileId, fileNamePreviewLocalPath: fileNamePreviewLocalPath, fileId: fileId, cell: cell, collectionView: collectionView))
  47. }
  48. }
  49. // MARK: - Download Avatar
  50. func downloadAvatar(user: String, dispalyName: String?, fileName: String, cell: NCCellProtocol, view: UIView?, cellImageView: UIImageView?) {
  51. let fileNameLocalPath = String(CCUtility.getDirectoryUserData()) + "/" + fileName
  52. if let image = NCManageDatabase.shared.getImageAvatarLoaded(fileName: fileName) {
  53. cellImageView?.image = image
  54. cell.fileAvatarImageView?.image = image
  55. return
  56. }
  57. if let account = NCManageDatabase.shared.getActiveAccount() {
  58. cellImageView?.image = NCUtility.shared.loadUserImage(
  59. for: user,
  60. displayName: dispalyName,
  61. userBaseUrl: account)
  62. }
  63. for case let operation as NCOperationDownloadAvatar in appDelegate.downloadAvatarQueue.operations where operation.fileName == fileName { return }
  64. appDelegate.downloadAvatarQueue.addOperation(NCOperationDownloadAvatar(user: user, fileName: fileName, fileNameLocalPath: fileNameLocalPath, cell: cell, view: view, cellImageView: cellImageView))
  65. }
  66. // MARK: - Unified Search
  67. func unifiedSearchAddSection(collectionViewCommon: NCCollectionViewCommon, metadatas: [tableMetadata], searchResult: NKSearchResult) {
  68. appDelegate.unifiedSearchQueue.addOperation(NCOperationUnifiedSearch(collectionViewCommon: collectionViewCommon, metadatas: metadatas, searchResult: searchResult))
  69. }
  70. // MARK: - Save Live Photo
  71. func saveLivePhoto(metadata: tableMetadata, metadataMOV: tableMetadata) {
  72. for case let operation as NCOperationSaveLivePhoto in appDelegate.saveLivePhotoQueue.operations where operation.metadata.fileName == metadata.fileName { return }
  73. appDelegate.saveLivePhotoQueue.addOperation(NCOperationSaveLivePhoto(metadata: metadata, metadataMOV: metadataMOV))
  74. }
  75. }
  76. // MARK: -
  77. class NCOperationDownload: ConcurrentOperation {
  78. var metadata: tableMetadata
  79. var selector: String
  80. init(metadata: tableMetadata, selector: String) {
  81. self.metadata = tableMetadata.init(value: metadata)
  82. self.selector = selector
  83. }
  84. override func start() {
  85. guard !isCancelled else { return self.finish() }
  86. NCNetworking.shared.download(metadata: metadata, selector: self.selector) { _, _ in
  87. self.finish()
  88. }
  89. }
  90. }
  91. // MARK: -
  92. class NCOperationDownloadThumbnailActivity: ConcurrentOperation {
  93. var cell: NCActivityCollectionViewCell?
  94. var collectionView: UICollectionView?
  95. var fileNamePathOrFileId: String
  96. var fileNamePreviewLocalPath: String
  97. var fileId: String
  98. init(fileNamePathOrFileId: String, fileNamePreviewLocalPath: String, fileId: String, cell: NCActivityCollectionViewCell?, collectionView: UICollectionView?) {
  99. self.fileNamePathOrFileId = fileNamePathOrFileId
  100. self.fileNamePreviewLocalPath = fileNamePreviewLocalPath
  101. self.fileId = fileId
  102. self.cell = cell
  103. self.collectionView = collectionView
  104. }
  105. override func start() {
  106. guard !isCancelled else { return self.finish() }
  107. NextcloudKit.shared.downloadPreview(fileNamePathOrFileId: fileNamePathOrFileId,
  108. fileNamePreviewLocalPath: fileNamePreviewLocalPath,
  109. widthPreview: 0,
  110. heightPreview: 0,
  111. etag: nil,
  112. useInternalEndpoint: false,
  113. options: NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)) { _, imagePreview, _, _, _, error in
  114. if error == .success, let imagePreview = imagePreview {
  115. DispatchQueue.main.async {
  116. if self.fileId == self.cell?.fileId, let imageView = self.cell?.imageView {
  117. UIView.transition(with: imageView,
  118. duration: 0.75,
  119. options: .transitionCrossDissolve,
  120. animations: { imageView.image = imagePreview },
  121. completion: nil)
  122. } else {
  123. self.collectionView?.reloadData()
  124. }
  125. }
  126. }
  127. self.finish()
  128. }
  129. }
  130. }
  131. // MARK: -
  132. class NCOperationDownloadAvatar: ConcurrentOperation {
  133. var user: String
  134. var fileName: String
  135. var etag: String?
  136. var fileNameLocalPath: String
  137. var cell: NCCellProtocol!
  138. var view: UIView?
  139. var cellImageView: UIImageView?
  140. init(user: String, fileName: String, fileNameLocalPath: String, cell: NCCellProtocol, view: UIView?, cellImageView: UIImageView?) {
  141. self.user = user
  142. self.fileName = fileName
  143. self.fileNameLocalPath = fileNameLocalPath
  144. self.cell = cell
  145. self.view = view
  146. self.etag = NCManageDatabase.shared.getTableAvatar(fileName: fileName)?.etag
  147. self.cellImageView = cellImageView
  148. }
  149. override func start() {
  150. guard !isCancelled else { return self.finish() }
  151. NextcloudKit.shared.downloadAvatar(user: user,
  152. fileNameLocalPath: fileNameLocalPath,
  153. sizeImage: NCGlobal.shared.avatarSize,
  154. avatarSizeRounded: NCGlobal.shared.avatarSizeRounded,
  155. etag: self.etag,
  156. options: NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)) { _, imageAvatar, _, etag, error in
  157. if error == .success, let imageAvatar = imageAvatar, let etag = etag {
  158. NCManageDatabase.shared.addAvatar(fileName: self.fileName, etag: etag)
  159. DispatchQueue.main.async {
  160. if self.user == self.cell.fileUser, let avatarImageView = self.cellImageView {
  161. UIView.transition(with: avatarImageView,
  162. duration: 0.75,
  163. options: .transitionCrossDissolve,
  164. animations: { avatarImageView.image = imageAvatar },
  165. completion: nil)
  166. } else {
  167. if self.view is UICollectionView {
  168. (self.view as? UICollectionView)?.reloadData()
  169. } else if self.view is UITableView {
  170. (self.view as? UITableView)?.reloadData()
  171. }
  172. }
  173. }
  174. } else if error.errorCode == NCGlobal.shared.errorNotModified {
  175. NCManageDatabase.shared.setAvatarLoaded(fileName: self.fileName)
  176. }
  177. self.finish()
  178. }
  179. }
  180. }
  181. // MARK: -
  182. class NCOperationUnifiedSearch: ConcurrentOperation {
  183. var collectionViewCommon: NCCollectionViewCommon
  184. var metadatas: [tableMetadata]
  185. var searchResult: NKSearchResult
  186. init(collectionViewCommon: NCCollectionViewCommon, metadatas: [tableMetadata], searchResult: NKSearchResult) {
  187. self.collectionViewCommon = collectionViewCommon
  188. self.metadatas = metadatas
  189. self.searchResult = searchResult
  190. }
  191. func reloadDataThenPerform(_ closure: @escaping (() -> Void)) {
  192. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  193. CATransaction.begin()
  194. CATransaction.setCompletionBlock(closure)
  195. self.collectionViewCommon.collectionView.reloadData()
  196. CATransaction.commit()
  197. }
  198. }
  199. override func start() {
  200. guard !isCancelled else { return self.finish() }
  201. self.collectionViewCommon.dataSource.addSection(metadatas: metadatas, searchResult: searchResult)
  202. self.collectionViewCommon.searchResults?.append(self.searchResult)
  203. reloadDataThenPerform {
  204. self.finish()
  205. }
  206. }
  207. }
  208. // MARK: -
  209. class NCOperationSaveLivePhoto: ConcurrentOperation {
  210. var metadata: tableMetadata
  211. var metadataMOV: tableMetadata
  212. let hud = JGProgressHUD()
  213. let appDelegate = UIApplication.shared.delegate as? AppDelegate
  214. init(metadata: tableMetadata, metadataMOV: tableMetadata) {
  215. self.metadata = tableMetadata.init(value: metadata)
  216. self.metadataMOV = tableMetadata.init(value: metadataMOV)
  217. }
  218. override func start() {
  219. guard !isCancelled else { return self.finish() }
  220. DispatchQueue.main.async {
  221. self.hud.indicatorView = JGProgressHUDRingIndicatorView()
  222. if let indicatorView = self.hud.indicatorView as? JGProgressHUDRingIndicatorView {
  223. indicatorView.ringWidth = 1.5
  224. }
  225. self.hud.textLabel.text = NSLocalizedString("_download_image_", comment: "")
  226. self.hud.detailTextLabel.text = self.metadata.fileName
  227. self.hud.show(in: (self.appDelegate?.window?.rootViewController?.view)!)
  228. }
  229. NCNetworking.shared.download(metadata: metadata, selector: "", notificationCenterProgressTask: false, checkfileProviderStorageExists: true) { _ in
  230. } progressHandler: { progress in
  231. self.hud.progress = Float(progress.fractionCompleted)
  232. } completion: { _, error in
  233. guard error == .success else {
  234. DispatchQueue.main.async {
  235. self.hud.indicatorView = JGProgressHUDErrorIndicatorView()
  236. self.hud.textLabel.text = NSLocalizedString("_livephoto_save_error_", comment: "")
  237. self.hud.dismiss()
  238. }
  239. return self.finish()
  240. }
  241. NCNetworking.shared.download(metadata: self.metadataMOV, selector: "", notificationCenterProgressTask: false, checkfileProviderStorageExists: true) { _ in
  242. DispatchQueue.main.async {
  243. self.hud.textLabel.text = NSLocalizedString("_download_video_", comment: "")
  244. self.hud.detailTextLabel.text = self.metadataMOV.fileName
  245. }
  246. } progressHandler: { progress in
  247. self.hud.progress = Float(progress.fractionCompleted)
  248. } completion: { _, error in
  249. guard error == .success else {
  250. DispatchQueue.main.async {
  251. self.hud.indicatorView = JGProgressHUDErrorIndicatorView()
  252. self.hud.textLabel.text = NSLocalizedString("_livephoto_save_error_", comment: "")
  253. self.hud.dismiss()
  254. }
  255. return self.finish()
  256. }
  257. self.saveLivePhotoToDisk(metadata: self.metadata, metadataMov: self.metadataMOV)
  258. }
  259. }
  260. }
  261. func saveLivePhotoToDisk(metadata: tableMetadata, metadataMov: tableMetadata) {
  262. let fileNameImage = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!)
  263. let fileNameMov = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadataMov.ocId, fileNameView: metadataMov.fileNameView)!)
  264. DispatchQueue.main.async {
  265. self.hud.textLabel.text = NSLocalizedString("_livephoto_save_", comment: "")
  266. self.hud.detailTextLabel.text = ""
  267. }
  268. NCLivePhoto.generate(from: fileNameImage, videoURL: fileNameMov, progress: { progress in
  269. self.hud.progress = Float(progress)
  270. }, completion: { _, resources in
  271. if resources != nil {
  272. NCLivePhoto.saveToLibrary(resources!) { result in
  273. DispatchQueue.main.async {
  274. if !result {
  275. self.hud.indicatorView = JGProgressHUDErrorIndicatorView()
  276. self.hud.textLabel.text = NSLocalizedString("_livephoto_save_error_", comment: "")
  277. } else {
  278. self.hud.indicatorView = JGProgressHUDSuccessIndicatorView()
  279. self.hud.textLabel.text = NSLocalizedString("_success_", comment: "")
  280. }
  281. self.hud.dismiss()
  282. }
  283. return self.finish()
  284. }
  285. } else {
  286. DispatchQueue.main.async {
  287. self.hud.indicatorView = JGProgressHUDErrorIndicatorView()
  288. self.hud.textLabel.text = NSLocalizedString("_livephoto_save_error_", comment: "")
  289. self.hud.dismiss()
  290. }
  291. return self.finish()
  292. }
  293. })
  294. }
  295. }