NCOperationQueue.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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 Foundation
  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 readFileForMediaQueue = Queuer(name: "readFileForMediaQueue", maxConcurrentOperationCount: 10, qualityOfService: .default)
  37. private var timerReadFileForMediaQueue: Timer?
  38. @objc func cancelAllQueue() {
  39. downloadCancelAll()
  40. deleteCancelAll()
  41. copyMoveCancelAll()
  42. synchronizationCancelAll()
  43. downloadThumbnailCancelAll()
  44. readFileForMediaCancelAll()
  45. }
  46. // Download file
  47. @objc func download(metadata: tableMetadata, selector: String, setFavorite: Bool) {
  48. for operation in downloadQueue.operations as! [NCOperationDownload] {
  49. if operation.metadata.ocId == metadata.ocId {
  50. return
  51. }
  52. }
  53. downloadQueue.addOperation(NCOperationDownload.init(metadata: metadata, selector: selector, setFavorite: setFavorite))
  54. }
  55. @objc func downloadCancelAll() {
  56. downloadQueue.cancelAll()
  57. }
  58. @objc func downloadCount() -> Int {
  59. return downloadQueue.operationCount
  60. }
  61. // Delete file
  62. @objc func delete(metadata: tableMetadata, onlyLocal: Bool) {
  63. for operation in deleteQueue.operations as! [NCOperationDelete] {
  64. if operation.metadata.ocId == metadata.ocId {
  65. return
  66. }
  67. }
  68. deleteQueue.addOperation(NCOperationDelete.init(metadata: metadata, onlyLocal: onlyLocal))
  69. }
  70. @objc func deleteCancelAll() {
  71. deleteQueue.cancelAll()
  72. }
  73. @objc func deleteCount() -> Int {
  74. return deleteQueue.operationCount
  75. }
  76. // Copy Move file
  77. @objc func copyMove(metadata: tableMetadata, serverUrl: String, overwrite: Bool, move: Bool) {
  78. for operation in copyMoveQueue.operations as! [NCOperationCopyMove] {
  79. if operation.metadata.ocId == metadata.ocId {
  80. return
  81. }
  82. }
  83. copyMoveQueue.addOperation(NCOperationCopyMove.init(metadata: metadata, serverUrlTo: serverUrl, overwrite: overwrite, move: move))
  84. }
  85. @objc func copyMoveCancelAll() {
  86. copyMoveQueue.cancelAll()
  87. }
  88. @objc func copyMoveCount() -> Int {
  89. return copyMoveQueue.operationCount
  90. }
  91. // Synchronization
  92. @objc func synchronizationMetadata(_ metadata: tableMetadata, selector: String) {
  93. for operation in synchronizationQueue.operations as! [NCOperationSynchronization] {
  94. if operation.metadata.ocId == metadata.ocId {
  95. return
  96. }
  97. }
  98. synchronizationQueue.addOperation(NCOperationSynchronization.init(metadata: metadata, selector: selector))
  99. }
  100. @objc func synchronizationCancelAll() {
  101. synchronizationQueue.cancelAll()
  102. }
  103. // Download Thumbnail
  104. @objc func downloadThumbnail(metadata: tableMetadata, urlBase: String, view: Any, indexPath: IndexPath) {
  105. if metadata.hasPreview && metadata.status == k_metadataStatusNormal && (!CCUtility.fileProviderStoragePreviewIconExists(metadata.ocId, etag: metadata.etag)) {
  106. for operation in downloadThumbnailQueue.operations as! [NCOperationDownloadThumbnail] {
  107. if operation.metadata.ocId == metadata.ocId {
  108. return
  109. }
  110. }
  111. downloadThumbnailQueue.addOperation(NCOperationDownloadThumbnail.init(metadata: metadata, urlBase: urlBase, view: view, indexPath: indexPath))
  112. }
  113. }
  114. func cancelDownloadThumbnail(metadata: tableMetadata) {
  115. for operation in downloadThumbnailQueue.operations as! [NCOperationDownloadThumbnail] {
  116. if operation.metadata.ocId == metadata.ocId {
  117. operation.cancel()
  118. }
  119. }
  120. }
  121. @objc func downloadThumbnailCancelAll() {
  122. downloadThumbnailQueue.cancelAll()
  123. }
  124. // Get file information
  125. @objc func readFileForMedia(metadata: tableMetadata) {
  126. for operation in readFileForMediaQueue.operations as! [NCOperationReadFileForMediaQueue] {
  127. if operation.metadata.ocId == metadata.ocId {
  128. return
  129. }
  130. }
  131. readFileForMediaQueue.addOperation(NCOperationReadFileForMediaQueue.init(metadata: metadata))
  132. }
  133. func cancelReadFileForMedia(metadata: tableMetadata) {
  134. for operation in readFileForMediaQueue.operations as! [NCOperationReadFileForMediaQueue] {
  135. if operation.metadata.ocId == metadata.ocId {
  136. operation.cancel()
  137. }
  138. }
  139. }
  140. @objc func readFileForMediaCancelAll() {
  141. readFileForMediaQueue.cancelAll()
  142. }
  143. @objc func notificationReloadDataSourceMedia() {
  144. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadMediaDataSource)
  145. }
  146. func reloadDataSourceMedia() {
  147. if !(timerReadFileForMediaQueue?.isValid ?? false) {
  148. timerReadFileForMediaQueue = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(notificationReloadDataSourceMedia), userInfo: nil, repeats: false)
  149. }
  150. }
  151. }
  152. //MARK: -
  153. class NCOperationDownload: ConcurrentOperation {
  154. var metadata: tableMetadata
  155. var selector: String
  156. var setFavorite: Bool
  157. init(metadata: tableMetadata, selector: String, setFavorite: Bool) {
  158. self.metadata = tableMetadata.init(value: metadata)
  159. self.selector = selector
  160. self.setFavorite = setFavorite
  161. }
  162. override func start() {
  163. if isCancelled {
  164. self.finish()
  165. } else {
  166. NCNetworking.shared.download(metadata: metadata, selector: self.selector, setFavorite: self.setFavorite) { (_) in
  167. self.finish()
  168. }
  169. }
  170. }
  171. }
  172. //MARK: -
  173. class NCOperationDelete: ConcurrentOperation {
  174. var metadata: tableMetadata
  175. var onlyLocal: Bool
  176. init(metadata: tableMetadata, onlyLocal: Bool) {
  177. self.metadata = tableMetadata.init(value: metadata)
  178. self.onlyLocal = onlyLocal
  179. }
  180. override func start() {
  181. if isCancelled {
  182. self.finish()
  183. } else {
  184. NCNetworking.shared.deleteMetadata(metadata, account: metadata.account, urlBase: metadata.urlBase, onlyLocal: onlyLocal) { (_, _) in
  185. self.finish()
  186. }
  187. }
  188. }
  189. }
  190. //MARK: -
  191. class NCOperationCopyMove: ConcurrentOperation {
  192. var metadata: tableMetadata
  193. var serverUrlTo: String
  194. var overwrite: Bool
  195. var move: Bool
  196. init(metadata: tableMetadata, serverUrlTo: String, overwrite: Bool, move: Bool) {
  197. self.metadata = tableMetadata.init(value: metadata)
  198. self.serverUrlTo = serverUrlTo
  199. self.overwrite = overwrite
  200. self.move = move
  201. }
  202. override func start() {
  203. if isCancelled {
  204. self.finish()
  205. } else {
  206. if move {
  207. NCNetworking.shared.moveMetadata(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite) { (errorCode, errorDescription) in
  208. self.finish()
  209. }
  210. } else {
  211. NCNetworking.shared.copyMetadata(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite) { (errorCode, errorDescription) in
  212. self.finish()
  213. }
  214. }
  215. }
  216. }
  217. }
  218. //MARK: -
  219. class NCOperationSynchronization: ConcurrentOperation {
  220. var metadata: tableMetadata
  221. var selector: String
  222. var download: Bool
  223. init(metadata: tableMetadata, selector: String) {
  224. self.metadata = tableMetadata.init(value: metadata)
  225. self.selector = selector
  226. if selector == selectorDownloadFile {
  227. self.download = true
  228. } else {
  229. self.download = false
  230. }
  231. }
  232. override func start() {
  233. if isCancelled {
  234. self.finish()
  235. } else {
  236. if metadata.directory {
  237. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  238. NCCommunication.shared.readFileOrFolder(serverUrlFileName: serverUrlFileName, depth: "1", showHiddenFiles: CCUtility.getShowHiddenFiles()) { (account, files, responseData, errorCode, errorDescription) in
  239. if errorCode == 0 {
  240. NCManageDatabase.sharedInstance.convertNCCommunicationFilesToMetadatas(files, useMetadataFolder: true, account: account) { (metadataFolder, metadatasFolder, metadatas) in
  241. let metadatasResult = NCManageDatabase.sharedInstance.getMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND status == %d", account, serverUrlFileName, k_metadataStatusNormal))
  242. if self.selector == selectorDownloadAllFile {
  243. NCManageDatabase.sharedInstance.updateMetadatas(metadatas, metadatasResult: metadatasResult)
  244. for metadata in metadatas {
  245. if metadata.directory {
  246. NCOperationQueue.shared.synchronizationMetadata(metadata, selector: self.selector)
  247. } else {
  248. let localFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  249. if localFile == nil || localFile?.etag != metadata.etag {
  250. NCOperationQueue.shared.download(metadata: metadata, selector: self.selector, setFavorite: false)
  251. }
  252. }
  253. }
  254. } else {
  255. let metadatasChanged = NCManageDatabase.sharedInstance.updateMetadatas(metadatas, metadatasResult: metadatasResult, addExistsInLocal: self.download, addCompareEtagLocal: true)
  256. for metadata in metadatasChanged.metadatasUpdate {
  257. if metadata.directory {
  258. NCOperationQueue.shared.synchronizationMetadata(metadata, selector: self.selector)
  259. }
  260. }
  261. for metadata in metadatasChanged.metadatasLocalUpdate {
  262. NCOperationQueue.shared.download(metadata: metadata, selector: self.selector, setFavorite: false)
  263. }
  264. }
  265. // Update etag directory
  266. NCManageDatabase.sharedInstance.addDirectory(encrypted: metadataFolder.e2eEncrypted, favorite: metadataFolder.favorite, ocId: metadataFolder.ocId, fileId: metadataFolder.fileId, etag: metadataFolder.etag, permissions: metadataFolder.permissions, serverUrl: serverUrlFileName, richWorkspace: metadataFolder.richWorkspace, account: metadataFolder.account)
  267. }
  268. } else if errorCode == 404 && self.metadata.directory {
  269. NCManageDatabase.sharedInstance.deleteDirectoryAndSubDirectory(serverUrl: self.metadata.serverUrl, account: self.metadata.account)
  270. }
  271. self.finish()
  272. }
  273. } else {
  274. if self.download {
  275. let localFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  276. if localFile == nil || localFile?.etag != metadata.etag {
  277. NCOperationQueue.shared.download(metadata: metadata, selector: self.selector, setFavorite: false)
  278. }
  279. }
  280. self.finish()
  281. }
  282. }
  283. }
  284. }
  285. //MARK: -
  286. class NCOperationDownloadThumbnail: ConcurrentOperation {
  287. var metadata: tableMetadata
  288. var urlBase: String
  289. var view: Any
  290. var indexPath: IndexPath
  291. init(metadata: tableMetadata, urlBase: String, view: Any, indexPath: IndexPath) {
  292. self.metadata = tableMetadata.init(value: metadata)
  293. self.urlBase = urlBase
  294. self.view = view
  295. self.indexPath = indexPath
  296. }
  297. override func start() {
  298. if isCancelled {
  299. self.finish()
  300. } else {
  301. let fileNamePath = CCUtility.returnFileNamePath(fromFileName: metadata.fileName, serverUrl: metadata.serverUrl, urlBase: urlBase, account: metadata.account)!
  302. let fileNamePreviewLocalPath = CCUtility.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag)!
  303. let fileNameIconLocalPath = CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)!
  304. NCCommunication.shared.downloadPreview(fileNamePathOrFileId: fileNamePath, fileNamePreviewLocalPath: fileNamePreviewLocalPath , widthPreview: Int(k_sizePreview), heightPreview: Int(k_sizePreview), fileNameIconLocalPath: fileNameIconLocalPath, sizeIcon: Int(k_sizeIcon)) { (account, imagePreview, imageIcon, errorCode, errorDescription) in
  305. var cell: NCImageCellProtocol?
  306. if self.view is UICollectionView && NCMainCommon.shared.isValidIndexPath(self.indexPath, view: self.view) {
  307. cell = (self.view as! UICollectionView).cellForItem(at: self.indexPath) as? NCImageCellProtocol
  308. } else if self.view is UITableView && NCMainCommon.shared.isValidIndexPath(self.indexPath, view: self.view) {
  309. cell = (self.view as! UITableView).cellForRow(at: self.indexPath) as? NCImageCellProtocol
  310. }
  311. if (cell != nil) {
  312. var previewImage: UIImage!
  313. if errorCode == 0 && imageIcon != nil {
  314. previewImage = imageIcon
  315. } else {
  316. if self.metadata.iconName.count > 0 {
  317. previewImage = UIImage(named: self.metadata.iconName)
  318. } else {
  319. previewImage = UIImage(named: "file")
  320. }
  321. }
  322. cell!.filePreviewImageView.backgroundColor = nil
  323. UIView.transition(with: cell!.filePreviewImageView,
  324. duration: 0.75,
  325. options: .transitionCrossDissolve,
  326. animations: { cell!.filePreviewImageView.image = previewImage! },
  327. completion: nil)
  328. }
  329. self.finish()
  330. }
  331. }
  332. }
  333. }
  334. //MARK: -
  335. class NCOperationReadFileForMediaQueue: ConcurrentOperation {
  336. var metadata: tableMetadata
  337. init(metadata: tableMetadata) {
  338. self.metadata = tableMetadata.init(value: metadata)
  339. }
  340. override func start() {
  341. if isCancelled {
  342. self.finish()
  343. } else {
  344. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  345. let requestBody =
  346. """
  347. <?xml version=\"1.0\" encoding=\"UTF-8\"?>
  348. <d:propfind xmlns:d=\"DAV:\" xmlns:oc=\"http://owncloud.org/ns\" xmlns:nc=\"http://nextcloud.org/ns\">
  349. <d:prop>
  350. <has-preview xmlns=\"http://nextcloud.org/ns\"/>
  351. <creation_time xmlns=\"http://nextcloud.org/ns\"/>
  352. <upload_time xmlns=\"http://nextcloud.org/ns\"/>
  353. </d:prop>
  354. </d:propfind>
  355. """
  356. NCCommunication.shared.readFileOrFolder(serverUrlFileName: serverUrlFileName, depth: "0", requestBody: requestBody.data(using: .utf8)) { (account, files, responseData, errorCode, errorDescription) in
  357. if errorCode == 0 && files.count > 0 {
  358. let file = files[0]
  359. let metadata = tableMetadata.init(value: self.metadata)
  360. var modify = false
  361. if metadata.hasPreview != file.hasPreview {
  362. metadata.hasPreview = file.hasPreview
  363. modify = true
  364. }
  365. if file.creationDate != nil && metadata.creationDate != file.creationDate {
  366. metadata.creationDate = file.creationDate!
  367. modify = true
  368. }
  369. if file.uploadDate != nil && metadata.uploadDate != file.uploadDate {
  370. metadata.uploadDate = file.uploadDate!
  371. modify = true
  372. }
  373. if modify {
  374. NCManageDatabase.sharedInstance.addMetadata(metadata)
  375. NCOperationQueue.shared.reloadDataSourceMedia()
  376. }
  377. } else if errorCode == 404 {
  378. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", self.metadata.ocId))
  379. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_deleteFile, userInfo: ["metadata": self.metadata, "errorCode": errorCode])
  380. }
  381. self.finish()
  382. }
  383. }
  384. }
  385. }