NCOperationQueue.swift 14 KB

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