知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.
Swift androidlinuxlive-captionsmacosmeeting-notesmenubar-appsimultaneous-interpretationspeech-recognitionsubtitlesswiftswiftuitranslationwindows
fix(linux): a slow or cut-off update download resumes instead of failing, and if it still fails Cicada says whether the download page really opened
wqugurucdeae316bf3d
diff --git a/linux/cicada/app/debug.py b/linux/cicada/app/debug.pyindex 5939d74..ed002e9 100644--- a/linux/cicada/app/debug.py+++ b/linux/cicada/app/debug.py@@ -190,10 +190,14 @@ def command(app, line: str) -> dict:if cmd == "updatecheck": # the Mac's updateCheck: check the feed now (CICADA_UPDATE_FEED in a dev build)app.updates.check_now()return {"ok": True}+ if cmd == "updateinstall": # the Mac's updateInstall: what 安装并重新打开 does+ app.updates.install()+ return {"ok": True}if cmd == "updatestate":u = app.updatesreturn {"update": u.update.version if u.update else None, "notified": updates_notified(),- "afterMeeting": u.after_meeting, "failure": u.failure}+ "afterMeeting": u.after_meeting, "failure": u.failure, "opened": u.opened,+ "progress": u.progress, "detail": u.detail()}if cmd == "feed":if not os.path.isfile(arg):return {"ok": False, "error": "no such file"}diff --git a/linux/cicada/app/settings_window.py b/linux/cicada/app/settings_window.pyindex b1e9ff3..f6f85eb 100644--- a/linux/cicada/app/settings_window.py+++ b/linux/cicada/app/settings_window.py@@ -244,6 +244,8 @@ class SettingsWindow(Gtk.Window):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")+ # The release page's address, when no browser opened: copyable.+ sub.set_selectable(bool(u.failure and u.update and not u.opened))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):returndiff --git a/linux/cicada/app/updater.py b/linux/cicada/app/updater.pyindex 866d246..d6498e5 100644--- a/linux/cicada/app/updater.py+++ b/linux/cicada/app/updater.py@@ -6,6 +6,7 @@ the update waits for it to end (会后安装) instead of ending it."""from __future__ import annotationsimport os+import subprocessimport threadingimport time@@ -17,6 +18,49 @@ from ..core.strings import L, LFfrom ..core.support import Log, Paths+def open_uri(url: str, done=None) -> None:+ """Opens `url` in the browser, then calls done(opened) on the main thread: True only when+ something said it took it: the browser GIO names for the scheme, else xdg-open exiting cleanly+ (waited for on a thread, up to 10 s: it can take a while to try its fallbacks and fail). Logged: a page+ that doesn't open leaves no other trace."""+ def tell(opened):+ if done is not None:+ GLib.idle_add(lambda: done(opened) and False)++ def xdg_open():+ try:+ p = subprocess.Popen(["xdg-open", url], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL, start_new_session=True)+ except OSError as e:+ Log.d("open: no xdg-open (%s)" % type(e).__name__)+ return tell(False)+ try:+ code = p.wait(10)+ except subprocess.TimeoutExpired:+ Log.d("open: xdg-open still running after 10 s")+ tell(False) # unconfirmed: say where the page is rather than claim it opened+ p.wait() # reaped whenever it ends+ return+ if code != 0:+ Log.d("open: xdg-open exited %d" % code)+ tell(code == 0)++ # The scheme's handler, asked for by name: launch_default_for_uri, without one, reads the page+ # through gvfs to guess its type, which blocked the main loop for minutes behind a bad network.+ scheme = url.split(":", 1)[0]+ browser = Gio.AppInfo.get_default_for_uri_scheme(scheme)+ if browser is None:+ Log.d("open: no handler for %s" % scheme)+ else:+ try:+ if browser.launch_uris([url], None):+ return tell(True)+ Log.d("open: %s didn't start" % browser.get_id())+ except GLib.Error as e:+ Log.d("open: %s failed (%s)" % (browser.get_id(), e.message))+ threading.Thread(target=xdg_open, name="OpenPage", daemon=True).start()++class Updates:def __init__(self, app):self.app = app@@ -24,6 +68,7 @@ class Updates: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 doneself.failure: str | None = None # why the last in-place update failed+ self.opened = False # and whether the release page opened thenself.after_meeting = False # 会后安装: install once this meeting endsself.installing = Falseself.started = False@@ -131,13 +176,12 @@ class Updates: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+ """Opens the release page, then says why, and whether the page really opened."""+ def done(opened):+ self.installing, self.progress, self.failure, self.opened = False, None, why, opened+ Log.d("update: in place failed; release page %s" % ("opened" if opened else "didn't open"))+ self.app.changed()+ open_uri(u.url, done)def notify_if_due(self) -> None:"""One desktop notification per version, for people who never open the tray menu; a click@@ -160,10 +204,7 @@ class Updates:def open_notes(self) -> None:if self.update is not None:- try:- Gio.AppInfo.launch_default_for_uri(self.update.url, None)- except GLib.Error:- pass+ open_uri(self.update.url)def meeting_ended(self) -> None:self.notify_if_due()@@ -202,8 +243,11 @@ class Updates:if u is not None:if self.progress is not None:return LF("正在下载 %@:%lld%%", u.version, int(self.progress * 100))- if self.failure:+ if self.failure and self.opened:return LF("没能自动更新:%@。已打开下载页", self.failure)+ if self.failure:+ # No browser came up: the address to type, selectable in 设置 › 关于.+ return LF("没能自动更新:%@。请在浏览器里打开 %@ 下载", self.failure, u.url.split("://", 1)[-1])if self.after_meeting:return LF("有新版本 %@", u.version) + " · " + L("会议结束后安装")size = ("%.1f MB · " % (u.size / 1e6)) if u.size else ""diff --git a/linux/cicada/core/updates.py b/linux/cicada/core/updates.pyindex baabbd1..ada78de 100644--- a/linux/cicada/core/updates.py+++ b/linux/cicada/core/updates.py@@ -7,14 +7,18 @@ UI-free and stdlib only: the app shows the state, this module finds, fetches andfrom __future__ import annotationsimport hashlib+import http.clientimport jsonimport os+import reimport shleximport shutilimport subprocessimport tarfileimport tempfileimport time+import urllib.error+import urllib.parseimport urllib.requestfrom . import jsonfmt, proxy@@ -28,6 +32,10 @@ FEED = "https://api.github.com/repos/wquguru/cicada/releases?per_page=20"EVERY = 4 * 60 * 60STALE = 60 * 60USER_AGENT = "Cicada-Linux"+# Downloading: seconds without a byte before it counts as stalled (each read, not the whole file),+# and how many times a cut-off download is picked up again.+STALL = 30+ATTEMPTS = 3class Update:@@ -42,7 +50,7 @@ class Update:class Failure(Exception):- """Why installing in place didn't work, said to the user (the release page opens instead): a+ """Why installing in place didn't work, said to the user beside the release page: aMac string key and its values, translated by the app."""def __init__(self, key: str, *args):@@ -169,11 +177,27 @@ def should_notify(version: str, told: str | None, busy: bool) -> bool:return not busy and version != told-def _get(url: str, timeout: float = 20):- req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT, "Accept": "application/vnd.github+json"})+def _get(url: str, timeout: float = 20, headers=None):+ req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT, "Accept": "application/vnd.github+json",+ **(headers or {})})return proxy.urlopen(req, timeout=timeout) # our feed, or file:// in tests+def why(e: BaseException) -> str:+ """A failure for the log: its kind and reason, with any URL in it left out (a URL may carry a+ token one day; the host is logged on its own)."""+ if isinstance(e, urllib.error.HTTPError):+ return "HTTP %d" % e.code+ if isinstance(e, urllib.error.URLError) and isinstance(e.reason, BaseException):+ e = e.reason+ text = re.sub(r"[A-Za-z][A-Za-z0-9+.-]*://\S+", "<url>", str(e)).strip()+ return type(e).__name__ + (": " + text if text else "")+++def _host(url: str) -> str:+ return urllib.parse.urlsplit(url).hostname or urllib.parse.urlsplit(url).scheme++def check(current: str) -> tuple:"""(ok, update): ok is False when the feed couldn't be reached or answered oddly; update is arelease newer than `current`, or None. Blocking: run it off the main thread."""@@ -203,18 +227,38 @@ def install_root() -> str | None: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 _download(url: str, to: str, progress, expected: int = 0, attempts: int = ATTEMPTS) -> None:+ """A slow link is fine (a 13 MB release took 100 s in a VM behind a proxy): only `STALL` seconds+ without a byte counts as failing, and a cut-off download picks up where it stopped (Range)."""+ got, total = 0, 0+ with open(to, "wb") as f:+ for attempt in range(1, attempts + 1):+ try:+ with _get(url, timeout=STALL, headers={"Range": "bytes=%d-" % got} if got else None) as r:+ if got and getattr(r, "status", None) != 206:+ f.seek(0) # the server sent the whole file again+ f.truncate()+ got = 0+ if not got:+ total = int(r.headers.get("Content-Length") or expected or 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))+ if total and got < total:+ raise http.client.IncompleteRead(b"", total - got)+ return+ except urllib.error.HTTPError:+ raise # the server said no: asking again won't change it+ except (OSError, http.client.HTTPException) as e:+ Log.d("update: download from %s stopped at %d of %d bytes, try %d of %d (%s)"+ % (_host(url), got, total, attempt, attempts, why(e)))+ if attempt == attempts:+ raisedef _safe_extract(tar_path: str, into: str) -> None:@@ -244,6 +288,7 @@ def prepare(u: Update, progress=None) -> str:except Failure:raiseexcept Exception as e: # noqa: BLE001+ Log.d("update: download of %s failed (%s)" % (u.version, why(e)))code = getattr(e, "code", None)raise (Failure("下载失败(HTTP %lld)", code) if code else Failure("下载失败")) from eh = hashlib.sha256()diff --git a/linux/strings/en.lproj/Linux.strings b/linux/strings/en.lproj/Linux.stringsindex 2a88060..94da2c5 100644--- a/linux/strings/en.lproj/Linux.strings+++ b/linux/strings/en.lproj/Linux.strings@@ -193,3 +193,5 @@/* The proxy hint for GNOME's proxy (proxy.py). */"代理 %@ 没有回应。打开代理软件,或在 设置 › 网络 › 网络代理 里改正。" = "The proxy %@ doesn’t answer. Open your proxy app, or fix it in Settings › Network › Network Proxy.";"系统代理设成了“自动”,知了用不了。在 设置 › 网络 › 网络代理 里改成“手动”。" = "The system proxy is set to Automatic, which Cicada can’t use. Set it to Manual in Settings › Network › Network Proxy.";+/* An update that failed and couldn't open the browser either (updater.py): the address to open. */+"没能自动更新:%@。请在浏览器里打开 %@ 下载" = "Couldn’t update automatically: %@. Open %@ in a browser to download it";diff --git a/linux/strings/ja.lproj/Linux.strings b/linux/strings/ja.lproj/Linux.stringsindex 266768e..d790506 100644--- a/linux/strings/ja.lproj/Linux.strings+++ b/linux/strings/ja.lproj/Linux.strings@@ -193,3 +193,5 @@/* The proxy hint for GNOME's proxy (proxy.py). */"代理 %@ 没有回应。打开代理软件,或在 设置 › 网络 › 网络代理 里改正。" = "プロキシ %@ が応答しません。プロキシアプリを開くか、設定 › ネットワーク › ネットワークプロキシ で直してください。";"系统代理设成了“自动”,知了用不了。在 设置 › 网络 › 网络代理 里改成“手动”。" = "システムプロキシが「自動」になっていて、Cicada では使えません。設定 › ネットワーク › ネットワークプロキシ で「手動」にしてください。";+/* An update that failed and couldn't open the browser either (updater.py): the address to open. */+"没能自动更新:%@。请在浏览器里打开 %@ 下载" = "自動アップデートできませんでした:%@。ブラウザで %@ を開いてダウンロードしてください";diff --git a/linux/strings/ko.lproj/Linux.strings b/linux/strings/ko.lproj/Linux.stringsindex d2faac2..179a79d 100644--- a/linux/strings/ko.lproj/Linux.strings+++ b/linux/strings/ko.lproj/Linux.strings@@ -193,3 +193,5 @@/* The proxy hint for GNOME's proxy (proxy.py). */"代理 %@ 没有回应。打开代理软件,或在 设置 › 网络 › 网络代理 里改正。" = "프록시 %@이(가) 응답하지 않아요. 프록시 앱을 열거나 설정 › 네트워크 › 네트워크 프록시에서 고치세요.";"系统代理设成了“自动”,知了用不了。在 设置 › 网络 › 网络代理 里改成“手动”。" = "시스템 프록시가 ‘자동’으로 되어 있어 Cicada에서 쓸 수 없어요. 설정 › 네트워크 › 네트워크 프록시에서 ‘수동’으로 바꾸세요.";+/* An update that failed and couldn't open the browser either (updater.py): the address to open. */+"没能自动更新:%@。请在浏览器里打开 %@ 下载" = "자동 업데이트 실패: %@. 브라우저에서 %@을(를) 열어 다운로드하세요";diff --git a/linux/tests/test_updates.py b/linux/tests/test_updates.pyindex 78bdad2..54b50a7 100644--- a/linux/tests/test_updates.py+++ b/linux/tests/test_updates.py@@ -3,13 +3,17 @@ from a file:// feed, the way the app installs one."""from __future__ import annotationsimport hashlib+import http.serverimport ioimport jsonimport osimport sysimport tarfileimport tempfile+import threading+import timeimport unittest+import urllib.errorsys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))@@ -196,5 +200,87 @@ class Notify(unittest.TestCase):self.assertEqual(updates.last_checked(), NOW + 1)+class _Flaky(http.server.BaseHTTPRequestHandler):+ """Serves BODY with Range; the first request is cut off halfway, or stalls when `stall`."""+ protocol_version = "HTTP/1.1"+ requests: list = []+ stall = False++ def do_GET(self):+ _Flaky.requests.append(self.headers.get("Range"))+ start = int(self.headers["Range"][6:-1]) if self.headers.get("Range") else 0+ part = BODY[start:]+ self.send_response(206 if start else 200)+ self.send_header("Content-Length", str(len(part)))+ self.end_headers()+ if len(_Flaky.requests) == 1:+ self.wfile.write(part[:len(part) // 2])+ self.wfile.flush()+ if _Flaky.stall:+ time.sleep(1.5)+ self.close_connection = True+ return+ self.wfile.write(part)++ def log_message(self, *a):+ pass+++BODY = bytes(range(256)) * 4000+++class Download(unittest.TestCase):+ def setUp(self):+ self.dir = tempfile.mkdtemp()+ Paths.home_override = os.path.join(self.dir, "home")+ os.makedirs(Paths.data(), exist_ok=True)+ self.addCleanup(setattr, Paths, "home_override", None)+ # A proxy in the shell running the tests would carry these local requests off through it.+ for k in ("http_proxy", "https_proxy", "all_proxy", "no_proxy"):+ for name in (k, k.upper()):+ if name in os.environ:+ self.addCleanup(os.environ.__setitem__, name, os.environ.pop(name))+ server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _Flaky)+ threading.Thread(target=server.serve_forever, daemon=True).start()+ self.addCleanup(server.server_close)+ self.addCleanup(server.shutdown)+ self.url = "http://127.0.0.1:%d/Cicada.tar.gz" % server.server_address[1]+ _Flaky.requests, _Flaky.stall = [], False++ def log(self) -> str:+ with open(Paths.log(), encoding="utf-8") as f:+ return f.read()++ def test_a_cut_off_download_picks_up_where_it_stopped(self):+ to = os.path.join(self.dir, "t")+ updates._download(self.url, to, None)+ with open(to, "rb") as f:+ self.assertEqual(BODY, f.read())+ self.assertEqual([None, "bytes=%d-" % (len(BODY) // 2)], _Flaky.requests)+ self.assertIn("stopped at %d of %d bytes, try 1 of 3 (IncompleteRead" % (len(BODY) // 2, len(BODY)), self.log())+ self.assertNotIn("http://", self.log()) # the host only++ def test_a_stall_is_a_timeout_per_read_not_for_the_whole_file(self):+ _Flaky.stall = True+ old = updates.STALL+ updates.STALL = 0.5+ self.addCleanup(setattr, updates, "STALL", old)+ to = os.path.join(self.dir, "t")+ updates._download(self.url, to, None)+ with open(to, "rb") as f:+ self.assertEqual(BODY, f.read())+ self.assertRegex(self.log(), r"try 1 of 3 \((timeout|TimeoutError): timed out\)") # socket.timeout's name varies++ def test_giving_up_says_why(self):+ with self.assertRaises(OSError):+ updates._download("http://127.0.0.1:9/x", os.path.join(self.dir, "t"), None, attempts=2)+ self.assertIn("try 2 of 2 (ConnectionRefusedError", self.log())++ def test_why_leaves_urls_out(self):+ e = urllib.error.URLError(OSError("bad https://x.example/a?token=s3cret"))+ self.assertEqual("OSError: bad <url>", updates.why(e))+ self.assertEqual("HTTP 404", updates.why(urllib.error.HTTPError("https://x/?k=1", 404, "nf", {}, None)))++if __name__ == "__main__":unittest.main()