NCOperationQueue.swift 18 KB

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