KMResourceDownloadManager.swift 15 KB

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