feat(updates): 使用 Sparkle 从发布 ZIP 下载并重启更新

This commit is contained in:
2026-11-16 16:17:31 +08:00
parent 451d31682d
commit ec37b8e3f9
23 changed files with 716 additions and 219 deletions
+49 -122
View File
@@ -1,147 +1,74 @@
import Foundation
import Observation
/// The release tag carries the marketing version. Kymo's ZIP also carries its build number.
nonisolated struct PublishedRelease: Decodable, Equatable {
struct Asset: Decodable, Equatable { let name: String }
let tagName: String
let draft: Bool
let prerelease: Bool
let assets: [Asset]
private enum CodingKeys: String, CodingKey {
case tagName = "tag_name"
case draft, prerelease, assets
}
static let repository = URL(string: "https://git.airnan.cn/wangairnan/Kymo")!
static let endpoint = URL(string: "https://git.airnan.cn/api/v1/repos/wangairnan/Kymo/releases/latest")!
var page: URL { Self.repository.appending(path: "releases/tag").appending(component: tagName) }
var version: String { tagName.hasPrefix("v") ? String(tagName.dropFirst()) : tagName }
private static func components(_ value: String) throws -> [Int] {
var numbers: [Int] = []
for part in value.components(separatedBy: ".") {
guard !part.isEmpty, part.utf8.allSatisfy({ (48...57).contains($0) }), let n = Int(part) else {
throw URLError(.cannotParseResponse)
}
numbers.append(n)
}
while numbers.last == 0 { numbers.removeLast() }
return numbers
}
var build: Int? {
let prefix = "kymo-" + version + "-"
return assets.compactMap { asset -> Int? in
let name = asset.name
guard name.hasPrefix(prefix), name.hasSuffix(".zip") else { return nil }
let remainder = name.dropFirst(prefix.count)
guard let separator = remainder.firstIndex(of: "-") else { return nil }
let build = remainder[..<separator]
guard build.allSatisfy({ $0.isASCII && $0.isNumber }) else { return nil }
return Int(build)
}.max()
}
func isNewer(than localVersion: String, build localBuild: Int) throws -> Bool {
guard !draft, !prerelease else { throw URLError(.cannotParseResponse) }
let remote = try Self.components(version)
let local = try Self.components(localVersion)
if remote != local { return local.lexicographicallyPrecedes(remote) }
return build.map { $0 > localBuild } ?? false
}
static func latest() async throws -> Self {
let config = URLSessionConfiguration.ephemeral
config.urlCache = nil
config.httpCookieStorage = nil
config.urlCredentialStorage = nil
config.timeoutIntervalForRequest = 15
let session = URLSession(configuration: config)
defer { session.finishTasksAndInvalidate() }
let (data, response) = try await session.data(from: endpoint)
guard (response as? HTTPURLResponse)?.statusCode == 200 else { throw URLError(.badServerResponse) }
return try JSONDecoder().decode(Self.self, from: data)
}
}
/// Shared by the panel badge and About page. Sparkle owns the actual update session.
@MainActor @Observable final class ReleaseUpdates {
enum Phase { case idle, checking, checked, failed }
enum Phase { case idle, checking, current, available, downloading, extracting, ready, restarting, failed }
struct Version: Equatable {
let display: String
let build: String
let infoURL: URL?
var label: String { "v\(display) (\(build))" }
}
private(set) var phase = Phase.idle
private(set) var available: PublishedRelease?
private(set) var version: Version?
private(set) var errorMessage: String?
private(set) var fraction: Double?
var automatic: Bool {
didSet {
guard automatic != oldValue else { return }
guard oldValue != automatic else { return }
defaults.set(automatic, forKey: Self.preferenceKey)
if automatic { check(manual: false) }
else {
timer?.cancel()
if automaticRequest { cancelRequest() }
}
changeAutomatic?(automatic)
}
}
private static let preferenceKey = "updates.automatic"
private let defaults: UserDefaults
private let version: String
private let build: Int
private let fetch: () async throws -> PublishedRelease
@ObservationIgnored private var timer: Task<Void, Never>?
@ObservationIgnored private var request: Task<Void, Never>?
@ObservationIgnored private var automaticRequest = false
@ObservationIgnored var changeAutomatic: ((Bool) -> Void)?
@ObservationIgnored var beginCheck: (() -> Void)?
@ObservationIgnored var beginDownload: ((Version) -> Void)?
@ObservationIgnored private var restart: (() -> Void)?
init(defaults: UserDefaults = .standard,
version: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "",
build: Int = Int(Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "") ?? 0,
fetch: @escaping () async throws -> PublishedRelease = PublishedRelease.latest) {
init(defaults: UserDefaults = .standard) {
self.defaults = defaults
self.version = version
self.build = build
self.fetch = fetch
automatic = defaults.object(forKey: Self.preferenceKey) as? Bool ?? true
}
func start() { if automatic { check(manual: false) } }
func check() {
guard [.idle, .available, .current, .failed].contains(phase) else { return }
beginCheck?()
}
func check(manual: Bool = true) {
guard request == nil else { return }
timer?.cancel()
phase = .checking
automaticRequest = !manual
request = Task { [weak self, fetch] in
guard !Task.isCancelled else { return }
do {
let release = try await fetch()
guard !Task.isCancelled, let self else { return }
available = try release.isNewer(than: version, build: build) ? release : nil
phase = .checked
} catch {
guard !Task.isCancelled else { return }
self?.phase = .failed
}
guard let self else { return }
request = nil
automaticRequest = false
if automatic {
let delay: Duration = phase == .failed ? .seconds(3600) : .seconds(86400)
timer = Task { [weak self] in
do { try await Task.sleep(for: delay) } catch { return }
self?.check(manual: false)
}
}
func performAction() {
switch phase {
case .available:
if let version, version.infoURL == nil { beginDownload?(version) }
case .ready:
guard let restart else { return }
self.restart = nil
transition(to: .restarting)
restart()
case .failed, .idle, .current: check()
default: break
}
}
private func cancelRequest() {
request?.cancel()
request = nil
automaticRequest = false
if phase == .checking { phase = .idle }
func found(_ version: Version) {
self.version = version
transition(to: .available)
}
func stop() {
timer?.cancel()
cancelRequest()
func ready(restart: @escaping () -> Void) {
transition(to: .ready)
self.restart = restart
}
func transition(to phase: Phase, fraction: Double? = nil, error: String? = nil) {
self.phase = phase
self.fraction = fraction
errorMessage = error
restart = nil
if phase == .current || phase == .idle { version = nil }
}
}
+126
View File
@@ -0,0 +1,126 @@
import Foundation
import Sparkle
@MainActor final class SparkleUpdater: NSObject, SPUUserDriver, SPUUpdaterDelegate {
private let updates: ReleaseUpdates
private lazy var updater = SPUUpdater(hostBundle: .main, applicationBundle: .main, userDriver: self, delegate: self)
private var started = false
private var requestedBuild: String?
private var expectedBytes: UInt64 = 0
private var receivedBytes: UInt64 = 0
init(updates: ReleaseUpdates) {
self.updates = updates
super.init()
updates.changeAutomatic = { [weak self] enabled in self?.updater.automaticallyChecksForUpdates = enabled }
updates.beginCheck = { [weak self] in self?.check() }
updates.beginDownload = { [weak self] in self?.check(download: $0) }
}
func start() {
guard prepare() else { return }
if updates.automatic { updater.checkForUpdatesInBackground() }
}
private func prepare() -> Bool {
if started { return true }
do {
if updater.automaticallyChecksForUpdates != updates.automatic {
updater.automaticallyChecksForUpdates = updates.automatic
}
try updater.start()
started = true
return true
} catch {
updates.transition(to: .failed, error: error.localizedDescription)
return false
}
}
private func check(download: ReleaseUpdates.Version? = nil) {
guard prepare(), !updater.sessionInProgress else { return }
requestedBuild = download?.build
updates.transition(to: .checking)
updater.checkForUpdates()
}
func show(_ request: SPUUpdatePermissionRequest, reply: @escaping (SUUpdatePermissionResponse) -> Void) {
reply(SUUpdatePermissionResponse(automaticUpdateChecks: updates.automatic, sendSystemProfile: false))
}
func showUserInitiatedUpdateCheck(cancellation: @escaping () -> Void) {}
func showUpdateFound(with appcastItem: SUAppcastItem, state: SPUUserUpdateState,
reply: @escaping (SPUUserUpdateChoice) -> Void) {
guard state.userInitiated || updates.automatic else { reply(.dismiss); return }
let version = ReleaseUpdates.Version(display: appcastItem.displayVersionString, build: appcastItem.versionString,
infoURL: appcastItem.isInformationOnlyUpdate ? appcastItem.infoURL : nil)
updates.found(version)
if state.stage == .installing {
updates.ready { reply(.install) }
} else if state.userInitiated, requestedBuild == version.build, !appcastItem.isInformationOnlyUpdate {
updates.transition(to: .downloading)
reply(.install)
} else {
// Keep the badge, release the session so Sparkle can check again in six hours.
reply(.dismiss)
}
}
func showUpdateReleaseNotes(with downloadData: SPUDownloadData) {}
func showUpdateReleaseNotesFailedToDownloadWithError(_ error: Error) {}
func showUpdateNotFoundWithError(_ error: Error, acknowledgement: @escaping () -> Void) {
updates.transition(to: .current)
acknowledgement()
}
func showUpdaterError(_ error: Error, acknowledgement: @escaping () -> Void) {
updates.transition(to: .failed, error: error.localizedDescription)
acknowledgement()
}
func showDownloadInitiated(cancellation: @escaping () -> Void) {
expectedBytes = 0
receivedBytes = 0
updates.transition(to: .downloading)
}
func showDownloadDidReceiveExpectedContentLength(_ expectedContentLength: UInt64) {
expectedBytes = expectedContentLength
}
func showDownloadDidReceiveData(ofLength length: UInt64) {
receivedBytes += length
let fraction = expectedBytes > 0 ? min(1, Double(receivedBytes) / Double(expectedBytes)) : nil
updates.transition(to: .downloading, fraction: fraction)
}
func showDownloadDidStartExtractingUpdate() { updates.transition(to: .extracting) }
func showExtractionReceivedProgress(_ progress: Double) { updates.transition(to: .extracting, fraction: progress) }
func showReady(toInstallAndRelaunch reply: @escaping (SPUUserUpdateChoice) -> Void) {
updates.ready { reply(.install) }
}
func showInstallingUpdate(withApplicationTerminated terminated: Bool, retryTerminatingApplication: @escaping () -> Void) {
if !terminated { updates.ready(restart: retryTerminatingApplication) }
}
func showUpdateInstalledAndRelaunched(_ relaunched: Bool, acknowledgement: @escaping () -> Void) {
updates.transition(to: .current)
acknowledgement()
}
func dismissUpdateInstallation() {}
func updater(_ updater: SPUUpdater, didFinishUpdateCycleFor updateCheck: SPUUpdateCheck, error: Error?) {
requestedBuild = nil
guard let error = error as NSError? else { return }
if error.domain == SUSparkleErrorDomain, error.code == SUError.noUpdateError.rawValue {
updates.transition(to: .current)
} else {
updates.transition(to: .failed, error: error.localizedDescription)
}
}
}