KMResourceDownloadManager.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. //
  2. // KMResourceDownloadManager.swift
  3. // PDF Master
  4. //
  5. // Created by lizhe on 2023/8/29.
  6. //
  7. import Cocoa
  8. import Foundation
  9. import ZipArchive // 请确保已导入 SSZipArchive 或其他合适的解压库
  10. let xmlURLString = "http://test-pdf-pro.kdan.cn:3021/downloads/DocumentAI.xml"
  11. let documentAIString = "http://test-pdf-pro.kdan.cn:3021/downloads/DocumentAI.bundle.zip"
  12. let kResourcePath = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first?.path
  13. enum KMResourceDownloadState {
  14. case none
  15. case unzipFailed
  16. case moveFailed
  17. case success
  18. }
  19. class KMResourceDownloadManager: NSObject {
  20. static let manager = KMResourceDownloadManager()
  21. var downloadTask: URLSessionDownloadTask?
  22. var progressBlock: ((Double) -> Void)?
  23. var downloadResultBlock: ((Bool, KMResourceDownloadState) -> Void)?
  24. func downloadFramework(progress: @escaping (Double) -> Void, result: @escaping (Bool, KMResourceDownloadState) -> Void) {
  25. self.progressBlock = progress
  26. self.downloadResultBlock = result
  27. if self.downloadTask == nil {
  28. self.downloadXML { [unowned self] content in
  29. let urlString = self.dealXML(content: content)
  30. // let urlString = "http://test-pdf-pro.kdan.cn:3021/downloads/DocumentAI.bundle.zip"
  31. if let url = URL(string: urlString) {
  32. let configuration = URLSessionConfiguration.default
  33. let session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
  34. let downloadTask = session.downloadTask(with: url)
  35. downloadTask.resume()
  36. self.downloadTask = downloadTask
  37. } else {
  38. dealDownloadResult(isSuccess: false, state: .none)
  39. }
  40. }
  41. } else {
  42. dealDownloadResult(isSuccess: false, state: .none)
  43. }
  44. }
  45. func documentAIBundleExists() -> Bool {
  46. let filePath: String = kResourcePath! + "/DocumentAI.bundle"
  47. let fileManager = FileManager.default
  48. let exists = fileManager.fileExists(atPath: filePath as String)
  49. if exists {
  50. self.checkDocumentAIVersion()
  51. }
  52. return exists
  53. }
  54. func cancelDownload() {
  55. downloadTask?.cancel()
  56. downloadTask = nil
  57. progressBlock = nil
  58. downloadResultBlock = nil
  59. }
  60. //结果处理
  61. func dealDownloadResult(isSuccess: Bool, state: KMResourceDownloadState) {
  62. DispatchQueue.main.async {
  63. self.downloadResultBlock?(isSuccess, state)
  64. self.cancelDownload()
  65. }
  66. }
  67. func checkDocumentAIVersion() {
  68. self.downloadXML { [unowned self] content in
  69. let urlString = self.dealXML(content: content)
  70. if urlString.count != 0 {
  71. let filePath: String = kResourcePath! + "/DocumentAI.bundle"
  72. try?FileManager.default.removeItem(atPath: filePath)
  73. let fileManager = FileManager.default
  74. let folderURL = fileManager.temporaryDirectory.appendingPathComponent("XMLResources")
  75. let xmlURL = folderURL.appendingPathComponent("DocumentAI.xml")
  76. try?FileManager.default.removeItem(at: xmlURL)
  77. }
  78. }
  79. }
  80. }
  81. extension KMResourceDownloadManager: XMLParserDelegate {
  82. func downloadXML(completion: @escaping (_ content: String) -> Void) {
  83. // 将 URL 字符串转换为 URL 对象
  84. if let xmlURL = URL(string: xmlURLString) {
  85. // 创建一个 URL 请求
  86. let request = URLRequest(url: xmlURL)
  87. // 创建一个 URLSession
  88. let session = URLSession.shared
  89. // 创建一个数据任务来下载 XML 数据
  90. let task = session.dataTask(with: request) { (data, response, error) in
  91. if let error = error {
  92. // 处理下载错误
  93. print("Error: \(error)")
  94. } else if let data = data {
  95. // 成功下载 XML 数据
  96. if let xmlString = String(data: data, encoding: .utf8) {
  97. // 将 XML 数据打印出来(你可以进一步处理它,比如解析它)
  98. print("XML Data: \(xmlString)")
  99. completion(xmlString)
  100. }
  101. }
  102. }
  103. // 启动任务
  104. task.resume()
  105. } else {
  106. // URL 字符串无效,进行错误处理
  107. print("Invalid URL")
  108. completion("")
  109. }
  110. }
  111. func dealXML(content: String) -> String {
  112. // 1. 定义 XML 内容,包括版本号
  113. // let xmlContent = """
  114. // <root>
  115. // <version>1.0</version>
  116. // <resourceURL>http://test-pdf-pro.kdan.cn:3021/downloads/DocumentAI.bundle.zip</resourceURL>
  117. // </root>
  118. // """
  119. let xmlContent = content
  120. // 2. 创建目标文件夹(如果不存在的话)
  121. let fileManager = FileManager.default
  122. let folderURL = fileManager.temporaryDirectory.appendingPathComponent("XMLResources")
  123. try? fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true, attributes: nil)
  124. // 3. 将 XML 内容写入文件
  125. let xmlURL = folderURL.appendingPathComponent("TempDocumentAI.xml")
  126. try? xmlContent.write(to: xmlURL, atomically: true, encoding: .utf8)
  127. // 4. 解析 XML 并比较版本号
  128. // 创建 XMLParser 实例
  129. var downloadedVersion = "0.0"
  130. if let xmlData = try? Data(contentsOf: self.fetchXMLURL()) {
  131. let xmlParser = XMLParser(data: xmlData)
  132. let xmlDelegate = XMLDelegate()
  133. xmlParser.delegate = xmlDelegate
  134. if xmlParser.parse() {
  135. downloadedVersion = xmlDelegate.version ?? "1.0"
  136. }
  137. }
  138. if let xmlData = try? Data(contentsOf: xmlURL) {
  139. let xmlParser = XMLParser(data: xmlData)
  140. let xmlDelegate = XMLDelegate()
  141. xmlParser.delegate = xmlDelegate
  142. if xmlParser.parse() {
  143. // Parsing was successful
  144. if let xmlVersion = xmlDelegate.version {
  145. if xmlVersion > downloadedVersion {
  146. // 下载资源的逻辑
  147. let resourceURL = xmlDelegate.resourceURL
  148. print("Download resource from \(resourceURL)")
  149. return resourceURL ?? ""
  150. } else {
  151. print("No need to download resources. Already up to date.")
  152. }
  153. }
  154. } else {
  155. // Parsing failed
  156. }
  157. } else {
  158. // Error handling for loading XML data
  159. }
  160. return ""
  161. }
  162. func fetchXMLURL() -> URL {
  163. // 2. 创建目标文件夹(如果不存在的话)
  164. let fileManager = FileManager.default
  165. let folderURL = fileManager.temporaryDirectory.appendingPathComponent("XMLResources")
  166. try? fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true, attributes: nil)
  167. // 3. 将 XML 内容写入文件
  168. let xmlURL = folderURL.appendingPathComponent("DocumentAI.xml")
  169. return xmlURL
  170. }
  171. func writeXML(content: String) {
  172. let xmlURL = self.fetchXMLURL()
  173. try? content.write(to: xmlURL, atomically: true, encoding: .utf8)
  174. }
  175. func xmlResourceDownloadSuccess() {
  176. let fileManager = FileManager.default
  177. let folderURL = fileManager.temporaryDirectory.appendingPathComponent("XMLResources")
  178. let xmlURL = folderURL.appendingPathComponent("DocumentAI.xml")
  179. let tempXmlURL = folderURL.appendingPathComponent("TempDocumentAI.xml")
  180. try?fileManager.removeItem(at: xmlURL)
  181. do {
  182. // 尝试更改文件名称
  183. try fileManager.moveItem(atPath: tempXmlURL.path, toPath: xmlURL.path)
  184. print("文件重命名成功:\(xmlURL.path)")
  185. } catch {
  186. // 处理重命名失败的错误
  187. print("文件重命名失败:\(error)")
  188. }
  189. }
  190. }
  191. extension KMResourceDownloadManager {
  192. //MARK: 解压
  193. func unzipFramework(at zipURL: URL, to destinationPath: String) {
  194. let fileManager = FileManager.default
  195. var success = false
  196. if zipURL.pathExtension == "zip" {
  197. success = SSZipArchive.unzipFile(atPath: zipURL.path, toDestination: destinationPath)
  198. } else {
  199. // 如果是其他类型的压缩文件,可以使用其他解压库
  200. // success = YourCustomUnzipLibrary.unzipFile(atPath: zipURL.path, toDestination: destinationPath)
  201. }
  202. if success {
  203. print("File unzipped successfully!")
  204. try? fileManager.removeItem(at: zipURL)
  205. } else {
  206. print("Failed to unzip file.")
  207. dealDownloadResult(isSuccess: false, state: .unzipFailed)
  208. }
  209. }
  210. func loadFramework(destinationPath: String) {
  211. let fileManager = FileManager.default
  212. let bundlePath = destinationPath + "/DocumentAI.bundle"
  213. if fileManager.fileExists(atPath: bundlePath) {
  214. if let bundle = Bundle(path: bundlePath) {
  215. // 使用 framework 中的代码和资源
  216. // 例如:bundle.load()
  217. print("Framework loaded successfully!")
  218. } else {
  219. print("Error loading bundle.")
  220. dealDownloadResult(isSuccess: false, state: .none)
  221. }
  222. } else {
  223. dealDownloadResult(isSuccess: false, state: .none)
  224. }
  225. }
  226. }
  227. extension KMResourceDownloadManager: URLSessionDelegate, URLSessionDownloadDelegate {
  228. //MARK: 网络下载
  229. func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
  230. let progress = Double(totalBytesWritten) / Double(totalBytesExpectedToWrite)
  231. print("Download progress: \(progress)")
  232. progressBlock?(progress)
  233. }
  234. func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
  235. guard let destinationPath = kResourcePath else {
  236. return
  237. }
  238. let fileManager = FileManager.default
  239. let destinationURL = URL(fileURLWithPath: destinationPath).appendingPathComponent("DocumentAI.bundle.zip")
  240. do {
  241. try fileManager.moveItem(at: location, to: destinationURL)
  242. print("Framework downloaded and installed successfully!")
  243. unzipFramework(at: destinationURL, to: destinationPath)
  244. dealDownloadResult(isSuccess: true, state: .success)
  245. self.xmlResourceDownloadSuccess()
  246. } catch {
  247. print("Failed to move framework: \(error)")
  248. dealDownloadResult(isSuccess: false, state: .moveFailed)
  249. }
  250. }
  251. }
  252. // 5. 定义一个 XML 解析器的代理类
  253. class XMLDelegate: NSObject, XMLParserDelegate {
  254. var currentElement: String = ""
  255. var version: String?
  256. var resourceURL: String?
  257. func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
  258. currentElement = elementName
  259. }
  260. func parser(_ parser: XMLParser, foundCharacters string: String) {
  261. if currentElement == "version" {
  262. if version == nil {
  263. version = string
  264. }
  265. } else if currentElement == "resourceURL" {
  266. if resourceURL == nil {
  267. resourceURL = string
  268. }
  269. }
  270. }
  271. }