KMResourceDownloadManager.swift 18 KB

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