知了 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
feat: share a meeting as a link (Share…), checked for keys and other sensitive content before upload
wquguru062f20fd2725
diff --git a/README.en.md b/README.en.mdindex e2135a6..8de9a51 100644--- a/README.en.md+++ b/README.en.md@@ -68,7 +68,7 @@ Hold the right `⌥` key and speak so the other side hears your translated voice### Meeting records-Bilingual transcripts, notes, and raw audio recordings are saved on your computer. Click any line to play the recording from that point. The bundled on-device voiceprint model automatically separates different speakers (and fills in their names when a Ling key is set), and you can rename or merge them anytime if it gets someone wrong. After a meeting, you can generate notes retroactively or export to Markdown, Word, or SRT subtitles. You can also turn local audio or video files into bilingual records via **File › Import Recording or Video…**. Right now "you" in the record only covers what you say while holding the talk key; capturing what you say directly in the meeting is on the [roadmap](#roadmap).+Bilingual transcripts, notes, and raw audio recordings are saved on your computer. Click any line to play the recording from that point. The bundled on-device voiceprint model automatically separates different speakers (and fills in their names when a Ling key is set), and you can rename or merge them anytime if it gets someone wrong. After a meeting, you can generate notes retroactively or export to Markdown, Word, or SRT subtitles. **Share…** turns the notes (and, if you like, the bilingual transcript) into a link with an expiry and an optional password; before anything is uploaded it is checked for keys, unpublished company information and other sensitive content, and held back if any is found. You can also turn local audio or video files into bilingual records via **File › Import Recording or Video…**. Right now "you" in the record only covers what you say while holding the talk key; capturing what you say directly in the meeting is on the [roadmap](#roadmap).<p align="center"><img src="docs/records.png" width="640" alt="Meeting records window showing identified speakers and a line-by-line English and Chinese transcript">diff --git a/README.ja.md b/README.ja.mdindex 46b070a..ff04ad0 100644--- a/README.ja.md+++ b/README.ja.md@@ -68,7 +68,7 @@ AI サービスをつなぐと、聞き間違えた人名や用語をその場### 会議の記録-二か国語の記録、メモ、元の録音はすべて端末内に保存されます。任意の文をクリックするとその位置から録音を再生でき、端末内の声紋モデルが話者を自動で区別します(Ling キーがあれば名前も補完)。間違っていればいつでも名前の変更や統合ができます。会議後にメモを追加生成したり、Markdown、Word、SRT 字幕にエクスポートしたりすることも可能です。「ファイル › 録音・動画を読み込む…」から手元の音声や動画を素早く二か国語の記録に変換することもできます。現在、記録内の「あなた」に含まれるのは話すキーを押して話した内容のみで、会議でそのまま話した分については[ロードマップ](#ロードマップ)をご覧ください。+二か国語の記録、メモ、元の録音はすべて端末内に保存されます。任意の文をクリックするとその位置から録音を再生でき、端末内の声紋モデルが話者を自動で区別します(Ling キーがあれば名前も補完)。間違っていればいつでも名前の変更や統合ができます。会議後にメモを追加生成したり、Markdown、Word、SRT 字幕にエクスポートしたりすることも可能です。「共有…」でメモ(希望すればバイリンガル全文も)を有効期限とパスワード付きのリンクにでき、アップロード前にキーや未公開の社内情報などの機密内容がないかチェックし、見つかれば止めます。「ファイル › 録音・動画を読み込む…」から手元の音声や動画を素早く二か国語の記録に変換することもできます。現在、記録内の「あなた」に含まれるのは話すキーを押して話した内容のみで、会議でそのまま話した分については[ロードマップ](#ロードマップ)をご覧ください。<p align="center"><img src="docs/records.png" width="640" alt="識別された話者と、1 行ずつの英語と中国語の書き起こしを表示した会議の記録のウィンドウ">diff --git a/README.ko.md b/README.ko.mdindex 549a2b3..a41a05d 100644--- a/README.ko.md+++ b/README.ko.md@@ -68,7 +68,7 @@ AI 서비스를 연결하면 잘못 들은 인명과 용어를 그 자리에서### 회의 기록-이중 언어 기록, 회의록, 원본 녹음은 모두 기기에 저장됩니다. 아무 문장이나 클릭하면 그 위치부터 녹음을 다시 들을 수 있고, 기기 내 성문 모델이 화자를 자동으로 구분하며(Ling 키가 있으면 이름도 채움), 잘못 구분되면 언제든 이름을 바꾸거나 합칠 수 있습니다. 회의 후 회의록을 추가로 생성하거나 Markdown, Word, SRT 자막으로 내보낼 수 있습니다. "파일 › 녹음 또는 동영상 가져오기…"로 로컬 오디오·비디오를 이중 언어 기록으로 빠르게 변환할 수도 있습니다. 현재 기록에 남는 내 발언은 말하기 키를 누르고 말한 내용뿐이며, 회의에서 바로 말한 부분은 [로드맵](#로드맵)을 참고하세요.+이중 언어 기록, 회의록, 원본 녹음은 모두 기기에 저장됩니다. 아무 문장이나 클릭하면 그 위치부터 녹음을 다시 들을 수 있고, 기기 내 성문 모델이 화자를 자동으로 구분하며(Ling 키가 있으면 이름도 채움), 잘못 구분되면 언제든 이름을 바꾸거나 합칠 수 있습니다. 회의 후 회의록을 추가로 생성하거나 Markdown, Word, SRT 자막으로 내보낼 수 있습니다. "공유…"로 회의록(원하면 이중 언어 전문까지)을 유효 기간과 비밀번호를 정한 링크로 만들 수 있으며, 업로드 전에 키나 공개되지 않은 회사 정보 같은 민감한 내용이 있는지 확인하고 있으면 막습니다. "파일 › 녹음 또는 동영상 가져오기…"로 로컬 오디오·비디오를 이중 언어 기록으로 빠르게 변환할 수도 있습니다. 현재 기록에 남는 내 발언은 말하기 키를 누르고 말한 내용뿐이며, 회의에서 바로 말한 부분은 [로드맵](#로드맵)을 참고하세요.<p align="center"><img src="docs/records.png" width="640" alt="구분된 화자 이름과 문장별 영중 이중 언어 기록이 표시된 회의 기록 창">diff --git a/README.md b/README.mdindex 0f67574..5c77ea6 100644--- a/README.md+++ b/README.md@@ -68,7 +68,7 @@### 会议记录-双语记录、纪要和原始录音都存在本机。点任意一句就能从那儿回放录音,本机声纹模型会自动区分不同说话人(填了 Ling key 会填上名字),认错了随时改名或合并。会后支持补生成纪要,或导出 Markdown、Word 和 SRT 字幕。你也可以通过“文件 › 导入录音或视频…”把本地音视频快速转成双语记录。目前记录里的你只包含按住说话键说的话,会上直接开口的部分见[路线图](#路线图)。+双语记录、纪要和原始录音都存在本机。点任意一句就能从那儿回放录音,本机声纹模型会自动区分不同说话人(填了 Ling key 会填上名字),认错了随时改名或合并。会后支持补生成纪要,或导出 Markdown、Word 和 SRT 字幕。点“分享…”可以把纪要(也可以带上双语全文)发成一个链接,能设有效期和密码;上传前会先检查有没有密钥、未公开的公司信息这类敏感内容,有就先拦下。你也可以通过“文件 › 导入录音或视频…”把本地音视频快速转成双语记录。目前记录里的你只包含按住说话键说的话,会上直接开口的部分见[路线图](#路线图)。<p align="center"><img src="docs/records.png" width="640" alt="会议记录窗口,显示识别出的说话人名字和逐句英中双语文字记录">diff --git a/Resources/en.lproj/Localizable.strings b/Resources/en.lproj/Localizable.stringsindex b735ba0..435d594 100644--- a/Resources/en.lproj/Localizable.strings+++ b/Resources/en.lproj/Localizable.strings@@ -1323,3 +1323,55 @@"导入 %lld 个" = "Import %lld";/* Notes: a to-do's owner after it */"待办的负责人 %@" = " (%@)";++/* Share a meeting as a link (ShareViews, ShareProjection) */+"分享者" = "Sharer";+"分享这场会议" = "Share this meeting";+"有效期" = "Expires after";+"显示说话人名字" = "Show speaker names";+"用密码保护" = "Protect with a password";+"预览卡显示摘要" = "Show the summary in link previews";+"建议把链接和密码分两条消息发送。" = "Send the link and the password in separate messages.";+"内容将上传至 cicada.indaloop.app,拿到链接的人都能看。" = "It will be uploaded to cicada.indaloop.app. Anyone with the link can read it.";+"内容" = "Content";+"只分享纪要" = "Notes only";+"纪要和双语全文" = "Notes and full bilingual transcript";+"7 天" = "7 days";+"30 天" = "30 days";+"1 年" = "1 year";+"换一个" = "New one";+"生成链接" = "Create link";+"分享得太频繁了,请稍后再试。" = "Too many shares just now. Try again later.";+"敏感内容检查暂时不可用,没有检查就不会分享。请稍后再试。" = "The check for sensitive content is unavailable right now, and nothing is shared unchecked. Try again later.";+"分享功能暂时关闭了。" = "Sharing is turned off for now.";+"请先更新知了。" = "Update Cicada first.";+"这场会议太长,可以只分享纪要。" = "This meeting is too long. You can share just the notes.";+"连不上 cicada.indaloop.app,请检查网络。" = "Can't reach cicada.indaloop.app. Check your connection.";+"服务器出了问题,请稍后再试。" = "Something went wrong on the server. Try again later.";+"正在检查有没有敏感内容…" = "Checking for sensitive content…";+"链接尚未生成。请先核对以下内容:" = "No link yet. Check these first:";+"去掉后再检查一次;你的记录不会改动。" = "They'll be left out and checked again. Your record stays as it is.";+"检测到潜在敏感内容" = "Possibly sensitive content found";+"返回修改" = "Go back";+"去掉这些内容后分享" = "Leave these out and share";+"密码或密钥" = "Password or key";+"未公开的公司信息" = "Unpublished company information";+"不宜跨境传输的信息" = "Information not to send across borders";+"个人身份信息" = "Personal identity data";+"违法或危险内容" = "Illegal or dangerous content";+"链接已复制" = "Link copied";+"已分享" = "Shared";+"复制链接" = "Copy link";+"复制密码" = "Copy password";+"%lld 天后失效" = "Expires in %lld days";+"打开 %lld 次" = "Opened %lld times";+"取消后链接立即失效" = "The link stops working right away";+"已查看过的人可能留有副本。" = "People who already opened it may have kept a copy.";+"暂不取消" = "Keep it";+"取消分享" = "Stop sharing";+"在浏览器中打开" = "Open in browser";+"没有分享出去" = "Not shared";+"分享…" = "Share…";+"去掉这些内容后就没有可分享的了。" = "Nothing would be left to share without these.";+"这场会议没有可分享的内容。" = "This meeting has nothing to share.";+"还有 %lld 处" = "And %lld more";diff --git a/Resources/ja.lproj/Localizable.strings b/Resources/ja.lproj/Localizable.stringsindex 0c65fa2..b47147e 100644--- a/Resources/ja.lproj/Localizable.strings+++ b/Resources/ja.lproj/Localizable.strings@@ -1323,3 +1323,55 @@"导入 %lld 个" = "%lld 個を追加";/* Notes: a to-do's owner after it */"待办的负责人 %@" = "(%@)";++/* Share a meeting as a link (ShareViews, ShareProjection) */+"分享者" = "共有者";+"分享这场会议" = "この会議を共有";+"有效期" = "有効期間";+"显示说话人名字" = "話者名を表示";+"用密码保护" = "パスワードで保護";+"预览卡显示摘要" = "リンクプレビューに要約を表示";+"建议把链接和密码分两条消息发送。" = "リンクとパスワードは別々のメッセージで送ってください。";+"内容将上传至 cicada.indaloop.app,拿到链接的人都能看。" = "cicada.indaloop.app にアップロードされ、リンクを知っている人は誰でも読めます。";+"内容" = "内容";+"只分享纪要" = "議事録のみ";+"纪要和双语全文" = "議事録とバイリンガル全文";+"7 天" = "7 日";+"30 天" = "30 日";+"1 年" = "1 年";+"换一个" = "別のもの";+"生成链接" = "リンクを作成";+"分享得太频繁了,请稍后再试。" = "共有が多すぎます。しばらくしてからもう一度お試しください。";+"敏感内容检查暂时不可用,没有检查就不会分享。请稍后再试。" = "機密内容のチェックが一時的に使えません。チェックなしでは共有しません。しばらくしてからもう一度お試しください。";+"分享功能暂时关闭了。" = "共有は現在停止しています。";+"请先更新知了。" = "先に Cicada をアップデートしてください。";+"这场会议太长,可以只分享纪要。" = "この会議は長すぎます。議事録だけなら共有できます。";+"连不上 cicada.indaloop.app,请检查网络。" = "cicada.indaloop.app に接続できません。ネットワークを確認してください。";+"服务器出了问题,请稍后再试。" = "サーバーで問題が起きました。しばらくしてからもう一度お試しください。";+"正在检查有没有敏感内容…" = "機密内容をチェックしています…";+"链接尚未生成。请先核对以下内容:" = "リンクはまだ作成されていません。まず次を確認してください:";+"去掉后再检查一次;你的记录不会改动。" = "除外してもう一度チェックします。記録は変わりません。";+"检测到潜在敏感内容" = "機密の可能性がある内容が見つかりました";+"返回修改" = "戻って変更";+"去掉这些内容后分享" = "これらを除いて共有";+"密码或密钥" = "パスワードまたはキー";+"未公开的公司信息" = "未公開の社内情報";+"不宜跨境传输的信息" = "国外に出すべきでない情報";+"个人身份信息" = "個人を特定する情報";+"违法或危险内容" = "違法または危険な内容";+"链接已复制" = "リンクをコピーしました";+"已分享" = "共有済み";+"复制链接" = "リンクをコピー";+"复制密码" = "パスワードをコピー";+"%lld 天后失效" = "%lld 日後に失効";+"打开 %lld 次" = "%lld 回開かれました";+"取消后链接立即失效" = "取り消すとリンクはすぐに無効になります";+"已查看过的人可能留有副本。" = "すでに見た人はコピーを持っているかもしれません。";+"暂不取消" = "取り消さない";+"取消分享" = "共有をやめる";+"在浏览器中打开" = "ブラウザで開く";+"没有分享出去" = "共有されませんでした";+"分享…" = "共有…";+"去掉这些内容后就没有可分享的了。" = "これらを除くと共有できるものが残りません。";+"这场会议没有可分享的内容。" = "この会議には共有できる内容がありません。";+"还有 %lld 处" = "ほか %lld か所";diff --git a/Resources/ko.lproj/Localizable.strings b/Resources/ko.lproj/Localizable.stringsindex e7e86b5..cabe7eb 100644--- a/Resources/ko.lproj/Localizable.strings+++ b/Resources/ko.lproj/Localizable.strings@@ -1323,3 +1323,55 @@"导入 %lld 个" = "%lld개 가져오기";/* Notes: a to-do's owner after it */"待办的负责人 %@" = " (%@)";++/* Share a meeting as a link (ShareViews, ShareProjection) */+"分享者" = "공유자";+"分享这场会议" = "이 회의 공유";+"有效期" = "유효 기간";+"显示说话人名字" = "화자 이름 표시";+"用密码保护" = "비밀번호로 보호";+"预览卡显示摘要" = "링크 미리보기에 요약 표시";+"建议把链接和密码分两条消息发送。" = "링크와 비밀번호는 따로 보내세요.";+"内容将上传至 cicada.indaloop.app,拿到链接的人都能看。" = "cicada.indaloop.app에 업로드되며 링크가 있는 사람은 누구나 볼 수 있습니다.";+"内容" = "내용";+"只分享纪要" = "회의록만";+"纪要和双语全文" = "회의록과 이중 언어 전문";+"7 天" = "7일";+"30 天" = "30일";+"1 年" = "1년";+"换一个" = "다른 것";+"生成链接" = "링크 만들기";+"分享得太频繁了,请稍后再试。" = "공유가 너무 잦습니다. 잠시 후 다시 시도하세요.";+"敏感内容检查暂时不可用,没有检查就不会分享。请稍后再试。" = "민감한 내용 검사를 지금 쓸 수 없으며, 검사 없이는 공유하지 않습니다. 잠시 후 다시 시도하세요.";+"分享功能暂时关闭了。" = "공유가 잠시 꺼져 있습니다.";+"请先更新知了。" = "먼저 Cicada를 업데이트하세요.";+"这场会议太长,可以只分享纪要。" = "이 회의는 너무 깁니다. 회의록만 공유할 수 있습니다.";+"连不上 cicada.indaloop.app,请检查网络。" = "cicada.indaloop.app에 연결할 수 없습니다. 네트워크를 확인하세요.";+"服务器出了问题,请稍后再试。" = "서버에 문제가 생겼습니다. 잠시 후 다시 시도하세요.";+"正在检查有没有敏感内容…" = "민감한 내용을 확인하는 중…";+"链接尚未生成。请先核对以下内容:" = "아직 링크가 없습니다. 먼저 다음을 확인하세요:";+"去掉后再检查一次;你的记录不会改动。" = "빼고 다시 확인합니다. 기록은 바뀌지 않습니다.";+"检测到潜在敏感内容" = "민감할 수 있는 내용이 있습니다";+"返回修改" = "돌아가서 수정";+"去掉这些内容后分享" = "이 내용을 빼고 공유";+"密码或密钥" = "비밀번호 또는 키";+"未公开的公司信息" = "공개되지 않은 회사 정보";+"不宜跨境传输的信息" = "국외로 보내면 안 되는 정보";+"个人身份信息" = "개인 식별 정보";+"违法或危险内容" = "불법이거나 위험한 내용";+"链接已复制" = "링크 복사됨";+"已分享" = "공유됨";+"复制链接" = "링크 복사";+"复制密码" = "비밀번호 복사";+"%lld 天后失效" = "%lld일 후 만료";+"打开 %lld 次" = "%lld번 열림";+"取消后链接立即失效" = "취소하면 링크가 바로 작동하지 않습니다";+"已查看过的人可能留有副本。" = "이미 본 사람은 사본을 갖고 있을 수 있습니다.";+"暂不取消" = "유지";+"取消分享" = "공유 중지";+"在浏览器中打开" = "브라우저에서 열기";+"没有分享出去" = "공유되지 않았습니다";+"分享…" = "공유…";+"去掉这些内容后就没有可分享的了。" = "이 내용을 빼면 공유할 것이 남지 않습니다.";+"这场会议没有可分享的内容。" = "이 회의에는 공유할 내용이 없습니다.";+"还有 %lld 处" = "외 %lld곳";diff --git a/Sources/Cicada/AppModel.swift b/Sources/Cicada/AppModel.swiftindex 921415a..23e3410 100644--- a/Sources/Cicada/AppModel.swift+++ b/Sources/Cicada/AppModel.swift@@ -1716,6 +1716,29 @@ final class AppModel: ObservableObject {// recordTrack:off compares the meeting record without its own recognizer (next start).Recognition.recordTrackOff = arg == "off"debugLog("record track: \(Recognition.recordTrack ? "on" : "off")")+ case "share":+ // share:<record id>[,full][,pw] shares a meeting as the sheet would (point a dev build at a+ // local Worker with the shareServer default); unshare:<record id> turns it off.+ let p = arg.split(separator: ",").map(String.init)+ guard let s = p.first.flatMap({ store.session($0) }) else { debugLog("share: no such record"); break }+ var o = ShareClient.Options()+ o.scope = p.contains("full") || s.notes?.isEmpty ?? true ? .full : .notes+ o.password = p.contains("pw") ? SharePassword.make() : nil+ Task {+ switch await ShareClient.shared.share(s, o) {+ case .shared(let r): debugLog("share: \(r.url)\(r.password.map { " password \($0)" } ?? "")")+ case .blocked(let hits, let kept): debugLog("share: blocked lines \(ShareHit.recordLines(hits, kept: kept).sorted())")+ case .failed(let code, _): debugLog("share: failed \(code)")+ }+ }+ case "shareSheet":+ if !arg.isEmpty { openMainWindow?(); mainShow = arg }+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {+ NotificationCenter.default.post(name: .debugShareSheet, object: arg.isEmpty ? nil : arg)+ }+ case "unshare":+ guard let r = ShareStore.read(arg) else { debugLog("share: \(arg) not shared"); break }+ Task { debugLog("share: revoked \(await ShareClient.shared.revoke(r, sessionID: arg))") }case "recordState": debugLog("record track: \(Recognition.recordTrack ? "on" : "off") settling=\(settling.count) tracked=\(refining.count)")case "recognizer":// recognizer:legacy runs the macOS 14/15 recognizer (SFSpeechRecognizer) on 26; recognizer:clouddiff --git a/Sources/Cicada/ShareClient.swift b/Sources/Cicada/ShareClient.swiftnew file mode 100644index 0000000..920445c--- /dev/null+++ b/Sources/Cicada/ShareClient.swift@@ -0,0 +1,342 @@+import CommonCrypto+import CryptoKit+import Foundation++/// A meeting shared as a link: what the Mac keeps about it. The manage token (needed to turn the+/// link off) lives only here, in a 0600 file under Application Support (Shares/<record id>.json),+/// never in the record, exports or logs; so does the password, so it can be copied again.+struct ShareRecord: Codable, Equatable {+ var id: String+ var url: String+ var token: String+ var expiresAt: Date+ var scope: String+ var password: String?+ var createdAt: Date+}++/// Where the review found a problem: the notes, or lines `from`…`to` of what was sent.+struct ShareHit: Codable, Equatable {+ var part: String+ var from: Int?+ var to: Int?+ var questions: [String]++ /// The record's line indices behind the hits, given which record lines were sent (`kept`).+ static func recordLines(_ hits: [ShareHit], kept: [Int]) -> Set<Int> {+ var out: Set<Int> = []+ for h in hits where h.part == "lines" {+ guard let a = h.from, let b = h.to, a <= b else { continue }+ for i in a...b where i < kept.count { out.insert(kept[i]) }+ }+ return out+ }+}++enum SharePassword {+ static let iterations = 210_000++ /// 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.+ static func verifier(_ password: String, salt: Data, iterations: Int = iterations) -> Data {+ var out = Data(count: 32)+ let pw = Array(password.utf8)+ _ = out.withUnsafeMutableBytes { o in+ salt.withUnsafeBytes { s in+ CCKeyDerivationPBKDF(CCPBKDFAlgorithm(kCCPBKDF2), pw.map { Int8(bitPattern: $0) }, pw.count,+ s.bindMemory(to: UInt8.self).baseAddress, salt.count,+ CCPseudoRandomAlgorithm(kCCPRFHmacAlgSHA256), UInt32(iterations),+ o.bindMemory(to: UInt8.self).baseAddress, 32)+ }+ }+ return out+ }++ /// "ruby-41-lake": easy to read out and type; the server limits how many can be tried.+ static func make() -> String {+ let w = words.split(separator: " ")+ return "\(w.randomElement()!)-\(Int.random(in: 10...99))-\(w.randomElement()!)"+ }++ private static let 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"+}++/// Shares/<record id>.json, 0600 in a 0700 folder.+enum ShareStore {+ nonisolated(unsafe) static var folderOverride: URL?++ static var folder: URL {+ folderOverride ?? FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]+ .appendingPathComponent(DevBuild.supportFolder).appendingPathComponent("Shares")+ }++ static func read(_ sessionID: String) -> ShareRecord? {+ guard let data = try? Data(contentsOf: folder.appendingPathComponent(sessionID + ".json")) else { return nil }+ let d = JSONDecoder()+ d.dateDecodingStrategy = .iso8601+ return try? d.decode(ShareRecord.self, from: data)+ }++ static func save(_ r: ShareRecord, for sessionID: String) {+ let e = JSONEncoder()+ e.dateEncodingStrategy = .iso8601+ guard let data = try? e.encode(r) else { return }+ _ = SecretFile.write(data, to: folder.appendingPathComponent(sessionID + ".json"))+ }++ static func remove(_ sessionID: String) {+ try? FileManager.default.removeItem(at: folder.appendingPathComponent(sessionID + ".json"))+ }++ static func all() -> [String: ShareRecord] {+ let files = (try? FileManager.default.contentsOfDirectory(at: folder, includingPropertiesForKeys: nil)) ?? []+ var out: [String: ShareRecord] = [:]+ for f in files where f.pathExtension == "json" {+ let id = f.deletingPathExtension().lastPathComponent+ if let r = read(id) { out[id] = r }+ }+ return out+ }+}++/// A file only this user can read, left out of backups (like the AI keys in AIKey).+enum SecretFile {+ static func write(_ data: Data, to file: URL) -> Bool {+ let fm = FileManager.default+ let dir = file.deletingLastPathComponent()+ do {+ try fm.createDirectory(at: dir, withIntermediateDirectories: true)+ try fm.setAttributes([.posixPermissions: 0o700], ofItemAtPath: dir.path)+ if !fm.fileExists(atPath: file.path) {+ guard fm.createFile(atPath: file.path, contents: nil, attributes: [.posixPermissions: 0o600]) else { return false }+ }+ try fm.setAttributes([.posixPermissions: 0o600], ofItemAtPath: file.path)+ try data.write(to: file)+ var url = file+ var values = URLResourceValues()+ values.isExcludedFromBackup = true+ try? url.setResourceValues(values)+ return true+ } catch {+ debugLog("share: could not write \(file.lastPathComponent)")+ return false+ }+ }+}++/// Talks to the share service on cicada.indaloop.app (server/). There are no accounts: this Mac is+/// an Ed25519 key made on first use (share-device.json, 0600), registered once with a small proof of+/// work, and 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.+@MainActor+final class ShareClient {+ static let shared = ShareClient()++ enum Outcome {+ case shared(ShareRecord)+ case blocked([ShareHit], kept: [Int])+ case failed(code: String, retryAfter: Int?)+ }++ struct Stats: Decodable {+ var id: String+ var expiresAt: Double+ var state: String+ var views: Int+ }++ /// Dev builds can point at a local Worker: `defaults write com.wquguru.cicada.dev shareServer http://127.0.0.1:8787`.+ var base: URL {+ if let s = UserDefaults.standard.string(forKey: "shareServer"), let u = URL(string: s) { return u }+ return URL(string: "https://cicada.indaloop.app")!+ }++ private struct DeviceFile: Codable {+ var key: String+ var device: String?+ var server: String?+ }++ private var deviceFile: URL { ShareStore.folder.deletingLastPathComponent().appendingPathComponent("share-device.json") }++ private func loadDevice() -> (Curve25519.Signing.PrivateKey, DeviceFile) {+ if let data = try? Data(contentsOf: deviceFile), let f = try? JSONDecoder().decode(DeviceFile.self, from: data),+ let raw = Data(base64Encoded: f.key), let key = try? Curve25519.Signing.PrivateKey(rawRepresentation: raw) {+ return (key, f)+ }+ let key = Curve25519.Signing.PrivateKey()+ let f = DeviceFile(key: key.rawRepresentation.base64EncodedString(), device: nil, server: nil)+ saveDevice(f)+ return (key, f)+ }++ private func saveDevice(_ f: DeviceFile) {+ if let data = try? JSONEncoder().encode(f) { _ = SecretFile.write(data, to: deviceFile) }+ }++ /// The device id, registering this Mac with the server first if needed.+ private func device(force: Bool = false) async throws -> (Curve25519.Signing.PrivateKey, String) {+ var (key, f) = loadDevice()+ if !force, let id = f.device, f.server == base.absoluteString { return (key, id) }+ let pub = key.publicKey.rawRepresentation+ let nonce = await Task.detached(priority: .userInitiated) { Self.proofOfWork(pub) }.value+ let body: [String: Any] = ["key": Self.b64url(pub), "pow": Self.b64url(nonce), "platform": "mac", "version": Updates.current]+ let (data, status) = try await send("POST", "/api/v1/devices", body: try JSONSerialization.data(withJSONObject: body), signer: nil)+ guard status == 201, let id = (try? JSONSerialization.jsonObject(with: data) as? [String: Any])?["device"] as? String else {+ throw Failure(code: Self.code(data) ?? "register_failed", retryAfter: nil)+ }+ f.device = id+ f.server = base.absoluteString+ saveDevice(f)+ (key, _) = loadDevice()+ return (key, id)+ }++ /// 20 leading zero bits of sha256(public key ‖ nonce): about a million hashes, a second or two.+ nonisolated static func proofOfWork(_ pub: Data) -> Data {+ var n: UInt64 = 0+ while true {+ var nonce = Data(count: 8)+ nonce.withUnsafeMutableBytes { $0.storeBytes(of: n.bigEndian, as: UInt64.self) }+ let h = Array(SHA256.hash(data: pub + nonce))+ if h[0] == 0, h[1] == 0, h[2] < 16 { return nonce }+ n += 1+ }+ }++ struct Failure: Error {+ var code: String+ var retryAfter: Int?+ }++ private func send(_ method: String, _ path: String, body: Data? = nil, headers: [String: String] = [:],+ signer: (Curve25519.Signing.PrivateKey, String)?) async throws -> (Data, Int) {+ var req = URLRequest(url: URL(string: path, relativeTo: base)!)+ req.httpMethod = method+ req.timeoutInterval = 90+ req.httpBody = body+ req.setValue("application/json", forHTTPHeaderField: "Content-Type")+ req.setValue("mac/\(Updates.current)", forHTTPHeaderField: "X-Cicada-Client")+ for (k, v) in headers { req.setValue(v, forHTTPHeaderField: k) }+ if let (key, id) = signer {+ let time = String(Int(Date().timeIntervalSince1970))+ var raw = Data(count: 16)+ _ = raw.withUnsafeMutableBytes { SecRandomCopyBytes(kSecRandomDefault, 16, $0.baseAddress!) }+ let nonce = Self.b64url(raw)+ let hash = SHA256.hash(data: body ?? Data()).map { String(format: "%02x", $0) }.joined()+ let message = "\(method)\n\(path)\n\(time)\n\(nonce)\n\(hash)"+ let sig = try key.signature(for: Data(message.utf8))+ req.setValue(id, forHTTPHeaderField: "X-Cicada-Device")+ req.setValue(time, forHTTPHeaderField: "X-Cicada-Time")+ req.setValue(nonce, forHTTPHeaderField: "X-Cicada-Nonce")+ req.setValue(Self.b64url(sig), forHTTPHeaderField: "X-Cicada-Signature")+ }+ do {+ let (data, resp) = try await URLSession.shared.data(for: req)+ return (data, (resp as? HTTPURLResponse)?.statusCode ?? 0)+ } catch {+ throw Failure(code: "network", retryAfter: nil)+ }+ }++ /// A signed call; registers again once if the server no longer knows this Mac.+ private func signed(_ method: String, _ path: String, body: Data? = nil, headers: [String: String] = [:]) async throws -> (Data, Int) {+ var signer = try await device()+ var (data, status) = try await send(method, path, body: body, headers: headers, signer: signer)+ if status == 401, Self.code(data) == "unknown_device" {+ signer = try await device(force: true)+ (data, status) = try await send(method, path, body: body, headers: headers, signer: signer)+ }+ return (data, status)+ }++ struct Options {+ var scope: ShareScope = .notes+ var days = 7+ var names = false+ var password: String?+ var summaryInPreview = false+ var removed: Set<Int> = []+ var dropNotes = false+ }++ func share(_ s: Session, _ o: Options) async -> Outcome {+ let doc = ShareProjection.doc(s, scope: o.scope, names: o.names, removed: o.removed, dropNotes: o.dropNotes)+ let kept = o.scope == .full ? s.lines.indices.filter { !o.removed.contains($0) && !s.lines[$0].src.isEmpty } : []+ var body: [String: Any] = [+ "doc": (try? JSONSerialization.jsonObject(with: ShareProjection.encode(doc))) ?? [:],+ "scope": o.scope.rawValue, "days": o.days, "summaryInPreview": o.summaryInPreview,+ ]+ if let pw = o.password {+ var salt = Data(count: 16)+ _ = salt.withUnsafeMutableBytes { SecRandomCopyBytes(kSecRandomDefault, 16, $0.baseAddress!) }+ let v = await Task.detached { SharePassword.verifier(pw, salt: salt) }.value+ body["password"] = ["salt": Self.b64url(salt), "iter": SharePassword.iterations,+ "hash": Self.b64url(Data(SHA256.hash(data: v)))]+ }+ do {+ let data = try JSONSerialization.data(withJSONObject: body)+ // The same meeting, content and settings sent again (the answer was lost) gets the same+ // link back; any other setting makes a new share.+ let settings = "\(o.scope.rawValue)|\(o.days)|\(o.names)|\(o.password ?? "")|\(o.summaryInPreview)"+ let idem = s.id + "-" + SHA256.hash(data: ShareProjection.encode(doc) + Data(settings.utf8)).prefix(8)+ .map { String(format: "%02x", $0) }.joined()+ let (out, status) = try await signed("POST", "/api/v1/shares", body: data, headers: ["Idempotency-Key": idem])+ let obj = (try? JSONSerialization.jsonObject(with: out)) as? [String: Any] ?? [:]+ switch status {+ case 200, 201:+ guard let id = obj["id"] as? String, let url = obj["url"] as? String, let token = obj["token"] as? String,+ let exp = obj["expiresAt"] as? Double else { return .failed(code: "server_error", retryAfter: nil) }+ if let old = ShareStore.read(s.id), old.id != id { await revoke(old, sessionID: nil) }+ let r = ShareRecord(id: id, url: url, token: token, expiresAt: Date(timeIntervalSince1970: exp),+ scope: o.scope.rawValue, password: o.password, createdAt: Date())+ ShareStore.save(r, for: s.id)+ debugLog("share: \(s.id) shared (\(o.scope.rawValue), \(o.days) days\(o.password == nil ? "" : ", password"))")+ return .shared(r)+ case 422:+ let hits = (try? JSONDecoder().decode([ShareHit].self, from: JSONSerialization.data(withJSONObject: obj["hits"] ?? []))) ?? []+ debugLog("share: \(s.id) blocked " + hits.map { h in+ h.part + (h.from.map { " \($0)-\(h.to ?? $0)" } ?? "") + " " + h.questions.joined(separator: ",")+ }.joined(separator: "; "))+ return .blocked(hits, kept: kept)+ default:+ debugLog("share: \(s.id) failed \(status) \(obj["code"] as? String ?? "?")")+ return .failed(code: obj["code"] as? String ?? "server_error", retryAfter: obj["retryAfter"] as? Int)+ }+ } catch let f as Failure {+ return .failed(code: f.code, retryAfter: f.retryAfter)+ } catch {+ return .failed(code: "server_error", retryAfter: nil)+ }+ }++ /// Turns the link off on the server and forgets it here. `sessionID` nil: the record is being replaced.+ @discardableResult+ func revoke(_ r: ShareRecord, sessionID: String?) async -> Bool {+ let ok: Bool+ if let (data, status) = try? await signed("DELETE", "/api/v1/shares/\(r.id)", headers: ["Authorization": "Bearer \(r.token)"]) {+ // 404: already gone (or never ours); either way nothing to keep.+ ok = status == 204 || status == 404+ if !ok { debugLog("share: revoke \(r.id) failed \(status) \(Self.code(data) ?? "?")") }+ } else {+ ok = false+ }+ if ok, let sessionID { ShareStore.remove(sessionID) }+ return ok+ }++ func stats(_ ids: [String]) async -> [String: Stats] {+ guard !ids.isEmpty, let (data, status) = try? await signed("GET", "/api/v1/shares?ids=\(ids.joined(separator: ","))"),+ status == 200, let list = try? JSONDecoder().decode([String: [Stats]].self, from: data)["shares"] else { return [:] }+ return Dictionary(uniqueKeysWithValues: list.map { ($0.id, $0) })+ }++ nonisolated static func b64url(_ d: Data) -> String {+ d.base64EncodedString().replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_")+ .replacingOccurrences(of: "=", with: "")+ }++ private static func code(_ data: Data) -> String? {+ ((try? JSONSerialization.jsonObject(with: data)) as? [String: Any])?["code"] as? String+ }+}diff --git a/Sources/Cicada/ShareProjection.swift b/Sources/Cicada/ShareProjection.swiftnew file mode 100644index 0000000..2e6c10a--- /dev/null+++ b/Sources/Cicada/ShareProjection.swift@@ -0,0 +1,112 @@+import Foundation++/// The share document (v1): what goes to the share page, made from a meeting record. Only these+/// fields leave the Mac: never the record's file paths (`sourcePath` has the user's name in it),+/// Ling's guesses at names with the lines they came from, or the record's own bookkeeping. Speakers+/// are 说话人 N unless the user chose to show names. The ports produce the same bytes+/// (Tests/fixtures/share), and server/src/doc.js reads exactly these fields.+struct ShareDoc: Codable, Equatable {+ struct Line: Codable, Equatable {+ var t: Double+ var who: String+ var src: String+ var dst: String?+ }+ struct Topic: Codable, Equatable {+ var start: Double+ var title: String+ var summary: String+ var points: [String]+ }+ struct Item: Codable, Equatable {+ var text: String+ var owner: String?+ var t: Double?+ }+ struct Term: Codable, Equatable {+ var name: String+ var note: String+ }+ struct Notes: Codable, Equatable {+ var summary: String+ var topics: [Topic]+ var conclusions: [Item]+ var todos: [Item]+ var terms: [Term]+ }++ var v = 1+ var title: String+ var startedAt: String+ var duration: Int+ var langs: [String]+ var notes: Notes?+ var lines: [Line]+ /// How many parts the user left out (the review flagged them): the page says so.+ var hidden: Int+}++enum ShareScope: String, CaseIterable {+ case notes, full+}++enum ShareProjection {+ /// `removed`: indices into the record's lines the user took out; `dropNotes` leaves the notes out.+ static func doc(_ s: Session, scope: ShareScope, names: Bool, removed: Set<Int> = [], dropNotes: Bool = false) -> ShareDoc {+ let numbers = SpeakerLabels.numbers(s.lines)+ let nameMap = names ? SpeakerLabels.names(s) : [:]+ func who(_ l: TranscriptLine) -> String {+ if l.speaker == "me" { return L("分享者") }+ guard let n = numbers[l.id] else { return L("对方") }+ return names ? SpeakerLabels.label(n, nameMap) : L("说话人 \(n)")+ }+ var lines: [ShareDoc.Line] = []+ if scope == .full {+ for (i, l) in s.lines.enumerated() where !removed.contains(i) && !l.src.isEmpty {+ let dst = l.dst.flatMap { $0.isEmpty || $0 == l.src ? nil : $0 }+ lines.append(.init(t: round(l.t), who: who(l), src: l.src, dst: dst))+ }+ }+ var notes: ShareDoc.Notes?+ if !dropNotes, let raw = s.notes, !raw.isEmpty {+ let n = names ? SpeakerLabels.named(raw, nameMap) : raw+ notes = .init(+ summary: n.summary,+ topics: n.topics.map { .init(start: round($0.start), title: $0.title, summary: $0.summary, points: $0.points) },+ conclusions: n.conclusions.map { .init(text: $0.text, owner: nil, t: $0.t.map(round)) },+ todos: n.todos.map { .init(text: $0.text, owner: names ? $0.owner : nil, t: $0.t.map(round)) },+ terms: names ? n.terms.map { .init(name: $0.name, note: $0.note) } : [])+ }+ let hidden = (scope == .full ? removed.count : 0) + (dropNotes && !(s.notes?.isEmpty ?? true) ? 1 : 0)+ return ShareDoc(title: s.displayTitle, startedAt: iso.string(from: s.startedAt),+ duration: Int(s.duration.rounded()), langs: languages(s.lines),+ notes: notes, lines: lines, hidden: hidden)+ }++ /// The meeting's usual direction ("en" → "zh"), by the most lines.+ static func languages(_ lines: [TranscriptLine]) -> [String] {+ var count: [String: Int] = [:], first: [String: Int] = [:]+ for (i, l) in lines.enumerated() where l.dst != nil {+ let key = base(l.srcLang) + ">" + base(l.dstLang)+ count[key, default: 0] += 1+ if first[key] == nil { first[key] = i }+ }+ guard let top = count.keys.max(by: { (count[$0]!, -first[$0]!) < (count[$1]!, -first[$1]!) }) else { return [] }+ return top.split(separator: ">").map(String.init)+ }++ private static func base(_ code: String) -> String {+ String(code.split(separator: "-").first ?? Substring(code)).lowercased()+ }++ /// One decimal: the page shows seconds, and short numbers keep the bytes the same on every platform.+ private static func round(_ t: Double) -> Double { (t * 10).rounded() / 10 }++ private static let iso = ISO8601DateFormatter()++ static func encode(_ d: ShareDoc) -> Data {+ let e = JSONEncoder()+ e.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]+ return (try? e.encode(d)) ?? Data()+ }+}diff --git a/Sources/Cicada/ShareViews.swift b/Sources/Cicada/ShareViews.swiftnew file mode 100644index 0000000..f2e8e0d--- /dev/null+++ b/Sources/Cicada/ShareViews.swift@@ -0,0 +1,312 @@+import AppKit+import SwiftUI++/// 分享…: a meeting as a link on cicada.indaloop.app. 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.+struct ShareSheet: View {+ let session: Session+ let onClose: () -> Void++ private enum Step: Equatable {+ case settings, working, blocked([ShareHit], kept: [Int]), done(ShareRecord), failed(String)+ }++ @State private var step: Step = .settings+ @State private var scope: ShareScope = .notes+ @State private var days = 7+ @State private var names = false+ @State private var usePassword = false+ @State private var password = SharePassword.make()+ @State private var summaryInPreview = false+ @State private var removed: Set<Int> = []+ @State private var dropNotes = false+ @State private var views: Int?+ @State private var confirmRevoke = false+ @State private var copied: String?++ private var hasNotes: Bool { !(session.notes?.isEmpty ?? true) }++ var body: some View {+ VStack(alignment: .leading, spacing: 16) {+ switch step {+ case .settings: settings+ case .working: working+ case .blocked(let hits, let kept): blocked(hits, kept: kept)+ case .done(let r): done(r)+ case .failed(let message): failed(message)+ }+ }+ .padding(24)+ .frame(width: 420)+ .onAppear {+ if !hasNotes { scope = .full }+ if let r = ShareStore.read(session.id), r.expiresAt > Date() { step = .done(r); loadViews(r) }+ }+ }++ // MARK: Settings++ private var settings: some View {+ VStack(alignment: .leading, spacing: 16) {+ header(L("分享这场会议"), session.displayTitle)+ VStack(alignment: .leading, spacing: 8) {+ Text("内容").font(.system(size: 12, weight: .semibold)).foregroundStyle(Palette.secondary)+ Picker("", selection: $scope) {+ Text("只分享纪要").tag(ShareScope.notes).disabled(!hasNotes)+ Text("纪要和双语全文").tag(ShareScope.full)+ }+ .pickerStyle(.radioGroup).labelsHidden()+ }+ row(L("有效期")) {+ Picker("", selection: $days) {+ Text("7 天").tag(7)+ Text("30 天").tag(30)+ Text("1 年").tag(365)+ }+ .labelsHidden().fixedSize()+ }+ row(L("显示说话人名字")) { Toggle("", isOn: $names).toggleStyle(.switch).controlSize(.small).labelsHidden() }+ row(L("用密码保护")) { Toggle("", isOn: $usePassword).toggleStyle(.switch).controlSize(.small).labelsHidden() }+ if usePassword {+ HStack(spacing: 8) {+ TextField("", text: $password).textFieldStyle(.roundedBorder).font(.system(size: 13, design: .monospaced))+ Button("换一个") { password = SharePassword.make() }.controlSize(.small)+ }+ } else if hasNotes {+ row(L("预览卡显示摘要")) { Toggle("", isOn: $summaryInPreview).toggleStyle(.switch).controlSize(.small).labelsHidden() }+ }+ Text(usePassword ? L("建议把链接和密码分两条消息发送。") : L("内容将上传至 cicada.indaloop.app,拿到链接的人都能看。"))+ .font(.system(size: 12)).foregroundStyle(Palette.tertiary).fixedSize(horizontal: false, vertical: true)+ HStack {+ Spacer()+ Button("取消", action: onClose).keyboardShortcut(.cancelAction)+ Button("生成链接") { go() }.keyboardShortcut(.defaultAction)+ .disabled(usePassword && password.count < 6)+ }+ }+ }++ private func go() {+ step = .working+ var o = ShareClient.Options()+ o.scope = scope+ o.days = days+ o.names = names+ o.password = usePassword ? password : nil+ o.summaryInPreview = !usePassword && summaryInPreview+ o.removed = removed+ o.dropNotes = dropNotes+ Task {+ switch await ShareClient.shared.share(session, o) {+ case .shared(let r):+ copy(r.url, as: "link")+ step = .done(r)+ views = 0+ case .blocked(let hits, let kept): step = .blocked(hits, kept: kept)+ case .failed(let code, let retry): step = .failed(Self.message(code, retry))+ }+ }+ }++ private var working: some View {+ VStack(alignment: .leading, spacing: 16) {+ header(L("分享这场会议"), session.displayTitle)+ HStack(spacing: 10) {+ ProgressView().controlSize(.small)+ Text("正在检查有没有敏感内容…").font(.system(size: 13)).foregroundStyle(Palette.secondary)+ }+ .frame(maxWidth: .infinity, minHeight: 80)+ }+ }++ // MARK: Blocked++ private func blocked(_ hits: [ShareHit], kept: [Int]) -> some View {+ VStack(alignment: .leading, spacing: 14) {+ HStack(spacing: 8) {+ Image(systemName: "exclamationmark.triangle").foregroundStyle(Palette.accentInk)+ Text("检测到潜在敏感内容").font(.system(size: 15, weight: .semibold))+ }+ Text("链接尚未生成。请先核对以下内容:").font(.system(size: 12)).foregroundStyle(Palette.secondary)+ // A plain stack, not a ScrollView: in a sheet that sizes itself, a ScrollView gets no height.+ VStack(alignment: .leading, spacing: 8) {+ ForEach(Array(hits.prefix(5).enumerated()), id: \.offset) { _, h in hitRow(h, kept: kept) }+ if hits.count > 5 {+ Text("还有 \(hits.count - 5) 处").font(.system(size: 12)).foregroundStyle(Palette.secondary)+ }+ }+ let leftover = leftAfterRemoving(hits, kept: kept)+ Text(leftover ? L("去掉后再检查一次;你的记录不会改动。") : L("去掉这些内容后就没有可分享的了。"))+ .font(.system(size: 12)).foregroundStyle(Palette.tertiary)+ HStack {+ Spacer()+ Button("返回修改") { step = .settings }.keyboardShortcut(.cancelAction)+ if leftover {+ Button("去掉这些内容后分享") {+ removed.formUnion(ShareHit.recordLines(hits, kept: kept))+ if hits.contains(where: { $0.part == "notes" }) { dropNotes = true }+ go()+ }+ .keyboardShortcut(.defaultAction)+ }+ }+ }+ }++ /// 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.)+ private func leftAfterRemoving(_ hits: [ShareHit], kept: [Int]) -> Bool {+ let notesLeft = hasNotes && !dropNotes && !hits.contains { $0.part == "notes" }+ guard scope == .full else { return notesLeft }+ let out = removed.union(ShareHit.recordLines(hits, kept: kept))+ let linesLeft = session.lines.indices.contains { !out.contains($0) && !session.lines[$0].src.isEmpty }+ return notesLeft || linesLeft+ }++ private func hitRow(_ h: ShareHit, kept: [Int]) -> some View {+ let what = h.questions.map(Self.category).joined(separator: "、")+ let quote: String+ let place: String+ if h.part == "notes" {+ place = L("纪要")+ quote = session.notes?.summary ?? ""+ } else {+ let lines = ShareHit.recordLines([h], kept: kept).sorted()+ let a = lines.first.map { TranscriptExport.clock(session.lines[$0].t) } ?? ""+ let b = lines.last.map { TranscriptExport.clock(session.lines[$0].t) } ?? ""+ place = a == b ? a : "\(a)–\(b)"+ quote = lines.first.map { session.lines[$0].src } ?? ""+ }+ return VStack(alignment: .leading, spacing: 3) {+ Text("\(what) · \(place)").font(.system(size: 12, weight: .semibold))+ Text(quote).font(.system(size: 12)).foregroundStyle(Palette.secondary).lineLimit(2)+ }+ .padding(10).frame(maxWidth: .infinity, alignment: .leading)+ .background(RoundedRectangle(cornerRadius: 8).fill(Palette.accentPale))+ }++ static func category(_ q: String) -> String {+ switch q {+ case "credential": return L("密码或密钥")+ case "confidential": return L("未公开的公司信息")+ case "crossborder": return L("不宜跨境传输的信息")+ case "personal": return L("个人身份信息")+ case "harmful": return L("违法或危险内容")+ default: return q+ }+ }++ // MARK: Done++ private func done(_ r: ShareRecord) -> some View {+ VStack(alignment: .leading, spacing: 14) {+ header(copied == "link" ? L("链接已复制") : L("已分享"), session.displayTitle)+ HStack(spacing: 8) {+ Text(r.url).font(.system(size: 12, design: .monospaced)).lineLimit(1).truncationMode(.middle)+ .textSelection(.enabled)+ .padding(.horizontal, 8).padding(.vertical, 6)+ .frame(maxWidth: .infinity, alignment: .leading)+ .background(RoundedRectangle(cornerRadius: 6).fill(Palette.fill))+ Button(copied == "link" ? L("已复制") : L("复制链接")) { copy(r.url, as: "link") }+ }+ if let pw = r.password {+ HStack(spacing: 8) {+ Text(pw).font(.system(size: 12, design: .monospaced)).textSelection(.enabled)+ .padding(.horizontal, 8).padding(.vertical, 6)+ .frame(maxWidth: .infinity, alignment: .leading)+ .background(RoundedRectangle(cornerRadius: 6).fill(Palette.fill))+ Button(copied == "password" ? L("已复制") : L("复制密码")) { copy(pw, as: "password") }+ }+ }+ Text(status(r)).font(.system(size: 12)).foregroundStyle(Palette.secondary)+ Divider()+ if confirmRevoke {+ VStack(alignment: .leading, spacing: 6) {+ Text("取消后链接立即失效").font(.system(size: 13, weight: .semibold))+ Text("已查看过的人可能留有副本。").font(.system(size: 12)).foregroundStyle(Palette.tertiary)+ HStack {+ Spacer()+ Button("暂不取消") { confirmRevoke = false }+ Button("取消分享") {+ Task {+ if await ShareClient.shared.revoke(r, sessionID: session.id) { onClose() }+ else { step = .failed(Self.message("network", nil)) }+ }+ }+ }+ }+ } else {+ HStack {+ Button("取消分享") { confirmRevoke = true }+ Spacer()+ Button("在浏览器中打开") { if let u = URL(string: r.url) { NSWorkspace.shared.open(u) } }+ Button("完成", action: onClose).keyboardShortcut(.defaultAction)+ }+ }+ }+ }++ private func status(_ r: ShareRecord) -> String {+ let left = max(1, Int(ceil(r.expiresAt.timeIntervalSinceNow / 86400)))+ let expiry = L("\(left) 天后失效")+ guard let views else { return expiry }+ return expiry + " · " + L("打开 \(views) 次")+ }++ private func loadViews(_ r: ShareRecord) {+ Task {+ let s = await ShareClient.shared.stats([r.id])[r.id]+ if let s {+ if s.state != "live" { ShareStore.remove(session.id); step = .settings } else { views = s.views }+ }+ }+ }++ private func failed(_ message: String) -> some View {+ VStack(alignment: .leading, spacing: 14) {+ header(L("没有分享出去"), session.displayTitle)+ Text(message).font(.system(size: 13)).foregroundStyle(Palette.ink).fixedSize(horizontal: false, vertical: true)+ HStack {+ Spacer()+ Button("关闭", action: onClose).keyboardShortcut(.cancelAction)+ Button("重试") { go() }.keyboardShortcut(.defaultAction)+ }+ }+ }++ static func message(_ code: String, _ retry: Int?) -> String {+ switch code {+ case "rate_limited", "too_many_shares": return L("分享得太频繁了,请稍后再试。")+ case "review_unavailable": return L("敏感内容检查暂时不可用,没有检查就不会分享。请稍后再试。")+ case "sharing_off": return L("分享功能暂时关闭了。")+ case "update_required": return L("请先更新知了。")+ case "too_large": return L("这场会议太长,可以只分享纪要。")+ case "bad_document": return L("这场会议没有可分享的内容。")+ case "network": return L("连不上 cicada.indaloop.app,请检查网络。")+ default: return L("服务器出了问题,请稍后再试。")+ }+ }++ // MARK: Parts++ private func header(_ title: String, _ sub: String) -> some View {+ VStack(alignment: .leading, spacing: 4) {+ Text(title).font(.system(size: 15, weight: .semibold))+ Text(sub).font(.system(size: 12)).foregroundStyle(Palette.secondary).lineLimit(1)+ }+ }++ private func row<C: View>(_ title: String, @ViewBuilder _ control: () -> C) -> some View {+ HStack {+ Text(title).font(.system(size: 13))+ Spacer()+ control()+ }+ }++ private func copy(_ text: String, as what: String) {+ NSPasteboard.general.clearContents()+ NSPasteboard.general.setString(text, forType: .string)+ copied = what+ }+}diff --git a/Sources/Cicada/Views.swift b/Sources/Cicada/Views.swiftindex 3b12193..1075be4 100644--- a/Sources/Cicada/Views.swift+++ b/Sources/Cicada/Views.swift@@ -797,6 +797,8 @@ struct MainWindowView: View {/// The bilingual column beside the notes is opt-in: three full columns of text read as crowded.@AppStorage("mainShowQuotes") private var showQuotes = false@State private var showOlder = false+ /// 分享…: the meeting whose share sheet is open.+ @State private var sharing: Session?/// 改这句…: the line being rewritten, and what the editor opens with.@State private var editingLine: String?@State private var editingStart = ""@@ -854,6 +856,9 @@ struct MainWindowView: View {.onReceive(NotificationCenter.default.publisher(for: .debugPlay)) { n inif let t = n.object as? Double { player.play(from: t) }}+ .onReceive(NotificationCenter.default.publisher(for: .debugShareSheet)) { n in+ sharing = (n.object as? String).flatMap { store.session($0) }+ }.onChange(of: model.mainShow) { _, show inguard let parts = show?.split(separator: ",").map(String.init), let id = parts.first else { return }selection = id@@ -1135,6 +1140,13 @@ struct MainWindowView: View {.buttonStyle(.plain).help(showQuotes ? L("收起原话") : L("在纪要旁显示原话"))}+ // Not while the meeting is still going, nor before an import has its text.+ Button { sharing = s } label: {+ Text("分享…").font(.system(size: 13)).foregroundStyle(Palette.secondary)+ }+ .buttonStyle(.plain)+ .disabled((s.lines.isEmpty && (s.notes?.isEmpty ?? true)) || store.liveID == s.id || importer.status(of: s) != nil)+ .sheet(item: $sharing) { shared in ShareSheet(session: shared) { sharing = nil } }Menu {Button("复制为 Markdown") { model.export(s, kind: "copy") }Divider()@@ -1716,4 +1728,6 @@ struct LanguageNotice: View {extension Notification.Name {/// Debug `play:<seconds>`: the shown record plays from there.static let debugPlay = Notification.Name("cicada.debugPlay")+ /// Debug `shareSheet:<id>`: the 分享… sheet opens for that record (no id: it closes).+ static let debugShareSheet = Notification.Name("cicada.debugShareSheet")}diff --git a/Tests/CicadaTests/ShareTests.swift b/Tests/CicadaTests/ShareTests.swiftnew file mode 100644index 0000000..b8e30b8--- /dev/null+++ b/Tests/CicadaTests/ShareTests.swift@@ -0,0 +1,70 @@+import Foundation+import Testing+@testable import Cicada++/// The share document is a contract with the server (server/src/doc.js) and the ports: the same+/// record must give the same bytes (Tests/fixtures/share).+struct ShareTests {+ static let fixtures = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()+ .appendingPathComponent("fixtures/share")++ static func session() throws -> Session {+ let d = JSONDecoder()+ d.dateDecodingStrategy = .iso8601+ return try d.decode(Session.self, from: Data(contentsOf: fixtures.appendingPathComponent("session.json")))+ }++ @Test func fixtureBytes() throws {+ let doc = ShareProjection.doc(try Self.session(), scope: .full, names: false)+ let want = try String(contentsOf: Self.fixtures.appendingPathComponent("share-doc.json"), encoding: .utf8)+ .trimmingCharacters(in: .whitespacesAndNewlines)+ #expect(String(decoding: ShareProjection.encode(doc), as: UTF8.self) == want)+ }++ @Test func nothingPrivateLeaves() throws {+ let text = String(decoding: ShareProjection.encode(ShareProjection.doc(try Self.session(), scope: .full, names: false)), as: UTF8.self)+ for secret in ["/Users/someone", "Emma", "Kenji", "Emmer", "Sure, Emma"] { #expect(!text.contains(secret), "\(secret)") }+ }++ @Test func namesWhenAsked() throws {+ let doc = ShareProjection.doc(try Self.session(), scope: .full, names: true)+ #expect(doc.notes?.todos.first?.owner == "Emma")+ #expect(doc.notes?.terms.first?.name == "Emma")+ }++ @Test func notesOnlyAndRemoved() throws {+ let s = try Self.session()+ #expect(ShareProjection.doc(s, scope: .notes, names: false).lines.isEmpty)+ let d = ShareProjection.doc(s, scope: .full, names: false, removed: [3], dropNotes: true)+ #expect(d.lines.count == 3 && d.notes == nil && d.hidden == 2)+ }++ @Test func speakerNumbersWithoutNames() throws {+ var s = try Self.session()+ // Two voices with five substantive lines each get numbers; their names stay out.+ s.lines = (0..<10).map { i in+ TranscriptLine(id: "v\(i)", t: Double(i), speaker: "them", src: "this is line number \(i)", dst: "第 \(i) 句话", srcLang: "en", dstLang: "zh", voice: i % 2 == 0 ? 3 : 7)+ }+ let d = ShareProjection.doc(s, scope: .full, names: false)+ #expect(Set(d.lines.map(\.who)) == ["说话人 1", "说话人 2"])+ let named = ShareProjection.doc(s, scope: .full, names: true)+ #expect(Set(named.lines.map(\.who)) == ["Emma", "Kenji"])+ }++ @Test func password() {+ let salt = Data(repeating: 1, count: 16)+ // Same as the browser's crypto.subtle PBKDF2-SHA256, 32 bytes (server/test/api.test.mjs).+ let v = SharePassword.verifier("ruby-41-lake", salt: salt, iterations: 1000)+ #expect(v.map { String(format: "%02x", $0) }.joined() == "eab69fcd00a0517794c156495dd76ad1fbfb036ea03df3d59a68a33519009c81")+ #expect(v == SharePassword.verifier("ruby-41-lake", salt: salt, iterations: 1000))+ #expect(v != SharePassword.verifier("ruby-41-laka", salt: salt, iterations: 1000))+ #expect(SharePassword.make().split(separator: "-").count == 3)+ }++ @Test func blockedHitsMapBack() {+ // The server counts lines of what was sent; the app maps them back to the record.+ let kept = [0, 1, 4, 5, 6]+ let hits = [ShareHit(part: "lines", from: 2, to: 3, questions: ["credential"])]+ #expect(ShareHit.recordLines(hits, kept: kept) == [4, 5])+ }+}diff --git a/site/changelog.json b/site/changelog.jsonindex 8b1b1e4..3089579 100644--- a/site/changelog.json+++ b/site/changelog.json@@ -1,4 +1,21 @@[+ {+ "version": "1.6.0",+ "date": null,+ "title": "把会议分享成一个链接",+ "summary": "会议记录可以分享成 cicada.indaloop.app 上的网页,能设有效期和密码,随时取消;上传前先检查有没有敏感内容。",+ "image": null,+ "items": [+ {+ "kind": "new",+ "platforms": [+ "mac"+ ],+ "title": "会议记录可以分享成一个链接。",+ "text": "记录右上角点“分享…”,选只分享纪要或连同双语全文,设有效期(7 天、30 天或 1 年),可以加密码。上传前会检查有没有写出来的密码和密钥、未公开的公司信息、不宜跨境的信息、个人身份信息和违法内容,有就先拦下并指出在哪,可以去掉这些内容再分享;检查不可用时不会分享。说话人默认显示为“说话人 N”,录音从不上传,取消分享后链接立即失效。"+ }+ ]+ },{"version": "1.5.1","date": "2026-11-07",