KMResourceDownloadManager.swift 12 KB

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