NCOperationQueue.swift 19 KB

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