NCOperationQueue.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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. NextcloudKit.shared.downloadPreview(
  196. fileNamePathOrFileId: fileNamePath,
  197. fileNamePreviewLocalPath: fileNamePreviewLocalPath,
  198. widthPreview: NCGlobal.shared.sizePreview,
  199. heightPreview: NCGlobal.shared.sizePreview,
  200. fileNameIconLocalPath: fileNameIconLocalPath,
  201. sizeIcon: NCGlobal.shared.sizeIcon,
  202. etag: etagResource,
  203. options: NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)) { _, _, imageIcon, _, etag, error in
  204. if error == .success, let imageIcon = imageIcon {
  205. NCManageDatabase.shared.setMetadataEtagResource(ocId: self.metadata.ocId, etagResource: etag)
  206. DispatchQueue.main.async {
  207. if self.metadata.ocId == self.cell?.fileObjectId, let filePreviewImageView = self.cell?.filePreviewImageView {
  208. UIView.transition(with: filePreviewImageView,
  209. duration: 0.75,
  210. options: .transitionCrossDissolve,
  211. animations: { filePreviewImageView.image = imageIcon },
  212. completion: nil)
  213. } else {
  214. if self.view is UICollectionView {
  215. (self.view as? UICollectionView)?.reloadData()
  216. } else if self.view is UITableView {
  217. (self.view as? UITableView)?.reloadData()
  218. }
  219. }
  220. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDownloadedThumbnail, userInfo: ["ocId": self.metadata.ocId])
  221. }
  222. }
  223. self.finish()
  224. }
  225. }
  226. }
  227. }
  228. // MARK: -
  229. class NCOperationDownloadThumbnailActivity: ConcurrentOperation {
  230. var cell: NCActivityCollectionViewCell?
  231. var collectionView: UICollectionView?
  232. var fileNamePathOrFileId: String
  233. var fileNamePreviewLocalPath: String
  234. var fileId: String
  235. init(fileNamePathOrFileId: String, fileNamePreviewLocalPath: String, fileId: String, cell: NCActivityCollectionViewCell?, collectionView: UICollectionView?) {
  236. self.fileNamePathOrFileId = fileNamePathOrFileId
  237. self.fileNamePreviewLocalPath = fileNamePreviewLocalPath
  238. self.fileId = fileId
  239. self.cell = cell
  240. self.collectionView = collectionView
  241. }
  242. override func start() {
  243. if isCancelled {
  244. self.finish()
  245. } else {
  246. NextcloudKit.shared.downloadPreview(
  247. fileNamePathOrFileId: fileNamePathOrFileId,
  248. fileNamePreviewLocalPath: fileNamePreviewLocalPath,
  249. widthPreview: 0,
  250. heightPreview: 0,
  251. etag: nil,
  252. useInternalEndpoint: false,
  253. options: NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)) { _, imagePreview, _, _, _, error in
  254. if error == .success, let imagePreview = imagePreview {
  255. DispatchQueue.main.async {
  256. if self.fileId == self.cell?.fileId, let imageView = self.cell?.imageView {
  257. UIView.transition(with: imageView,
  258. duration: 0.75,
  259. options: .transitionCrossDissolve,
  260. animations: { imageView.image = imagePreview },
  261. completion: nil)
  262. } else {
  263. self.collectionView?.reloadData()
  264. }
  265. }
  266. }
  267. self.finish()
  268. }
  269. }
  270. }
  271. }
  272. // MARK: -
  273. class NCOperationDownloadAvatar: ConcurrentOperation {
  274. var user: String
  275. var fileName: String
  276. var etag: String?
  277. var fileNameLocalPath: String
  278. var cell: NCCellProtocol!
  279. var view: UIView?
  280. var cellImageView: UIImageView?
  281. init(user: String, fileName: String, fileNameLocalPath: String, cell: NCCellProtocol, view: UIView?, cellImageView: UIImageView?) {
  282. self.user = user
  283. self.fileName = fileName
  284. self.fileNameLocalPath = fileNameLocalPath
  285. self.cell = cell
  286. self.view = view
  287. self.etag = NCManageDatabase.shared.getTableAvatar(fileName: fileName)?.etag
  288. self.cellImageView = cellImageView
  289. }
  290. override func start() {
  291. if isCancelled {
  292. self.finish()
  293. } else {
  294. NextcloudKit.shared.downloadAvatar(user: user,
  295. fileNameLocalPath: fileNameLocalPath,
  296. sizeImage: NCGlobal.shared.avatarSize,
  297. avatarSizeRounded: NCGlobal.shared.avatarSizeRounded,
  298. etag: self.etag,
  299. options: NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)) { _, imageAvatar, _, etag, error in
  300. if error == .success, let imageAvatar = imageAvatar, let etag = etag {
  301. NCManageDatabase.shared.addAvatar(fileName: self.fileName, etag: etag)
  302. DispatchQueue.main.async {
  303. if self.user == self.cell.fileUser, let avatarImageView = self.cellImageView {
  304. UIView.transition(with: avatarImageView,
  305. duration: 0.75,
  306. options: .transitionCrossDissolve,
  307. animations: { avatarImageView.image = imageAvatar },
  308. completion: nil)
  309. } else {
  310. if self.view is UICollectionView {
  311. (self.view as? UICollectionView)?.reloadData()
  312. } else if self.view is UITableView {
  313. (self.view as? UITableView)?.reloadData()
  314. }
  315. }
  316. }
  317. } else if error.errorCode == NCGlobal.shared.errorNotModified {
  318. NCManageDatabase.shared.setAvatarLoaded(fileName: self.fileName)
  319. }
  320. self.finish()
  321. }
  322. }
  323. }
  324. }
  325. // MARK: -
  326. class NCOperationUnifiedSearch: ConcurrentOperation {
  327. var collectionViewCommon: NCCollectionViewCommon
  328. var metadatas: [tableMetadata]
  329. var searchResult: NKSearchResult
  330. init(collectionViewCommon: NCCollectionViewCommon, metadatas: [tableMetadata], searchResult: NKSearchResult) {
  331. self.collectionViewCommon = collectionViewCommon
  332. self.metadatas = metadatas
  333. self.searchResult = searchResult
  334. }
  335. func reloadDataThenPerform(_ closure: @escaping (() -> Void)) {
  336. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  337. CATransaction.begin()
  338. CATransaction.setCompletionBlock(closure)
  339. self.collectionViewCommon.collectionView.reloadData()
  340. CATransaction.commit()
  341. }
  342. }
  343. override func start() {
  344. if isCancelled {
  345. self.finish()
  346. } else {
  347. self.collectionViewCommon.dataSource.addSection(metadatas: metadatas, searchResult: searchResult)
  348. self.collectionViewCommon.searchResults?.append(self.searchResult)
  349. reloadDataThenPerform {
  350. self.finish()
  351. }
  352. }
  353. }
  354. }
  355. // MARK: -
  356. class NCOperationReadFile: ConcurrentOperation {
  357. var serverUrlFileName: String
  358. init(serverUrlFileName: String) {
  359. self.serverUrlFileName = serverUrlFileName
  360. }
  361. override func start() {
  362. if isCancelled {
  363. self.finish()
  364. } else {
  365. NCNetworking.shared.readFile(serverUrlFileName: serverUrlFileName) { account, metadata, error in
  366. if error == .success, let metadata = metadata {
  367. NCManageDatabase.shared.addMetadata(metadata)
  368. if metadata.directory {
  369. 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)
  370. }
  371. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterOperationReadFile, userInfo: ["ocId": metadata.ocId])
  372. }
  373. }
  374. }
  375. }
  376. }