KMResourceDownloadManager.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. //
  2. // KMResourceDownloadManager.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by lizhe on 2023/8/29.
  6. //
  7. import Cocoa
  8. import Foundation
  9. import ZipArchive // 请确保已导入 SSZipArchive 或其他合适的解压库
  10. import ComDocumentAIKit
  11. import ComPDFKit_Conversion
  12. //#if DEBUG
  13. //let xmlURLString = "http://test-pdf-pro.kdan.cn:3021/downloads/DocumentAI.xml"
  14. //#else
  15. //let xmlURLString = "https://www.pdfreaderpro.com/downloads/DocumentAI.xml"
  16. //#endif
  17. //let documentAIString = "http://test-pdf-pro.kdan.cn:3021/downloads/DocumentAI.bundle.zip"
  18. let xmlURLString = KMServerConfig().kResourceServerURL
  19. let kResourcePath: String = kAppSupportOfBundleIdentifierDirectory.path
  20. let kLocalFilePath: String = kAppSupportOfBundleIdentifierDirectory.appendingPathComponent("DocumentAI.bundle").path
  21. enum KMResourceDownloadState {
  22. case none
  23. case unzipFailed
  24. case moveFailed
  25. case success
  26. case retry
  27. }
  28. struct Version: Comparable {
  29. let components: [Int]
  30. init?(_ version: String) {
  31. components = version.split(separator: ".").compactMap { Int($0) }
  32. guard !components.isEmpty else { return nil }
  33. }
  34. static func < (lhs: Version, rhs: Version) -> Bool {
  35. for (l, r) in zip(lhs.components, rhs.components) {
  36. if l != r { return l < r }
  37. }
  38. return lhs.components.count < rhs.components.count
  39. }
  40. }
  41. class KMResourceDownloadManager: NSObject {
  42. static let manager = KMResourceDownloadManager()
  43. var downloadTask: URLSessionDownloadTask?
  44. var progressBlock: ((Double) -> Void)?
  45. var downloadResultBlock: ((Bool, KMResourceDownloadState) -> Void)?
  46. var reachabilityAlert: NSAlert?
  47. func downloadFramework(progress: @escaping (Double) -> Void, result: @escaping (Bool, KMResourceDownloadState) -> Void) {
  48. self.progressBlock = progress
  49. self.downloadResultBlock = result
  50. KMRequestServer.requestServer.reachabilityStatusChange { [weak self] status in
  51. if status == .notReachable {
  52. KMPrint("无网络")
  53. self?.downloadTask?.cancel()
  54. self?.downloadTask = nil
  55. self?.downloadResultBlock?(false, .none)
  56. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2, execute: { [weak self] in
  57. if self?.reachabilityAlert == nil {
  58. self?.reachabilityAlert = NSAlert()
  59. self?.reachabilityAlert?.messageText = NSLocalizedString("Network Disconnected", comment: "")
  60. self?.reachabilityAlert?.informativeText = NSLocalizedString("Please connect to the internet and download again.", comment: "")
  61. self?.reachabilityAlert?.addButton(withTitle: NSLocalizedString("Retry", comment: ""))
  62. self?.reachabilityAlert?.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  63. var window = NSWindow.currentWindow()
  64. if window != nil {
  65. self?.reachabilityAlert?.beginSheetModal(for: window) { result in
  66. if (result == .alertSecondButtonReturn) {
  67. self?.reachabilityAlert = nil
  68. self?.cancelDownload()
  69. } else if result == .alertFirstButtonReturn {
  70. self?.reachabilityAlert = nil
  71. self?.downloadResultBlock?(false, .retry)
  72. self?.cancelDownload()
  73. return
  74. }
  75. self?.reachabilityAlert = nil
  76. }
  77. } else {
  78. self?.reachabilityAlert = nil
  79. }
  80. } else {
  81. self?.reachabilityAlert = nil
  82. }
  83. })
  84. } else {
  85. KMPrint("有网络")
  86. }
  87. }
  88. if self.downloadTask == nil {
  89. self.downloadXML { [unowned self] content in
  90. let urlString = self.dealXML(content: content)
  91. // let urlString = "http://test-pdf-pro.kdan.cn:3021/downloads/DocumentAI.bundle.zip"
  92. if let url = URL(string: urlString) {
  93. let configuration = URLSessionConfiguration.default
  94. let session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
  95. let downloadTask = session.downloadTask(with: url)
  96. downloadTask.resume()
  97. self.downloadTask = downloadTask
  98. } else {
  99. dealDownloadResult(isSuccess: false, state: .none)
  100. }
  101. }
  102. } else {
  103. dealDownloadResult(isSuccess: false, state: .none)
  104. }
  105. }
  106. func documentAIBundleExists(complete:@escaping (_ result: Bool) -> Void) {
  107. let filePath: String = kLocalFilePath
  108. let fileManager = FileManager.default
  109. debugPrint(filePath)
  110. debugPrint(FileManager.default.temporaryDirectory.appendingPathComponent("XMLResources"))
  111. let exists = fileManager.fileExists(atPath: filePath as String)
  112. //如果存在则判断版本是否符合,如果不符合则删除后重新下载
  113. if exists {
  114. self.checkDocumentAIVersion(complete: complete)
  115. self.loadDocumentAIBundle(bundlePath: kLocalFilePath)
  116. } else {
  117. self.removeDownloadResourcePath()
  118. complete(false)
  119. }
  120. }
  121. func cancelDownload() {
  122. downloadTask?.cancel()
  123. downloadTask = nil
  124. progressBlock = nil
  125. downloadResultBlock = nil
  126. }
  127. //结果处理
  128. func dealDownloadResult(isSuccess: Bool, state: KMResourceDownloadState) {
  129. DispatchQueue.main.async {
  130. self.downloadResultBlock?(isSuccess, state)
  131. self.cancelDownload()
  132. }
  133. }
  134. func checkDocumentAIVersion(complete: @escaping (_ results: Bool) -> Void) {
  135. self.downloadXML { [unowned self] content in
  136. let urlString = self.dealXML(content: content)
  137. if urlString.count != 0 {
  138. try?FileManager.default.removeItem(atPath: kLocalFilePath)
  139. complete(false)
  140. } else {
  141. complete(true)
  142. }
  143. }
  144. }
  145. func loadDocumentAIBundle(bundlePath: String) {
  146. guard FileManager.default.fileExists(atPath: bundlePath) else {
  147. print("Bundle does not exist at specified path.")
  148. return
  149. }
  150. if let bundle = Bundle(path: bundlePath) {
  151. if let resourcePath = bundle.path(forResource: "DocumentAI", ofType: "model") {
  152. print("Found resource at path: \(resourcePath)")
  153. //绑定资源包
  154. CDocumentAIKit.sharedInstance().setOCRModelPath(bundlePath)
  155. CPDFConvertKit.setOCRModelPath(bundlePath)
  156. } else {
  157. print("Resource not found.")
  158. }
  159. } else {
  160. print("Failed to load bundle.")
  161. }
  162. }
  163. }
  164. extension KMResourceDownloadManager: XMLParserDelegate {
  165. func downloadXML(completion: @escaping (_ content: String) -> Void) {
  166. if let xmlURL = URL(string: xmlURLString) {
  167. let request = URLRequest(url: xmlURL)
  168. let session = URLSession.shared
  169. let task = session.dataTask(with: request) { (data, response, error) in
  170. if let error = error {
  171. print("Error: \(error)")
  172. } else if let data = data {
  173. if let xmlString = String(data: data, encoding: .utf8) {
  174. print("XML Data: \(xmlString)")
  175. completion(xmlString)
  176. }
  177. }
  178. }
  179. task.resume()
  180. } else {
  181. print("Invalid URL")
  182. completion("")
  183. }
  184. }
  185. func dealXML(content: String) -> String {
  186. //
  187. // 1. 定义 XML 内容,包括版本号
  188. // let xmlContent = """
  189. // <root>
  190. // <resources>
  191. // <resource>
  192. // <maxVersion>1.3.0</maxVersion>
  193. // <minVersion>1.1.0</minVersion>
  194. // <resourceURL>https://www.pdfreaderpro.com/downloads/DocumentAI.bundle.1.0.0.zip</resourceURL>
  195. // </resource>
  196. // <resource>
  197. // <maxVersion>4.6.3</maxVersion>
  198. // <minVersion>1.4.0</minVersion>
  199. // <resourceURL>https://www.pdfreaderpro.com/downloads/DocumentAI.bundle.2.0.0.zip</resourceURL>
  200. // </resource>
  201. // </resources>
  202. // </root>
  203. // """
  204. let xmlContent = content
  205. let parser = ResourceParser()
  206. let resources = parser.parse(data: xmlContent.data(using: .utf8)!)
  207. // 从捆绑包的 Info.plist 文件中获取版本号
  208. var appVersion = "1.0.0"
  209. if let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String {
  210. appVersion = version
  211. print("应用程序版本号:\(appVersion)")
  212. } else {
  213. print("无法获取应用程序版本号。")
  214. }
  215. if let resourceURL = shouldDownloadResource(for: appVersion, resources: resources) {
  216. if let local = self.getDownloadedResourcePath(for: kLocalFilePath) {
  217. if local != resourceURL {
  218. //如果本地存在两个地址不相同 则下载
  219. print("No suitable resource found for the current version.")
  220. return resourceURL
  221. } else {
  222. //如果本地存在 两个地址相同 则不下载
  223. print("No suitable resource found for the current version.")
  224. return ""
  225. }
  226. } else {
  227. //如果本地不存在 则下载
  228. print("Download resource from: \(resourceURL)")
  229. return resourceURL
  230. }
  231. } else {
  232. //如果找不到下载链接 则不下载
  233. print("No suitable resource found for the current version.")
  234. return ""
  235. }
  236. }
  237. func shouldDownloadResource(for currentVersion: String, resources: [Resource]) -> String? {
  238. for resource in resources {
  239. if isVersion(currentVersion, between: resource.minVersion, and: resource.maxVersion) {
  240. return resource.resourceURL
  241. }
  242. }
  243. return nil
  244. }
  245. func isVersion(_ version: String, between minVersion: String, and maxVersion: String) -> Bool {
  246. guard let current = Version(version),
  247. let min = Version(minVersion),
  248. let max = Version(maxVersion) else {
  249. return false
  250. }
  251. return current >= min && current <= max
  252. }
  253. func saveDownloadedResource(resourceURL: String, localPath: String) {
  254. var resources = UserDefaults.standard.dictionary(forKey: "downloadedResources") as? [String: String] ?? [:]
  255. resources[localPath] = resourceURL
  256. UserDefaults.standard.set(resources, forKey: "downloadedResources")
  257. }
  258. func getDownloadedResourcePath(for resourceURL: String) -> String? {
  259. let resources = UserDefaults.standard.dictionary(forKey: "downloadedResources") as? [String: String]
  260. return resources?[resourceURL]
  261. }
  262. func removeDownloadResourcePath() {
  263. UserDefaults.standard.removeObject(forKey: "downloadedResources")
  264. }
  265. func validateResource(for resourceURL: String) -> Bool {
  266. if let localPath = getDownloadedResourcePath(for: resourceURL) {
  267. return FileManager.default.fileExists(atPath: localPath)
  268. }
  269. return false
  270. }
  271. }
  272. extension KMResourceDownloadManager {
  273. //MARK: 解压
  274. func unzipFramework(at zipURL: URL, to destinationPath: String) {
  275. let fileManager = FileManager.default
  276. var success = false
  277. if zipURL.pathExtension == "zip" {
  278. success = SSZipArchive.unzipFile(atPath: zipURL.path, toDestination: destinationPath)
  279. } else {
  280. // 如果是其他类型的压缩文件,可以使用其他解压库
  281. // success = YourCustomUnzipLibrary.unzipFile(atPath: zipURL.path, toDestination: destinationPath)
  282. }
  283. if success {
  284. print("File unzipped successfully!")
  285. try? fileManager.removeItem(at: zipURL)
  286. } else {
  287. print("Failed to unzip file.")
  288. dealDownloadResult(isSuccess: false, state: .unzipFailed)
  289. }
  290. }
  291. }
  292. extension KMResourceDownloadManager: URLSessionDelegate, URLSessionDownloadDelegate {
  293. //MARK: 网络下载
  294. func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
  295. let progress = Double(totalBytesWritten) / Double(totalBytesExpectedToWrite)
  296. print("Download progress: \(progress)")
  297. progressBlock?(progress)
  298. }
  299. func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
  300. let destinationPath = kResourcePath
  301. let fileManager = FileManager.default
  302. let destinationURL = URL(fileURLWithPath: destinationPath).appendingPathComponent("DocumentAI.bundle.zip")
  303. do {
  304. try fileManager.moveItem(at: location, to: destinationURL)
  305. print("Framework downloaded and installed successfully!")
  306. unzipFramework(at: destinationURL, to: destinationPath)
  307. dealDownloadResult(isSuccess: true, state: .success)
  308. if let sourceURL = downloadTask.originalRequest?.url {
  309. saveDownloadedResource(resourceURL: sourceURL.absoluteString, localPath: kLocalFilePath)
  310. }
  311. } catch {
  312. print("Failed to move framework: \(error)")
  313. dealDownloadResult(isSuccess: false, state: .moveFailed)
  314. }
  315. }
  316. }
  317. struct Resource {
  318. let maxVersion: String
  319. let minVersion: String
  320. let resourceURL: String
  321. }
  322. // 5. 定义一个 XML 解析器的代理类
  323. class ResourceParser: NSObject, XMLParserDelegate {
  324. private var resources: [Resource] = []
  325. private var currentElement = ""
  326. var currentMaxVersion = ""
  327. var currentMinVersion = ""
  328. var currentResourceURL = ""
  329. func parse(data: Data) -> [Resource] {
  330. let parser = XMLParser(data: data)
  331. parser.delegate = self
  332. parser.parse()
  333. return resources
  334. }
  335. func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
  336. currentElement = elementName
  337. }
  338. func parser(_ parser: XMLParser, foundCharacters string: String) {
  339. switch currentElement {
  340. case "maxVersion":
  341. currentMaxVersion += string
  342. case "minVersion":
  343. currentMinVersion += string
  344. case "resourceURL":
  345. currentResourceURL += string
  346. default:
  347. break
  348. }
  349. }
  350. func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
  351. if elementName == "resource" {
  352. resources.append(
  353. Resource(
  354. maxVersion: currentMaxVersion.trimmingCharacters(in: .whitespacesAndNewlines),
  355. minVersion: currentMinVersion.trimmingCharacters(in: .whitespacesAndNewlines),
  356. resourceURL: currentResourceURL.trimmingCharacters(in: .whitespacesAndNewlines)
  357. )
  358. )
  359. currentMaxVersion = ""
  360. currentMinVersion = ""
  361. currentResourceURL = ""
  362. }
  363. }
  364. }