NCOperationQueue.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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 var timerReadFileForMediaQueue: Timer?
  36. @objc func cancelAllQueue() {
  37. downloadCancelAll()
  38. synchronizationCancelAll()
  39. downloadThumbnailCancelAll()
  40. readFileForMediaCancelAll()
  41. }
  42. // Download file
  43. @objc func download(metadata: tableMetadata, selector: String, setFavorite: Bool) {
  44. downloadQueue.addOperation(NCOperationDownload.init(metadata: metadata, selector: selector, setFavorite: setFavorite))
  45. }
  46. @objc func downloadCancelAll() {
  47. downloadQueue.cancelAll()
  48. }
  49. @objc func downloadCount() -> Int {
  50. return downloadQueue.operationCount
  51. }
  52. // Synchronization
  53. @objc func synchronizationMetadata(_ metadata: tableMetadata, selector: String) {
  54. synchronizationQueue.addOperation(NCOperationSynchronization.init(metadata: metadata, selector: selector))
  55. }
  56. @objc func synchronizationCancelAll() {
  57. synchronizationQueue.cancelAll()
  58. }
  59. // Download Thumbnail
  60. @objc func downloadThumbnail(metadata: tableMetadata, urlBase: String, view: Any, indexPath: IndexPath) {
  61. if metadata.hasPreview && (!CCUtility.fileProviderStoragePreviewIconExists(metadata.ocId, etag: metadata.etag)) {
  62. for operation in downloadThumbnailQueue.operations {
  63. if (operation as! NCOperationDownloadThumbnail).metadata.ocId == metadata.ocId { return }
  64. }
  65. downloadThumbnailQueue.addOperation(NCOperationDownloadThumbnail.init(metadata: metadata, urlBase: urlBase, view: view, indexPath: indexPath))
  66. }
  67. }
  68. func cancelDownloadThumbnail(metadata: tableMetadata) {
  69. for operation in downloadThumbnailQueue.operations {
  70. if (operation as! NCOperationDownloadThumbnail).metadata.ocId == metadata.ocId {
  71. (operation as! NCOperationDownloadThumbnail).cancel()
  72. }
  73. }
  74. }
  75. @objc func downloadThumbnailCancelAll() {
  76. downloadThumbnailQueue.cancelAll()
  77. }
  78. // Get file information
  79. @objc func readFileForMedia(metadata: tableMetadata) {
  80. for operation in readFileForMediaQueue.operations {
  81. if (operation as! NCOperationReadFileForMediaQueue).metadata.ocId == metadata.ocId { return }
  82. }
  83. readFileForMediaQueue.addOperation(NCOperationReadFileForMediaQueue.init(metadata: metadata))
  84. }
  85. func cancelReadFileForMedia(metadata: tableMetadata) {
  86. for operation in readFileForMediaQueue.operations {
  87. if (operation as! NCOperationReadFileForMediaQueue).metadata.ocId == metadata.ocId {
  88. (operation as! NCOperationReadFileForMediaQueue).cancel()
  89. }
  90. }
  91. }
  92. @objc func readFileForMediaCancelAll() {
  93. readFileForMediaQueue.cancelAll()
  94. }
  95. @objc func notificationReloadDataSourceMedia() {
  96. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadMediaDataSource)
  97. }
  98. func reloadDataSourceMedia() {
  99. if !(timerReadFileForMediaQueue?.isValid ?? false) {
  100. timerReadFileForMediaQueue = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(notificationReloadDataSourceMedia), userInfo: nil, repeats: false)
  101. }
  102. }
  103. }
  104. //MARK: -
  105. class NCOperationDownload: ConcurrentOperation {
  106. private var metadata: tableMetadata
  107. private var selector: String
  108. private var setFavorite: Bool
  109. init(metadata: tableMetadata, selector: String, setFavorite: Bool) {
  110. self.metadata = metadata
  111. self.selector = selector
  112. self.setFavorite = setFavorite
  113. }
  114. override func start() {
  115. if isCancelled {
  116. self.finish()
  117. } else {
  118. NCNetworking.shared.download(metadata: metadata, selector: self.selector, setFavorite: self.setFavorite) { (_) in
  119. self.finish()
  120. }
  121. }
  122. }
  123. }
  124. //MARK: -
  125. class NCOperationSynchronization: ConcurrentOperation {
  126. private var metadata: tableMetadata
  127. private var selector: String
  128. private var download: Bool
  129. init(metadata: tableMetadata, selector: String) {
  130. self.metadata = metadata
  131. self.selector = selector
  132. if selector == selectorDownloadSynchronize {
  133. self.download = true
  134. } else {
  135. self.download = false
  136. }
  137. }
  138. override func start() {
  139. if isCancelled {
  140. self.finish()
  141. } else {
  142. if metadata.directory {
  143. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  144. NCCommunication.shared.readFileOrFolder(serverUrlFileName: serverUrlFileName, depth: "infinity", showHiddenFiles: CCUtility.getShowHiddenFiles()) { (account, files, responseData, errorCode, errorDescription) in
  145. if errorCode == 0 {
  146. NCManageDatabase.sharedInstance.convertNCCommunicationFilesToMetadatas(files, useMetadataFolder: true, account: account) { (metadataFolder, metadatasFolder, metadatas) in
  147. if metadatas.count > 0 {
  148. let metadatasResult = NCManageDatabase.sharedInstance.getMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl BEGINSWITH %@ AND status == %d", account, serverUrlFileName, k_metadataStatusNormal))
  149. let metadatasChanged = NCManageDatabase.sharedInstance.updateMetadatas(metadatas, metadatasResult: metadatasResult, withVerifyLocal: self.download)
  150. if self.download {
  151. for metadata in metadatasChanged {
  152. if metadata.directory == false {
  153. NCOperationQueue.shared.download(metadata: metadata, selector: selectorSave, setFavorite: false)
  154. }
  155. }
  156. }
  157. }
  158. }
  159. } else if errorCode == 404 && self.metadata.directory {
  160. NCManageDatabase.sharedInstance.deleteDirectoryAndSubDirectory(serverUrl: self.metadata.serverUrl, account: self.metadata.account)
  161. }
  162. self.finish()
  163. }
  164. } else {
  165. if self.download {
  166. NCOperationQueue.shared.download(metadata: metadata, selector: selectorSave, setFavorite: false)
  167. }
  168. self.finish()
  169. }
  170. }
  171. }
  172. }
  173. //MARK: -
  174. class NCOperationDownloadThumbnail: ConcurrentOperation {
  175. var metadata: tableMetadata
  176. var urlBase: String
  177. var view: Any
  178. var indexPath: IndexPath
  179. init(metadata: tableMetadata, urlBase: String, view: Any, indexPath: IndexPath) {
  180. self.metadata = metadata
  181. self.urlBase = urlBase
  182. self.view = view
  183. self.indexPath = indexPath
  184. }
  185. override func start() {
  186. if isCancelled {
  187. self.finish()
  188. } else {
  189. let fileNamePath = CCUtility.returnFileNamePath(fromFileName: metadata.fileName, serverUrl: metadata.serverUrl, urlBase: urlBase, account: metadata.account)!
  190. let fileNamePreviewLocalPath = CCUtility.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag)!
  191. let fileNameIconLocalPath = CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)!
  192. 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
  193. var cell: NCImageCellProtocol?
  194. if self.view is UICollectionView && NCMainCommon.sharedInstance.isValidIndexPath(self.indexPath, view: self.view) {
  195. cell = (self.view as! UICollectionView).cellForItem(at: self.indexPath) as? NCImageCellProtocol
  196. } else if self.view is UITableView && NCMainCommon.sharedInstance.isValidIndexPath(self.indexPath, view: self.view) {
  197. cell = (self.view as! UITableView).cellForRow(at: self.indexPath) as? NCImageCellProtocol
  198. }
  199. if (cell != nil) {
  200. var previewImage: UIImage!
  201. if errorCode == 0 && imageIcon != nil {
  202. previewImage = imageIcon
  203. } else {
  204. if self.metadata.iconName.count > 0 {
  205. previewImage = UIImage(named: self.metadata.iconName)
  206. } else {
  207. previewImage = UIImage(named: "file")
  208. }
  209. }
  210. cell!.filePreviewImageView.backgroundColor = nil
  211. UIView.transition(with: cell!.filePreviewImageView,
  212. duration: 0.75,
  213. options: .transitionCrossDissolve,
  214. animations: { cell!.filePreviewImageView.image = previewImage! },
  215. completion: nil)
  216. }
  217. self.finish()
  218. }
  219. }
  220. }
  221. }
  222. //MARK: -
  223. class NCOperationReadFileForMediaQueue: ConcurrentOperation {
  224. var metadata: tableMetadata
  225. init(metadata: tableMetadata) {
  226. self.metadata = metadata
  227. }
  228. override func start() {
  229. if isCancelled {
  230. self.finish()
  231. } else {
  232. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  233. let requestBody =
  234. """
  235. <?xml version=\"1.0\" encoding=\"UTF-8\"?>
  236. <d:propfind xmlns:d=\"DAV:\" xmlns:oc=\"http://owncloud.org/ns\" xmlns:nc=\"http://nextcloud.org/ns\">
  237. <d:prop>
  238. <has-preview xmlns=\"http://nextcloud.org/ns\"/>
  239. <creation_time xmlns=\"http://nextcloud.org/ns\"/>
  240. <upload_time xmlns=\"http://nextcloud.org/ns\"/>
  241. </d:prop>
  242. </d:propfind>
  243. """
  244. NCCommunication.shared.readFileOrFolder(serverUrlFileName: serverUrlFileName, depth: "0", requestBody: requestBody.data(using: .utf8)) { (account, files, responseData, errorCode, errorDescription) in
  245. if errorCode == 0 && files.count > 0 {
  246. let file = files[0]
  247. let metadata = tableMetadata.init(value: self.metadata)
  248. var modify = false
  249. if metadata.hasPreview != file.hasPreview {
  250. metadata.hasPreview = file.hasPreview
  251. modify = true
  252. }
  253. if file.creationDate != nil && metadata.creationDate != file.creationDate {
  254. metadata.creationDate = file.creationDate!
  255. modify = true
  256. }
  257. if file.uploadDate != nil && metadata.uploadDate != file.uploadDate {
  258. metadata.uploadDate = file.uploadDate!
  259. modify = true
  260. }
  261. if modify {
  262. NCManageDatabase.sharedInstance.addMetadata(metadata)
  263. NCOperationQueue.shared.reloadDataSourceMedia()
  264. }
  265. } else if errorCode == 404 {
  266. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", self.metadata.ocId))
  267. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_deleteFile, userInfo: ["metadata": self.metadata, "errorCode": errorCode])
  268. }
  269. self.finish()
  270. }
  271. }
  272. }
  273. }