75 lines
2.3 KiB
Swift
75 lines
2.3 KiB
Swift
import Foundation
|
|
import Observation
|
|
|
|
/// Shared by the panel badge and About page. Sparkle owns the actual update session.
|
|
@MainActor @Observable final class ReleaseUpdates {
|
|
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 version: Version?
|
|
private(set) var errorMessage: String?
|
|
private(set) var fraction: Double?
|
|
var automatic: Bool {
|
|
didSet {
|
|
guard oldValue != automatic else { return }
|
|
defaults.set(automatic, forKey: Self.preferenceKey)
|
|
changeAutomatic?(automatic)
|
|
}
|
|
}
|
|
|
|
private static let preferenceKey = "updates.automatic"
|
|
private let defaults: UserDefaults
|
|
@ObservationIgnored var changeAutomatic: ((Bool) -> Void)?
|
|
@ObservationIgnored var beginCheck: (() -> Void)?
|
|
@ObservationIgnored var beginDownload: ((Version) -> Void)?
|
|
@ObservationIgnored private var restart: (() -> Void)?
|
|
|
|
init(defaults: UserDefaults = .standard) {
|
|
self.defaults = defaults
|
|
automatic = defaults.object(forKey: Self.preferenceKey) as? Bool ?? true
|
|
}
|
|
|
|
func check() {
|
|
guard [.idle, .available, .current, .failed].contains(phase) else { return }
|
|
beginCheck?()
|
|
}
|
|
|
|
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
|
|
}
|
|
}
|
|
|
|
func found(_ version: Version) {
|
|
self.version = version
|
|
transition(to: .available)
|
|
}
|
|
|
|
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 }
|
|
}
|
|
}
|