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)) { _, _, imageIcon, _, etag, error in
  155. if error == .success, let imageIcon = imageIcon {
  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 = imageIcon },
  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. }
  174. self.finish()
  175. }
  176. }
  177. }
  178. // MARK: -
  179. class NCOperationDownloadThumbnailActivity: ConcurrentOperation {
  180. var cell: NCActivityCollectionViewCell?
  181. var collectionView: UICollectionView?
  182. var fileNamePathOrFileId: String
  183. var fileNamePreviewLocalPath: String
  184. var fileId: String
  185. init(fileNamePathOrFileId: String, fileNamePreviewLocalPath: String, fileId: String, cell: NCActivityCollectionViewCell?, collectionView: UICollectionView?) {
  186. self.fileNamePathOrFileId = fileNamePathOrFileId
  187. self.fileNamePreviewLocalPath = fileNamePreviewLocalPath
  188. self.fileId = fileId
  189. self.cell = cell
  190. self.collectionView = collectionView
  191. }
  192. override func start() {
  193. guard !isCancelled else { return self.finish() }
  194. NextcloudKit.shared.downloadPreview(
  195. fileNamePathOrFileId: fileNamePathOrFileId,
  196. fileNamePreviewLocalPath: fileNamePreviewLocalPath,
  197. widthPreview: 0,
  198. heightPreview: 0,
  199. etag: nil,
  200. useInternalEndpoint: false,
  201. options: NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)) { _, imagePreview, _, _, _, error in
  202. if error == .success, let imagePreview = imagePreview {
  203. DispatchQueue.main.async {
  204. if self.fileId == self.cell?.fileId, let imageView = self.cell?.imageView {
  205. UIView.transition(with: imageView,
  206. duration: 0.75,
  207. options: .transitionCrossDissolve,
  208. animations: { imageView.image = imagePreview },
  209. completion: nil)
  210. } else {
  211. self.collectionView?.reloadData()
  212. }
  213. }
  214. }
  215. self.finish()
  216. }
  217. }
  218. }
  219. // MARK: -
  220. class NCOperationDownloadAvatar: ConcurrentOperation {
  221. var user: String
  222. var fileName: String
  223. var etag: String?
  224. var fileNameLocalPath: String
  225. var cell: NCCellProtocol!
  226. var view: UIView?
  227. var cellImageView: UIImageView?
  228. init(user: String, fileName: String, fileNameLocalPath: String, cell: NCCellProtocol, view: UIView?, cellImageView: UIImageView?) {
  229. self.user = user
  230. self.fileName = fileName
  231. self.fileNameLocalPath = fileNameLocalPath
  232. self.cell = cell
  233. self.view = view
  234. self.etag = NCManageDatabase.shared.getTableAvatar(fileName: fileName)?.etag
  235. self.cellImageView = cellImageView
  236. }
  237. override func start() {
  238. guard !isCancelled else { return self.finish() }
  239. NextcloudKit.shared.downloadAvatar(user: user,
  240. fileNameLocalPath: fileNameLocalPath,
  241. sizeImage: NCGlobal.shared.avatarSize,
  242. avatarSizeRounded: NCGlobal.shared.avatarSizeRounded,
  243. etag: self.etag,
  244. options: NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)) { _, imageAvatar, _, etag, error in
  245. if error == .success, let imageAvatar = imageAvatar, let etag = etag {
  246. NCManageDatabase.shared.addAvatar(fileName: self.fileName, etag: etag)
  247. DispatchQueue.main.async {
  248. if self.user == self.cell.fileUser, let avatarImageView = self.cellImageView {
  249. UIView.transition(with: avatarImageView,
  250. duration: 0.75,
  251. options: .transitionCrossDissolve,
  252. animations: { avatarImageView.image = imageAvatar },
  253. completion: nil)
  254. } else {
  255. if self.view is UICollectionView {
  256. (self.view as? UICollectionView)?.reloadData()
  257. } else if self.view is UITableView {
  258. (self.view as? UITableView)?.reloadData()
  259. }
  260. }
  261. }
  262. } else if error.errorCode == NCGlobal.shared.errorNotModified {
  263. NCManageDatabase.shared.setAvatarLoaded(fileName: self.fileName)
  264. }
  265. self.finish()
  266. }
  267. }
  268. }
  269. // MARK: -
  270. class NCOperationUnifiedSearch: ConcurrentOperation {
  271. var collectionViewCommon: NCCollectionViewCommon
  272. var metadatas: [tableMetadata]
  273. var searchResult: NKSearchResult
  274. init(collectionViewCommon: NCCollectionViewCommon, metadatas: [tableMetadata], searchResult: NKSearchResult) {
  275. self.collectionViewCommon = collectionViewCommon
  276. self.metadatas = metadatas
  277. self.searchResult = searchResult
  278. }
  279. func reloadDataThenPerform(_ closure: @escaping (() -> Void)) {
  280. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  281. CATransaction.begin()
  282. CATransaction.setCompletionBlock(closure)
  283. self.collectionViewCommon.collectionView.reloadData()
  284. CATransaction.commit()
  285. }
  286. }
  287. override func start() {
  288. guard !isCancelled else { return self.finish() }
  289. self.collectionViewCommon.dataSource.addSection(metadatas: metadatas, searchResult: searchResult)
  290. self.collectionViewCommon.searchResults?.append(self.searchResult)
  291. reloadDataThenPerform {
  292. self.finish()
  293. }
  294. }
  295. }
  296. // MARK: -
  297. class NCOperationSaveLivePhoto: ConcurrentOperation {
  298. var metadata: tableMetadata
  299. var metadataMOV: tableMetadata
  300. let hud = JGProgressHUD()
  301. let appDelegate = UIApplication.shared.delegate as? AppDelegate
  302. init(metadata: tableMetadata, metadataMOV: tableMetadata) {
  303. self.metadata = tableMetadata.init(value: metadata)
  304. self.metadataMOV = tableMetadata.init(value: metadataMOV)
  305. }
  306. override func start() {
  307. guard !isCancelled else { return self.finish() }
  308. DispatchQueue.main.async {
  309. self.hud.indicatorView = JGProgressHUDRingIndicatorView()
  310. if let indicatorView = self.hud.indicatorView as? JGProgressHUDRingIndicatorView {
  311. indicatorView.ringWidth = 1.5
  312. }
  313. self.hud.textLabel.text = NSLocalizedString("_download_image_", comment: "")
  314. self.hud.detailTextLabel.text = self.metadata.fileName
  315. self.hud.show(in: (self.appDelegate?.window?.rootViewController?.view)!)
  316. }
  317. NCNetworking.shared.download(metadata: metadata, selector: "", notificationCenterProgressTask: false, checkfileProviderStorageExists: true) { _ in
  318. } progressHandler: { progress in
  319. self.hud.progress = Float(progress.fractionCompleted)
  320. } completion: { _, error in
  321. guard error == .success else {
  322. DispatchQueue.main.async {
  323. self.hud.indicatorView = JGProgressHUDErrorIndicatorView()
  324. self.hud.textLabel.text = NSLocalizedString("_livephoto_save_error_", comment: "")
  325. self.hud.dismiss()
  326. }
  327. return self.finish()
  328. }
  329. NCNetworking.shared.download(metadata: self.metadataMOV, selector: "", notificationCenterProgressTask: false, checkfileProviderStorageExists: true) { _ in
  330. DispatchQueue.main.async {
  331. self.hud.textLabel.text = NSLocalizedString("_download_video_", comment: "")
  332. self.hud.detailTextLabel.text = self.metadataMOV.fileName
  333. }
  334. } progressHandler: { progress in
  335. self.hud.progress = Float(progress.fractionCompleted)
  336. } completion: { _, error in
  337. guard error == .success else {
  338. DispatchQueue.main.async {
  339. self.hud.indicatorView = JGProgressHUDErrorIndicatorView()
  340. self.hud.textLabel.text = NSLocalizedString("_livephoto_save_error_", comment: "")
  341. self.hud.dismiss()
  342. }
  343. return self.finish()
  344. }
  345. self.saveLivePhotoToDisk(metadata: self.metadata, metadataMov: self.metadataMOV)
  346. }
  347. }
  348. }
  349. func saveLivePhotoToDisk(metadata: tableMetadata, metadataMov: tableMetadata) {
  350. let fileNameImage = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!)
  351. let fileNameMov = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadataMov.ocId, fileNameView: metadataMov.fileNameView)!)
  352. DispatchQueue.main.async {
  353. self.hud.textLabel.text = NSLocalizedString("_livephoto_save_", comment: "")
  354. self.hud.detailTextLabel.text = ""
  355. }
  356. NCLivePhoto.generate(from: fileNameImage, videoURL: fileNameMov, progress: { progress in
  357. self.hud.progress = Float(progress)
  358. }, completion: { _, resources in
  359. if resources != nil {
  360. NCLivePhoto.saveToLibrary(resources!) { result in
  361. DispatchQueue.main.async {
  362. if !result {
  363. self.hud.indicatorView = JGProgressHUDErrorIndicatorView()
  364. self.hud.textLabel.text = NSLocalizedString("_livephoto_save_error_", comment: "")
  365. } else {
  366. self.hud.indicatorView = JGProgressHUDSuccessIndicatorView()
  367. self.hud.textLabel.text = NSLocalizedString("_success_", comment: "")
  368. }
  369. self.hud.dismiss()
  370. }
  371. return self.finish()
  372. }
  373. } else {
  374. DispatchQueue.main.async {
  375. self.hud.indicatorView = JGProgressHUDErrorIndicatorView()
  376. self.hud.textLabel.text = NSLocalizedString("_livephoto_save_error_", comment: "")
  377. self.hud.dismiss()
  378. }
  379. return self.finish()
  380. }
  381. })
  382. }
  383. }