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(linux): tell you when a new version is out and update in place with one click

wquguruc8fd22613741
diff --git a/linux/README.md b/linux/README.md
index a84fac9..84f0333 100644
--- a/linux/README.md
+++ b/linux/README.md
@@ -44,6 +44,8 @@ tar xzf Cicada-<版本>-Linux.tar.gz && cicada-linux/install.sh
装到 `~/.local`,不用 sudo,之后从应用列表打开“知了”。缺 `python3-gi`、`gir1.2-gtk-3.0`、`libpulse0` 时会提示用 apt 装(Ubuntu 桌面版默认都有)。
+有新版本时顶栏菜单第一项和设置 › 关于会提示,点一下就下载、核对 SHA-256、装好并重新打开;正在听时等会议结束再装。测试用 `CICADA_UPDATE_FEED=<releases.json 的地址>` 换一个更新源(开发版只在设了它时才检查)。
+
## 在虚拟机里验证
```bash
diff --git a/linux/cicada/app/main.py b/linux/cicada/app/main.py
index 7474ddc..3991dc1 100644
--- a/linux/cicada/app/main.py
+++ b/linux/cicada/app/main.py
@@ -111,6 +111,8 @@ class Controller:
self.fake_calls = None # debug: meeting apps pretending to be in a call
self.end_times = None # debug: (silence, countdown, grace) in seconds
self._calls_busy = False
+ from .updater import Updates
+ self.updates = Updates(self) # 新版本: GitHub Releases, the tray menu and 设置 › 关于
GLib.timeout_add_seconds(1, self._tick)
GLib.timeout_add_seconds(2, self._watch_end)
@@ -152,6 +154,11 @@ class Controller:
# Without a tray (plain GNOME has none) the records window is how the app is reached.
if self.tray is None:
self.show_records()
+ reopened = self.updates.reopened()
+ if reopened and self.settings.onboarded:
+ self.show_records() # where 已更新到 … is said, once
+ self.records_window.toasts.show(reopened)
+ self.updates.start()
def changed(self) -> None:
"""Engine threads call this: one coalesced refresh on the main loop."""
@@ -169,6 +176,8 @@ class Controller:
self.onboarding.refresh()
if self.tray is not None:
self.tray.update()
+ if self.settings_window is not None:
+ self.settings_window.refresh_version()
return False
GLib.idle_add(run)
@@ -460,6 +469,7 @@ class Controller:
if sid and self.settings.speakerVoices:
self.namer.guess(sid, force=True) # the whole meeting read once more for names
self.changed()
+ GLib.idle_add(lambda: self.updates.meeting_ended() and False) # 会后安装
threading.Thread(target=run, daemon=True).start()
# 说话人识别
diff --git a/linux/cicada/app/settings_window.py b/linux/cicada/app/settings_window.py
index 6698893..47a48b2 100644
--- a/linux/cicada/app/settings_window.py
+++ b/linux/cicada/app/settings_window.py
@@ -233,7 +233,10 @@ class SettingsWindow(Gtk.Window):
ui.prow(L("语音识别"), ui.text(L("Ming(云端)"), 12, "tertiary", wrap=False))])), False, False, 0)
# About
- rows = [ui.prow(L("版本"), ui.text(VERSION + " · Linux", 12, "tertiary", wrap=False))]
+ # 版本 with the update check under it and its button (UpdateViews' settings row).
+ self.version_slot = ui.hbox(0)
+ self.version_row = ui.prow(LF("版本 %@", VERSION + " · Linux"), self.version_slot, " ")
+ rows = [self.version_row]
for label, action in ((L("打开记录文件夹"), lambda: self._open_folder(Paths.sessions())),
(L("打开日志"), lambda: open_uri("file://" + Paths.log())),
(L("重看新手引导"), app.show_onboarding)):
@@ -252,6 +255,34 @@ class SettingsWindow(Gtk.Window):
ui.no_wheel(c, scroll)
app.ling.on_change(lambda: GLib.idle_add(self.show_key_state))
self.connect("show", lambda *_: self.show_key_state())
+ self.refresh_version()
+
+ def refresh_version(self) -> None:
+ """The update line and button: 检查更新, 安装并重新打开 / 重试, nothing while downloading."""
+ u = self.app.updates
+ detail = u.detail()
+ sub = next((w for w in _labels(self.version_row) if w.get_style_context().has_class("secondary")
+ or w.get_style_context().has_class("tertiary")), None)
+ if sub is not None:
+ ui.retext(sub, detail or " ")
+ ui.classes(sub, "err") if u.failure and u.update else sub.get_style_context().remove_class("err")
+ key = (u.update is not None, u.progress is not None, bool(u.failure), u.check == "checking", u.after_meeting)
+ if key == getattr(self, "_version_key", None):
+ return
+ self._version_key = key
+ ui.clear(self.version_slot)
+ if u.update is not None and u.progress is None:
+ if u.after_meeting:
+ return
+ b = ui.button(L("重试") if u.failure else L("安装并重新打开"), u.install, "outline" if u.failure else "darkbtn")
+ elif u.update is None:
+ b = ui.button(L("检查更新"), u.check_now, "outline")
+ b.set_sensitive(u.check != "checking")
+ else:
+ return
+ b.set_valign(Gtk.Align.CENTER)
+ self.version_slot.pack_start(b, False, False, 0)
+ self.version_slot.show_all()
def _end_group(self) -> Gtk.Widget:
"""结束会议: when a meeting ends by itself (meeting_end.py), as the Mac's settings say it."""
@@ -482,3 +513,11 @@ class SettingsWindow(Gtk.Window):
def _open_folder(path) -> None:
os.makedirs(path, exist_ok=True)
open_uri("file://" + path)
+
+
+def _labels(w) -> list:
+ out = [w] if isinstance(w, Gtk.Label) else []
+ if hasattr(w, "get_children"):
+ for c in w.get_children():
+ out += _labels(c)
+ return out
diff --git a/linux/cicada/app/tray.py b/linux/cicada/app/tray.py
index d2e9153..ed05ab6 100644
--- a/linux/cicada/app/tray.py
+++ b/linux/cicada/app/tray.py
@@ -68,6 +68,12 @@ class Tray:
i.set_sensitive(sensitive)
menu.append(i)
return i
+ # A new version first, with the accent dot the Mac's panel gives it; greyed while it downloads.
+ upd = self.app.updates.menu_label()
+ if upd:
+ item("● " + upd, self.app.updates.install, sensitive=self.app.updates.progress is None
+ and not self.app.updates.after_meeting)
+ menu.append(Gtk.SeparatorMenuItem())
# A status header, as the design's tray menu: what's happening, then the actions.
self.status_item = item(self._status(), None, False)
if listening:
@@ -84,6 +90,7 @@ class Tray:
menu.append(Gtk.SeparatorMenuItem())
item(L("退出知了"), self.app.quit)
menu.show_all()
+ menu.connect("show", lambda *_: self.app.updates.menu_opened()) # an hour-old check: check again
self.lib.app_indicator_set_menu(self.ind, _gpointer(menu))
self.menu = menu # the indicator holds a ref too; keep ours so Python doesn't free it early
self.lib.app_indicator_set_label(self.ind, (self._clock() if listening else "").encode(), b"")
diff --git a/linux/cicada/app/updater.py b/linux/cicada/app/updater.py
new file mode 100644
index 0000000..b3c3b65
--- /dev/null
+++ b/linux/cicada/app/updater.py
@@ -0,0 +1,194 @@
+"""What the tray menu and 设置 › 关于 show about new versions (the Mac's Updates): a newer release, a
+manual check's result, download progress, and why installing in place failed. Checks at launch and
+every 4 hours (a 15-minute tick that checks when due, so a laptop that sleeps still checks); a dev
+build checks only when CICADA_UPDATE_FEED points at a test feed. While a meeting is being recorded
+the update waits for it to end (会后安装) instead of ending it."""
+from __future__ import annotations
+
+import os
+import threading
+import time
+
+from gi.repository import Gio, GLib
+
+from .. import VERSION
+from ..core import updates
+from ..core.strings import L, LF
+from ..core.support import Log, Paths
+
+
+class Updates:
+ def __init__(self, app):
+ self.app = app
+ self.update: updates.Update | None = None
+ self.check = "idle" # idle | checking | upToDate | failed (the last manual check)
+ self.progress: float | None = None # 0…1 while downloading; the app quits and reopens when done
+ self.failure: str | None = None # why the last in-place update failed
+ self.after_meeting = False # 会后安装: install once this meeting ends
+ self.installing = False
+ self.started = False
+ self._inflight = False # one check at a time (the tray menu's "show" also fires as it's built)
+ # When the last check started, failed or not: a failed one isn't remembered on disk, and the
+ # menu is rebuilt (firing "show") whenever a check ends, so offline it would check again at once.
+ self._last_try: float | None = None
+
+ @property
+ def last_checked(self) -> float | None:
+ return updates.last_checked()
+
+ def start(self) -> None:
+ if Paths.dev and not os.environ.get("CICADA_UPDATE_FEED"):
+ return
+ self.started = True
+ self._run_check(manual=False)
+ GLib.timeout_add_seconds(15 * 60, self._tick)
+
+ def _tick(self) -> bool:
+ if updates.due(self.last_checked, time.time(), updates.EVERY):
+ self._run_check(manual=False)
+ return True
+
+ def menu_opened(self) -> None:
+ last = max((t for t in (self.last_checked, self._last_try) if t is not None), default=None)
+ if self.started and updates.due(last, time.time(), updates.STALE):
+ self._run_check(manual=False)
+
+ def check_now(self) -> None:
+ self._run_check(manual=True)
+
+ def _run_check(self, manual: bool) -> None:
+ if self._inflight:
+ return
+ self._inflight = True
+ self._last_try = time.time()
+ if manual:
+ self.check = "checking"
+ self.app.changed()
+
+ def run():
+ ok, u = updates.check(VERSION)
+
+ def done():
+ self._inflight = False
+ if ok:
+ if u != self.update:
+ self.failure = None
+ self.update = u
+ if manual:
+ self.check = ("upToDate" if u is None else "idle") if ok else "failed"
+ self.app.changed()
+ return False
+ GLib.idle_add(done)
+ threading.Thread(target=run, name="Updates", daemon=True).start()
+
+ # Installing
+
+ def install(self) -> None:
+ """安装并重新打开; while listening, 会后安装 (the meeting isn't cut short)."""
+ u = self.update
+ if u is None or self.installing:
+ return
+ if self.app.listen.listening:
+ self.after_meeting = True
+ Log.d("update: %s after the meeting" % u.version)
+ self.app.changed()
+ return
+ if updates.install_root() is None:
+ # A checkout or a build tree, not an install.sh install: nothing to replace in place.
+ self._fail(L("请先用 install.sh 安装知了"), u)
+ return
+ self.installing, self.failure, self.progress = True, None, 0.0
+ self.app.changed()
+
+ def progress(p):
+ # Whole percents only: every 64 KB would rebuild the tray menu hundreds of times.
+ if self.progress is not None and int(p * 100) == int(self.progress * 100):
+ return
+
+ def show():
+ self.progress = p
+ self.app.changed()
+ return False
+ GLib.idle_add(show)
+
+ def run():
+ try:
+ tree = updates.prepare(u, progress)
+ except updates.Failure as e:
+ why = LF(e.key, *e.args)
+ GLib.idle_add(lambda: self._fail(why, u) and False)
+ return
+ except Exception as e: # noqa: BLE001
+ Log.d("update: failed %s" % type(e).__name__)
+ GLib.idle_add(lambda: self._fail(L("更新包无效"), u) and False)
+ return
+ GLib.idle_add(lambda: self._hand_over(tree, u) and False)
+ threading.Thread(target=run, name="Update", daemon=True).start()
+
+ def _hand_over(self, tree: str, u) -> None:
+ updates.hand_over(tree, u.version, ["--dev"] if Paths.dev else [])
+ self.app.quit()
+
+ def _fail(self, why: str, u) -> None:
+ self.installing, self.progress, self.failure = False, None, why
+ Log.d("update: in place failed, opening the release page")
+ self.app.changed()
+ try:
+ Gio.AppInfo.launch_default_for_uri(u.url, None)
+ except GLib.Error:
+ pass
+
+ def meeting_ended(self) -> None:
+ if self.after_meeting and not self.app.listen.listening:
+ self.after_meeting = False
+ self.install()
+
+ def reopened(self) -> str | None:
+ """After an update reopened the app: the line to show once (已更新到 …), or None."""
+ r = updates.take_result()
+ if r is None:
+ return None
+ if r[0] == "ok" and r[1] == VERSION:
+ Log.d("update: now %s" % VERSION)
+ return LF("已更新到 %@", VERSION)
+ Log.d("update: install of %s didn't finish" % r[1])
+ self.failure = L("安装没有完成")
+ return LF("没能更新到 %@,还是原来的版本", r[1])
+
+ # What the UI shows
+
+ def menu_label(self) -> str | None:
+ """The tray menu's first item, or None (no update)."""
+ u = self.update
+ if u is None:
+ return None
+ if self.progress is not None:
+ return LF("正在下载 %@:%lld%%", u.version, int(self.progress * 100))
+ if self.after_meeting or self.app.listen.listening:
+ return LF("新版本 %@", u.version) + " · " + L("会后安装")
+ return LF("新版本 %@", u.version) + " · " + L("安装并重新打开")
+
+ def detail(self) -> str:
+ """The grey line under 版本 in 设置 › 关于."""
+ u = self.update
+ if u is not None:
+ if self.progress is not None:
+ return LF("正在下载 %@:%lld%%", u.version, int(self.progress * 100))
+ if self.failure:
+ return LF("没能自动更新:%@。已打开下载页", self.failure)
+ if self.after_meeting:
+ return LF("有新版本 %@", u.version) + " · " + L("会议结束后安装")
+ size = ("%.1f MB · " % (u.size / 1e6)) if u.size else ""
+ return LF("有新版本 %@", u.version) + " · " + size + L("安装后自动重新打开")
+ if self.check == "checking":
+ return L("正在检查…")
+ if self.check == "upToDate":
+ return L("已是最新版本")
+ if self.check == "failed":
+ return L("连不上 GitHub,请稍后再试")
+ last = self.last_checked
+ if last:
+ t = time.localtime(last)
+ same_day = time.strftime("%Y%m%d", t) == time.strftime("%Y%m%d")
+ return LF("上次检查 %@", time.strftime("%H:%M" if same_day else "%m-%d %H:%M", t))
+ return ""
diff --git a/linux/cicada/core/strings.py b/linux/cicada/core/strings.py
index 539b431..b5baab4 100644
--- a/linux/cicada/core/strings.py
+++ b/linux/cicada/core/strings.py
@@ -39,6 +39,10 @@ def LF(key: str, *args) -> str:
i = 0
while i < len(text):
# %@, and the Mac's numbers (%lld, %d) the same way: the Mac keys 说话人 N as "说话人 %lld".
+ if text.startswith("%%", i): # a literal %, as in the Mac's "%lld%%"
+ out.append("%")
+ i += 2
+ continue
m = next((t for t in ("%@", "%lld", "%d") if text.startswith(t, i)), None)
if m:
out.append(str(args[nxt]) if nxt < len(args) else "")
diff --git a/linux/cicada/core/updates.py b/linux/cicada/core/updates.py
new file mode 100644
index 0000000..8acc91d
--- /dev/null
+++ b/linux/cicada/core/updates.py
@@ -0,0 +1,283 @@
+"""New versions (the Mac's UpdateChecker and Updater): GitHub Releases is read at launch and when a
+check is due, the newest release that ships the Linux tarball is offered, and installing it
+downloads the tarball, checks it against the release's checksums.txt, unpacks it and hands it to a
+small script that runs its install.sh once the app has quit, then opens Cicada again.
+
+UI-free and stdlib only: the app shows the state, this module finds, fetches and checks."""
+from __future__ import annotations
+
+import hashlib
+import json
+import os
+import shlex
+import shutil
+import subprocess
+import tarfile
+import tempfile
+import time
+import urllib.request
+
+from . import jsonfmt
+from .support import Log, Paths
+
+# The list, not releases/latest: every platform shares one version, and a release that only ships
+# the Mac or Windows has no Linux tarball, so the newest Linux release may be further down.
+FEED = "https://api.github.com/repos/wquguru/cicada/releases?per_page=20"
+# How often a running app checks, and how old a check must be before a manual-ish one (the tray
+# menu, waking) checks again. GitHub allows 60 anonymous API calls an hour.
+EVERY = 4 * 60 * 60
+STALE = 60 * 60
+USER_AGENT = "Cicada-Linux"
+
+
+class Update:
+ def __init__(self, version: str, url: str, tarball: str | None, checksums: str | None, size: int, name: str):
+ self.version, self.url, self.tarball, self.checksums, self.size, self.name = version, url, tarball, checksums, size, name
+
+ def __eq__(self, other) -> bool:
+ return isinstance(other, Update) and vars(self) == vars(other)
+
+ def __repr__(self) -> str:
+ return "Update(%s)" % self.version
+
+
+class Failure(Exception):
+ """Why installing in place didn't work, said to the user (the release page opens instead): a
+ Mac string key and its values, translated by the app."""
+
+ def __init__(self, key: str, *args):
+ super().__init__(key)
+ self.key, self.args = key, args
+
+
+def feed() -> str:
+ """CICADA_UPDATE_FEED points at another release JSON (a list or one release); file:// works."""
+ return os.environ.get("CICADA_UPDATE_FEED") or FEED
+
+
+def is_newer(a: str, than: str) -> bool:
+ """Dotted numeric versions: "2.10.0" is newer than "2.9.1"."""
+ def parts(v):
+ out = []
+ for p in v.strip().lstrip("v").split("."):
+ try:
+ out.append(int(p))
+ except ValueError:
+ out.append(0)
+ return out
+ x, y = parts(a), parts(than)
+ for i in range(max(len(x), len(y))):
+ l, r = (x[i] if i < len(x) else 0), (y[i] if i < len(y) else 0)
+ if l != r:
+ return l > r
+ return False
+
+
+def due(last: float | None, now: float, after: float) -> bool:
+ if last is None:
+ return True
+ # A clock set back leaves `last` in the future: check rather than wait for it.
+ return now - last >= after or last > now
+
+
+def decode(data: bytes) -> list | None:
+ try:
+ v = json.loads(data)
+ except ValueError:
+ return None
+ if isinstance(v, dict):
+ v = [v]
+ return v if isinstance(v, list) else None
+
+
+def newest_linux(releases: list) -> Update | None:
+ """The newest published release with the Linux tarball. One without it carries only other
+ platforms (Linux had no change), so it is skipped, not offered."""
+ best = None
+ for r in releases:
+ if not isinstance(r, dict) or r.get("draft") or r.get("prerelease"):
+ continue
+ assets = [a for a in r.get("assets") or [] if isinstance(a, dict)]
+ tar = next((a for a in assets if str(a.get("name", "")).startswith("Cicada-")
+ and str(a.get("name", "")).endswith("-Linux.tar.gz")), None)
+ if tar is None or not r.get("tag_name") or not r.get("html_url"):
+ continue
+ sums = next((a for a in assets if a.get("name") == "checksums.txt"), None)
+ u = Update(str(r["tag_name"]).strip().lstrip("v"), r["html_url"], tar.get("browser_download_url"),
+ sums.get("browser_download_url") if sums else None, int(tar.get("size") or 0), tar["name"])
+ if best is None or is_newer(u.version, best.version):
+ best = u
+ return best
+
+
+def checksum_for(text: str, name: str) -> str | None:
+ """The SHA-256 of `name` in a sha256sum listing ("<hex> <name>", or "<hex> *<name>")."""
+ for line in text.splitlines():
+ parts = line.strip().split(None, 1)
+ if len(parts) == 2 and parts[1].lstrip("*") == name:
+ return parts[0].lower()
+ return None
+
+
+# Where the last successful check is remembered (the Mac keeps it in UserDefaults).
+
+def _state_file() -> str:
+ return os.path.join(Paths.data(), "updates.json")
+
+
+def last_checked() -> float | None:
+ try:
+ with open(_state_file(), encoding="utf-8") as f:
+ v = json.load(f).get("lastChecked")
+ return float(v) if v is not None else None
+ except (OSError, ValueError, AttributeError):
+ return None
+
+
+def _remember(when: float) -> None:
+ os.makedirs(Paths.data(), exist_ok=True)
+ with open(_state_file(), "w", encoding="utf-8") as f:
+ f.write(jsonfmt.write({"lastChecked": when}))
+
+
+def _get(url: str, timeout: float = 20):
+ req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT, "Accept": "application/vnd.github+json"})
+ return urllib.request.urlopen(req, timeout=timeout) # noqa: S310 - our feed, or file:// in tests
+
+
+def check(current: str) -> tuple:
+ """(ok, update): ok is False when the feed couldn't be reached or answered oddly; update is a
+ release newer than `current`, or None. Blocking: run it off the main thread."""
+ try:
+ with _get(feed()) as r:
+ if getattr(r, "status", 200) not in (200, None):
+ return False, None
+ releases = decode(r.read())
+ except Exception as e: # noqa: BLE001 - offline, rate-limited, private repo (404): all silent
+ Log.d("update: check failed (%s)" % type(e).__name__)
+ return False, None
+ if releases is None:
+ return False, None
+ u = newest_linux(releases)
+ _remember(time.time())
+ Log.d("update: checked, latest Linux %s, running %s" % (u.version if u else "none", current))
+ return True, (u if u and is_newer(u.version, current) else None)
+
+
+# Installing
+
+def install_root() -> str | None:
+ """The install this app runs from, when it's one install.sh made (~/.local/lib/cicada): only
+ that can be replaced in place. A checkout or a build tree gets the release page instead."""
+ here = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+ lib = os.path.realpath(os.path.expanduser("~/.local/lib/cicada"))
+ return here if os.path.realpath(here) == lib and os.path.isfile(os.path.join(here, "VERSION")) else None
+
+
+def _download(url: str, to: str, progress, expected: int = 0) -> None:
+ with _get(url, timeout=60) as r, open(to, "wb") as f:
+ total = int(r.headers.get("Content-Length") or expected or 0)
+ got = 0
+ while True:
+ chunk = r.read(64 * 1024)
+ if not chunk:
+ break
+ f.write(chunk)
+ got += len(chunk)
+ if total and progress:
+ progress(min(1.0, got / total))
+
+
+def _safe_extract(tar_path: str, into: str) -> None:
+ """Unpacks only regular files and folders that stay inside `into`: a tarball that names
+ absolute paths, "..", links or devices is refused rather than trusted."""
+ root = os.path.realpath(into)
+ with tarfile.open(tar_path, "r:gz") as t:
+ for m in t.getmembers():
+ target = os.path.realpath(os.path.join(root, m.name))
+ if not (m.isfile() or m.isdir()) or os.path.isabs(m.name) or not target.startswith(root + os.sep):
+ raise Failure("更新包无效")
+ t.extractall(root) # noqa: S202 - every member checked above
+
+
+def prepare(u: Update, progress=None) -> str:
+ """Downloads and checks the release; returns the unpacked tree (…/cicada-linux) ready for its
+ install.sh. Raises Failure with a reason to show. Blocking: run it off the main thread."""
+ if not u.tarball or not u.checksums:
+ raise Failure("这个版本没有可安装的文件")
+ work = tempfile.mkdtemp(prefix="cicada-update-")
+ try:
+ tar_path = os.path.join(work, u.name)
+ try:
+ with _get(u.checksums) as r:
+ want = checksum_for(r.read().decode("utf-8", "replace"), u.name)
+ _download(u.tarball, tar_path, progress, u.size)
+ except Failure:
+ raise
+ except Exception as e: # noqa: BLE001
+ code = getattr(e, "code", None)
+ raise (Failure("下载失败(HTTP %lld)", code) if code else Failure("下载失败")) from e
+ h = hashlib.sha256()
+ with open(tar_path, "rb") as f:
+ for chunk in iter(lambda: f.read(1 << 20), b""):
+ h.update(chunk)
+ if want is None or h.hexdigest() != want:
+ raise Failure("下载的文件校验不通过")
+ _safe_extract(tar_path, work)
+ tree = os.path.join(work, "cicada-linux")
+ try:
+ with open(os.path.join(tree, "VERSION"), encoding="utf-8") as f:
+ got = f.read().strip()
+ except OSError:
+ raise Failure("更新包无效") from None
+ if got != u.version:
+ raise Failure("下载的不是预期的版本")
+ # The new version's own dependency check, before anything is replaced or the app quits.
+ r = subprocess.run(["sh", os.path.join(tree, "install.sh"), "--check"], capture_output=True, text=True)
+ if r.returncode != 0:
+ # install.sh says which packages are missing (and the apt line); shown as it is.
+ raise Failure("%@", (r.stdout or r.stderr).strip() or "The update package is invalid")
+ return tree
+ except BaseException:
+ shutil.rmtree(work, ignore_errors=True)
+ raise
+
+
+def marker_file() -> str:
+ """Left by the swap script for the reopened app: "ok <version>" or "failed <version>"."""
+ return os.path.join(Paths.data(), "update-result")
+
+
+def take_result() -> tuple | None:
+ """("ok"|"failed", version) once after an update reopened the app, then forgotten."""
+ p = marker_file()
+ try:
+ with open(p, encoding="utf-8") as f:
+ parts = f.read().split()
+ os.unlink(p)
+ except OSError:
+ return None
+ return (parts[0], parts[1]) if len(parts) == 2 and parts[0] in ("ok", "failed") else None
+
+
+def hand_over(tree: str, version: str, argv: list) -> None:
+ """Starts the script that waits for this process to quit, runs the new install.sh and opens
+ Cicada again with the same arguments; the caller quits next. If install.sh fails the old
+ install is untouched (it only replaces after its checks), so that one reopens."""
+ pid = os.getpid()
+ os.makedirs(Paths.data(), exist_ok=True)
+ marker = marker_file()
+ launcher = os.path.expanduser("~/.local/lib/cicada/bin/cicada")
+ log = os.path.join(tempfile.gettempdir(), "cicada-update.log")
+ script = (
+ "while kill -0 %d 2>/dev/null; do sleep 0.2; done\n"
+ "if sh %s >%s 2>&1; then echo 'ok %s' > %s; else echo 'failed %s' > %s; fi\n"
+ "rm -rf %s\n"
+ "exec %s %s\n"
+ ) % (pid, shlex.quote(os.path.join(tree, "install.sh")), shlex.quote(log), version, shlex.quote(marker),
+ version, shlex.quote(marker), shlex.quote(os.path.dirname(tree)), shlex.quote(launcher),
+ " ".join(shlex.quote(a) for a in argv))
+ subprocess.Popen(["sh", "-c", script], start_new_session=True, stdin=subprocess.DEVNULL,
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, close_fds=True,
+ env={k: v for k, v in os.environ.items() if k != "PYTHONPATH"})
+ Log.d("update: handing over to install %s (pid %d)" % (version, pid))
diff --git a/linux/packaging/install.sh b/linux/packaging/install.sh
index 2d8a350..27713ed 100755
--- a/linux/packaging/install.sh
+++ b/linux/packaging/install.sh
@@ -1,6 +1,6 @@
#!/bin/sh
# Installs Cicada for this user, no sudo: the app in ~/.local/lib/cicada, `cicada` in
-# ~/.local/bin, the menu entry and icon in ~/.local/share. Run it again to update; --remove undoes it
+# ~/.local/bin, the menu entry and icon in ~/.local/share. Run it again to update; --remove undoes it; --check only checks the libraries
# (records and the Ling key stay in ~/.local/share/cicada and ~/.config/cicada).
set -e
src="$(cd "$(dirname "$0")" && pwd)"
@@ -24,6 +24,8 @@ missing=""
python3 -c 'import gi; gi.require_version("Gtk", "3.0"); from gi.repository import Gtk' 2>/dev/null || missing="$missing python3-gi gir1.2-gtk-3.0"
python3 -c 'import ctypes.util, sys; sys.exit(0 if ctypes.util.find_library("pulse-simple") else 1)' || missing="$missing libpulse0"
if [ -n "$missing" ]; then echo "Cicada needs:$missing (sudo apt install$missing)"; exit 1; fi
+# --check: only the checks above (an update runs the new version's before anything is replaced).
+[ "$1" = "--check" ] && exit 0
rm -rf "$lib" && mkdir -p "$lib" "$bin" "$share/applications" "$share/icons/hicolor/scalable/apps"
cp -R "$src/cicada" "$src/lproj" "$src/bin" "$lib/"
[ -f "$src/sample.wav" ] && cp "$src/sample.wav" "$lib/"
diff --git a/linux/strings/en.lproj/Linux.strings b/linux/strings/en.lproj/Linux.strings
index 7085c2c..6142695 100644
--- a/linux/strings/en.lproj/Linux.strings
+++ b/linux/strings/en.lproj/Linux.strings
@@ -94,7 +94,6 @@
"登录后在顶栏待命" = "Stand by in top bar after login";
"翻译与纪要模型" = "Translation & notes model";
"Ming(云端)" = "Ming (cloud)";
-"版本" = "Version";
"打开记录文件夹" = "Open meetings folder";
"打开会议记录" = "Open meetings";
"没能开始听" = "Couldn't start listening";
@@ -142,3 +141,9 @@
"活动" = "Activities";
"让知了听到电脑里的声音" = "Let Cicada hear your computer";
"听电脑里的声音" = "Hear the computer's audio";
+"请先用 install.sh 安装知了" = "Install Cicada with install.sh first";
+"已更新到 %@" = "Updated to %@";
+"安装没有完成" = "The install didn’t finish";
+"没能更新到 %@,还是原来的版本" = "Couldn’t update to %@; still on the previous version";
+"会后安装" = "Install after the meeting";
+"会议结束后安装" = "installs when the meeting ends";
diff --git a/linux/strings/ja.lproj/Linux.strings b/linux/strings/ja.lproj/Linux.strings
index c85ab08..b406635 100644
--- a/linux/strings/ja.lproj/Linux.strings
+++ b/linux/strings/ja.lproj/Linux.strings
@@ -94,7 +94,6 @@
"登录后在顶栏待命" = "ログイン後、トップバーに常駐";
"翻译与纪要模型" = "翻訳・議事メモモデル";
"Ming(云端)" = "Ming(クラウド)";
-"版本" = "バージョン";
"打开记录文件夹" = "記録フォルダを開く";
"打开会议记录" = "会議の記録を開く";
"没能开始听" = "聞き取りを開始できませんでした";
@@ -142,3 +141,9 @@
"活动" = "アクティビティ";
"让知了听到电脑里的声音" = "Cicada にパソコンの音を聞かせる";
"听电脑里的声音" = "パソコンの音声を聞く";
+"请先用 install.sh 安装知了" = "先に install.sh で Cicada をインストールしてください";
+"已更新到 %@" = "%@ にアップデートしました";
+"安装没有完成" = "インストールが完了しませんでした";
+"没能更新到 %@,还是原来的版本" = "%@ にアップデートできませんでした。以前のバージョンのままです";
+"会后安装" = "会議後にインストール";
+"会议结束后安装" = "会議が終わったらインストール";
diff --git a/linux/strings/ko.lproj/Linux.strings b/linux/strings/ko.lproj/Linux.strings
index 8bf8989..9a5cc3e 100644
--- a/linux/strings/ko.lproj/Linux.strings
+++ b/linux/strings/ko.lproj/Linux.strings
@@ -94,7 +94,6 @@
"登录后在顶栏待命" = "로그인 후 상단 바에서 대기";
"翻译与纪要模型" = "번역 및 회의록 모델";
"Ming(云端)" = "Ming (클라우드)";
-"版本" = "버전";
"打开记录文件夹" = "기록 폴더 열기";
"打开会议记录" = "회의 기록 열기";
"没能开始听" = "듣기를 시작하지 못했습니다";
@@ -141,3 +140,9 @@
"顶栏没有知了的图标?装上 AppIndicator 扩展,就能从顶栏打开知了。" = "상단 바에 知了 아이콘이 없나요? AppIndicator 확장을 설치하면 거기서 열 수 있습니다.";
"活动" = "현재 활동";
"让知了听到电脑里的声音" = "Cicada가 컴퓨터 소리를 듣게 하세요";
+"请先用 install.sh 安装知了" = "먼저 install.sh로 Cicada를 설치하세요";
+"已更新到 %@" = "%@(으)로 업데이트했습니다";
+"安装没有完成" = "설치를 마치지 못했습니다";
+"没能更新到 %@,还是原来的版本" = "%@(으)로 업데이트하지 못했습니다. 이전 버전 그대로입니다";
+"会后安装" = "회의 후 설치";
+"会议结束后安装" = "회의가 끝나면 설치";
diff --git a/linux/tests/test_updates.py b/linux/tests/test_updates.py
new file mode 100644
index 0000000..3e8b10c
--- /dev/null
+++ b/linux/tests/test_updates.py
@@ -0,0 +1,178 @@
+"""Updates: the Mac's UpdateTests case for case, then downloading, checking and unpacking a release
+from a file:// feed, the way the app installs one."""
+from __future__ import annotations
+
+import hashlib
+import io
+import json
+import os
+import sys
+import tarfile
+import tempfile
+import unittest
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+from cicada.core import updates # noqa: E402
+from cicada.core.strings import LF # noqa: E402
+from cicada.core.support import Paths # noqa: E402
+
+NOW = 1_000_000.0
+
+
+def release(tag, assets, prerelease=False, base="https://x/"):
+ return {"tag_name": tag, "html_url": "https://x/" + tag, "prerelease": prerelease,
+ "assets": [{"name": a, "browser_download_url": base + a, "size": 1} for a in assets]}
+
+
+def newest(rs):
+ u = updates.newest_linux(updates.decode(json.dumps(rs).encode()))
+ return u.version if u else None
+
+
+class Versions(unittest.TestCase):
+ def test_versions_compare_numerically(self):
+ self.assertTrue(updates.is_newer("2.10.0", "2.9.1"))
+ self.assertTrue(updates.is_newer("2.0.1", "2.0"))
+ self.assertFalse(updates.is_newer("2.0", "2.0.0"))
+ self.assertFalse(updates.is_newer("1.9.9", "2.0.0"))
+ self.assertFalse(updates.is_newer("2.0.0", "2.0.0"))
+
+ def test_checksum_is_found_by_name(self):
+ f = "AAA111 Cicada-2.1.0-Linux.tar.gz\nBBB222 *Cicada-2.1.0-Windows-x64.zip\n"
+ self.assertEqual("bbb222", updates.checksum_for(f, "Cicada-2.1.0-Windows-x64.zip"))
+ self.assertEqual("aaa111", updates.checksum_for(f, "Cicada-2.1.0-Linux.tar.gz"))
+ self.assertIsNone(updates.checksum_for(f, "Cicada-2.0.0-Linux.tar.gz"))
+
+ def test_a_literal_percent(self):
+ self.assertEqual("正在下载 1.3.0:42%", LF("正在下载 %@:%lld%%", "1.3.0", 42))
+
+
+class Releases(unittest.TestCase):
+ def test_a_release_without_the_linux_tarball_is_skipped(self):
+ linux = release("v1.1.0", ["Cicada-1.1.0-Linux.tar.gz", "checksums.txt"])
+ mac = release("v1.2.0", ["Cicada-1.2.0-macOS-AppleSilicon.zip", "checksums.txt"])
+ self.assertEqual("1.1.0", newest([mac, linux]))
+ self.assertIsNone(newest([mac]))
+
+ def test_prereleases_are_skipped_and_newest_wins(self):
+ old = release("v1.0.0", ["Cicada-1.0.0-Linux.tar.gz"])
+ new = release("v1.10.0", ["Cicada-1.10.0-Linux.tar.gz"])
+ beta = release("v2.0.0", ["Cicada-2.0.0-Linux.tar.gz"], prerelease=True)
+ self.assertEqual("1.10.0", newest([beta, old, new]))
+
+ def test_a_single_release_feed_still_works(self):
+ one = release("v1.3.0", ["Cicada-1.3.0-Linux.tar.gz"])
+ self.assertEqual("1.3.0", updates.newest_linux(updates.decode(json.dumps(one).encode())).version)
+
+ def test_drafts_are_skipped(self):
+ d = release("v3.0.0", ["Cicada-3.0.0-Linux.tar.gz"])
+ d["draft"] = True
+ self.assertIsNone(newest([d]))
+
+
+class Schedule(unittest.TestCase):
+ def test_due_when_never_checked_or_old_enough(self):
+ self.assertTrue(updates.due(None, NOW, updates.EVERY))
+ self.assertTrue(updates.due(NOW - 4 * 3600, NOW, updates.EVERY))
+ self.assertFalse(updates.due(NOW - 3 * 3600, NOW, updates.EVERY))
+ self.assertTrue(updates.due(NOW - 3601, NOW, updates.STALE))
+ self.assertFalse(updates.due(NOW - 600, NOW, updates.STALE))
+
+ def test_due_when_last_check_is_in_the_future(self):
+ self.assertTrue(updates.due(NOW + 86_400, NOW, updates.EVERY))
+
+
+class Install(unittest.TestCase):
+ """A release on disk: a tarball like scripts/build.sh makes, its checksums, and a feed."""
+
+ def setUp(self):
+ self.dir = tempfile.mkdtemp()
+ Paths.home_override = os.path.join(self.dir, "home")
+ self.addCleanup(setattr, Paths, "home_override", None)
+ self.addCleanup(os.environ.pop, "CICADA_UPDATE_FEED", None)
+
+ def publish(self, version="9.0.0", tree_version=None, install_ok=True, extra=None, bad_sum=False):
+ name = "Cicada-%s-Linux.tar.gz" % version
+ buf = io.BytesIO()
+ with tarfile.open(fileobj=buf, mode="w:gz") as t:
+ def add(path, text, mode=0o644):
+ data = text.encode()
+ info = tarfile.TarInfo(path)
+ info.size, info.mode = len(data), mode
+ t.addfile(info, io.BytesIO(data))
+ add("cicada-linux/VERSION", (tree_version or version) + "\n")
+ add("cicada-linux/install.sh", "#!/bin/sh\n[ \"$1\" = --check ] && exit %d\nexit 0\n" % (0 if install_ok else 1)
+ if install_ok else "#!/bin/sh\necho 'Cicada needs: libpulse0 (sudo apt install libpulse0)'\nexit 1\n", 0o755)
+ if extra:
+ extra(t)
+ data = buf.getvalue()
+ with open(os.path.join(self.dir, name), "wb") as f:
+ f.write(data)
+ digest = "0" * 64 if bad_sum else hashlib.sha256(data).hexdigest()
+ with open(os.path.join(self.dir, "checksums.txt"), "w") as f:
+ f.write("%s %s\n" % (digest, name))
+ feed = os.path.join(self.dir, "releases.json")
+ with open(feed, "w") as f:
+ json.dump([release("v" + version, [name, "checksums.txt"], base="file://" + self.dir + "/")], f)
+ os.environ["CICADA_UPDATE_FEED"] = "file://" + feed
+
+ def test_a_newer_release_is_found_and_remembered(self):
+ self.publish("9.0.0")
+ ok, u = updates.check("1.2.0")
+ self.assertTrue(ok)
+ self.assertEqual("9.0.0", u.version)
+ self.assertIsNotNone(updates.last_checked())
+ ok, u = updates.check("9.0.0")
+ self.assertTrue(ok)
+ self.assertIsNone(u, "the same version isn't offered")
+
+ def test_an_unreachable_feed_fails_quietly(self):
+ os.environ["CICADA_UPDATE_FEED"] = "file://" + os.path.join(self.dir, "missing.json")
+ self.assertEqual((False, None), updates.check("1.0.0"))
+
+ def test_prepare_unpacks_a_checked_release(self):
+ self.publish("9.0.0")
+ seen = []
+ tree = updates.prepare(updates.check("1.0.0")[1], seen.append)
+ self.assertTrue(os.path.isfile(os.path.join(tree, "install.sh")))
+ self.assertEqual(1.0, seen[-1])
+
+ def failure(self, **kw):
+ self.publish("9.0.0", **kw)
+ u = updates.check("1.0.0")[1]
+ with self.assertRaises(updates.Failure) as c:
+ updates.prepare(u)
+ return c.exception
+
+ def test_a_bad_checksum_is_refused(self):
+ self.assertEqual("下载的文件校验不通过", self.failure(bad_sum=True).key)
+
+ def test_the_wrong_version_inside_is_refused(self):
+ self.assertEqual("下载的不是预期的版本", self.failure(tree_version="8.0.0").key)
+
+ def test_missing_libraries_are_said_before_anything_changes(self):
+ e = self.failure(install_ok=False)
+ self.assertIn("sudo apt install libpulse0", e.args[0])
+
+ def test_a_tarball_escaping_its_folder_is_refused(self):
+ def evil(t):
+ info = tarfile.TarInfo("../outside.txt")
+ info.size = 1
+ t.addfile(info, io.BytesIO(b"x"))
+ self.assertEqual("更新包无效", self.failure(extra=evil).key)
+ self.assertFalse(os.path.exists(os.path.join(tempfile.gettempdir(), "outside.txt")))
+
+ def test_the_reopened_app_hears_the_result_once(self):
+ os.makedirs(Paths.data(), exist_ok=True)
+ with open(updates.marker_file(), "w") as f:
+ f.write("ok 9.0.0\n")
+ self.assertEqual(("ok", "9.0.0"), updates.take_result())
+ self.assertIsNone(updates.take_result())
+
+ def test_only_an_installed_copy_updates_in_place(self):
+ self.assertIsNone(updates.install_root(), "a checkout is not ~/.local/lib/cicada")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/site/changelog.json b/site/changelog.json
index 10fc8e7..1cdb43a 100644
--- a/site/changelog.json
+++ b/site/changelog.json
@@ -6,6 +6,11 @@
"summary": "实时纪要窗口重新排版,纪要落后时说清楚还差多少;说话人的名字在实时纪要里就能改。",
"image": null,
"items": [
+ {
+ "kind": "new",
+ "title": "Linux 版有新版本时会提示,点一下就更新并重新打开。",
+ "text": "顶栏菜单第一项和设置 › 关于都会显示;下载后先核对校验值再安装,正在听时等会议结束再装。"
+ },
{
"kind": "fixed",
"title": "录“我自己的声音”时读得太慢会提醒重录,克隆的声音不再拖得很慢。",