NCOperationQueue.swift 19 KB

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