NCOperationQueue.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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(
  108. fileNamePathOrFileId: fileNamePathOrFileId,
  109. fileNamePreviewLocalPath: fileNamePreviewLocalPath,
  110. widthPreview: 0,
  111. heightPreview: 0,
  112. etag: nil,
  113. useInternalEndpoint: false,
  114. options: NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)) { _, imagePreview, _, _, _, error in
  115. if error == .success, let imagePreview = imagePreview {
  116. DispatchQueue.main.async {
  117. if self.fileId == self.cell?.fileId, let imageView = self.cell?.imageView {
  118. UIView.transition(with: imageView,
  119. duration: 0.75,
  120. options: .transitionCrossDissolve,
  121. animations: { imageView.image = imagePreview },
  122. completion: nil)
  123. } else {
  124. self.collectionView?.reloadData()
  125. }
  126. }
  127. }
  128. self.finish()
  129. }
  130. }
  131. }
  132. // MARK: -
  133. class NCOperationDownloadAvatar: ConcurrentOperation {
  134. var user: String
  135. var fileName: String
  136. var etag: String?
  137. var fileNameLocalPath: String
  138. var cell: NCCellProtocol!
  139. var view: UIView?
  140. var cellImageView: UIImageView?
  141. init(user: String, fileName: String, fileNameLocalPath: String, cell: NCCellProtocol, view: UIView?, cellImageView: UIImageView?) {
  142. self.user = user
  143. self.fileName = fileName
  144. self.fileNameLocalPath = fileNameLocalPath
  145. self.cell = cell
  146. self.view = view
  147. self.etag = NCManageDatabase.shared.getTableAvatar(fileName: fileName)?.etag
  148. self.cellImageView = cellImageView
  149. }
  150. override func start() {
  151. guard !isCancelled else { return self.finish() }
  152. NextcloudKit.shared.downloadAvatar(user: user,
  153. fileNameLocalPath: fileNameLocalPath,
  154. sizeImage: NCGlobal.shared.avatarSize,
  155. avatarSizeRounded: NCGlobal.shared.avatarSizeRounded,
  156. etag: self.etag,
  157. options: NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)) { _, imageAvatar, _, etag, error in
  158. if error == .success, let imageAvatar = imageAvatar, let etag = etag {
  159. NCManageDatabase.shared.addAvatar(fileName: self.fileName, etag: etag)
  160. DispatchQueue.main.async {
  161. if self.user == self.cell.fileUser, let avatarImageView = self.cellImageView {
  162. UIView.transition(with: avatarImageView,
  163. duration: 0.75,
  164. options: .transitionCrossDissolve,
  165. animations: { avatarImageView.image = imageAvatar },
  166. completion: nil)
  167. } else {
  168. if self.view is UICollectionView {
  169. (self.view as? UICollectionView)?.reloadData()
  170. } else if self.view is UITableView {
  171. (self.view as? UITableView)?.reloadData()
  172. }
  173. }
  174. }
  175. } else if error.errorCode == NCGlobal.shared.errorNotModified {
  176. NCManageDatabase.shared.setAvatarLoaded(fileName: self.fileName)
  177. }
  178. self.finish()
  179. }
  180. }
  181. }
  182. // MARK: -
  183. class NCOperationUnifiedSearch: ConcurrentOperation {
  184. var collectionViewCommon: NCCollectionViewCommon
  185. var metadatas: [tableMetadata]
  186. var searchResult: NKSearchResult
  187. init(collectionViewCommon: NCCollectionViewCommon, metadatas: [tableMetadata], searchResult: NKSearchResult) {
  188. self.collectionViewCommon = collectionViewCommon
  189. self.metadatas = metadatas
  190. self.searchResult = searchResult
  191. }
  192. func reloadDataThenPerform(_ closure: @escaping (() -> Void)) {
  193. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  194. CATransaction.begin()
  195. CATransaction.setCompletionBlock(closure)
  196. self.collectionViewCommon.collectionView.reloadData()
  197. CATransaction.commit()
  198. }
  199. }
  200. override func start() {
  201. guard !isCancelled else { return self.finish() }
  202. self.collectionViewCommon.dataSource.addSection(metadatas: metadatas, searchResult: searchResult)
  203. self.collectionViewCommon.searchResults?.append(self.searchResult)
  204. reloadDataThenPerform {
  205. self.finish()
  206. }
  207. }
  208. }
  209. // MARK: -
  210. class NCOperationSaveLivePhoto: ConcurrentOperation {
  211. var metadata: tableMetadata
  212. var metadataMOV: tableMetadata
  213. let hud = JGProgressHUD()
  214. let appDelegate = UIApplication.shared.delegate as? AppDelegate
  215. init(metadata: tableMetadata, metadataMOV: tableMetadata) {
  216. self.metadata = tableMetadata.init(value: metadata)
  217. self.metadataMOV = tableMetadata.init(value: metadataMOV)
  218. }
  219. override func start() {
  220. guard !isCancelled else { return self.finish() }
  221. DispatchQueue.main.async {
  222. self.hud.indicatorView = JGProgressHUDRingIndicatorView()
  223. if let indicatorView = self.hud.indicatorView as? JGProgressHUDRingIndicatorView {
  224. indicatorView.ringWidth = 1.5
  225. }
  226. self.hud.textLabel.text = NSLocalizedString("_download_image_", comment: "")
  227. self.hud.detailTextLabel.text = self.metadata.fileName
  228. self.hud.show(in: (self.appDelegate?.window?.rootViewController?.view)!)
  229. }
  230. NCNetworking.shared.download(metadata: metadata, selector: "", notificationCenterProgressTask: false, checkfileProviderStorageExists: true) { _ in
  231. } progressHandler: { progress in
  232. self.hud.progress = Float(progress.fractionCompleted)
  233. } completion: { _, error in
  234. guard error == .success else {
  235. DispatchQueue.main.async {
  236. self.hud.indicatorView = JGProgressHUDErrorIndicatorView()
  237. self.hud.textLabel.text = NSLocalizedString("_livephoto_save_error_", comment: "")
  238. self.hud.dismiss()
  239. }
  240. return self.finish()
  241. }
  242. NCNetworking.shared.download(metadata: self.metadataMOV, selector: "", notificationCenterProgressTask: false, checkfileProviderStorageExists: true) { _ in
  243. DispatchQueue.main.async {
  244. self.hud.textLabel.text = NSLocalizedString("_download_video_", comment: "")
  245. self.hud.detailTextLabel.text = self.metadataMOV.fileName
  246. }
  247. } progressHandler: { progress in
  248. self.hud.progress = Float(progress.fractionCompleted)
  249. } completion: { _, error in
  250. guard error == .success else {
  251. DispatchQueue.main.async {
  252. self.hud.indicatorView = JGProgressHUDErrorIndicatorView()
  253. self.hud.textLabel.text = NSLocalizedString("_livephoto_save_error_", comment: "")
  254. self.hud.dismiss()
  255. }
  256. return self.finish()
  257. }
  258. self.saveLivePhotoToDisk(metadata: self.metadata, metadataMov: self.metadataMOV)
  259. }
  260. }
  261. }
  262. func saveLivePhotoToDisk(metadata: tableMetadata, metadataMov: tableMetadata) {
  263. let fileNameImage = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!)
  264. let fileNameMov = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadataMov.ocId, fileNameView: metadataMov.fileNameView)!)
  265. DispatchQueue.main.async {
  266. self.hud.textLabel.text = NSLocalizedString("_livephoto_save_", comment: "")
  267. self.hud.detailTextLabel.text = ""
  268. }
  269. NCLivePhoto.generate(from: fileNameImage, videoURL: fileNameMov, progress: { progress in
  270. self.hud.progress = Float(progress)
  271. }, completion: { _, resources in
  272. if resources != nil {
  273. NCLivePhoto.saveToLibrary(resources!) { result in
  274. DispatchQueue.main.async {
  275. if !result {
  276. self.hud.indicatorView = JGProgressHUDErrorIndicatorView()
  277. self.hud.textLabel.text = NSLocalizedString("_livephoto_save_error_", comment: "")
  278. } else {
  279. self.hud.indicatorView = JGProgressHUDSuccessIndicatorView()
  280. self.hud.textLabel.text = NSLocalizedString("_success_", comment: "")
  281. }
  282. self.hud.dismiss()
  283. }
  284. return self.finish()
  285. }
  286. } else {
  287. DispatchQueue.main.async {
  288. self.hud.indicatorView = JGProgressHUDErrorIndicatorView()
  289. self.hud.textLabel.text = NSLocalizedString("_livephoto_save_error_", comment: "")
  290. self.hud.dismiss()
  291. }
  292. return self.finish()
  293. }
  294. })
  295. }
  296. }