NCOperationQueue.swift 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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. private var downloadQueue = Queuer(name: "downloadQueue", maxConcurrentOperationCount: NCGlobal.shared.maxConcurrentOperationCountDownload, qualityOfService: .default)
  33. private let downloadThumbnailQueue = Queuer(name: "downloadThumbnailQueue", maxConcurrentOperationCount: 10, qualityOfService: .default)
  34. private let downloadThumbnailActivityQueue = Queuer(name: "downloadThumbnailActivityQueue", maxConcurrentOperationCount: 10, qualityOfService: .default)
  35. private let downloadAvatarQueue = Queuer(name: "downloadAvatarQueue", maxConcurrentOperationCount: 10, qualityOfService: .default)
  36. private let unifiedSearchQueue = Queuer(name: "unifiedSearchQueue", maxConcurrentOperationCount: 1, qualityOfService: .default)
  37. private let saveLivePhotoQueue = Queuer(name: "saveLivePhotoQueue", maxConcurrentOperationCount: 1, qualityOfService: .default)
  38. @objc func cancelAllQueue() {
  39. downloadQueue.cancelAll()
  40. downloadThumbnailQueue.cancelAll()
  41. downloadThumbnailActivityQueue.cancelAll()
  42. downloadAvatarQueue.cancelAll()
  43. unifiedSearchQueue.cancelAll()
  44. saveLivePhotoQueue.cancelAll()
  45. }
  46. // MARK: - Download file
  47. func download(metadata: tableMetadata, selector: String) {
  48. for case let operation as NCOperationDownload in downloadQueue.operations where operation.metadata.ocId == metadata.ocId { return }
  49. downloadQueue.addOperation(NCOperationDownload(metadata: metadata, selector: selector))
  50. }
  51. // MARK: - Download Thumbnail
  52. func downloadThumbnail(metadata: tableMetadata, placeholder: Bool, cell: UIView?, view: UIView?) {
  53. let cell: NCCellProtocol? = cell as? NCCellProtocol
  54. if placeholder {
  55. if metadata.iconName.isEmpty {
  56. cell?.filePreviewImageView?.image = NCBrandColor.cacheImages.file
  57. } else {
  58. cell?.filePreviewImageView?.image = UIImage(named: metadata.iconName)
  59. }
  60. }
  61. if metadata.hasPreview && metadata.status == NCGlobal.shared.metadataStatusNormal && (!CCUtility.fileProviderStoragePreviewIconExists(metadata.ocId, etag: metadata.etag)) {
  62. for case let operation as NCOperationDownloadThumbnail in downloadThumbnailQueue.operations where operation.metadata.ocId == metadata.ocId { return }
  63. downloadThumbnailQueue.addOperation(NCOperationDownloadThumbnail(metadata: metadata, cell: cell, view: view))
  64. }
  65. }
  66. func cancelDownloadThumbnail(metadata: tableMetadata) {
  67. for case let operation as NCOperationDownloadThumbnail in downloadThumbnailQueue.operations where operation.metadata.ocId == metadata.ocId {
  68. operation.cancel()
  69. }
  70. }
  71. // MARK: - Download Thumbnail Activity
  72. func downloadThumbnailActivity(fileNamePathOrFileId: String, fileNamePreviewLocalPath: String, fileId: String, cell: NCActivityCollectionViewCell, collectionView: UICollectionView?) {
  73. cell.imageView?.image = UIImage(named: "file_photo")
  74. cell.fileId = fileId
  75. if !FileManager.default.fileExists(atPath: fileNamePreviewLocalPath) {
  76. for case let operation as NCOperationDownloadThumbnailActivity in downloadThumbnailActivityQueue.operations where operation.fileId == fileId {
  77. return
  78. }
  79. downloadThumbnailActivityQueue.addOperation(NCOperationDownloadThumbnailActivity(fileNamePathOrFileId: fileNamePathOrFileId, fileNamePreviewLocalPath: fileNamePreviewLocalPath, fileId: fileId, cell: cell, collectionView: collectionView))
  80. }
  81. }
  82. // MARK: - Download Avatar
  83. func downloadAvatar(user: String, dispalyName: String?, fileName: String, cell: NCCellProtocol, view: UIView?, cellImageView: UIImageView?) {
  84. let fileNameLocalPath = String(CCUtility.getDirectoryUserData()) + "/" + fileName
  85. if let image = NCManageDatabase.shared.getImageAvatarLoaded(fileName: fileName) {
  86. cellImageView?.image = image
  87. cell.fileAvatarImageView?.image = image
  88. return
  89. }
  90. if let account = NCManageDatabase.shared.getActiveAccount() {
  91. cellImageView?.image = NCUtility.shared.loadUserImage(
  92. for: user,
  93. displayName: dispalyName,
  94. userBaseUrl: account)
  95. }
  96. for case let operation as NCOperationDownloadAvatar in downloadAvatarQueue.operations where operation.fileName == fileName { return }
  97. downloadAvatarQueue.addOperation(NCOperationDownloadAvatar(user: user, fileName: fileName, fileNameLocalPath: fileNameLocalPath, cell: cell, view: view, cellImageView: cellImageView))
  98. }
  99. // MARK: - Unified Search
  100. func unifiedSearchAddSection(collectionViewCommon: NCCollectionViewCommon, metadatas: [tableMetadata], searchResult: NKSearchResult) {
  101. unifiedSearchQueue.addOperation(NCOperationUnifiedSearch(collectionViewCommon: collectionViewCommon, metadatas: metadatas, searchResult: searchResult))
  102. }
  103. // MARK: - Save Live Photo
  104. func saveLivePhoto(metadata: tableMetadata, metadataMOV: tableMetadata) {
  105. for case let operation as NCOperationSaveLivePhoto in saveLivePhotoQueue.operations where operation.metadata.fileName == metadata.fileName { return }
  106. saveLivePhotoQueue.addOperation(NCOperationSaveLivePhoto(metadata: metadata, metadataMOV: metadataMOV))
  107. }
  108. }
  109. // MARK: -
  110. class NCOperationDownload: ConcurrentOperation {
  111. var metadata: tableMetadata
  112. var selector: String
  113. init(metadata: tableMetadata, selector: String) {
  114. self.metadata = tableMetadata.init(value: metadata)
  115. self.selector = selector
  116. }
  117. override func start() {
  118. guard !isCancelled else { return self.finish() }
  119. NCNetworking.shared.download(metadata: metadata, selector: self.selector) { _, _ in
  120. self.finish()
  121. }
  122. }
  123. }
  124. // MARK: -
  125. class NCOperationDownloadThumbnail: ConcurrentOperation {
  126. var metadata: tableMetadata
  127. var cell: NCCellProtocol?
  128. var view: UIView?
  129. var fileNamePath: String
  130. var fileNamePreviewLocalPath: String
  131. var fileNameIconLocalPath: String
  132. init(metadata: tableMetadata, cell: NCCellProtocol?, view: UIView?) {
  133. self.metadata = tableMetadata.init(value: metadata)
  134. self.cell = cell
  135. self.view = view
  136. self.fileNamePath = CCUtility.returnFileNamePath(fromFileName: metadata.fileName, serverUrl: metadata.serverUrl, urlBase: metadata.urlBase, userId: metadata.userId, account: metadata.account)!
  137. self.fileNamePreviewLocalPath = CCUtility.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag)!
  138. self.fileNameIconLocalPath = CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)!
  139. }
  140. override func start() {
  141. guard !isCancelled else { return self.finish() }
  142. var etagResource: String?
  143. if FileManager.default.fileExists(atPath: fileNameIconLocalPath) && FileManager.default.fileExists(atPath: fileNamePreviewLocalPath) {
  144. etagResource = metadata.etagResource
  145. }
  146. NextcloudKit.shared.downloadPreview(
  147. fileNamePathOrFileId: fileNamePath,
  148. fileNamePreviewLocalPath: fileNamePreviewLocalPath,
  149. widthPreview: NCGlobal.shared.sizePreview,
  150. heightPreview: NCGlobal.shared.sizePreview,
  151. fileNameIconLocalPath: fileNameIconLocalPath,
  152. sizeIcon: NCGlobal.shared.sizeIcon,
  153. etag: etagResource,
  154. options: NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)) { _, imagePreview, _, _, etag, error in
  155. if error == .success, let image = imagePreview {
  156. NCManageDatabase.shared.setMetadataEtagResource(ocId: self.metadata.ocId, etagResource: etag)
  157. DispatchQueue.main.async {
  158. if self.metadata.ocId == self.cell?.fileObjectId, let filePreviewImageView = self.cell?.filePreviewImageView {
  159. UIView.transition(with: filePreviewImageView,
  160. duration: 0.75,
  161. options: .transitionCrossDissolve,
  162. animations: { filePreviewImageView.image = image },
  163. completion: nil)
  164. } else {
  165. if self.view is UICollectionView {
  166. (self.view as? UICollectionView)?.reloadData()
  167. } else if self.view is UITableView {
  168. (self.view as? UITableView)?.reloadData()
  169. }
  170. }
  171. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDownloadedThumbnail, userInfo: ["ocId": self.metadata.ocId])
  172. }
  173. NCMediaManager.shared.setImage(ocId: self.metadata.ocId, image: image)
  174. }
  175. self.finish()
  176. }
  177. }
  178. }
  179. // MARK: -
  180. class NCOperationDownloadThumbnailActivity: ConcurrentOperation {
  181. var cell: NCActivityCollectionViewCell?
  182. var collectionView: UICollectionView?
  183. var fileNamePathOrFileId: String
  184. var fileNamePreviewLocalPath: String
  185. var fileId: String
  186. init(fileNamePathOrFileId: String, fileNamePreviewLocalPath: String, fileId: String, cell: NCActivityCollectionViewCell?, collectionView: UICollectionView?) {
  187. self.fileNamePathOrFileId = fileNamePathOrFileId
  188. self.fileNamePreviewLocalPath = fileNamePreviewLocalPath
  189. self.fileId = fileId
  190. self.cell = cell
  191. self.collectionView = collectionView
  192. }
  193. override func start() {
  194. guard !isCancelled else { return self.finish() }
  195. NextcloudKit.shared.downloadPreview(
  196. fileNamePathOrFileId: fileNamePathOrFileId,
  197. fileNamePreviewLocalPath: fileNamePreviewLocalPath,
  198. widthPreview: 0,
  199. heightPreview: 0,
  200. etag: nil,
  201. useInternalEndpoint: false,
  202. options: NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)) { _, imagePreview, _, _, _, error in
  203. if error == .success, let imagePreview = imagePreview {
  204. DispatchQueue.main.async {
  205. if self.fileId == self.cell?.fileId, let imageView = self.cell?.imageView {
  206. UIView.transition(with: imageView,
  207. duration: 0.75,
  208. options: .transitionCrossDissolve,
  209. animations: { imageView.image = imagePreview },
  210. completion: nil)
  211. } else {
  212. self.collectionView?.reloadData()
  213. }
  214. }
  215. }
  216. self.finish()
  217. }
  218. }
  219. }
  220. // MARK: -
  221. class NCOperationDownloadAvatar: ConcurrentOperation {
  222. var user: String
  223. var fileName: String
  224. var etag: String?
  225. var fileNameLocalPath: String
  226. var cell: NCCellProtocol!
  227. var view: UIView?
  228. var cellImageView: UIImageView?
  229. init(user: String, fileName: String, fileNameLocalPath: String, cell: NCCellProtocol, view: UIView?, cellImageView: UIImageView?) {
  230. self.user = user
  231. self.fileName = fileName
  232. self.fileNameLocalPath = fileNameLocalPath
  233. self.cell = cell
  234. self.view = view
  235. self.etag = NCManageDatabase.shared.getTableAvatar(fileName: fileName)?.etag
  236. self.cellImageView = cellImageView
  237. }
  238. override func start() {
  239. guard !isCancelled else { return self.finish() }
  240. NextcloudKit.shared.downloadAvatar(user: user,
  241. fileNameLocalPath: fileNameLocalPath,
  242. sizeImage: NCGlobal.shared.avatarSize,
  243. avatarSizeRounded: NCGlobal.shared.avatarSizeRounded,
  244. etag: self.etag,
  245. options: NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)) { _, imageAvatar, _, etag, error in
  246. if error == .success, let imageAvatar = imageAvatar, let etag = etag {
  247. NCManageDatabase.shared.addAvatar(fileName: self.fileName, etag: etag)
  248. DispatchQueue.main.async {
  249. if self.user == self.cell.fileUser, let avatarImageView = self.cellImageView {
  250. UIView.transition(with: avatarImageView,
  251. duration: 0.75,
  252. options: .transitionCrossDissolve,
  253. animations: { avatarImageView.image = imageAvatar },
  254. completion: nil)
  255. } else {
  256. if self.view is UICollectionView {
  257. (self.view as? UICollectionView)?.reloadData()
  258. } else if self.view is UITableView {
  259. (self.view as? UITableView)?.reloadData()
  260. }
  261. }
  262. }
  263. } else if error.errorCode == NCGlobal.shared.errorNotModified {
  264. NCManageDatabase.shared.setAvatarLoaded(fileName: self.fileName)
  265. }
  266. self.finish()
  267. }
  268. }
  269. }
  270. // MARK: -
  271. class NCOperationUnifiedSearch: ConcurrentOperation {
  272. var collectionViewCommon: NCCollectionViewCommon
  273. var metadatas: [tableMetadata]
  274. var searchResult: NKSearchResult
  275. init(collectionViewCommon: NCCollectionViewCommon, metadatas: [tableMetadata], searchResult: NKSearchResult) {
  276. self.collectionViewCommon = collectionViewCommon
  277. self.metadatas = metadatas
  278. self.searchResult = searchResult
  279. }
  280. func reloadDataThenPerform(_ closure: @escaping (() -> Void)) {
  281. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  282. CATransaction.begin()
  283. CATransaction.setCompletionBlock(closure)
  284. self.collectionViewCommon.collectionView.reloadData()
  285. CATransaction.commit()
  286. }
  287. }
  288. override func start() {
  289. guard !isCancelled else { return self.finish() }
  290. self.collectionViewCommon.dataSource.addSection(metadatas: metadatas, searchResult: searchResult)
  291. self.collectionViewCommon.searchResults?.append(self.searchResult)
  292. reloadDataThenPerform {
  293. self.finish()
  294. }
  295. }
  296. }
  297. // MARK: -
  298. class NCOperationSaveLivePhoto: ConcurrentOperation {
  299. var metadata: tableMetadata
  300. var metadataMOV: tableMetadata
  301. let hud = JGProgressHUD()
  302. let appDelegate = UIApplication.shared.delegate as? AppDelegate
  303. init(metadata: tableMetadata, metadataMOV: tableMetadata) {
  304. self.metadata = tableMetadata.init(value: metadata)
  305. self.metadataMOV = tableMetadata.init(value: metadataMOV)
  306. }
  307. override func start() {
  308. guard !isCancelled else { return self.finish() }
  309. DispatchQueue.main.async {
  310. self.hud.indicatorView = JGProgressHUDRingIndicatorView()
  311. if let indicatorView = self.hud.indicatorView as? JGProgressHUDRingIndicatorView {
  312. indicatorView.ringWidth = 1.5
  313. }
  314. self.hud.textLabel.text = NSLocalizedString("_download_image_", comment: "")
  315. self.hud.detailTextLabel.text = self.metadata.fileName
  316. self.hud.show(in: (self.appDelegate?.window?.rootViewController?.view)!)
  317. }
  318. NCNetworking.shared.download(metadata: metadata, selector: "", notificationCenterProgressTask: false, checkfileProviderStorageExists: true) { _ in
  319. } progressHandler: { progress in
  320. self.hud.progress = Float(progress.fractionCompleted)
  321. } completion: { _, error in
  322. guard error == .success else {
  323. DispatchQueue.main.async {
  324. self.hud.indicatorView = JGProgressHUDErrorIndicatorView()
  325. self.hud.textLabel.text = NSLocalizedString("_livephoto_save_error_", comment: "")
  326. self.hud.dismiss()
  327. }
  328. return self.finish()
  329. }
  330. NCNetworking.shared.download(metadata: self.metadataMOV, selector: "", notificationCenterProgressTask: false, checkfileProviderStorageExists: true) { _ in
  331. DispatchQueue.main.async {
  332. self.hud.textLabel.text = NSLocalizedString("_download_video_", comment: "")
  333. self.hud.detailTextLabel.text = self.metadataMOV.fileName
  334. }
  335. } progressHandler: { progress in
  336. self.hud.progress = Float(progress.fractionCompleted)
  337. } completion: { _, error in
  338. guard error == .success else {
  339. DispatchQueue.main.async {
  340. self.hud.indicatorView = JGProgressHUDErrorIndicatorView()
  341. self.hud.textLabel.text = NSLocalizedString("_livephoto_save_error_", comment: "")
  342. self.hud.dismiss()
  343. }
  344. return self.finish()
  345. }
  346. self.saveLivePhotoToDisk(metadata: self.metadata, metadataMov: self.metadataMOV)
  347. }
  348. }
  349. }
  350. func saveLivePhotoToDisk(metadata: tableMetadata, metadataMov: tableMetadata) {
  351. let fileNameImage = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!)
  352. let fileNameMov = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadataMov.ocId, fileNameView: metadataMov.fileNameView)!)
  353. DispatchQueue.main.async {
  354. self.hud.textLabel.text = NSLocalizedString("_livephoto_save_", comment: "")
  355. self.hud.detailTextLabel.text = ""
  356. }
  357. NCLivePhoto.generate(from: fileNameImage, videoURL: fileNameMov, progress: { progress in
  358. self.hud.progress = Float(progress)
  359. }, completion: { _, resources in
  360. if resources != nil {
  361. NCLivePhoto.saveToLibrary(resources!) { result in
  362. DispatchQueue.main.async {
  363. if !result {
  364. self.hud.indicatorView = JGProgressHUDErrorIndicatorView()
  365. self.hud.textLabel.text = NSLocalizedString("_livephoto_save_error_", comment: "")
  366. } else {
  367. self.hud.indicatorView = JGProgressHUDSuccessIndicatorView()
  368. self.hud.textLabel.text = NSLocalizedString("_success_", comment: "")
  369. }
  370. self.hud.dismiss()
  371. }
  372. return self.finish()
  373. }
  374. } else {
  375. DispatchQueue.main.async {
  376. self.hud.indicatorView = JGProgressHUDErrorIndicatorView()
  377. self.hud.textLabel.text = NSLocalizedString("_livephoto_save_error_", comment: "")
  378. self.hud.dismiss()
  379. }
  380. return self.finish()
  381. }
  382. })
  383. }
  384. }