NCOperationQueue.swift 19 KB

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