NCOperationQueue.swift 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  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 NCCommunication
  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 deleteQueue = Queuer(name: "deleteQueue", maxConcurrentOperationCount: 1, qualityOfService: .default)
  33. private let copyMoveQueue = Queuer(name: "copyMoveQueue", maxConcurrentOperationCount: 1, qualityOfService: .default)
  34. private let synchronizationQueue = Queuer(name: "synchronizationQueue", maxConcurrentOperationCount: 1, qualityOfService: .default)
  35. private let downloadThumbnailQueue = Queuer(name: "downloadThumbnailQueue", maxConcurrentOperationCount: 10, qualityOfService: .default)
  36. private let downloadAvatarQueue = Queuer(name: "downloadAvatarQueue", maxConcurrentOperationCount: 10, qualityOfService: .default)
  37. private let unifiedSearchQueue = Queuer(name: "unifiedSearchQueue", maxConcurrentOperationCount: 1, qualityOfService: .default)
  38. private var timerReadFileForMediaQueue: Timer?
  39. @objc func cancelAllQueue() {
  40. downloadCancelAll()
  41. deleteCancelAll()
  42. copyMoveCancelAll()
  43. synchronizationCancelAll()
  44. downloadThumbnailCancelAll()
  45. downloadAvatarCancelAll()
  46. unifiedSearchCancelAll()
  47. }
  48. // MARK: - Download file
  49. func download(metadata: tableMetadata, selector: String) {
  50. for operation in downloadQueue.operations as! [NCOperationDownload] {
  51. if operation.metadata.ocId == metadata.ocId {
  52. return
  53. }
  54. }
  55. downloadQueue.addOperation(NCOperationDownload(metadata: metadata, selector: selector))
  56. }
  57. @objc func downloadCancelAll() {
  58. downloadQueue.cancelAll()
  59. }
  60. @objc func downloadQueueCount() -> Int {
  61. return downloadQueue.operationCount
  62. }
  63. @objc func downloadExists(metadata: tableMetadata) -> Bool {
  64. for operation in downloadQueue.operations as! [NCOperationDownload] {
  65. if operation.metadata.ocId == metadata.ocId {
  66. return true
  67. }
  68. }
  69. return false
  70. }
  71. // MARK: - Delete file
  72. @objc func delete(metadata: tableMetadata, onlyLocalCache: Bool) {
  73. for operation in deleteQueue.operations as! [NCOperationDelete] {
  74. if operation.metadata.ocId == metadata.ocId {
  75. return
  76. }
  77. }
  78. deleteQueue.addOperation(NCOperationDelete(metadata: metadata, onlyLocalCache: onlyLocalCache))
  79. }
  80. @objc func deleteCancelAll() {
  81. deleteQueue.cancelAll()
  82. }
  83. // MARK: - Copy Move file
  84. @objc func copyMove(metadata: tableMetadata, serverUrl: String, overwrite: Bool, move: Bool) {
  85. for operation in copyMoveQueue.operations as! [NCOperationCopyMove] {
  86. if operation.metadata.ocId == metadata.ocId {
  87. return
  88. }
  89. }
  90. copyMoveQueue.addOperation(NCOperationCopyMove(metadata: metadata, serverUrlTo: serverUrl, overwrite: overwrite, move: move))
  91. }
  92. @objc func copyMoveCancelAll() {
  93. copyMoveQueue.cancelAll()
  94. }
  95. // MARK: - Synchronization
  96. @objc func synchronizationMetadata(_ metadata: tableMetadata, selector: String) {
  97. for operation in synchronizationQueue.operations as! [NCOperationSynchronization] {
  98. if operation.metadata.ocId == metadata.ocId {
  99. return
  100. }
  101. }
  102. synchronizationQueue.addOperation(NCOperationSynchronization(metadata: metadata, selector: selector))
  103. }
  104. @objc func synchronizationCancelAll() {
  105. synchronizationQueue.cancelAll()
  106. }
  107. // MARK: - Download Thumbnail
  108. @objc func downloadThumbnail(metadata: tableMetadata, placeholder: Bool, cell: UIView?, view: UIView?) {
  109. let cell: NCCellProtocol? = cell as? NCCellProtocol
  110. if placeholder {
  111. if metadata.iconName.count > 0 {
  112. cell?.filePreviewImageView?.image = UIImage(named: metadata.iconName)
  113. } else {
  114. cell?.filePreviewImageView?.image = NCBrandColor.cacheImages.file
  115. }
  116. }
  117. if metadata.hasPreview && metadata.status == NCGlobal.shared.metadataStatusNormal && (!CCUtility.fileProviderStoragePreviewIconExists(metadata.ocId, etag: metadata.etag)) {
  118. for operation in downloadThumbnailQueue.operations as! [NCOperationDownloadThumbnail] {
  119. if operation.metadata.ocId == metadata.ocId {
  120. return
  121. }
  122. }
  123. downloadThumbnailQueue.addOperation(NCOperationDownloadThumbnail(metadata: metadata, cell: cell, view: view))
  124. }
  125. }
  126. func cancelDownloadThumbnail(metadata: tableMetadata) {
  127. for operation in downloadThumbnailQueue.operations as! [NCOperationDownloadThumbnail] {
  128. if operation.metadata.ocId == metadata.ocId {
  129. operation.cancel()
  130. }
  131. }
  132. }
  133. @objc func downloadThumbnailCancelAll() {
  134. downloadThumbnailQueue.cancelAll()
  135. }
  136. // MARK: - Download Avatar
  137. func downloadAvatar(user: String, dispalyName: String?, fileName: String, cell: NCCellProtocol, view: UIView?, cellImageView: UIImageView?) {
  138. let fileNameLocalPath = String(CCUtility.getDirectoryUserData()) + "/" + fileName
  139. if let image = NCManageDatabase.shared.getImageAvatarLoaded(fileName: fileName) {
  140. cellImageView?.image = image
  141. cell.fileAvatarImageView?.image = image
  142. return
  143. }
  144. if let account = NCManageDatabase.shared.getActiveAccount() {
  145. cellImageView?.image = NCUtility.shared.loadUserImage(
  146. for: user,
  147. displayName: dispalyName,
  148. userBaseUrl: account)
  149. }
  150. for operation in downloadAvatarQueue.operations as! [NCOperationDownloadAvatar] {
  151. if operation.fileName == fileName {
  152. return
  153. }
  154. }
  155. downloadAvatarQueue.addOperation(NCOperationDownloadAvatar(user: user, fileName: fileName, fileNameLocalPath: fileNameLocalPath, cell: cell, view: view, cellImageView: cellImageView))
  156. }
  157. func cancelDownloadAvatar(user: String) {
  158. for operation in downloadAvatarQueue.operations as! [NCOperationDownloadAvatar] {
  159. if operation.user == user {
  160. operation.cancel()
  161. }
  162. }
  163. }
  164. @objc func downloadAvatarCancelAll() {
  165. downloadAvatarQueue.cancelAll()
  166. }
  167. // MARK: - Unified Search
  168. func unifiedSearchAddSection(collectionViewCommon: NCCollectionViewCommon, metadatas: [tableMetadata], searchResult: NCCSearchResult) {
  169. unifiedSearchQueue.addOperation(NCOperationUnifiedSearch.init(collectionViewCommon: collectionViewCommon, metadatas: metadatas, searchResult: searchResult))
  170. }
  171. @objc func unifiedSearchCancelAll() {
  172. unifiedSearchQueue.cancelAll()
  173. }
  174. }
  175. // MARK: -
  176. class NCOperationDownload: ConcurrentOperation {
  177. var metadata: tableMetadata
  178. var selector: String
  179. init(metadata: tableMetadata, selector: String) {
  180. self.metadata = tableMetadata.init(value: metadata)
  181. self.selector = selector
  182. }
  183. override func start() {
  184. if isCancelled {
  185. self.finish()
  186. } else {
  187. NCNetworking.shared.download(metadata: metadata, selector: self.selector) { _ in
  188. self.finish()
  189. }
  190. }
  191. }
  192. }
  193. // MARK: -
  194. class NCOperationDelete: ConcurrentOperation {
  195. var metadata: tableMetadata
  196. var onlyLocalCache: Bool
  197. init(metadata: tableMetadata, onlyLocalCache: Bool) {
  198. self.metadata = tableMetadata.init(value: metadata)
  199. self.onlyLocalCache = onlyLocalCache
  200. }
  201. override func start() {
  202. if isCancelled {
  203. self.finish()
  204. } else {
  205. NCNetworking.shared.deleteMetadata(metadata, onlyLocalCache: onlyLocalCache) { errorCode, errorDescription in
  206. if errorCode != 0 {
  207. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
  208. }
  209. self.finish()
  210. }
  211. }
  212. }
  213. }
  214. // MARK: -
  215. class NCOperationCopyMove: ConcurrentOperation {
  216. var metadata: tableMetadata
  217. var serverUrlTo: String
  218. var overwrite: Bool
  219. var move: Bool
  220. init(metadata: tableMetadata, serverUrlTo: String, overwrite: Bool, move: Bool) {
  221. self.metadata = tableMetadata.init(value: metadata)
  222. self.serverUrlTo = serverUrlTo
  223. self.overwrite = overwrite
  224. self.move = move
  225. }
  226. override func start() {
  227. if isCancelled {
  228. self.finish()
  229. } else {
  230. if move {
  231. NCNetworking.shared.moveMetadata(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite) { errorCode, errorDescription in
  232. if errorCode != 0 {
  233. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
  234. }
  235. self.finish()
  236. }
  237. } else {
  238. NCNetworking.shared.copyMetadata(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite) { errorCode, errorDescription in
  239. if errorCode != 0 {
  240. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
  241. }
  242. self.finish()
  243. }
  244. }
  245. }
  246. }
  247. }
  248. // MARK: -
  249. class NCOperationSynchronization: ConcurrentOperation {
  250. var metadata: tableMetadata
  251. var selector: String
  252. var download: Bool
  253. init(metadata: tableMetadata, selector: String) {
  254. self.metadata = tableMetadata.init(value: metadata)
  255. self.selector = selector
  256. if selector == NCGlobal.shared.selectorDownloadFile || selector == NCGlobal.shared.selectorDownloadAllFile {
  257. self.download = true
  258. } else {
  259. self.download = false
  260. }
  261. }
  262. override func start() {
  263. if isCancelled {
  264. self.finish()
  265. } else {
  266. if metadata.directory {
  267. let serverUrl = metadata.serverUrl + "/" + metadata.fileName
  268. let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", metadata.account, serverUrl))
  269. NCCommunication.shared.readFileOrFolder(serverUrlFileName: serverUrl, depth: "0", showHiddenFiles: CCUtility.getShowHiddenFiles()) { account, files, _, errorCode, _ in
  270. if (errorCode == 0) && (directory?.etag != files.first?.etag || self.selector == NCGlobal.shared.selectorDownloadAllFile) {
  271. NCCommunication.shared.readFileOrFolder(serverUrlFileName: serverUrl, depth: "1", showHiddenFiles: CCUtility.getShowHiddenFiles(), queue: NCCommunicationCommon.shared.backgroundQueue) { account, files, _, errorCode, _ in
  272. if errorCode == 0 {
  273. NCManageDatabase.shared.convertNCCommunicationFilesToMetadatas(files, useMetadataFolder: true, account: account) { metadataFolder, _, metadatas in
  274. let metadatasResult = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND status == %d", account, serverUrl, NCGlobal.shared.metadataStatusNormal))
  275. if self.selector == NCGlobal.shared.selectorDownloadAllFile {
  276. NCManageDatabase.shared.updateMetadatas(metadatas, metadatasResult: metadatasResult)
  277. for metadata in metadatas {
  278. if metadata.directory {
  279. NCOperationQueue.shared.synchronizationMetadata(metadata, selector: self.selector)
  280. } else {
  281. if NCManageDatabase.shared.isDownloadMetadata(metadata, download: true) {
  282. NCOperationQueue.shared.download(metadata: metadata, selector: self.selector)
  283. }
  284. }
  285. }
  286. } else {
  287. let metadatasChanged = NCManageDatabase.shared.updateMetadatas(metadatas, metadatasResult: metadatasResult, addExistsInLocal: self.download, addCompareEtagLocal: true, addDirectorySynchronized: true)
  288. for metadata in metadatasChanged.metadatasUpdate {
  289. if metadata.directory {
  290. NCOperationQueue.shared.synchronizationMetadata(metadata, selector: self.selector)
  291. }
  292. }
  293. for metadata in metadatasChanged.metadatasLocalUpdate {
  294. NCOperationQueue.shared.download(metadata: metadata, selector: self.selector)
  295. }
  296. }
  297. // Update etag directory
  298. NCManageDatabase.shared.addDirectory(encrypted: metadataFolder.e2eEncrypted, favorite: metadataFolder.favorite, ocId: metadataFolder.ocId, fileId: metadataFolder.fileId, etag: metadataFolder.etag, permissions: metadataFolder.permissions, serverUrl: serverUrl, account: metadataFolder.account)
  299. }
  300. } else if errorCode == NCGlobal.shared.errorResourceNotFound && self.metadata.directory {
  301. NCManageDatabase.shared.deleteDirectoryAndSubDirectory(serverUrl: self.metadata.serverUrl, account: self.metadata.account)
  302. }
  303. self.finish()
  304. }
  305. } else {
  306. let metadatas = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", account, serverUrl))
  307. for metadata in metadatas {
  308. if metadata.directory {
  309. NCOperationQueue.shared.synchronizationMetadata(metadata, selector: self.selector)
  310. } else {
  311. if NCManageDatabase.shared.isDownloadMetadata(metadata, download: self.download) {
  312. NCOperationQueue.shared.download(metadata: metadata, selector: self.selector)
  313. }
  314. }
  315. }
  316. self.finish()
  317. }
  318. }
  319. } else {
  320. if NCManageDatabase.shared.isDownloadMetadata(metadata, download: self.download) {
  321. NCOperationQueue.shared.download(metadata: metadata, selector: self.selector)
  322. }
  323. self.finish()
  324. }
  325. }
  326. }
  327. }
  328. // MARK: -
  329. class NCOperationDownloadThumbnail: ConcurrentOperation {
  330. var metadata: tableMetadata
  331. var cell: NCCellProtocol?
  332. var view: UIView?
  333. var fileNamePath: String = ""
  334. var fileNamePreviewLocalPath: String = ""
  335. var fileNameIconLocalPath: String = ""
  336. init(metadata: tableMetadata, cell: NCCellProtocol?, view: UIView?) {
  337. self.metadata = tableMetadata.init(value: metadata)
  338. self.cell = cell
  339. self.view = view
  340. self.fileNamePath = CCUtility.returnFileNamePath(fromFileName: metadata.fileName, serverUrl: metadata.serverUrl, urlBase: metadata.urlBase, account: metadata.account)!
  341. self.fileNamePreviewLocalPath = CCUtility.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag)!
  342. self.fileNameIconLocalPath = CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)!
  343. }
  344. override func start() {
  345. if isCancelled {
  346. self.finish()
  347. } else {
  348. var etagResource: String?
  349. if FileManager.default.fileExists(atPath: fileNameIconLocalPath) && FileManager.default.fileExists(atPath: fileNamePreviewLocalPath) {
  350. etagResource = metadata.etagResource
  351. }
  352. NCCommunication.shared.downloadPreview(
  353. fileNamePathOrFileId: fileNamePath,
  354. fileNamePreviewLocalPath: fileNamePreviewLocalPath,
  355. widthPreview: NCGlobal.shared.sizePreview,
  356. heightPreview: NCGlobal.shared.sizePreview,
  357. fileNameIconLocalPath: fileNameIconLocalPath,
  358. sizeIcon: NCGlobal.shared.sizeIcon,
  359. etag: etagResource,
  360. queue: NCCommunicationCommon.shared.backgroundQueue) { _, _, imageIcon, _, etag, errorCode, _ in
  361. if errorCode == 0, let imageIcon = imageIcon {
  362. NCManageDatabase.shared.setMetadataEtagResource(ocId: self.metadata.ocId, etagResource: etag)
  363. DispatchQueue.main.async {
  364. if self.metadata.ocId == self.cell?.fileObjectId, let filePreviewImageView = self.cell?.filePreviewImageView {
  365. UIView.transition(with: filePreviewImageView,
  366. duration: 0.75,
  367. options: .transitionCrossDissolve,
  368. animations: { filePreviewImageView.image = imageIcon },
  369. completion: nil)
  370. } else {
  371. if self.view is UICollectionView {
  372. (self.view as? UICollectionView)?.reloadData()
  373. } else if self.view is UITableView {
  374. (self.view as? UITableView)?.reloadData()
  375. }
  376. }
  377. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDownloadedThumbnail, userInfo: ["ocId": self.metadata.ocId])
  378. }
  379. }
  380. self.finish()
  381. }
  382. }
  383. }
  384. }
  385. // MARK: -
  386. class NCOperationDownloadAvatar: ConcurrentOperation {
  387. var user: String
  388. var fileName: String
  389. var etag: String?
  390. var fileNameLocalPath: String
  391. var cell: NCCellProtocol!
  392. var view: UIView?
  393. var cellImageView: UIImageView?
  394. init(user: String, fileName: String, fileNameLocalPath: String, cell: NCCellProtocol, view: UIView?, cellImageView: UIImageView?) {
  395. self.user = user
  396. self.fileName = fileName
  397. self.fileNameLocalPath = fileNameLocalPath
  398. self.cell = cell
  399. self.view = view
  400. self.etag = NCManageDatabase.shared.getTableAvatar(fileName: fileName)?.etag
  401. self.cellImageView = cellImageView
  402. }
  403. override func start() {
  404. if isCancelled {
  405. self.finish()
  406. } else {
  407. NCCommunication.shared.downloadAvatar(user: user, fileNameLocalPath: fileNameLocalPath, sizeImage: NCGlobal.shared.avatarSize, avatarSizeRounded: NCGlobal.shared.avatarSizeRounded, etag: self.etag, queue: NCCommunicationCommon.shared.backgroundQueue) { _, imageAvatar, _, etag, errorCode, _ in
  408. if errorCode == 0, let imageAvatar = imageAvatar, let etag = etag {
  409. NCManageDatabase.shared.addAvatar(fileName: self.fileName, etag: etag)
  410. DispatchQueue.main.async {
  411. if self.user == self.cell.fileUser, let avatarImageView = self.cellImageView {
  412. UIView.transition(with: avatarImageView,
  413. duration: 0.75,
  414. options: .transitionCrossDissolve,
  415. animations: { avatarImageView.image = imageAvatar },
  416. completion: nil)
  417. } else {
  418. if self.view is UICollectionView {
  419. (self.view as? UICollectionView)?.reloadData()
  420. } else if self.view is UITableView {
  421. (self.view as? UITableView)?.reloadData()
  422. }
  423. }
  424. }
  425. } else if errorCode == NCGlobal.shared.errorNotModified {
  426. NCManageDatabase.shared.setAvatarLoaded(fileName: self.fileName)
  427. }
  428. self.finish()
  429. }
  430. }
  431. }
  432. }
  433. // MARK: -
  434. class NCOperationUnifiedSearch: ConcurrentOperation {
  435. var collectionViewCommon: NCCollectionViewCommon
  436. var metadatas: [tableMetadata]
  437. var searchResult: NCCSearchResult
  438. init(collectionViewCommon: NCCollectionViewCommon, metadatas: [tableMetadata], searchResult: NCCSearchResult) {
  439. self.collectionViewCommon = collectionViewCommon
  440. self.metadatas = metadatas
  441. self.searchResult = searchResult
  442. }
  443. func reloadDataThenPerform(_ closure: @escaping (() -> Void)) {
  444. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  445. CATransaction.begin()
  446. CATransaction.setCompletionBlock(closure)
  447. self.collectionViewCommon.collectionView.reloadData()
  448. CATransaction.commit()
  449. }
  450. }
  451. override func start() {
  452. if isCancelled {
  453. self.finish()
  454. } else {
  455. self.collectionViewCommon.dataSource.addSection(metadatas: metadatas, searchResult: searchResult)
  456. self.collectionViewCommon.searchResults?.append(self.searchResult)
  457. reloadDataThenPerform {
  458. self.finish()
  459. }
  460. }
  461. }
  462. }