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): share a meeting as a link, checked for keys and other sensitive content before upload

wquguru117a7351abfc
diff --git a/linux/README.md b/linux/README.md
index 1c0f9bc..64ec8b5 100644
--- a/linux/README.md
+++ b/linux/README.md
@@ -55,7 +55,7 @@ linux/vm/vmctl.sh shot shot.png # 截屏(QEMU,不受 Wayland
linux/scripts/build.sh && linux/vm/push.sh # 把 build/cicada-linux 和测试工具放进虚拟机的 ~/cicada-linux
```
-在虚拟机里 `~/cicada-linux/bin/cicada --dev` 启动开发版(记录在 `~/.local/share/cicada-dev`,日志在 `~/.local/state/cicada-dev/debug.log`),再用 `scripts/cicadactl` 驱动它:`state`、`start`、`stop`、`feed <wav>`、`sample`、`view notes|subtitles`、`show records|notes|settings|onboarding`、`windows`、`quit`;结束会议用 `calls zoom=Zoom|none|real`(假装会议软件在通话)、`realcalls`、`endtimes <没人说话秒数> <倒计时> <挂断宽限>|off`、`endkeep`;纪要窗用 `notes-tab notes|transcript`、`notes-search <词>`、`notes-wide on|off`、`notes-end ask|keep|end`(结束前的确认)、`notes-status failed|invalidKey|rateLimited|idle`(看出错横幅);记录用 `rename <id> [标题]`(不给标题即恢复自动标题)、`delete <id>`;还有 `onboarding-step <0-4>`、`settings-scroll <0-1>`;AI 服务检查用 `ai-check`(现在查一次)、`ai-check-sim <原因|lowBalance|off>`(每次检查都按这个原因结束,截各状态的图)、`ask settings|fix|close`(回答开始听时的对话框)、`settings-ai`、`tray-menu`(顶栏菜单的各项);只有你能修的问题(key、余额、模型、地址)在顶栏图标上加橙点,纪要窗收起时每场会议发一次通知(连不上的话持续 2 分钟后才发),`hide notes` 收起纪要窗、`problem-wait <秒>|off` 缩短这 2 分钟、`state` 的 `aiProblem` 看结果。保存会议录音用 `codecs`(这台电脑有没有 AAC 编码器 / 解码器)、`play [秒]`、`pause`、`rate`、`playstate`(播放到哪、亮着哪一句)、`settings-general`;Ubuntu 默认没有 AAC 编码器,测录音要先在虚拟机里 `sudo apt install gstreamer1.0-libav`,测完再删掉,看默认的灰开关。改正听错的词:`start` 后用 `heard <一句话>`(不用声音,当作听到的一整句,走真实的翻译 + 改词请求),`fix-state` 看每句的改法,`fix-answer yes|no`、`fix-later`、`fix-revert <句子 id>`、`fix-edit <句子 id>=<改后>[|one][|keep0]`、`fix-undo`,`fix-editor <句子 id>=<改后>` 在会议记录里打开“改这句…”,`vocab-add Morpho=莫拉`、`vocab-state`、`word-list [import <文字>|edit <词>|heard <词>=<听成>|delete <词>]` 看设置里的词表。`scripts/smoke.sh` 一步跑完:开窗口、放一段声音、确认 monitor 听到了。
+在虚拟机里 `~/cicada-linux/bin/cicada --dev` 启动开发版(记录在 `~/.local/share/cicada-dev`,日志在 `~/.local/state/cicada-dev/debug.log`),再用 `scripts/cicadactl` 驱动它:`state`、`start`、`stop`、`feed <wav>`、`sample`、`view notes|subtitles`、`show records|notes|settings|onboarding`、`windows`、`quit`;结束会议用 `calls zoom=Zoom|none|real`(假装会议软件在通话)、`realcalls`、`endtimes <没人说话秒数> <倒计时> <挂断宽限>|off`、`endkeep`;纪要窗用 `notes-tab notes|transcript`、`notes-search <词>`、`notes-wide on|off`、`notes-end ask|keep|end`(结束前的确认)、`notes-status failed|invalidKey|rateLimited|idle`(看出错横幅);记录用 `rename <id> [标题]`(不给标题即恢复自动标题)、`delete <id>`;还有 `onboarding-step <0-4>`、`settings-scroll <0-1>`;AI 服务检查用 `ai-check`(现在查一次)、`ai-check-sim <原因|lowBalance|off>`(每次检查都按这个原因结束,截各状态的图)、`ask settings|fix|close`(回答开始听时的对话框)、`settings-ai`、`tray-menu`(顶栏菜单的各项);只有你能修的问题(key、余额、模型、地址)在顶栏图标上加橙点,纪要窗收起时每场会议发一次通知(连不上的话持续 2 分钟后才发),`hide notes` 收起纪要窗、`problem-wait <秒>|off` 缩短这 2 分钟、`state` 的 `aiProblem` 看结果。保存会议录音用 `codecs`(这台电脑有没有 AAC 编码器 / 解码器)、`play [秒]`、`pause`、`rate`、`playstate`(播放到哪、亮着哪一句)、`settings-general`;Ubuntu 默认没有 AAC 编码器,测录音要先在虚拟机里 `sudo apt install gstreamer1.0-libav`,测完再删掉,看默认的灰开关。改正听错的词:`start` 后用 `heard <一句话>`(不用声音,当作听到的一整句,走真实的翻译 + 改词请求),`fix-state` 看每句的改法,`fix-answer yes|no`、`fix-later`、`fix-revert <句子 id>`、`fix-edit <句子 id>=<改后>[|one][|keep0]`、`fix-undo`,`fix-editor <句子 id>=<改后>` 在会议记录里打开“改这句…”,`vocab-add Morpho=莫拉`、`vocab-state`、`word-list [import <文字>|edit <词>|heard <词>=<听成>|delete <词>]` 看设置里的词表。分享成链接(`cicada/core/share.py`,设备密钥是纯 Python 的 Ed25519,`cicada/core/ed25519.py`):`share <id>[,full][,pw]`、`unshare <id>`、`share-last`、`shareSheet <id>` 打开“分享…”,`share-ui scope|days|names|pw|summary|go|strip|back|confirm|revoke|close|state` 操作它;虚拟机连不上 cicada.indaloop.app 时用 `https_proxy=http://10.0.2.2:7890` 启动。`scripts/smoke.sh` 一步跑完:开窗口、放一段声音、确认 monitor 听到了。
焦点:`bin/focus_test.sh` 开一个最大化的“会议 app”(`focus_probe.py`),用 `click.py`(uinput,真实指针)点纪要窗和“字幕”链接,再在 Mac 上 `linux/vm/vmctl.sh type ok`;`/tmp/focus-probe.log` 里不能出现 `active=False`,最后一行应是 `text=…ok`。xdotool 只到 XWayland,测不了这个。
diff --git a/linux/cicada/app/debug.py b/linux/cicada/app/debug.py
index 1a8cd90..9acd7f2 100644
--- a/linux/cicada/app/debug.py
+++ b/linux/cicada/app/debug.py
@@ -18,7 +18,9 @@ per connection, one JSON line back. Never in release builds.
online both|no (answer 线上也有人?) | room-mic-force <source>|"" (a null sink's monitor as the room mic)
hide notes | problem-wait <seconds>|off (how long unreachable lasts before its notification; off: 2 min)
codecs (AAC encoder / decoders here) | play [<seconds>] | pause | rate (next speed) | playstate (the shown record's
- recording: state, time, length, rate, the highlighted line) | settings-general (设置 at 通用)"""
+ recording: state, time, length, rate, the highlighted line) | settings-general (设置 at 通用)
+ share <record id>[,full][,pw] | unshare <record id> | share-last (how the last ended) | shareSheet <record id>|""
+ share-ui scope notes|full | days 7|30|365 | names|pw|summary on|off | go | strip | back | confirm | revoke | close | state"""
from __future__ import annotations
import os
@@ -413,12 +415,94 @@ def command(app, line: str) -> dict:
return {"ok": True, "step": app.onboarding.step if app.onboarding is not None else "done"}
if cmd.startswith(("fix", "vocab")) or cmd in ("heard", "ask-names", "resettle", "word-list"):
return _fixes(app, cmd, arg)
+ if cmd in ("share", "unshare", "share-last", "shareSheet", "share-ui"):
+ return _share(app, cmd, arg)
if cmd == "quit":
app.quit()
return {"ok": True}
return {"ok": False, "error": "unknown command " + cmd}
+_share_last: dict = {}
+
+
+def _share(app, cmd: str, arg: str) -> dict:
+ """分享… (the Mac's share / unshare / shareSheet debug commands). The network runs on a thread:
+ `share` and `unshare` answer at once, `share-last` says how the last one ended."""
+ from ..core import share
+ from . import share_dialog
+ if cmd == "share-last":
+ return {"ok": True, **_share_last}
+ if cmd in ("share", "unshare"):
+ p = arg.split(",")
+ sid = p[0]
+ s = app.store.get(sid)
+ if s is None:
+ return {"ok": False, "error": "no such record"}
+ _share_last.clear()
+ _share_last["running"] = cmd
+
+ def run():
+ c = share_dialog.client()
+ if cmd == "unshare":
+ r = share.ShareStore.read(sid)
+ ok = r is not None and c.revoke(r, sid)
+ Log.d("share: revoked %s" % ok)
+ out = {"revoked": ok, "id": r.id if r else None}
+ else:
+ o = share.Options(scope="full" if "full" in p else "notes", password=share.make_password() if "pw" in p else None)
+ res = c.share(s, o)
+ out = {"kind": res.kind, "code": res.code, "hits": res.hits,
+ "lines": sorted(share.record_lines(res.hits, res.kept))}
+ if res.record is not None:
+ out.update({"id": res.record.id, "url": res.record.url, "password": res.record.password})
+ Log.d("share: %s" % res.record.url)
+ _share_last.clear()
+ _share_last.update(out)
+ threading.Thread(target=run, name="Share", daemon=True).start()
+ return {"ok": True, "started": cmd}
+ if cmd == "shareSheet":
+ if not arg:
+ if app.share_dialog is not None:
+ app.share_dialog.close()
+ return {"ok": True}
+ s = app.store.get(arg)
+ if s is None:
+ return {"ok": False, "error": "no such record"}
+ app.show_records()
+ w = app.records_window
+ w.selected = arg
+ w.fill()
+ return {"ok": True, **share_dialog.open_for(app, s, w).state()}
+ # share-ui scope notes|full | days 7|30|365 | names|pw|summary on|off | go | strip | back | confirm | revoke | close | state
+ d = app.share_dialog
+ if d is None:
+ return {"ok": False, "error": "no share dialog"}
+ act, _, val = arg.partition(" ")
+ if act == "scope":
+ d.scope = val
+ elif act == "days":
+ d.days = int(val)
+ elif act in ("names", "pw", "summary"):
+ setattr(d, {"names": "names", "pw": "use_password", "summary": "summary"}[act], val == "on")
+ elif act == "go":
+ d.go()
+ elif act == "strip":
+ d.strip()
+ elif act == "back":
+ d.step = "settings"
+ elif act == "confirm":
+ d.confirm = True
+ elif act == "revoke":
+ d.revoke()
+ elif act == "close":
+ d.close()
+ return {"ok": True}
+ if act in ("scope", "days", "names", "pw", "summary", "back", "confirm"):
+ d.render()
+ return {"ok": True, **d.state()}
+
+
def _fix_state(app, sid: str) -> dict:
lines = app.store.lines(sid)
every = [f for l in lines for f in l.fixes or []]
diff --git a/linux/cicada/app/main.py b/linux/cicada/app/main.py
index 744d42a..8a72326 100644
--- a/linux/cicada/app/main.py
+++ b/linux/cicada/app/main.py
@@ -119,6 +119,7 @@ class Controller:
self.store.on_words(self._words)
self.ling.on_change(self.changed)
self.notes_window = None
+ self.share_dialog = None # 分享… (share_dialog.py), one at a time
self.records_window = None
self.settings_window = None
self.onboarding = None
diff --git a/linux/cicada/app/records_window.py b/linux/cicada/app/records_window.py
index 7a5ed1e..c04fbc6 100644
--- a/linux/cicada/app/records_window.py
+++ b/linux/cicada/app/records_window.py
@@ -13,7 +13,7 @@ from gi.repository import Gdk, Gio, GLib, Gtk, Pango
from ..core import aac, roommic, session_store, speakers
from ..core.strings import L, LF
from ..core.support import SOURCES, TARGETS, Log, clock
-from . import ui
+from . import share_dialog, ui
LANG_NAMES = {code: name for name, code in SOURCES + TARGETS}
@@ -460,6 +460,7 @@ class RecordsWindow(Gtk.Window):
row.pack_start(title, True, True, 0)
row.pack_end(self._more_menu(s), False, False, 0)
row.pack_end(ui.button(L("导出…"), lambda: self.export(s), "outline", "document-save-symbolic"), False, False, 0)
+ row.pack_end(self._share_button(s), False, False, 0)
heads = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=40)
heads.set_homogeneous(True)
heads.pack_start(self._section_title(L("纪要")), True, True, 0)
@@ -700,6 +701,7 @@ class RecordsWindow(Gtk.Window):
top.pack_start(left, True, True, 0)
actions = ui.hbox(8)
actions.set_valign(Gtk.Align.START)
+ actions.pack_start(self._share_button(s), False, False, 0)
actions.pack_start(ui.button(L("导出…"), lambda: self.export(s), "outline", "document-save-symbolic"), False, False, 0)
actions.pack_start(self._more_menu(s), False, False, 0)
top.pack_end(actions, False, False, 0)
@@ -1527,6 +1529,18 @@ class RecordsWindow(Gtk.Window):
# Actions
+ def _share_button(self, s) -> Gtk.Widget:
+ """分享…, beside 导出…: off while the meeting is live or has nothing in it (share_dialog.can_share)."""
+ sid = s.id
+ b = ui.button(L("分享…"), lambda: self.share(sid), "outline", "emblem-shared-symbolic")
+ b.set_sensitive(share_dialog.can_share(self.app, s))
+ return b
+
+ def share(self, sid: str) -> None:
+ s = self.app.store.get(sid)
+ if s is not None and share_dialog.can_share(self.app, s):
+ share_dialog.open_for(self.app, s, self)
+
def export(self, s) -> None:
dialog = Gtk.FileChooserDialog(title=L("导出"), transient_for=self, action=Gtk.FileChooserAction.SAVE)
dialog.add_buttons(L("取消"), Gtk.ResponseType.CANCEL, L("保存"), Gtk.ResponseType.ACCEPT)
diff --git a/linux/cicada/app/share_dialog.py b/linux/cicada/app/share_dialog.py
new file mode 100644
index 0000000..503b5d7
--- /dev/null
+++ b/linux/cicada/app/share_dialog.py
@@ -0,0 +1,396 @@
+"""分享…: a meeting as a link on cicada.indaloop.app (the Mac's ShareViews.swift). Settings, then the
+server's review, then the link (and its password) or what the review stopped. A meeting already
+shared opens on its link. The network runs on a worker thread; the dialog never blocks the app."""
+from __future__ import annotations
+
+import threading
+import time
+
+from gi.repository import Gdk, Gio, GLib, Gtk, Pango
+
+from ..core import share
+from ..core.share import ShareClient, ShareStore
+from ..core.strings import L, LF
+from ..core.support import Log, clock
+from ..core import session_store
+from . import ui
+
+_client = None
+
+
+def client() -> ShareClient:
+ global _client
+ if _client is None:
+ _client = ShareClient()
+ return _client
+
+
+def can_share(app, s) -> bool:
+ """Not while the meeting is still going, nor before an import has its text, nor with nothing in it."""
+ has_notes = s.notes is not None and not s.notes.is_empty
+ return bool(s.lines or has_notes) and s.id != app.store.live and not s.importing
+
+
+class ShareDialog:
+ def __init__(self, app, s, parent=None):
+ self.app, self.s = app, s
+ self.has_notes = s.notes is not None and not s.notes.is_empty
+ self.step = "settings"
+ self.scope = "notes" if self.has_notes else "full"
+ self.days = 7
+ self.names = False
+ self.use_password = False
+ self.password = share.make_password()
+ self.summary = False
+ self.removed: set = set()
+ self.drop_notes = False
+ self.views = None
+ self.confirm = False
+ self.copied = None
+ self.hits, self.kept, self.record, self.message = [], [], None, ""
+ self.busy = False
+
+ d = Gtk.Dialog(transient_for=parent, modal=True)
+ d.set_decorated(False)
+ d.set_resizable(False)
+ ui.classes(d, "endask", "sharesheet")
+ d.connect("key-press-event", self._key)
+ d.connect("destroy", lambda *_: self._gone())
+ self.window = d
+ self.body = ui.vbox(16)
+ self.body.set_size_request(372, -1) # 420 with the padding, as on the Mac
+ d.get_content_area().pack_start(ui.pad(self.body, 24), True, True, 0)
+ r = ShareStore.read(s.id)
+ if r is not None and r.expiresAt > time.time():
+ self.step, self.record = "done", r
+ self._load_views(r)
+ self.render()
+ d.show_all()
+
+ # Steps
+
+ def render(self) -> None:
+ ui.clear(self.body)
+ {"settings": self._settings, "working": self._working, "blocked": self._blocked, "done": self._done,
+ "failed": self._failed}[self.step]()
+ self.body.show_all()
+ # Shrink back after a taller step, once the new content has its size.
+ GLib.idle_add(lambda: self.window is not None and self.window.resize(1, 1) and False)
+
+ def _header(self, title: str) -> None:
+ self.body.pack_start(ui.vbox(4, ui.text(title, 15, "ink", bold=True, wrap=False),
+ ui.text(session_store.display_title(self.s), 12, "secondary", wrap=False)),
+ False, False, 0)
+
+ def _row(self, title: str, control) -> Gtk.Widget:
+ row = ui.hbox(12)
+ row.pack_start(ui.text(title, 13, "ink", wrap=False, ellipsize=False), True, True, 0)
+ control.set_valign(Gtk.Align.CENTER)
+ row.pack_end(control, False, False, 0)
+ return row
+
+ def _switch(self, on: bool, changed) -> Gtk.Switch:
+ sw = Gtk.Switch()
+ sw.set_active(on)
+ sw.connect("notify::active", lambda w, _p: changed(w.get_active()))
+ return sw
+
+ def _buttons(self, *buttons) -> Gtk.Widget:
+ row = ui.hbox(8)
+ row.set_halign(Gtk.Align.END)
+ for b in buttons:
+ row.pack_start(b, False, False, 0)
+ return row
+
+ def _settings(self) -> None:
+ self._header(L("分享这场会议"))
+ content = ui.vbox(8, ui.text(L("内容"), 12, "secondary", bold=True, wrap=False))
+
+ def scope(v):
+ self.scope = v
+ seg = ui.segmented([("notes", L("只分享纪要")), ("full", L("纪要和双语全文"))], self.scope, scope)
+ ui.classes(seg, "big")
+ if not self.has_notes:
+ seg.get_children()[0].set_sensitive(False)
+ content.pack_start(seg, False, False, 0)
+ self.body.pack_start(content, False, False, 0)
+
+ days = Gtk.ComboBoxText()
+ for n, label in zip(share.DAYS, (L("7 天"), L("30 天"), L("1 年"))):
+ days.append(str(n), label)
+ days.set_active_id(str(self.days))
+ days.connect("changed", lambda c: setattr(self, "days", int(c.get_active_id())))
+ self.body.pack_start(self._row(L("有效期"), days), False, False, 0)
+ self.body.pack_start(self._row(L("显示说话人名字"), self._switch(self.names, lambda v: setattr(self, "names", v))),
+ False, False, 0)
+
+ def password(v):
+ self.use_password = v
+ self.render()
+ self.body.pack_start(self._row(L("用密码保护"), self._switch(self.use_password, password)), False, False, 0)
+ go = ui.button(L("生成链接"), self.go, "darkbtn")
+ if self.use_password:
+ entry = Gtk.Entry()
+ entry.set_text(self.password)
+ ui.classes(entry, "mono")
+
+ def typed(e):
+ self.password = e.get_text()
+ go.set_sensitive(len(self.password) >= 6)
+ entry.connect("changed", typed)
+
+ def again():
+ entry.set_text(share.make_password())
+ row = ui.hbox(8)
+ row.pack_start(entry, True, True, 0)
+ row.pack_start(ui.button(L("换一个"), again, "outline"), False, False, 0)
+ self.body.pack_start(row, False, False, 0)
+ go.set_sensitive(len(self.password) >= 6)
+ elif self.has_notes:
+ self.body.pack_start(self._row(L("预览卡显示摘要"), self._switch(self.summary, lambda v: setattr(self, "summary", v))),
+ False, False, 0)
+ self.body.pack_start(ui.text(L("建议把链接和密码分两条消息发送。") if self.use_password
+ else L("内容将上传至 cicada.indaloop.app,拿到链接的人都能看。"), 12, "tertiary", width_chars=46),
+ False, False, 0)
+ self.body.pack_start(self._buttons(ui.button(L("取消"), self.close, "outline"), go), False, False, 0)
+ go.set_can_default(True)
+ self.window.set_default(go)
+
+ def options(self) -> share.Options:
+ return share.Options(scope=self.scope, days=self.days, names=self.names,
+ password=self.password if self.use_password else None,
+ summary_in_preview=not self.use_password and self.summary,
+ removed=self.removed, drop_notes=self.drop_notes)
+
+ def go(self) -> None:
+ if self.busy:
+ return
+ self.busy = True
+ self.step = "working"
+ self.render()
+ s, o = self.s, self.options()
+
+ def run():
+ out = client().share(s, o)
+ GLib.idle_add(lambda: self._finished(out) and False)
+ threading.Thread(target=run, name="Share", daemon=True).start()
+
+ def _finished(self, out) -> None:
+ self.busy = False
+ if self.window is None:
+ return
+ if out.kind == "shared":
+ self.record, self.views, self.confirm = out.record, 0, False
+ self._copy(out.record.url, "link")
+ self.step = "done"
+ elif out.kind == "blocked":
+ self.hits, self.kept, self.step = out.hits, out.kept, "blocked"
+ else:
+ self.message, self.step = share.message(out.code or ""), "failed"
+ self.render()
+
+ def _working(self) -> None:
+ self._header(L("分享这场会议"))
+ spin = Gtk.Spinner()
+ spin.start()
+ row = ui.hbox(10, spin, ui.text(L("正在检查有没有敏感内容…"), 13, "secondary", wrap=False))
+ row.set_halign(Gtk.Align.CENTER)
+ row.set_valign(Gtk.Align.CENTER)
+ row.set_size_request(-1, 80)
+ self.body.pack_start(row, False, False, 0)
+
+ # Blocked
+
+ def _left_after(self) -> bool:
+ """Would anything be left to share once the flagged parts are out? (A notes-only share whose
+ notes were flagged has nothing; the server would refuse an empty document.)"""
+ notes_left = self.has_notes and not self.drop_notes and not any(h.get("part") == "notes" for h in self.hits)
+ if self.scope != "full":
+ return notes_left
+ out = self.removed | share.record_lines(self.hits, self.kept)
+ return notes_left or any(i not in out and l.src for i, l in enumerate(self.s.lines))
+
+ def _hit_row(self, h) -> Gtk.Widget:
+ what = "、".join(share.category(q) for q in h.get("questions") or [])
+ if h.get("part") == "notes":
+ place, quote = L("纪要"), self.s.notes.summary if self.s.notes else ""
+ else:
+ lines = sorted(share.record_lines([h], self.kept))
+ a = clock(self.s.lines[lines[0]].t) if lines else ""
+ b = clock(self.s.lines[lines[-1]].t) if lines else ""
+ place = a if a == b else "%s–%s" % (a, b)
+ quote = self.s.lines[lines[0]].src if lines else ""
+ q = ui.text(quote, 12, "secondary", width_chars=44)
+ q.set_lines(2)
+ q.set_ellipsize(Pango.EllipsizeMode.END) # two lines at most
+ box = ui.vbox(3, ui.text("%s · %s" % (what, place), 12, "ink", bold=True, width_chars=44), q)
+ return ui.panel(ui.pad(box, 10), "sharehit")
+
+ def _blocked(self) -> None:
+ icon = ui.icon("dialog-warning-symbolic", 16)
+ ui.classes(icon, "link")
+ self.body.pack_start(ui.hbox(8, icon, ui.text(L("检测到潜在敏感内容"), 15, "ink", bold=True, wrap=False)), False, False, 0)
+ self.body.pack_start(ui.text(L("链接尚未生成。请先核对以下内容:"), 12, "secondary"), False, False, 0)
+ hits = ui.vbox(8)
+ for h in self.hits[:5]:
+ hits.pack_start(self._hit_row(h), False, False, 0)
+ if len(self.hits) > 5:
+ hits.pack_start(ui.text(LF("还有 %lld 处", len(self.hits) - 5), 12, "secondary"), False, False, 0)
+ self.body.pack_start(hits, False, False, 0)
+ left = self._left_after()
+ self.body.pack_start(ui.text(L("去掉后再检查一次;你的记录不会改动。") if left else L("去掉这些内容后就没有可分享的了。"),
+ 12, "tertiary", width_chars=46), False, False, 0)
+
+ def back():
+ self.step = "settings"
+ self.render()
+ buttons = [ui.button(L("返回修改"), back, "outline")]
+ if left:
+ buttons.append(ui.button(L("去掉这些内容后分享"), self.strip, "darkbtn"))
+ self.body.pack_start(self._buttons(*buttons), False, False, 0)
+
+ def strip(self) -> None:
+ if self.step != "blocked" or not self._left_after():
+ return
+ self.removed |= share.record_lines(self.hits, self.kept)
+ if any(h.get("part") == "notes" for h in self.hits):
+ self.drop_notes = True
+ self.go()
+
+ # Done
+
+ def _field(self, value: str, copy_label: str, what: str) -> Gtk.Widget:
+ l = ui.text(value, 12, "ink", wrap=False, selectable=True)
+ ui.classes(l, "mono")
+ l.set_ellipsize(Pango.EllipsizeMode.MIDDLE)
+ row = ui.hbox(8)
+ row.pack_start(ui.panel(ui.pad(l, 6, 8), "sharefield"), True, True, 0)
+ row.pack_start(ui.button(L("已复制") if self.copied == what else copy_label,
+ lambda: (self._copy(value, what), self.render()), "outline"), False, False, 0)
+ return row
+
+ def _done(self) -> None:
+ r = self.record
+ self._header(L("链接已复制") if self.copied == "link" else L("已分享"))
+ self.body.pack_start(self._field(r.url, L("复制链接"), "link"), False, False, 0)
+ if r.password:
+ self.body.pack_start(self._field(r.password, L("复制密码"), "password"), False, False, 0)
+ status = LF("%lld 天后失效", r.days_left())
+ if self.views is not None:
+ status += " · " + LF("打开 %lld 次", self.views)
+ self.body.pack_start(ui.text(status, 12, "secondary", wrap=False), False, False, 0)
+ self.body.pack_start(Gtk.Separator(), False, False, 0)
+ if self.confirm:
+ def keep():
+ self.confirm = False
+ self.render()
+ self.body.pack_start(ui.vbox(6, ui.text(L("取消后链接立即失效"), 13, "ink", bold=True, wrap=False),
+ ui.text(L("已查看过的人可能留有副本。"), 12, "tertiary"),
+ self._buttons(ui.button(L("暂不取消"), keep, "outline"),
+ ui.button(L("取消分享"), self.revoke, "darkbtn"))), False, False, 0)
+ else:
+ def ask():
+ self.confirm = True
+ self.render()
+ row = ui.hbox(8)
+ row.pack_start(ui.button(L("取消分享"), ask, "outline"), False, False, 0)
+ done = ui.button(L("完成"), self.close, "darkbtn")
+ row.pack_end(done, False, False, 0)
+ row.pack_end(ui.button(L("在浏览器中打开"), lambda: self._open(r.url), "outline"), False, False, 0)
+ self.body.pack_start(row, False, False, 0)
+
+ def revoke(self) -> None:
+ if self.busy or self.record is None:
+ return
+ self.busy = True
+ r, sid = self.record, self.s.id
+
+ def run():
+ ok = client().revoke(r, sid)
+
+ def after():
+ self.busy = False
+ if self.window is None:
+ return False
+ if ok:
+ self.close()
+ else:
+ self.message, self.step = share.message("network"), "failed"
+ self.render()
+ return False
+ GLib.idle_add(after)
+ threading.Thread(target=run, name="Share", daemon=True).start()
+
+ def _load_views(self, r) -> None:
+ sid = self.s.id
+
+ def run():
+ st = client().stats([r.id]).get(r.id)
+
+ def after():
+ if st is None or self.window is None:
+ return False
+ if st.get("state") != "live":
+ ShareStore.remove(sid)
+ self.step, self.record = "settings", None
+ else:
+ self.views = st.get("views", 0)
+ self.render()
+ return False
+ GLib.idle_add(after)
+ threading.Thread(target=run, name="Share", daemon=True).start()
+
+ def _failed(self) -> None:
+ self._header(L("没有分享出去"))
+ self.body.pack_start(ui.text(self.message, 13, "ink", width_chars=46), False, False, 0)
+ self.body.pack_start(self._buttons(ui.button(L("关闭"), self.close, "outline"),
+ ui.button(L("重试"), self.go, "darkbtn")), False, False, 0)
+
+ # Parts
+
+ def _copy(self, text: str, what: str) -> None:
+ Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD).set_text(text, -1)
+ self.copied = what
+
+ def _open(self, url: str) -> None:
+ try:
+ Gio.AppInfo.launch_default_for_uri(url, None)
+ except GLib.Error as e:
+ Log.d("share: could not open the browser (%s)" % e.message)
+
+ def _key(self, _w, event) -> bool:
+ if event.keyval == Gdk.KEY_Escape:
+ if self.step == "blocked":
+ self.step = "settings"
+ self.render()
+ elif self.step != "working":
+ self.close()
+ return True
+ return False
+
+ def _gone(self) -> None:
+ self.window = None
+ if getattr(self.app, "share_dialog", None) is self:
+ self.app.share_dialog = None
+
+ def close(self) -> None:
+ if self.window is not None:
+ self.window.destroy()
+
+ def state(self) -> dict:
+ """For the control socket: where the dialog is and what it shows."""
+ r = self.record
+ return {"step": self.step, "session": self.s.id, "scope": self.scope, "days": self.days, "names": self.names,
+ "password": self.use_password, "summary": self.summary, "busy": self.busy, "confirm": self.confirm,
+ "hits": self.hits, "kept": self.kept, "removed": sorted(self.removed), "dropNotes": self.drop_notes,
+ "left": self._left_after() if self.step == "blocked" else None, "message": self.message or None,
+ "url": r.url if r else None, "views": self.views}
+
+
+def open_for(app, s, parent=None) -> ShareDialog:
+ """The one share dialog: a new record replaces whatever was open."""
+ old = getattr(app, "share_dialog", None)
+ if old is not None:
+ old.close()
+ app.share_dialog = ShareDialog(app, s, parent)
+ return app.share_dialog
diff --git a/linux/cicada/app/ui.py b/linux/cicada/app/ui.py
index 22f3962..fefb308 100644
--- a/linux/cicada/app/ui.py
+++ b/linux/cicada/app/ui.py
@@ -107,6 +107,11 @@ spinner { color: #6B7080; }
.endingstrip { background-color: #FDEEE8; border-radius: 12px; }
.notice { background-color: #F2F3F5; border-radius: 12px; }
dialog.endask { background-color: #FFFFFF; border: 1px solid #E4E6EA; border-radius: 12px; }
+/* The share dialog (ShareViews.swift): the review's hits on the accent's pale, the link and password on the fill. */
+.sharehit { background-color: #FCEDE7; border-radius: 8px; }
+.sharefield { background-color: #F2F3F5; border-radius: 6px; }
+dialog.sharesheet separator { background-color: #EEF0F3; min-height: 1px; }
+dialog.sharesheet entry.mono { font-family: "Ubuntu Sans Mono", monospace; }
.notice.error { background-color: #FDECEA; }
/* StatusLine (Views.swift): a service in trouble in one line on the plain fill; colour only in the dot. */
.statusline { background-color: #F2F3F5; border-radius: 10px; min-height: 36px; }
diff --git a/linux/cicada/core/ed25519.py b/linux/cicada/core/ed25519.py
new file mode 100644
index 0000000..96333bb
--- /dev/null
+++ b/linux/cicada/core/ed25519.py
@@ -0,0 +1,121 @@
+"""Ed25519 signatures (RFC 8032), for the share service's device key (share.py). Python's standard
+library has none, Ubuntu desktop's libsodium isn't always there, and the Mac's stub libcrypto
+aborts when loaded, so this is the RFC's reference algorithm in plain Python: extended twisted
+Edwards coordinates, a few milliseconds a signature. Not constant-time; the key only names this computer
+to the share service (rate limits, owning its links), and each link also needs its own token."""
+from __future__ import annotations
+
+import hashlib
+
+P = 2 ** 255 - 19
+L = 2 ** 252 + 27742317777372353535851937790883648493
+D = -121665 * pow(121666, P - 2, P) % P
+SQRT_M1 = pow(2, (P - 1) // 4, P)
+
+
+def _sha512(b: bytes) -> int:
+ return int.from_bytes(hashlib.sha512(b).digest(), "little")
+
+
+def _add(p, q):
+ x1, y1, z1, t1 = p
+ x2, y2, z2, t2 = q
+ a = (y1 - x1) * (y2 - x2) % P
+ b = (y1 + x1) * (y2 + x2) % P
+ c = 2 * t1 * t2 * D % P
+ d = 2 * z1 * z2 % P
+ e, f, g, h = b - a, d - c, d + c, b + a
+ return e * f % P, g * h % P, f * g % P, e * h % P
+
+
+def _mul(s: int, p):
+ q = (0, 1, 1, 0) # the neutral point
+ while s > 0:
+ if s & 1:
+ q = _add(q, p)
+ p = _add(p, p)
+ s >>= 1
+ return q
+
+
+def _equal(p, q) -> bool:
+ x1, y1, z1, _ = p
+ x2, y2, z2, _ = q
+ return (x1 * z2 - x2 * z1) % P == 0 and (y1 * z2 - y2 * z1) % P == 0
+
+
+def _recover_x(y: int, sign: int) -> int | None:
+ if y >= P:
+ return None
+ x2 = (y * y - 1) * pow(D * y * y + 1, P - 2, P)
+ if x2 == 0:
+ return None if sign else 0
+ x = pow(x2, (P + 3) // 8, P)
+ if (x * x - x2) % P != 0:
+ x = x * SQRT_M1 % P
+ if (x * x - x2) % P != 0:
+ return None
+ if (x & 1) != sign:
+ x = P - x
+ return x
+
+
+_GY = 4 * pow(5, P - 2, P) % P
+_GX = _recover_x(_GY, 0)
+G = (_GX, _GY, 1, _GX * _GY % P)
+
+
+def _compress(p) -> bytes:
+ x, y, z, _ = p
+ zi = pow(z, P - 2, P)
+ x, y = x * zi % P, y * zi % P
+ return int.to_bytes(y | ((x & 1) << 255), 32, "little")
+
+
+def _decompress(b: bytes):
+ if len(b) != 32:
+ return None
+ y = int.from_bytes(b, "little")
+ sign = y >> 255
+ y &= (1 << 255) - 1
+ x = _recover_x(y, sign)
+ return None if x is None else (x, y, 1, x * y % P)
+
+
+def _expand(seed: bytes):
+ if len(seed) != 32:
+ raise ValueError("an Ed25519 private key is 32 bytes")
+ h = hashlib.sha512(seed).digest()
+ a = int.from_bytes(h[:32], "little")
+ a &= (1 << 254) - 8
+ a |= 1 << 254
+ return a, h[32:]
+
+
+def public_key(seed: bytes) -> bytes:
+ a, _ = _expand(seed)
+ return _compress(_mul(a, G))
+
+
+def sign(seed: bytes, message: bytes) -> bytes:
+ a, prefix = _expand(seed)
+ pub = _compress(_mul(a, G))
+ r = _sha512(prefix + message) % L
+ big_r = _compress(_mul(r, G))
+ h = _sha512(big_r + pub + message) % L
+ s = (r + h * a) % L
+ return big_r + int.to_bytes(s, 32, "little")
+
+
+def verify(pub: bytes, message: bytes, signature: bytes) -> bool:
+ if len(pub) != 32 or len(signature) != 64:
+ return False
+ a = _decompress(pub)
+ r = _decompress(signature[:32])
+ if a is None or r is None:
+ return False
+ s = int.from_bytes(signature[32:], "little")
+ if s >= L:
+ return False
+ h = _sha512(signature[:32] + pub + message) % L
+ return _equal(_mul(s, G), _add(r, _mul(h, a)))
diff --git a/linux/cicada/core/share.py b/linux/cicada/core/share.py
new file mode 100644
index 0000000..83cb471
--- /dev/null
+++ b/linux/cicada/core/share.py
@@ -0,0 +1,515 @@
+"""A meeting shared as a link on cicada.indaloop.app: the Mac's ShareProjection.swift and
+ShareClient.swift. Three parts:
+
+- `doc`: the share document (v1), made from a record. Only whitelisted fields leave the computer:
+ never the record's file paths, Ling's guesses at names with the lines they came from, or its own
+ bookkeeping. Speakers are 说话人 N unless the user chose to show names. Same bytes as the Mac
+ (Tests/fixtures/share); the server (server/src/doc.js) reads exactly these fields.
+- `ShareStore`: what this computer keeps about each link (Shares/<record id>.json, 0600 in a 0700
+ folder): the manage token and password live only there, never in the record, exports or logs.
+- `ShareClient`: no accounts. This computer is an Ed25519 key made on first use (share-device.json,
+ 0600), registered once with a small proof of work; every write is signed (method, path, time,
+ nonce, body hash), as server/src/auth.js checks. Not an AI call, so not LingClient: the review
+ runs on the server."""
+from __future__ import annotations
+
+import base64
+import hashlib
+import json
+import math
+import os
+import secrets
+import time
+import urllib.error
+import urllib.request
+
+from . import ed25519, proxy, speakers
+from .models import iso_write
+from .strings import L, LF
+from .support import Log, Paths
+
+BASE = "https://cicada.indaloop.app"
+ITERATIONS = 210_000
+DAYS = (7, 30, 365)
+
+# The document
+
+
+def _round(t: float) -> float:
+ """One decimal, half away from zero (Swift's .rounded(), not Python's banker's round)."""
+ x = t * 10
+ r = math.floor(abs(x) + 0.5)
+ return math.copysign(r, x) / 10
+
+
+def _base(code: str) -> str:
+ return (code.split("-")[0] if code else "").lower()
+
+
+def languages(lines) -> list:
+ """The meeting's usual direction ("en" → "zh"), by the most lines; ties go to the earliest."""
+ count, first = {}, {}
+ for i, l in enumerate(lines):
+ if l.dst is None:
+ continue
+ key = _base(l.srcLang) + ">" + _base(l.dstLang)
+ count[key] = count.get(key, 0) + 1
+ first.setdefault(key, i)
+ if not count:
+ return []
+ top = max(count, key=lambda k: (count[k], -first[k]))
+ return top.split(">")
+
+
+def kept_lines(s, scope: str, removed=()) -> list:
+ """The record's line indices that go out, in order: what the server's line numbers count."""
+ if scope != "full":
+ return []
+ return [i for i, l in enumerate(s.lines) if i not in removed and l.src]
+
+
+def doc(s, scope: str, names: bool, removed=frozenset(), drop_notes: bool = False) -> dict:
+ """`removed`: indices into the record's lines the user took out; `drop_notes` leaves the notes out."""
+ from .session_store import display_title
+ nums = speakers.numbers(s.lines)
+ name_map = speakers.names(s) if names else {}
+
+ def who(l) -> str:
+ if l.speaker == "me":
+ return L("分享者")
+ n = nums.get(l.id)
+ if n is None:
+ return L("对方")
+ return speakers.label(n, name_map) if names else LF("说话人 %lld", n)
+
+ lines = []
+ for i in kept_lines(s, scope, removed):
+ l = s.lines[i]
+ line = {"t": _round(l.t), "who": who(l), "src": l.src}
+ if l.dst and l.dst != l.src:
+ line["dst"] = l.dst
+ lines.append(line)
+ notes = None
+ has_notes = s.notes is not None and not s.notes.is_empty
+ if not drop_notes and has_notes:
+ n = speakers.named(s.notes, name_map) if names else s.notes
+
+ def item(i, owner: bool) -> dict:
+ o = {"text": i.text}
+ if owner and i.owner is not None:
+ o["owner"] = i.owner
+ if i.t is not None:
+ o["t"] = _round(i.t)
+ return o
+ notes = {"summary": n.summary,
+ "topics": [{"start": _round(t.start), "title": t.title, "summary": t.summary, "points": list(t.points)}
+ for t in n.topics],
+ "conclusions": [item(c, False) for c in n.conclusions],
+ "todos": [item(t, names) for t in n.todos],
+ "terms": [{"name": t.name, "note": t.note} for t in n.terms] if names else []}
+ hidden = (len(removed) if scope == "full" else 0) + (1 if drop_notes and has_notes else 0)
+ out = {"v": 1, "title": display_title(s), "startedAt": iso_write(s.startedAt),
+ "duration": int(_round_whole(s.duration)), "langs": languages(s.lines), "lines": lines, "hidden": hidden}
+ if notes is not None:
+ out["notes"] = notes
+ return out
+
+
+def _round_whole(x: float) -> float:
+ return math.copysign(math.floor(abs(x) + 0.5), x)
+
+
+def _plain(v):
+ """Whole doubles as integers (605, not 605.0), as Swift's encoder writes them."""
+ if isinstance(v, float) and v == int(v) and abs(v) < 1e15:
+ return int(v)
+ if isinstance(v, dict):
+ return {k: _plain(x) for k, x in v.items()}
+ if isinstance(v, list):
+ return [_plain(x) for x in v]
+ return v
+
+
+def encode(d: dict) -> bytes:
+ """Compact, sorted keys, slashes and non-ASCII as they are: the Mac's [.sortedKeys, .withoutEscapingSlashes]."""
+ return json.dumps(_plain(d), sort_keys=True, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
+
+
+# Review hits
+
+
+def record_lines(hits: list, kept: list) -> set:
+ """The record's line indices behind the review's hits ({part, from, to, questions}), given which
+ record lines were sent (`kept`)."""
+ out = set()
+ for h in hits:
+ if h.get("part") != "lines":
+ continue
+ a, b = h.get("from"), h.get("to")
+ if not isinstance(a, int) or not isinstance(b, int) or a > b:
+ continue
+ for i in range(a, b + 1):
+ if 0 <= i < len(kept):
+ out.add(kept[i])
+ return out
+
+
+CATEGORIES = {"credential": "密码或密钥", "confidential": "未公开的公司信息", "crossborder": "不宜跨境传输的信息",
+ "personal": "个人身份信息", "harmful": "违法或危险内容"}
+
+
+def category(q: str) -> str:
+ return L(CATEGORIES[q]) if q in CATEGORIES else q
+
+
+def message(code: str) -> str:
+ """What a failed share says, by the server's code (ShareSheet.message)."""
+ if code in ("rate_limited", "too_many_shares"):
+ return L("分享得太频繁了,请稍后再试。")
+ return L({"review_unavailable": "敏感内容检查暂时不可用,没有检查就不会分享。请稍后再试。",
+ "sharing_off": "分享功能暂时关闭了。", "update_required": "请先更新知了。",
+ "too_large": "这场会议太长,可以只分享纪要。", "bad_document": "这场会议没有可分享的内容。",
+ "network": "连不上 cicada.indaloop.app,请检查网络。"}.get(code, "服务器出了问题,请稍后再试。"))
+
+
+# Passwords
+
+_WORDS = ("amber apple arrow aspen basil beach birch bloom brook cedar cherry cloud coral comet dawn delta dune ember fern "
+ "field flint frost grove harbor hazel honey iris island jade lake lark lemon lily linen maple meadow mint moss "
+ "olive orbit pearl pine plum pond quartz rain reed river ruby sage sand shell silk sky slate snow spruce stone "
+ "storm sun tide tulip velvet willow wind").split()
+
+
+def verifier(password: str, salt: bytes, iterations: int = ITERATIONS) -> bytes:
+ """PBKDF2-SHA256, 32 bytes: what the browser derives from the password (site/share.js). The
+ server keeps only its hash, so the password itself never leaves either side."""
+ return hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, iterations, 32)
+
+
+def make_password() -> str:
+ """"ruby-41-lake": easy to read out and type; the server limits how many can be tried."""
+ return "%s-%d-%s" % (secrets.choice(_WORDS), 10 + secrets.randbelow(90), secrets.choice(_WORDS))
+
+
+def b64url(b: bytes) -> str:
+ return base64.urlsafe_b64encode(b).decode().rstrip("=")
+
+
+def unb64(s: str) -> bytes:
+ return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))
+
+
+# Local storage
+
+
+def write_secret(path: str, data: bytes) -> bool:
+ """A file only this user can read, created 0600 from the start in a 0700 folder."""
+ try:
+ os.makedirs(os.path.dirname(path), mode=0o700, exist_ok=True)
+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
+ with os.fdopen(fd, "wb") as f:
+ f.write(data)
+ os.chmod(path, 0o600)
+ return True
+ except OSError as e:
+ Log.d("share: could not write %s (%s)" % (os.path.basename(path), type(e).__name__))
+ return False
+
+
+class ShareRecord:
+ """A link this computer made: `expiresAt` and `createdAt` are Unix seconds."""
+
+ def __init__(self, id: str, url: str, token: str, expiresAt: float, scope: str, password: str | None, createdAt: float):
+ self.id, self.url, self.token, self.expiresAt = id, url, token, expiresAt
+ self.scope, self.password, self.createdAt = scope, password, createdAt
+
+ def to_json(self) -> dict:
+ o = {"id": self.id, "url": self.url, "token": self.token, "expiresAt": iso_write(_utc(self.expiresAt)),
+ "scope": self.scope, "createdAt": iso_write(_utc(self.createdAt))}
+ if self.password is not None:
+ o["password"] = self.password
+ return o
+
+ @staticmethod
+ def from_json(o: dict) -> "ShareRecord | None":
+ from .models import iso_read
+ try:
+ exp, made = iso_read(o["expiresAt"]), iso_read(o.get("createdAt"))
+ return ShareRecord(o["id"], o["url"], o["token"], exp.timestamp(), o.get("scope") or "notes",
+ o.get("password"), made.timestamp() if made else exp.timestamp())
+ except (KeyError, TypeError, AttributeError):
+ return None
+
+ def days_left(self, now: float | None = None) -> int:
+ return max(1, math.ceil((self.expiresAt - (time.time() if now is None else now)) / 86400))
+
+
+def _utc(t: float):
+ from datetime import datetime, timezone
+ return datetime.fromtimestamp(t, timezone.utc)
+
+
+class ShareStore:
+ """Shares/<record id>.json, 0600 in a 0700 folder, beside the records' folder."""
+
+ @staticmethod
+ def folder() -> str:
+ return os.path.join(Paths.data(), "Shares")
+
+ @classmethod
+ def _path(cls, sid: str) -> str:
+ return os.path.join(cls.folder(), os.path.basename(sid) + ".json")
+
+ @classmethod
+ def read(cls, sid: str) -> ShareRecord | None:
+ try:
+ with open(cls._path(sid), encoding="utf-8") as f:
+ o = json.load(f)
+ except (OSError, ValueError):
+ return None
+ return ShareRecord.from_json(o) if isinstance(o, dict) else None
+
+ @classmethod
+ def save(cls, r: ShareRecord, sid: str) -> None:
+ write_secret(cls._path(sid), json.dumps(r.to_json(), sort_keys=True, ensure_ascii=False).encode("utf-8"))
+
+ @classmethod
+ def remove(cls, sid: str) -> None:
+ try:
+ os.remove(cls._path(sid))
+ except OSError:
+ pass
+
+ @classmethod
+ def all(cls) -> dict:
+ out = {}
+ try:
+ names = os.listdir(cls.folder())
+ except OSError:
+ return out
+ for n in names:
+ if n.endswith(".json"):
+ r = cls.read(n[:-5])
+ if r is not None:
+ out[n[:-5]] = r
+ return out
+
+
+# The client
+
+
+def proof_of_work(pub: bytes) -> bytes:
+ """20 leading zero bits of sha256(public key ‖ 8-byte big-endian nonce): about a million
+ hashes, a few seconds in Python. Run it off the main loop."""
+ head = hashlib.sha256(pub)
+ n = 0
+ while True:
+ nonce = n.to_bytes(8, "big")
+ h = head.copy()
+ h.update(nonce)
+ d = h.digest()
+ if d[0] == 0 and d[1] == 0 and d[2] < 16:
+ return nonce
+ n += 1
+
+
+class Failure(Exception):
+ def __init__(self, code: str, retry_after: int | None = None):
+ super().__init__(code)
+ self.code, self.retry_after = code, retry_after
+
+
+class Outcome:
+ """"shared" (record), "blocked" (hits, kept: the record lines sent) or "failed" (code)."""
+
+ def __init__(self, kind: str, record: ShareRecord | None = None, hits=None, kept=None, code: str | None = None,
+ retry_after: int | None = None):
+ self.kind, self.record, self.hits, self.kept, self.code, self.retry_after = kind, record, hits or [], kept or [], code, retry_after
+
+
+def _version() -> str:
+ try:
+ from .. import VERSION
+ return VERSION
+ except ImportError:
+ return "0.0.0"
+
+
+def http(method: str, url: str, body: bytes | None, headers: dict, timeout: float = 90) -> tuple:
+ """(status, body bytes) through this computer's proxy; a refused status is an answer, not an error."""
+ req = urllib.request.Request(url, data=body, method=method, headers=headers)
+ try:
+ with proxy.urlopen(req, timeout=timeout) as r:
+ return r.status, r.read()
+ except urllib.error.HTTPError as e:
+ try:
+ return e.code, e.read()
+ except OSError:
+ return e.code, b""
+ except (OSError, ValueError) as e:
+ raise Failure("network") from e
+
+
+def _code(data: bytes) -> str | None:
+ try:
+ o = json.loads(data.decode("utf-8"))
+ except (ValueError, UnicodeDecodeError):
+ return None
+ return o.get("code") if isinstance(o, dict) else None
+
+
+class Options:
+ def __init__(self, scope: str = "notes", days: int = 7, names: bool = False, password: str | None = None,
+ summary_in_preview: bool = False, removed=None, drop_notes: bool = False):
+ self.scope, self.days, self.names, self.password = scope, days, names, password
+ self.summary_in_preview, self.removed, self.drop_notes = summary_in_preview, set(removed or ()), drop_notes
+
+
+class ShareClient:
+ """Blocking calls: run them on a worker thread. `transport(method, url, body, headers)` →
+ (status, bytes); tests pass a fake. CICADA_SHARE_SERVER points a dev build at a local Worker."""
+
+ def __init__(self, transport=http, base: str | None = None, platform: str = "linux", version: str | None = None):
+ self.transport = transport
+ self.base = (base or os.environ.get("CICADA_SHARE_SERVER") or BASE).rstrip("/")
+ self.platform = platform
+ self.version = version or _version()
+
+ @staticmethod
+ def device_file() -> str:
+ return os.path.join(Paths.data(), "share-device.json")
+
+ def _load(self) -> tuple:
+ try:
+ with open(self.device_file(), encoding="utf-8") as f:
+ o = json.load(f)
+ seed = base64.b64decode(o["key"])
+ if len(seed) == 32:
+ return seed, o
+ except (OSError, ValueError, KeyError, TypeError):
+ pass
+ seed = secrets.token_bytes(32)
+ o = {"key": base64.b64encode(seed).decode()}
+ self._save(o)
+ return seed, o
+
+ def _save(self, o: dict) -> None:
+ write_secret(self.device_file(), json.dumps(o, sort_keys=True).encode())
+
+ def device(self, force: bool = False) -> tuple:
+ """(private key seed, device id), registering this computer with the server first if needed."""
+ seed, o = self._load()
+ if not force and o.get("device") and o.get("server") == self.base:
+ return seed, o["device"]
+ pub = ed25519.public_key(seed)
+ nonce = proof_of_work(pub)
+ body = json.dumps({"key": b64url(pub), "pow": b64url(nonce), "platform": self.platform,
+ "version": self.version}).encode()
+ status, data = self._send("POST", "/api/v1/devices", body, {}, None)
+ try:
+ device = json.loads(data.decode())["device"] if status == 201 else None
+ except (ValueError, KeyError, TypeError, UnicodeDecodeError):
+ device = None
+ if not isinstance(device, str):
+ Log.d("share: register failed %d %s" % (status, _code(data) or "?"))
+ raise Failure(_code(data) or "register_failed")
+ o["device"], o["server"] = device, self.base
+ self._save(o)
+ Log.d("share: registered this computer")
+ return seed, device
+
+ def _send(self, method: str, path: str, body: bytes | None, headers: dict, signer) -> tuple:
+ h = {"Content-Type": "application/json", "X-Cicada-Client": "%s/%s" % (self.platform, self.version),
+ "User-Agent": "Cicada-Linux", **headers}
+ if signer is not None:
+ seed, device = signer
+ t = str(int(time.time()))
+ nonce = b64url(secrets.token_bytes(16))
+ digest = hashlib.sha256(body or b"").hexdigest()
+ msg = "%s\n%s\n%s\n%s\n%s" % (method, path, t, nonce, digest)
+ h.update({"X-Cicada-Device": device, "X-Cicada-Time": t, "X-Cicada-Nonce": nonce,
+ "X-Cicada-Signature": b64url(ed25519.sign(seed, msg.encode("utf-8")))})
+ return self.transport(method, self.base + path, body, h)
+
+ def signed(self, method: str, path: str, body: bytes | None = None, headers: dict | None = None) -> tuple:
+ """A signed call; registers again once if the server no longer knows this computer."""
+ signer = self.device()
+ status, data = self._send(method, path, body, headers or {}, signer)
+ if status == 401 and _code(data) == "unknown_device":
+ signer = self.device(force=True)
+ status, data = self._send(method, path, body, headers or {}, signer)
+ return status, data
+
+ def share(self, s, o: Options) -> Outcome:
+ d = doc(s, o.scope, o.names, o.removed, o.drop_notes)
+ kept = kept_lines(s, o.scope, o.removed)
+ body = {"doc": d, "scope": o.scope, "days": o.days, "summaryInPreview": o.summary_in_preview}
+ if o.password:
+ salt = secrets.token_bytes(16)
+ v = verifier(o.password, salt)
+ body["password"] = {"salt": b64url(salt), "iter": ITERATIONS, "hash": b64url(hashlib.sha256(v).digest())}
+ data = json.dumps(_plain(body), ensure_ascii=False, separators=(",", ":")).encode("utf-8")
+ # The same meeting, content and settings sent again (the answer was lost) gets the same link
+ # back; any other setting makes a new share.
+ settings = "%s|%d|%s|%s|%s" % (o.scope, o.days, _b(o.names), o.password or "", _b(o.summary_in_preview))
+ idem = s.id + "-" + hashlib.sha256(encode(d) + settings.encode("utf-8")).digest()[:8].hex()
+ try:
+ status, out = self.signed("POST", "/api/v1/shares", data, {"Idempotency-Key": idem})
+ except Failure as f:
+ return Outcome("failed", code=f.code, retry_after=f.retry_after)
+ try:
+ obj = json.loads(out.decode("utf-8"))
+ except (ValueError, UnicodeDecodeError):
+ obj = {}
+ if not isinstance(obj, dict):
+ obj = {}
+ if status in (200, 201):
+ try:
+ r = ShareRecord(obj["id"], obj["url"], obj["token"], float(obj["expiresAt"]), o.scope, o.password, time.time())
+ except (KeyError, TypeError, ValueError):
+ return Outcome("failed", code="server_error")
+ old = ShareStore.read(s.id)
+ if old is not None and old.id != r.id:
+ self.revoke(old, None)
+ ShareStore.save(r, s.id)
+ Log.d("share: %s shared (%s, %d days%s)" % (s.id, o.scope, o.days, ", password" if o.password else ""))
+ return Outcome("shared", record=r)
+ if status == 422:
+ hits = [h for h in obj.get("hits") or [] if isinstance(h, dict)]
+ Log.d("share: %s blocked %s" % (s.id, "; ".join(
+ "%s%s %s" % (h.get("part"), " %s-%s" % (h.get("from"), h.get("to")) if h.get("from") is not None else "",
+ ",".join(h.get("questions") or [])) for h in hits)))
+ return Outcome("blocked", hits=hits, kept=kept)
+ Log.d("share: %s failed %d %s" % (s.id, status, obj.get("code") or "?"))
+ return Outcome("failed", code=obj.get("code") or "server_error",
+ retry_after=obj.get("retryAfter") if isinstance(obj.get("retryAfter"), int) else None)
+
+ def revoke(self, r: ShareRecord, sid: str | None) -> bool:
+ """Turns the link off on the server and forgets it here. `sid` None: the record is being replaced."""
+ try:
+ status, data = self.signed("DELETE", "/api/v1/shares/" + r.id, None, {"Authorization": "Bearer " + r.token})
+ except Failure:
+ return False
+ # 404: already gone (or never ours); either way nothing to keep.
+ ok = status in (204, 404)
+ if not ok:
+ Log.d("share: revoke failed %d %s" % (status, _code(data) or "?"))
+ if ok and sid:
+ ShareStore.remove(sid)
+ return ok
+
+ def stats(self, ids: list) -> dict:
+ """id → {id, expiresAt, state, views} for this computer's links among `ids`."""
+ if not ids:
+ return {}
+ try:
+ status, data = self.signed("GET", "/api/v1/shares?ids=" + ",".join(ids))
+ if status != 200:
+ return {}
+ return {x["id"]: x for x in json.loads(data.decode("utf-8")).get("shares", []) if isinstance(x, dict)}
+ except (Failure, ValueError, KeyError, AttributeError, UnicodeDecodeError):
+ return {}
+
+
+def _b(v: bool) -> str:
+ return "true" if v else "false"
diff --git a/linux/scripts/cicadactl b/linux/scripts/cicadactl
index 62e7e8c..cabf523 100755
--- a/linux/scripts/cicadactl
+++ b/linux/scripts/cicadactl
@@ -8,6 +8,7 @@
fixes on|off | heard <text> | fix-state | fix-answer yes|no | fix-later | fix-revert <line> | fix-undo
fix-edit <line>=<text>[|one][|keep0] | fix-editor <line>=<text> | vocab-add <word>=<heard>[|…] | vocab-state
word-list [import <text>|edit <word>|heard <word>=<form>|delete <word>] (改正听错的词, debug.py › _fixes)
+ share <id>[,full][,pw] | unshare <id> | share-last | shareSheet <id>|"" | share-ui <action> (分享…, debug.py › _share)
Run it inside the Linux session (linux/vm/vmctl.sh ssh does that for the test VM)."""
import os
import socket
diff --git a/linux/tests/test_share.py b/linux/tests/test_share.py
new file mode 100644
index 0000000..aea74dc
--- /dev/null
+++ b/linux/tests/test_share.py
@@ -0,0 +1,225 @@
+"""分享…: the share document is a contract with the server (server/src/doc.js) and the Mac, so the
+same record must give the same bytes (Tests/fixtures/share); plus the password, the Ed25519
+signatures (RFC 8032) and the client against a fake server (never the real one: production limits
+how many devices an address may register)."""
+from __future__ import annotations
+
+import hashlib
+import json
+import os
+import shutil
+import stat
+import sys
+import tempfile
+import unittest
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+sys.path.insert(0, os.path.dirname(HERE))
+REPO = os.path.dirname(os.path.dirname(HERE))
+FIXTURES = os.path.join(REPO, "Tests", "fixtures", "share")
+
+from cicada.core import ed25519, share, strings # noqa: E402
+from cicada.core.models import Session, TranscriptLine # noqa: E402
+from cicada.core.support import Paths # noqa: E402
+
+
+def session() -> Session:
+ with open(os.path.join(FIXTURES, "session.json"), encoding="utf-8") as f:
+ return Session.read(f.read())
+
+
+class ShareDocTests(unittest.TestCase):
+ def setUp(self):
+ # Other suites switch the UI language; the document's speaker words follow it.
+ strings.load("zh-Hans", [os.path.join(REPO, "Resources")])
+
+ def test_fixture_bytes(self):
+ with open(os.path.join(FIXTURES, "share-doc.json"), encoding="utf-8") as f:
+ want = f.read().strip()
+ self.assertEqual(want, share.encode(share.doc(session(), "full", False)).decode("utf-8"))
+
+ def test_nothing_private_leaves(self):
+ text = share.encode(share.doc(session(), "full", False)).decode("utf-8")
+ for secret in ["/Users/someone", "Emma", "Kenji", "Emmer", "Sure, Emma", "hasAudio", "room", "voice"]:
+ self.assertNotIn(secret, text)
+
+ def test_names_when_asked(self):
+ d = share.doc(session(), "full", True)
+ self.assertEqual("Emma", d["notes"]["todos"][0]["owner"])
+ self.assertEqual("Emma", d["notes"]["terms"][0]["name"])
+ self.assertNotIn("owner", d["notes"]["conclusions"][0])
+
+ def test_notes_only_and_removed(self):
+ s = session()
+ self.assertEqual([], share.doc(s, "notes", False)["lines"])
+ d = share.doc(s, "full", False, removed={3}, drop_notes=True)
+ self.assertEqual(3, len(d["lines"]))
+ self.assertNotIn("notes", d)
+ self.assertEqual(2, d["hidden"])
+
+ def test_speaker_numbers_without_names(self):
+ s = session()
+ # Two voices with five substantive lines each get numbers; their names stay out.
+ s.lines = [TranscriptLine(id="v%d" % i, t=float(i), speaker="them", src="this is line number %d" % i,
+ dst="第 %d 句话" % i, srcLang="en", dstLang="zh", voice=3 if i % 2 == 0 else 7)
+ for i in range(10)]
+ self.assertEqual({"说话人 1", "说话人 2"}, {l["who"] for l in share.doc(s, "full", False)["lines"]})
+ self.assertEqual({"Emma", "Kenji"}, {l["who"] for l in share.doc(s, "full", True)["lines"]})
+
+ def test_rounding_and_numbers(self):
+ s = session()
+ s.lines[0].t = 0.25 # half away from zero, as Swift rounds: 0.3, not Python's 0.2
+ s.lines[1].dst = s.lines[1].src
+ d = share.doc(s, "full", False)
+ self.assertEqual(0.3, d["lines"][0]["t"])
+ self.assertNotIn("dst", d["lines"][1])
+ self.assertIn(b'"t":605,', share.encode(share.doc(session(), "full", False)))
+
+ def test_languages_by_most_lines(self):
+ self.assertEqual(["en", "zh"], share.languages(session().lines))
+ self.assertEqual([], share.languages([]))
+
+ def test_password(self):
+ salt = bytes([1] * 16)
+ # Same as the browser's crypto.subtle PBKDF2-SHA256, 32 bytes (server/test/api.test.mjs).
+ v = share.verifier("ruby-41-lake", salt, 1000)
+ self.assertEqual("eab69fcd00a0517794c156495dd76ad1fbfb036ea03df3d59a68a33519009c81", v.hex())
+ self.assertNotEqual(v, share.verifier("ruby-41-laka", salt, 1000))
+ self.assertEqual(3, len(share.make_password().split("-")))
+
+ def test_blocked_hits_map_back(self):
+ # The server counts lines of what was sent; the app maps them back to the record.
+ hits = [{"part": "lines", "from": 2, "to": 3, "questions": ["credential"]}, {"part": "notes", "questions": []}]
+ self.assertEqual({4, 5}, share.record_lines(hits, [0, 1, 4, 5, 6]))
+
+ def test_messages(self):
+ self.assertEqual("密码或密钥", share.category("credential"))
+ self.assertEqual("分享得太频繁了,请稍后再试。", share.message("too_many_shares"))
+ self.assertEqual("服务器出了问题,请稍后再试。", share.message("whatever"))
+
+
+class Ed25519Tests(unittest.TestCase):
+ # RFC 8032 §7.1, tests 1–3: secret key, public key, message, signature.
+ VECTORS = [
+ ("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60",
+ "d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a", "",
+ "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b"),
+ ("4ccd089b28ff96da9db6c346ec114e0f5b8a319f35aba624da8cf6ed4fb8a6fb",
+ "3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c", "72",
+ "92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00"),
+ ("c5aa8df43f9f837bedb7442f31dcb7b166d38535076f094b85ce3a2e0b4458f7",
+ "fc51cd8e6218a1a38da47ed00230f0580816ed13ba3303ac5deb911548908025", "af82",
+ "6291d657deec24024827e69c3abe01a30ce548a284743a445e3680d7db5ac3ac18ff9b538d16f290ae67f760984dc6594a7c15e9716ed28dc027beceea1ec40a"),
+ ]
+
+ def test_rfc8032_vectors(self):
+ for sk, pk, msg, sig in self.VECTORS:
+ seed, m = bytes.fromhex(sk), bytes.fromhex(msg)
+ self.assertEqual(pk, ed25519.public_key(seed).hex())
+ self.assertEqual(sig, ed25519.sign(seed, m).hex())
+ self.assertTrue(ed25519.verify(bytes.fromhex(pk), m, bytes.fromhex(sig)))
+ self.assertFalse(ed25519.verify(bytes.fromhex(pk), m + b"x", bytes.fromhex(sig)))
+
+
+class FakeServer:
+ """server/src's contract in miniature: registration with proof of work, signed requests."""
+
+ def __init__(self):
+ self.keys = {}
+ self.calls = []
+ self.forget = False
+ self.reply = None
+
+ def __call__(self, method, url, body, headers):
+ path = url.split("cicada.test", 1)[1]
+ self.calls.append((method, path, headers))
+ if path == "/api/v1/devices":
+ o = json.loads(body)
+ pub, nonce = share.unb64(o["key"]), share.unb64(o["pow"])
+ d = hashlib.sha256(pub + nonce).digest()
+ assert d[0] == 0 and d[1] == 0 and d[2] < 16, "bad proof"
+ assert o["platform"] == "linux"
+ dev = hashlib.sha256(pub).digest()[:16].hex()
+ self.keys[dev] = pub
+ return 201, json.dumps({"device": dev}).encode()
+ assert headers["X-Cicada-Client"].startswith("linux/")
+ dev = headers.get("X-Cicada-Device")
+ if self.forget:
+ self.forget = False
+ self.keys.clear()
+ if dev not in self.keys:
+ return 401, b'{"code":"unknown_device"}'
+ msg = "%s\n%s\n%s\n%s\n%s" % (method, path, headers["X-Cicada-Time"], headers["X-Cicada-Nonce"],
+ hashlib.sha256(body or b"").hexdigest())
+ if not ed25519.verify(self.keys[dev], msg.encode(), share.unb64(headers["X-Cicada-Signature"])):
+ return 401, b'{"code":"bad_signature"}'
+ if self.reply is not None:
+ return self.reply
+ if method == "POST":
+ return 201, json.dumps({"id": "A" * 22, "url": "https://cicada.test/s/" + "A" * 22, "token": "tok",
+ "expiresAt": 1900000000}).encode()
+ if method == "DELETE":
+ return 204, b""
+ return 200, b'{"shares":[]}'
+
+
+class ShareClientTests(unittest.TestCase):
+ def setUp(self):
+ strings.load("zh-Hans", [os.path.join(REPO, "Resources")])
+ self.dir = tempfile.mkdtemp()
+ Paths.home_override = self.dir
+ self.server = FakeServer()
+ self.client = share.ShareClient(transport=self.server, base="https://cicada.test", version="1.5.1")
+
+ def tearDown(self):
+ Paths.home_override = None
+ shutil.rmtree(self.dir, ignore_errors=True)
+
+ def test_registers_once_signs_and_keeps_secrets_private(self):
+ s = session()
+ out = self.client.share(s, share.Options(scope="full", password="ruby-41-lake"))
+ self.assertEqual("shared", out.kind)
+ out = self.client.share(s, share.Options(scope="notes"))
+ self.assertEqual(1, sum(1 for c in self.server.calls if c[1] == "/api/v1/devices"))
+ for f in (share.ShareClient.device_file(), os.path.join(share.ShareStore.folder(), s.id + ".json")):
+ self.assertEqual(0o600, stat.S_IMODE(os.stat(f).st_mode))
+ self.assertEqual(0o700, stat.S_IMODE(os.stat(share.ShareStore.folder()).st_mode))
+ r = share.ShareStore.read(s.id)
+ self.assertEqual(("A" * 22, "tok", 1900000000), (r.id, r.token, r.expiresAt))
+ post = [c for c in self.server.calls if c[0] == "POST" and c[1] == "/api/v1/shares"][0]
+ self.assertTrue(post[2]["Idempotency-Key"].startswith(s.id + "-"))
+
+ def test_registers_again_when_forgotten(self):
+ self.client.share(session(), share.Options())
+ self.server.forget = True
+ self.assertEqual("shared", self.client.share(session(), share.Options()).kind)
+ self.assertEqual(2, sum(1 for c in self.server.calls if c[1] == "/api/v1/devices"))
+
+ def test_blocked_and_failed(self):
+ s = session()
+ self.server.reply = (422, b'{"code":"blocked","hits":[{"part":"lines","from":1,"to":1,"questions":["credential"]}]}')
+ out = self.client.share(s, share.Options(scope="full"))
+ self.assertEqual("blocked", out.kind)
+ self.assertEqual({1}, share.record_lines(out.hits, out.kept))
+ self.assertIsNone(share.ShareStore.read(s.id))
+ self.server.reply = (429, b'{"code":"rate_limited","retryAfter":30}')
+ out = self.client.share(s, share.Options())
+ self.assertEqual(("failed", "rate_limited", 30), (out.kind, out.code, out.retry_after))
+
+ def test_revoke_forgets(self):
+ s = session()
+ r = self.client.share(s, share.Options()).record
+ self.assertTrue(self.client.revoke(r, s.id))
+ self.assertIsNone(share.ShareStore.read(s.id))
+ delete = [c for c in self.server.calls if c[0] == "DELETE"][0]
+ self.assertEqual("Bearer tok", delete[2]["Authorization"])
+
+ def test_network_failure(self):
+ def down(*_):
+ raise share.Failure("network")
+ c = share.ShareClient(transport=down, base="https://cicada.test")
+ self.assertEqual("network", c.share(session(), share.Options()).code)
+
+
+if __name__ == "__main__":
+ unittest.main()