KMResourceDownloadManager.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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. // 2. 创建目标文件夹(如果不存在的话)
  120. let fileManager = FileManager.default
  121. let folderURL = fileManager.temporaryDirectory.appendingPathComponent("XMLResources")
  122. try? fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true, attributes: nil)
  123. // 3. 将 XML 内容写入文件
  124. let xmlURL = folderURL.appendingPathComponent("TempDocumentAI.xml")
  125. try? xmlContent.write(to: xmlURL, atomically: true, encoding: .utf8)
  126. // 4. 解析 XML 并比较版本号
  127. // 创建 XMLParser 实例
  128. var downloadedVersion = "0.0"
  129. if let xmlData = try? Data(contentsOf: self.fetchXMLURL()) {
  130. let xmlParser = XMLParser(data: xmlData)
  131. let xmlDelegate = XMLDelegate()
  132. xmlParser.delegate = xmlDelegate
  133. if xmlParser.parse() {
  134. downloadedVersion = xmlDelegate.version ?? "1.0"
  135. }
  136. }
  137. if let xmlData = try? Data(contentsOf: xmlURL) {
  138. let xmlParser = XMLParser(data: xmlData)
  139. let xmlDelegate = XMLDelegate()
  140. xmlParser.delegate = xmlDelegate
  141. if xmlParser.parse() {
  142. // Parsing was successful
  143. if let xmlVersion = xmlDelegate.version {
  144. if xmlVersion > downloadedVersion {
  145. // 下载资源的逻辑
  146. let resourceURL = xmlDelegate.resourceURL
  147. print("Download resource from \(resourceURL)")
  148. return resourceURL ?? ""
  149. } else {
  150. print("No need to download resources. Already up to date.")
  151. }
  152. }
  153. } else {
  154. // Parsing failed
  155. }
  156. } else {
  157. // Error handling for loading XML data
  158. }
  159. return ""
  160. }
  161. func fetchXMLURL() -> URL {
  162. // 2. 创建目标文件夹(如果不存在的话)
  163. let fileManager = FileManager.default
  164. let folderURL = fileManager.temporaryDirectory.appendingPathComponent("XMLResources")
  165. try? fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true, attributes: nil)
  166. // 3. 将 XML 内容写入文件
  167. let xmlURL = folderURL.appendingPathComponent("DocumentAI.xml")
  168. return xmlURL
  169. }
  170. func writeXML(content: String) {
  171. let xmlURL = self.fetchXMLURL()
  172. try? content.write(to: xmlURL, atomically: true, encoding: .utf8)
  173. }
  174. func xmlResourceDownloadSuccess() {
  175. let fileManager = FileManager.default
  176. let folderURL = fileManager.temporaryDirectory.appendingPathComponent("XMLResources")
  177. let xmlURL = folderURL.appendingPathComponent("DocumentAI.xml")
  178. let tempXmlURL = folderURL.appendingPathComponent("TempDocumentAI.xml")
  179. try?fileManager.removeItem(at: xmlURL)
  180. do {
  181. // 尝试更改文件名称
  182. try fileManager.moveItem(atPath: tempXmlURL.path, toPath: xmlURL.path)
  183. print("文件重命名成功:\(xmlURL.path)")
  184. } catch {
  185. // 处理重命名失败的错误
  186. print("文件重命名失败:\(error)")
  187. }
  188. }
  189. }
  190. extension KMResourceDownloadManager {
  191. //MARK: 解压
  192. func unzipFramework(at zipURL: URL, to destinationPath: String) {
  193. let fileManager = FileManager.default
  194. var success = false
  195. if zipURL.pathExtension == "zip" {
  196. success = SSZipArchive.unzipFile(atPath: zipURL.path, toDestination: destinationPath)
  197. } else {
  198. // 如果是其他类型的压缩文件,可以使用其他解压库
  199. // success = YourCustomUnzipLibrary.unzipFile(atPath: zipURL.path, toDestination: destinationPath)
  200. }
  201. if success {
  202. print("File unzipped successfully!")
  203. try? fileManager.removeItem(at: zipURL)
  204. } else {
  205. print("Failed to unzip file.")
  206. dealDownloadResult(isSuccess: false, state: .unzipFailed)
  207. }
  208. }
  209. func loadFramework(destinationPath: String) {
  210. let fileManager = FileManager.default
  211. let bundlePath = destinationPath + "/DocumentAI.bundle"
  212. if fileManager.fileExists(atPath: bundlePath) {
  213. if let bundle = Bundle(path: bundlePath) {
  214. // 使用 framework 中的代码和资源
  215. // 例如:bundle.load()
  216. print("Framework loaded successfully!")
  217. } else {
  218. print("Error loading bundle.")
  219. dealDownloadResult(isSuccess: false, state: .none)
  220. }
  221. } else {
  222. dealDownloadResult(isSuccess: false, state: .none)
  223. }
  224. }
  225. }
  226. extension KMResourceDownloadManager: URLSessionDelegate, URLSessionDownloadDelegate {
  227. //MARK: 网络下载
  228. func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
  229. let progress = Double(totalBytesWritten) / Double(totalBytesExpectedToWrite)
  230. print("Download progress: \(progress)")
  231. progressBlock?(progress)
  232. }
  233. func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
  234. guard let destinationPath = kResourcePath else {
  235. return
  236. }
  237. let fileManager = FileManager.default
  238. let destinationURL = URL(fileURLWithPath: destinationPath).appendingPathComponent("DocumentAI.bundle.zip")
  239. do {
  240. try fileManager.moveItem(at: location, to: destinationURL)
  241. print("Framework downloaded and installed successfully!")
  242. unzipFramework(at: destinationURL, to: destinationPath)
  243. dealDownloadResult(isSuccess: true, state: .success)
  244. self.xmlResourceDownloadSuccess()
  245. } catch {
  246. print("Failed to move framework: \(error)")
  247. dealDownloadResult(isSuccess: false, state: .moveFailed)
  248. }
  249. }
  250. }
  251. // 5. 定义一个 XML 解析器的代理类
  252. class XMLDelegate: NSObject, XMLParserDelegate {
  253. var currentElement: String = ""
  254. var version: String?
  255. var resourceURL: String?
  256. func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
  257. currentElement = elementName
  258. }
  259. func parser(_ parser: XMLParser, foundCharacters string: String) {
  260. if currentElement == "version" {
  261. if version == nil {
  262. version = string
  263. }
  264. } else if currentElement == "resourceURL" {
  265. if resourceURL == nil {
  266. resourceURL = string
  267. }
  268. }
  269. }
  270. }