feat(settings): 新增关于菜单和基于正式发布的更新检测

This commit is contained in:
2026-11-16 11:26:18 +08:00
parent b9abb970d9
commit 0442398407
16 changed files with 540 additions and 31 deletions
+147
View File
@@ -0,0 +1,147 @@
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)
}
}
@MainActor @Observable final class ReleaseUpdates {
enum Phase { case idle, checking, checked, failed }
private(set) var phase = Phase.idle
private(set) var available: PublishedRelease?
var automatic: Bool {
didSet {
guard automatic != oldValue else { return }
defaults.set(automatic, forKey: Self.preferenceKey)
if automatic { check(manual: false) }
else {
timer?.cancel()
if automaticRequest { cancelRequest() }
}
}
}
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
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) {
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(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)
}
}
}
}
private func cancelRequest() {
request?.cancel()
request = nil
automaticRequest = false
if phase == .checking { phase = .idle }
}
func stop() {
timer?.cancel()
cancelRequest()
}
}