NCOperationQueue.swift 18 KB

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