KMResourceDownloadManager.swift 13 KB

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