Skip to content

知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.

feat: Check for updates every 4 hours and from the menu bar panel, with the result shown in place

wquguru76677e00f4b3
diff --git a/Sources/LiveSubs/AppMenu.swift b/Sources/LiveSubs/AppMenu.swift
index 5a53a8b..9ce514b 100644
--- a/Sources/LiveSubs/AppMenu.swift
+++ b/Sources/LiveSubs/AppMenu.swift
@@ -163,32 +163,9 @@ final class AppMenu: NSObject, NSMenuItemValidation {
@objc private func checkUpdates() {
guard let model else { return }
if model.updates.update != nil { model.updates.install(model: model); return }
- Task {
- model.updates.checkNow()
- // A manual check from the menu answers in an alert: the panel isn't open to show it.
- while model.updates.check == .checking { try? await Task.sleep(for: .milliseconds(100)) }
- let alert = NSAlert()
- if let u = model.updates.update {
- alert.messageText = L("有新版本 \(u.version)")
- alert.informativeText = L("当前版本 \(Updates.current)。安装后会自动重新打开。")
- alert.addButton(withTitle: L("安装并重新打开"))
- alert.addButton(withTitle: L("更新说明"))
- alert.addButton(withTitle: L("稍后"))
- switch alert.runModal() {
- case .alertFirstButtonReturn: model.updates.install(model: model)
- case .alertSecondButtonReturn: NSWorkspace.shared.open(u.url)
- default: break
- }
- } else if model.updates.check == .upToDate {
- alert.messageText = L("已是最新版本")
- alert.informativeText = L("当前版本 \(Updates.current)。")
- alert.runModal()
- } else {
- alert.messageText = L("暂时无法检查更新")
- alert.informativeText = L("连不上 GitHub,请稍后再试。")
- alert.runModal()
- }
- }
+ // The answer shows on the panel's version line, as for a check made there (no alert).
+ model.updates.checkNow()
+ model.openPanel?()
}
@objc private func openWebsite() { NSWorkspace.shared.open(AboutPanel.website) }
diff --git a/Sources/LiveSubs/AppModel.swift b/Sources/LiveSubs/AppModel.swift
index aa2739f..c19d369 100644
--- a/Sources/LiveSubs/AppModel.swift
+++ b/Sources/LiveSubs/AppModel.swift
@@ -1111,7 +1111,7 @@ final class AppModel: ObservableObject {
updates.checkNow()
case "updateCheck": updates.checkNow()
case "updateInstall": updates.install(model: self)
- case "updateState": debugLog("update current=\(Updates.current) found=\(updates.update?.version ?? "-") check=\(updates.check) progress=\(updates.progress.map { String($0) } ?? "-") failure=\(updates.failure ?? "-")")
+ case "updateState": debugLog("update current=\(Updates.current) found=\(updates.update?.version ?? "-") check=\(updates.check) last=\(updates.lastChecked.map { "\($0)" } ?? "-") progress=\(updates.progress.map { String($0) } ?? "-") failure=\(updates.failure ?? "-")")
case "loginItem":
if !arg.isEmpty { loginItem.set(arg == "on") }
loginItem.refresh()
@@ -1411,6 +1411,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate {
} else {
model.refreshOutputs()
model.refresh()
+ model.updates.panelOpened()
popover.show(relativeTo: button.bounds, of: button, preferredEdge: .minY)
popover.contentViewController?.view.window?.makeKey()
}
diff --git a/Sources/LiveSubs/UpdateChecker.swift b/Sources/LiveSubs/UpdateChecker.swift
index 313a0d9..5236297 100644
--- a/Sources/LiveSubs/UpdateChecker.swift
+++ b/Sources/LiveSubs/UpdateChecker.swift
@@ -1,7 +1,10 @@
+import AppKit
import Foundation
-/// Checks GitHub Releases once a day for a version newer than the running one.
-/// Failures (offline, rate-limited, or the repository not public: the API answers 404) are silent.
+/// Checks GitHub Releases for a version newer than the running one: at launch, every 4 hours,
+/// after the Mac wakes and when the menu bar panel opens (those two only once the last check is an
+/// hour old). Failures (offline, rate-limited, or the repository not public: the API answers 404)
+/// are silent.
@MainActor
final class UpdateChecker {
struct Update: Equatable {
@@ -17,12 +20,26 @@ final class UpdateChecker {
static let repository = URL(string: "https://github.com/wquguru/cicada")!
- /// `CICADA_UPDATE_FEED` (or the `updateFeed:` debug command) points at another release JSON;
- /// a file:// URL works, for testing.
+ /// `CICADA_UPDATE_FEED` (or the `updateFeed:` debug command) points at another release JSON,
+ /// a list or a single release; a file:// URL works, for testing.
+ /// The list, not `releases/latest`: every platform shares one version, and a release that only
+ /// ships Windows, Android or Linux has no Mac zip, so the newest Mac release may be further down.
var feed = ProcessInfo.processInfo.environment["CICADA_UPDATE_FEED"].flatMap(URL.init(string:))
- ?? URL(string: "https://api.github.com/repos/wquguru/cicada/releases/latest")!
+ ?? URL(string: "https://api.github.com/repos/wquguru/cicada/releases?per_page=20")!
private let onUpdate: (Update?) -> Void
private var timer: Timer?
+ private var wakeObserver: Any?
+ private var checking = false
+
+ /// How often a running app checks, and how old the last check must be before waking or
+ /// opening the panel checks again. GitHub allows 60 anonymous API calls an hour.
+ static let every: TimeInterval = 4 * 60 * 60
+ static let stale: TimeInterval = 60 * 60
+
+ /// The last time the feed answered, kept across launches.
+ private(set) var lastChecked = UserDefaults.standard.object(forKey: "updateLastChecked") as? Date {
+ didSet { UserDefaults.standard.set(lastChecked, forKey: "updateLastChecked") }
+ }
init(onUpdate: @escaping (Update?) -> Void) {
self.onUpdate = onUpdate
@@ -30,32 +47,72 @@ final class UpdateChecker {
func start() {
Task { await check() }
- timer = Timer.scheduledTimer(withTimeInterval: 24 * 60 * 60, repeats: true) { [weak self] _ in
- Task { await self?.check() }
+ // A short tick that checks when due, not one 4-hour timer: a timer doesn't count while
+ // the Mac sleeps, so a laptop that is often closed would hardly ever check.
+ timer = Timer.scheduledTimer(withTimeInterval: 15 * 60, repeats: true) { [weak self] _ in
+ Task { await self?.checkIfDue(after: Self.every) }
+ }
+ wakeObserver = NSWorkspace.shared.notificationCenter.addObserver(forName: NSWorkspace.didWakeNotification,
+ object: nil, queue: .main) { [weak self] _ in
+ // The network takes a moment to come back after waking.
+ Task { try? await Task.sleep(for: .seconds(15)); await self?.checkIfDue(after: Self.stale) }
}
}
+ /// Checks only when the last successful check is at least `age` old.
+ func checkIfDue(after age: TimeInterval) async {
+ guard Self.due(last: lastChecked, now: Date(), after: age) else { return }
+ await check()
+ }
+
+ nonisolated static func due(last: Date?, now: Date, after age: TimeInterval) -> Bool {
+ guard let last else { return true }
+ // A clock set back leaves `last` in the future: check rather than wait for it.
+ return now.timeIntervalSince(last) >= age || last > now
+ }
+
/// Returns false when the feed couldn't be reached or answered with something unexpected.
@discardableResult
func check() async -> Bool {
+ guard !checking else { return true }
+ checking = true
+ defer { checking = false }
var request = URLRequest(url: feed)
request.setValue("application/vnd.github+json", forHTTPHeaderField: "Accept")
guard let (data, response) = try? await URLSession.shared.data(for: request),
(response as? HTTPURLResponse)?.statusCode ?? 200 == 200,
- let release = try? JSONDecoder().decode(Release.self, from: data),
- let url = URL(string: release.html_url) else { return false }
- let latest = release.tag_name.trimmingCharacters(in: CharacterSet(charactersIn: "v"))
+ let releases = Self.decode(data) else { return false }
let current = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "0"
- let zip = release.assets.first { $0.name.hasPrefix("Cicada-") && $0.name.hasSuffix("-macOS-AppleSilicon.zip") }
- let checksums = release.assets.first { $0.name == "checksums.txt" }
- let update = Update(version: latest, url: url,
- zip: zip.flatMap { URL(string: $0.browser_download_url) },
- checksums: checksums.flatMap { URL(string: $0.browser_download_url) },
- size: zip?.size ?? 0)
- onUpdate(Self.isNewer(latest, than: current) ? update : nil)
+ let update = Self.newestMac(in: releases)
+ lastChecked = Date()
+ debugLog("update: checked, latest Mac \(update?.version ?? "none"), running \(current)")
+ onUpdate(update.flatMap { Self.isNewer($0.version, than: current) ? $0 : nil })
return true
}
+ nonisolated static func decode(_ data: Data) -> [Release]? {
+ let decoder = JSONDecoder()
+ return (try? decoder.decode([Release].self, from: data))
+ ?? (try? decoder.decode(Release.self, from: data)).map { [$0] }
+ }
+
+ /// The newest published release that ships the Mac app. A release without the Mac zip only
+ /// carries other platforms (the Mac app had no change), so it is skipped, not offered.
+ nonisolated static func newestMac(in releases: [Release]) -> Update? {
+ let shipped = releases.compactMap { release -> Update? in
+ guard release.draft != true, release.prerelease != true,
+ let url = URL(string: release.html_url),
+ let zip = release.assets.first(where: { $0.name.hasPrefix("Cicada-") && $0.name.hasSuffix("-macOS-AppleSilicon.zip") })
+ else { return nil }
+ let checksums = release.assets.first { $0.name == "checksums.txt" }
+ return Update(version: release.tag_name.trimmingCharacters(in: CharacterSet(charactersIn: "v")), url: url,
+ zip: URL(string: zip.browser_download_url),
+ checksums: checksums.flatMap { URL(string: $0.browser_download_url) },
+ size: zip.size ?? 0)
+ }
+ return shipped.max { isNewer($1.version, than: $0.version) }
+ }
+
/// Compares dotted numeric versions: "2.10.0" is newer than "2.9.1".
nonisolated static func isNewer(_ a: String, than b: String) -> Bool {
let x = a.split(separator: ".").map { Int($0) ?? 0 }
@@ -67,13 +124,15 @@ final class UpdateChecker {
return false
}
- private struct Release: Decodable {
+ struct Release: Decodable {
let tag_name: String
let html_url: String
let assets: [Asset]
+ var draft: Bool? = nil
+ var prerelease: Bool? = nil
}
- private struct Asset: Decodable {
+ struct Asset: Decodable {
let name: String
let browser_download_url: String
let size: Int?
diff --git a/Sources/LiveSubs/UpdateViews.swift b/Sources/LiveSubs/UpdateViews.swift
index c97e6de..4e94f86 100644
--- a/Sources/LiveSubs/UpdateViews.swift
+++ b/Sources/LiveSubs/UpdateViews.swift
@@ -82,7 +82,9 @@ struct AppRows: View {
case .checking: return L("正在检查…")
case .upToDate: return L("已是最新版本")
case .failed: return L("连不上 GitHub,请稍后再试")
- case .idle: return nil
+ case .idle:
+ guard let d = updates.lastChecked else { return nil }
+ return L("上次检查 \(dateText(d, Calendar.current.isDateInToday(d) ? "HHmm" : "MMMdHHmm"))")
}
}
}
diff --git a/Sources/LiveSubs/Updater.swift b/Sources/LiveSubs/Updater.swift
index bfa23f9..82ebfb2 100644
--- a/Sources/LiveSubs/Updater.swift
+++ b/Sources/LiveSubs/Updater.swift
@@ -45,6 +45,10 @@ enum Updater {
info?["CFBundleShortVersionString"] as? String == update.version else {
throw Failure(L("下载的不是预期的版本"))
}
+ // A later version may need a newer macOS than this Mac has: swapped in, it wouldn't open.
+ if let minimum = info?["LSMinimumSystemVersion"] as? String, !Self.runs(minimum) {
+ throw Failure(L("新版本需要 macOS \(minimum) 或更新版本"))
+ }
try await run("/usr/bin/codesign", "--verify", "--deep", "--strict", newApp.path)
let script = work.appendingPathComponent("swap.sh")
@@ -71,6 +75,13 @@ enum Updater {
rm -rf "$4"
"""
+ /// Whether this Mac's macOS is at least `minimum` ("14.4").
+ nonisolated static func runs(_ minimum: String,
+ on os: OperatingSystemVersion = ProcessInfo.processInfo.operatingSystemVersion) -> Bool {
+ let p = minimum.split(separator: ".").map { Int($0) ?? 0 } + [0, 0, 0]
+ return (os.majorVersion, os.minorVersion, os.patchVersion) >= (p[0], p[1], p[2])
+ }
+
/// The hash listed for `name` in a `shasum -a 256` file.
nonisolated static func expectedHash(of name: String, in checksums: Data) -> String? {
String(decoding: checksums, as: UTF8.self)
diff --git a/Sources/LiveSubs/Updates.swift b/Sources/LiveSubs/Updates.swift
index 901f85b..16dc295 100644
--- a/Sources/LiveSubs/Updates.swift
+++ b/Sources/LiveSubs/Updates.swift
@@ -8,6 +8,8 @@ final class Updates: ObservableObject {
@Published private(set) var update: UpdateChecker.Update?
@Published private(set) var check = Check.idle
+ /// When the feed last answered (nil: never), for the panel's version line.
+ @Published private(set) var lastChecked: Date?
/// Download progress (0...1) while an update installs; the app quits and reopens when done.
@Published private(set) var progress: Double?
/// Why the last in-place update failed (the release page was opened instead).
@@ -16,17 +18,38 @@ final class Updates: ObservableObject {
/// or the swap script would wait for a quit that the user cancelled.
private(set) var installing = false
- private(set) lazy var checker = UpdateChecker { [weak self] in self?.update = $0 }
+ private(set) lazy var checker: UpdateChecker = UpdateChecker { [weak self] in
+ self?.update = $0
+ self?.lastChecked = self?.checker.lastChecked
+ }
+ private var started = false
static let current = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? ""
- /// Daily checks. A dev build has its own bundle id, so a release can't replace it: it checks
- /// only when pointed at a test feed.
+ /// Regular checks (see `UpdateChecker`). A dev build has its own bundle id, so a release can't
+ /// replace it: it checks only when pointed at a test feed.
func start() {
+ lastChecked = checker.lastChecked
guard !DevBuild.isDev || ProcessInfo.processInfo.environment["CICADA_UPDATE_FEED"] != nil else { return }
+ started = true
checker.start()
}
+ /// The menu bar panel opened: check in the background if the last check is an hour old.
+ func panelOpened() {
+ guard started, check != .checking else { return }
+ Task { await checker.checkIfDue(after: UpdateChecker.stale) }
+ }
+
+ /// "刚刚查过", "2 小时前查过": how long ago the feed last answered.
+ static func checkedAgo(_ date: Date, now: Date = Date()) -> String {
+ let s = max(0, now.timeIntervalSince(date))
+ if s < 60 { return L("刚刚查过") }
+ if s < 3600 { return L("\(Int(s / 60)) 分钟前查过") }
+ if s < 86_400 { return L("\(Int(s / 3600)) 小时前查过") }
+ return L("\(Int(s / 86_400)) 天前查过")
+ }
+
func checkNow() {
guard check != .checking else { return }
check = .checking
diff --git a/Tests/LiveSubsTests/UpdateTests.swift b/Tests/LiveSubsTests/UpdateTests.swift
index a5d4596..2812bab 100644
--- a/Tests/LiveSubsTests/UpdateTests.swift
+++ b/Tests/LiveSubsTests/UpdateTests.swift
@@ -21,3 +21,70 @@ import Testing
#expect(Updater.expectedHash(of: "Cicada-2.0.0-macOS-AppleSilicon.zip", in: file) == nil)
}
}
+
+@Suite struct UpdateReleaseTests {
+ static func release(_ tag: String, _ assets: [String], prerelease: Bool = false) -> String {
+ let list = assets.map { #"{"name":"\#($0)","browser_download_url":"https://x/\#($0)","size":1}"# }
+ return #"{"tag_name":"\#(tag)","html_url":"https://x/\#(tag)","prerelease":\#(prerelease),"assets":[\#(list.joined(separator: ","))]}"#
+ }
+
+ static func newest(_ releases: [String]) -> String? {
+ UpdateChecker.decode(Data("[\(releases.joined(separator: ","))]".utf8))
+ .flatMap(UpdateChecker.newestMac)?.version
+ }
+
+ @Test func aReleaseWithoutTheMacZipIsSkipped() {
+ let mac = Self.release("v1.1.0", ["Cicada-1.1.0-macOS-AppleSilicon.zip", "checksums.txt"])
+ let windows = Self.release("v1.2.0", ["Cicada-1.2.0-Windows-x64.zip", "checksums.txt"])
+ #expect(Self.newest([windows, mac]) == "1.1.0")
+ #expect(Self.newest([windows]) == nil)
+ }
+
+ @Test func prereleasesAreSkippedAndNewestWins() {
+ let old = Self.release("v1.0.0", ["Cicada-1.0.0-macOS-AppleSilicon.zip"])
+ let new = Self.release("v1.10.0", ["Cicada-1.10.0-macOS-AppleSilicon.zip"])
+ let beta = Self.release("v2.0.0", ["Cicada-2.0.0-macOS-AppleSilicon.zip"], prerelease: true)
+ #expect(Self.newest([beta, old, new]) == "1.10.0")
+ }
+
+ @Test func aSingleReleaseFeedStillWorks() {
+ let one = Self.release("v1.3.0", ["Cicada-1.3.0-macOS-AppleSilicon.zip"])
+ #expect(UpdateChecker.decode(Data(one.utf8)).flatMap(UpdateChecker.newestMac)?.version == "1.3.0")
+ }
+}
+
+@Suite struct UpdateScheduleTests {
+ private let now = Date(timeIntervalSince1970: 1_000_000)
+
+ @Test func dueWhenNeverCheckedOrOldEnough() {
+ #expect(UpdateChecker.due(last: nil, now: now, after: UpdateChecker.every))
+ #expect(UpdateChecker.due(last: now.addingTimeInterval(-4 * 3600), now: now, after: UpdateChecker.every))
+ #expect(!UpdateChecker.due(last: now.addingTimeInterval(-3 * 3600), now: now, after: UpdateChecker.every))
+ // Waking or opening the panel checks once the last check is an hour old.
+ #expect(UpdateChecker.due(last: now.addingTimeInterval(-3601), now: now, after: UpdateChecker.stale))
+ #expect(!UpdateChecker.due(last: now.addingTimeInterval(-600), now: now, after: UpdateChecker.stale))
+ }
+
+ /// A clock set back must not stop checks until it catches up.
+ @Test func dueWhenLastCheckIsInTheFuture() {
+ #expect(UpdateChecker.due(last: now.addingTimeInterval(86_400), now: now, after: UpdateChecker.every))
+ }
+
+ @MainActor @Test func checkedAgoWording() {
+ #expect(Updates.checkedAgo(now.addingTimeInterval(-20), now: now) == L("刚刚查过"))
+ #expect(Updates.checkedAgo(now.addingTimeInterval(-5 * 60), now: now) == L("5 分钟前查过"))
+ #expect(Updates.checkedAgo(now.addingTimeInterval(-2 * 3600 - 59), now: now) == L("2 小时前查过"))
+ #expect(Updates.checkedAgo(now.addingTimeInterval(-3 * 86_400), now: now) == L("3 天前查过"))
+ }
+}
+
+@Suite struct UpdateMinimumSystemTests {
+ @Test func comparesMinimumMacOS() {
+ let os = OperatingSystemVersion(majorVersion: 14, minorVersion: 5, patchVersion: 0)
+ #expect(Updater.runs("14.4", on: os))
+ #expect(Updater.runs("14.5", on: os))
+ #expect(!Updater.runs("15.0", on: os))
+ #expect(!Updater.runs("26.0", on: os))
+ #expect(Updater.runs("14", on: os))
+ }
+}