NCOperationQueue.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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 NCOperationDownloadThumbnail: ConcurrentOperation {
  93. var metadata: tableMetadata
  94. var cell: NCCellProtocol?
  95. var view: UIView?
  96. var fileNamePath: String
  97. var fileNamePreviewLocalPath: String
  98. var fileNameIconLocalPath: String
  99. init(metadata: tableMetadata, cell: NCCellProtocol?, view: UIView?) {
  100. self.metadata = tableMetadata.init(value: metadata)
  101. self.cell = cell
  102. self.view = view
  103. self.fileNamePath = CCUtility.returnFileNamePath(fromFileName: metadata.fileName, serverUrl: metadata.serverUrl, urlBase: metadata.urlBase, userId: metadata.userId, account: metadata.account)!
  104. self.fileNamePreviewLocalPath = CCUtility.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag)!
  105. self.fileNameIconLocalPath = CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)!
  106. }
  107. override func start() {
  108. guard !isCancelled else { return self.finish() }
  109. var etagResource: String?
  110. if FileManager.default.fileExists(atPath: fileNameIconLocalPath) && FileManager.default.fileExists(atPath: fileNamePreviewLocalPath) {
  111. etagResource = metadata.etagResource
  112. }
  113. NextcloudKit.shared.downloadPreview(
  114. fileNamePathOrFileId: fileNamePath,
  115. fileNamePreviewLocalPath: fileNamePreviewLocalPath,
  116. widthPreview: NCGlobal.shared.sizePreview,
  117. heightPreview: NCGlobal.shared.sizePreview,
  118. fileNameIconLocalPath: fileNameIconLocalPath,
  119. sizeIcon: NCGlobal.shared.sizeIcon,
  120. etag: etagResource,
  121. options: NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)) { _, imagePreview, _, _, etag, error in
  122. if error == .success, let image = imagePreview {
  123. NCManageDatabase.shared.setMetadataEtagResource(ocId: self.metadata.ocId, etagResource: etag)
  124. DispatchQueue.main.async {
  125. if self.metadata.ocId == self.cell?.fileObjectId, let filePreviewImageView = self.cell?.filePreviewImageView {
  126. UIView.transition(with: filePreviewImageView,
  127. duration: 0.75,
  128. options: .transitionCrossDissolve,
  129. animations: { filePreviewImageView.image = image },
  130. completion: nil)
  131. } else {
  132. if self.view is UICollectionView {
  133. (self.view as? UICollectionView)?.reloadData()
  134. } else if self.view is UITableView {
  135. (self.view as? UITableView)?.reloadData()
  136. }
  137. }
  138. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDownloadedThumbnail, userInfo: ["ocId": self.metadata.ocId])
  139. }
  140. NCMediaManager.shared.setImage(ocId: self.metadata.ocId, image: image)
  141. }
  142. self.finish()
  143. }
  144. }
  145. }
  146. // MARK: -
  147. class NCOperationDownloadThumbnailActivity: ConcurrentOperation {
  148. var cell: NCActivityCollectionViewCell?
  149. var collectionView: UICollectionView?
  150. var fileNamePathOrFileId: String
  151. var fileNamePreviewLocalPath: String
  152. var fileId: String
  153. init(fileNamePathOrFileId: String, fileNamePreviewLocalPath: String, fileId: String, cell: NCActivityCollectionViewCell?, collectionView: UICollectionView?) {
  154. self.fileNamePathOrFileId = fileNamePathOrFileId
  155. self.fileNamePreviewLocalPath = fileNamePreviewLocalPath
  156. self.fileId = fileId
  157. self.cell = cell
  158. self.collectionView = collectionView
  159. }
  160. override func start() {
  161. guard !isCancelled else { return self.finish() }
  162. NextcloudKit.shared.downloadPreview(
  163. fileNamePathOrFileId: fileNamePathOrFileId,
  164. fileNamePreviewLocalPath: fileNamePreviewLocalPath,
  165. widthPreview: 0,
  166. heightPreview: 0,
  167. etag: nil,
  168. useInternalEndpoint: false,
  169. options: NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)) { _, imagePreview, _, _, _, error in
  170. if error == .success, let imagePreview = imagePreview {
  171. DispatchQueue.main.async {
  172. if self.fileId == self.cell?.fileId, let imageView = self.cell?.imageView {
  173. UIView.transition(with: imageView,
  174. duration: 0.75,
  175. options: .transitionCrossDissolve,
  176. animations: { imageView.image = imagePreview },
  177. completion: nil)
  178. } else {
  179. self.collectionView?.reloadData()
  180. }
  181. }
  182. }
  183. self.finish()
  184. }
  185. }
  186. }
  187. // MARK: -
  188. class NCOperationDownloadAvatar: ConcurrentOperation {
  189. var user: String
  190. var fileName: String
  191. var etag: String?
  192. var fileNameLocalPath: String
  193. var cell: NCCellProtocol!
  194. var view: UIView?
  195. var cellImageView: UIImageView?
  196. init(user: String, fileName: String, fileNameLocalPath: String, cell: NCCellProtocol, view: UIView?, cellImageView: UIImageView?) {
  197. self.user = user
  198. self.fileName = fileName
  199. self.fileNameLocalPath = fileNameLocalPath
  200. self.cell = cell
  201. self.view = view
  202. self.etag = NCManageDatabase.shared.getTableAvatar(fileName: fileName)?.etag
  203. self.cellImageView = cellImageView
  204. }
  205. override func start() {
  206. guard !isCancelled else { return self.finish() }
  207. NextcloudKit.shared.downloadAvatar(user: user,
  208. fileNameLocalPath: fileNameLocalPath,
  209. sizeImage: NCGlobal.shared.avatarSize,
  210. avatarSizeRounded: NCGlobal.shared.avatarSizeRounded,
  211. etag: self.etag,
  212. options: NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)) { _, imageAvatar, _, etag, error in
  213. if error == .success, let imageAvatar = imageAvatar, let etag = etag {
  214. NCManageDatabase.shared.addAvatar(fileName: self.fileName, etag: etag)
  215. DispatchQueue.main.async {
  216. if self.user == self.cell.fileUser, let avatarImageView = self.cellImageView {
  217. UIView.transition(with: avatarImageView,
  218. duration: 0.75,
  219. options: .transitionCrossDissolve,
  220. animations: { avatarImageView.image = imageAvatar },
  221. completion: nil)
  222. } else {
  223. if self.view is UICollectionView {
  224. (self.view as? UICollectionView)?.reloadData()
  225. } else if self.view is UITableView {
  226. (self.view as? UITableView)?.reloadData()
  227. }
  228. }
  229. }
  230. } else if error.errorCode == NCGlobal.shared.errorNotModified {
  231. NCManageDatabase.shared.setAvatarLoaded(fileName: self.fileName)
  232. }
  233. self.finish()
  234. }
  235. }
  236. }
  237. // MARK: -
  238. class NCOperationUnifiedSearch: ConcurrentOperation {
  239. var collectionViewCommon: NCCollectionViewCommon
  240. var metadatas: [tableMetadata]
  241. var searchResult: NKSearchResult
  242. init(collectionViewCommon: NCCollectionViewCommon, metadatas: [tableMetadata], searchResult: NKSearchResult) {
  243. self.collectionViewCommon = collectionViewCommon
  244. self.metadatas = metadatas
  245. self.searchResult = searchResult
  246. }
  247. func reloadDataThenPerform(_ closure: @escaping (() -> Void)) {
  248. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  249. CATransaction.begin()
  250. CATransaction.setCompletionBlock(closure)
  251. self.collectionViewCommon.collectionView.reloadData()
  252. CATransaction.commit()
  253. }
  254. }
  255. override func start() {
  256. guard !isCancelled else { return self.finish() }
  257. self.collectionViewCommon.dataSource.addSection(metadatas: metadatas, searchResult: searchResult)
  258. self.collectionViewCommon.searchResults?.append(self.searchResult)
  259. reloadDataThenPerform {
  260. self.finish()
  261. }
  262. }
  263. }
  264. // MARK: -
  265. class NCOperationSaveLivePhoto: ConcurrentOperation {
  266. var metadata: tableMetadata
  267. var metadataMOV: tableMetadata
  268. let hud = JGProgressHUD()
  269. let appDelegate = UIApplication.shared.delegate as? AppDelegate
  270. init(metadata: tableMetadata, metadataMOV: tableMetadata) {
  271. self.metadata = tableMetadata.init(value: metadata)
  272. self.metadataMOV = tableMetadata.init(value: metadataMOV)
  273. }
  274. override func start() {
  275. guard !isCancelled else { return self.finish() }
  276. DispatchQueue.main.async {
  277. self.hud.indicatorView = JGProgressHUDRingIndicatorView()
  278. if let indicatorView = self.hud.indicatorView as? JGProgressHUDRingIndicatorView {
  279. indicatorView.ringWidth = 1.5
  280. }
  281. self.hud.textLabel.text = NSLocalizedString("_download_image_", comment: "")
  282. self.hud.detailTextLabel.text = self.metadata.fileName
  283. self.hud.show(in: (self.appDelegate?.window?.rootViewController?.view)!)
  284. }
  285. NCNetworking.shared.download(metadata: metadata, selector: "", notificationCenterProgressTask: false, checkfileProviderStorageExists: true) { _ in
  286. } progressHandler: { progress in
  287. self.hud.progress = Float(progress.fractionCompleted)
  288. } completion: { _, error in
  289. guard error == .success else {
  290. DispatchQueue.main.async {
  291. self.hud.indicatorView = JGProgressHUDErrorIndicatorView()
  292. self.hud.textLabel.text = NSLocalizedString("_livephoto_save_error_", comment: "")
  293. self.hud.dismiss()
  294. }
  295. return self.finish()
  296. }
  297. NCNetworking.shared.download(metadata: self.metadataMOV, selector: "", notificationCenterProgressTask: false, checkfileProviderStorageExists: true) { _ in
  298. DispatchQueue.main.async {
  299. self.hud.textLabel.text = NSLocalizedString("_download_video_", comment: "")
  300. self.hud.detailTextLabel.text = self.metadataMOV.fileName
  301. }
  302. } progressHandler: { progress in
  303. self.hud.progress = Float(progress.fractionCompleted)
  304. } completion: { _, error in
  305. guard error == .success else {
  306. DispatchQueue.main.async {
  307. self.hud.indicatorView = JGProgressHUDErrorIndicatorView()
  308. self.hud.textLabel.text = NSLocalizedString("_livephoto_save_error_", comment: "")
  309. self.hud.dismiss()
  310. }
  311. return self.finish()
  312. }
  313. self.saveLivePhotoToDisk(metadata: self.metadata, metadataMov: self.metadataMOV)
  314. }
  315. }
  316. }
  317. func saveLivePhotoToDisk(metadata: tableMetadata, metadataMov: tableMetadata) {
  318. let fileNameImage = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!)
  319. let fileNameMov = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadataMov.ocId, fileNameView: metadataMov.fileNameView)!)
  320. DispatchQueue.main.async {
  321. self.hud.textLabel.text = NSLocalizedString("_livephoto_save_", comment: "")
  322. self.hud.detailTextLabel.text = ""
  323. }
  324. NCLivePhoto.generate(from: fileNameImage, videoURL: fileNameMov, progress: { progress in
  325. self.hud.progress = Float(progress)
  326. }, completion: { _, resources in
  327. if resources != nil {
  328. NCLivePhoto.saveToLibrary(resources!) { result in
  329. DispatchQueue.main.async {
  330. if !result {
  331. self.hud.indicatorView = JGProgressHUDErrorIndicatorView()
  332. self.hud.textLabel.text = NSLocalizedString("_livephoto_save_error_", comment: "")
  333. } else {
  334. self.hud.indicatorView = JGProgressHUDSuccessIndicatorView()
  335. self.hud.textLabel.text = NSLocalizedString("_success_", comment: "")
  336. }
  337. self.hud.dismiss()
  338. }
  339. return self.finish()
  340. }
  341. } else {
  342. DispatchQueue.main.async {
  343. self.hud.indicatorView = JGProgressHUDErrorIndicatorView()
  344. self.hud.textLabel.text = NSLocalizedString("_livephoto_save_error_", comment: "")
  345. self.hud.dismiss()
  346. }
  347. return self.finish()
  348. }
  349. })
  350. }
  351. }