feat(updates): 使用 Sparkle 从发布 ZIP 下载并重启更新
This commit is contained in:
@@ -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 }
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user