NCOperationQueue.swift 23 KB

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