NCOperationQueue.swift 24 KB

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