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

wqugurud9bb01d0b902
diff --git a/android/README.md b/android/README.md
index 7d4ee32..49cae10 100644
--- a/android/README.md
+++ b/android/README.md
@@ -46,7 +46,7 @@ scripts/shot.sh # 截图:悬浮窗应是黑块;capture o
scripts/tap.sh "开始听" # 按屏幕上的文字点(系统对话框也行),用来走真实界面
```
-`cicadactl.sh` 的命令见 `app/src/main/kotlin/com/wquguru/cicada/DebugReceiver.kt`(state、start、stop、feed、sample、view、capture、overlay show|hide|collapse|expand、target、ui、show main|live|records|record|settings|ai|onboarding、import、provider、ai-model、ai-custom-only on|off、key import、voice-try、updatefeed、update check|download|job|notify,以及改正听错的词的 fixes on|off、asknames on|off、silent、heard、vocab add|remove|state、fixstate、fixanswer yes|no、fixrevert、fixlater、fixundo、fixedit、pinyin)。`silent` 开一场没有声音的会,`heard <一句话>` 当作听到一整句,翻译和改词都走当前的 AI 服务,不用放声音。只有开发版有,且只接受 adb。开发版默认不检查更新(点设置里的“检查更新”或用下面的命令后才查):`cicadactl.sh push feed.json && cicadactl.sh updatefeed feed.json` 指向一份测试用的 release JSON(不带参数就是 GitHub),`adb shell cmd jobscheduler run -f com.wquguru.cicada.dev 7` 立刻跑一次后台检查。
+`cicadactl.sh` 的命令见 `app/src/main/kotlin/com/wquguru/cicada/DebugReceiver.kt`(state、start、stop、feed、sample、view、capture、overlay show|hide|collapse|expand、target、ui、show main|live|records|record|settings|ai|onboarding、import、provider、ai-model、ai-custom-only on|off、key import、voice-try、updatefeed、update check|download|job|notify,以及改正听错的词的 fixes on|off、asknames on|off、silent、heard、vocab add|remove|state、fixstate、fixanswer yes|no、fixrevert、fixlater、fixundo、fixedit、pinyin,分享链接的 share <id>[,full][,pw]、unshare、shares、shareSheet、delete)。`share` 用正式的 cicada.indaloop.app,设备只注册一次(files/share-device.json,别删);测试只用合成的会议记录,用完 unshare。`silent` 开一场没有声音的会,`heard <一句话>` 当作听到一整句,翻译和改词都走当前的 AI 服务,不用放声音。只有开发版有,且只接受 adb。开发版默认不检查更新(点设置里的“检查更新”或用下面的命令后才查):`cicadactl.sh push feed.json && cicadactl.sh updatefeed feed.json` 指向一份测试用的 release JSON(不带参数就是 GitHub),`adb shell cmd jobscheduler run -f com.wquguru.cicada.dev 7` 立刻跑一次后台检查。
界面按 claude.ai 上的设计画布实现:首页、正在听、悬浮窗(纪要卡片 / 字幕条 / 小圆点)、三步引导、会议记录、会议详情、设置。文案用 Gemini(`google/gemini-4-argon`)审过一遍,与 Mac 共用的文案沿用 Mac 的译法。
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/App.kt b/android/app/src/main/kotlin/com/wquguru/cicada/App.kt
index 30bb5fd..fb13c7c 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/App.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/App.kt
@@ -23,6 +23,7 @@ import cicada.Paths
import cicada.PcmAudioSource
import cicada.Providers
import cicada.SessionStore
+import cicada.ShareClient
import cicada.SpeakerLabels
import cicada.SpeakerNamer
import cicada.SpeakerTagger
@@ -50,6 +51,10 @@ class CicadaApp : Application() {
lateinit var overlay: Overlay
lateinit var voice: Voice
lateinit var updates: AppUpdates
+ /// 分享…: the share service on cicada.indaloop.app (Share.kt). Its version without "-dev".
+ val share by lazy {
+ ShareClient("android", (packageManager.getPackageInfo(packageName, 0).versionName ?: "0.0.0").substringBefore('-'))
+ }
val main = Handler(Looper.getMainLooper())
val background = Executors.newCachedThreadPool { r -> Thread(r, "App").apply { isDaemon = true } }
private val observers = LinkedHashSet<() -> Unit>()
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/DebugReceiver.kt b/android/app/src/main/kotlin/com/wquguru/cicada/DebugReceiver.kt
index 7192989..e3db05e 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/DebugReceiver.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/DebugReceiver.kt
@@ -25,6 +25,7 @@ import java.util.concurrent.TimeUnit
/// ai-check (重新检查) | ai-check-sim <reason|lowBalance|off> (every check ends that way; the state's ai.check has the steps)
/// 改正听错的词: fixes on|off · asknames on|off · silent (a meeting with no audio) · heard <text> · vocab add|remove|state
/// fixstate · fixanswer yes|no · fixrevert <line> · fixlater · fixundo · fixedit <line>=<text>[|one][|keep0] · pinyin <text>
+/// 分享…: share <id>[,full][,pw] · unshare <id> · shares · shareSheet <id> (no id: closes it) · delete <id>
class DebugReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (!BuildConfig.DEBUG) return
@@ -167,6 +168,35 @@ class DebugReceiver : BroadcastReceiver() {
val s = Session.read(File(app.filesDir, arg).readText()) ?: return mapOf("error" to "unreadable")
app.store.import(s)
}
+ "delete" -> app.store.delete(arg)
+ // 分享… (the Mac's share: / unshare: / shareSheet:): `share <id>[,full][,pw]` shares as the
+ // sheet would and logs the link; `unshare <id>` turns it off; `shares` lists them (never the token).
+ "share" -> {
+ val p = arg.split(",").map { it.trim() }
+ val s = app.store.get(p[0])?.let { Session.from(it.toJson()) } ?: return mapOf("error" to "no such record")
+ val o = cicada.ShareClient.Options(
+ scope = if ("full" in p || s.notes?.isEmpty != false) cicada.ShareScope.Full else cicada.ShareScope.Notes,
+ password = if ("pw" in p) cicada.SharePassword.make() else null)
+ app.background.execute {
+ when (val out = app.share.share(s, o)) {
+ is cicada.ShareClient.Outcome.Shared -> Log.d("debug: share ${out.record.url}${out.record.password?.let { " password $it" } ?: ""}")
+ is cicada.ShareClient.Outcome.Blocked -> Log.d("debug: share blocked lines ${cicada.ShareHit.recordLines(out.hits, out.kept).sorted()}${if (out.hits.any { it.part == "notes" }) " notes" else ""}")
+ is cicada.ShareClient.Outcome.Failed -> Log.d("debug: share failed ${out.code}")
+ }
+ }
+ return mapOf("sharing" to s.id)
+ }
+ "unshare" -> {
+ val r = cicada.ShareStore.read(arg) ?: return mapOf("error" to "$arg not shared")
+ app.background.execute { Log.d("debug: share revoked ${app.share.revoke(r, arg)}") }
+ return mapOf("unsharing" to arg)
+ }
+ "shares" -> return mapOf("shares" to cicada.ShareStore.all().mapValues { (_, r) ->
+ mapOf("id" to r.id, "url" to r.url, "scope" to r.scope, "password" to r.password, "expiresAt" to cicada.Iso8601.write(r.expiresAt))
+ })
+ "shareSheet" -> if (arg.isEmpty()) ShareSheet.open?.let { it.dismiss() } else
+ app.startActivity(Intent(app, RecordActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
+ .putExtra("id", arg).putExtra("share", true))
"show" -> when (arg.substringBefore(' ')) {
"settings" -> open(SettingsActivity::class.java)
"words" -> open(WordListActivity::class.java)
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/RecordsActivity.kt b/android/app/src/main/kotlin/com/wquguru/cicada/RecordsActivity.kt
index 3869d0c..0a8aab2 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/RecordsActivity.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/RecordsActivity.kt
@@ -199,6 +199,9 @@ class RecordActivity : Activity() {
ui.roundButton(R.drawable.i_share, L("分享"), onWhite = true) { cicada.store.get(id)?.let(::share) },
ui.roundButton(R.drawable.i_more, L("更多"), onWhite = true) { more() })))
toast = FixViews.Toast(this, ui, cicada, above = 140)
+ // Debug `shareSheet <id>`: the 分享… sheet opens over the record.
+ if (savedInstanceState == null && intent.getBooleanExtra("share", false))
+ list.post { cicada.store.get(id)?.takeIf { ShareSheet.canShare(cicada, it) }?.let { ShareSheet(this, ui, id).show() } }
}
private fun audio() = cicada.store.audioFile(id)
@@ -569,7 +572,10 @@ class RecordActivity : Activity() {
val s = cicada.store.get(id) ?: return
lateinit var d: android.app.Dialog
fun act(res: Int, label: String, helper: String? = null, red: Boolean = false, run: () -> Unit) = ui.sheetAction(res, label, helper, red) { d.dismiss(); run() }
- val box = ui.stack(0,
+ // 分享…: a link on cicada.indaloop.app (the round 分享 above sends the Markdown).
+ val link = act(R.drawable.i_external, L("分享…"), L("生成链接")) { ShareSheet(this, ui, s.id).show() }
+ if (!ShareSheet.canShare(cicada, s)) { link.alpha = 0.4f; link.isEnabled = false; link.isClickable = false }
+ val box = ui.stack(0, link,
act(R.drawable.i_clipboard, L("复制为 Markdown")) { copy(s) },
act(R.drawable.i_doc, L("导出 Markdown…")) { export(s, "md") },
act(R.drawable.i_doc, L("导出 Word…")) { export(s, "docx") },
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/ShareViews.kt b/android/app/src/main/kotlin/com/wquguru/cicada/ShareViews.kt
new file mode 100644
index 0000000..15ddf1f
--- /dev/null
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/ShareViews.kt
@@ -0,0 +1,356 @@
+package com.wquguru.cicada
+
+import android.app.Activity
+import android.content.Intent
+import android.graphics.Typeface
+import android.net.Uri
+import android.text.Editable
+import android.text.TextWatcher
+import android.util.TypedValue
+import android.view.Gravity
+import android.view.View
+import android.widget.EditText
+import android.widget.LinearLayout
+import android.widget.ProgressBar
+import android.widget.ScrollView
+import cicada.Languages
+import cicada.Session
+import cicada.SessionStore
+import cicada.ShareClient
+import cicada.ShareHit
+import cicada.SharePassword
+import cicada.ShareRecord
+import cicada.ShareScope
+import cicada.ShareStore
+import cicada.Strings.L
+import cicada.Strings.LF
+import java.time.Instant
+
+/// 分享…: a meeting as a link on cicada.indaloop.app (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. A bottom sheet whose content follows the step.
+class ShareSheet(private val activity: Activity, private val ui: Ui, private val sessionId: String) {
+ private val app = activity.cicada
+ private sealed class Step {
+ object Settings : Step()
+ object Working : Step()
+ class Blocked(val hits: List<ShareHit>, val kept: List<Int>) : Step()
+ class Done(val record: ShareRecord) : Step()
+ class Failed(val message: String) : Step()
+ }
+
+ // A copy: the record is read while the request runs.
+ private val session: Session = Session.from(app.store.get(sessionId)!!.toJson())
+ private val hasNotes = session.notes?.isEmpty == false
+ private var step: Step = Step.Settings
+ private var scope = if (hasNotes) ShareScope.Notes else ShareScope.Full
+ private var days = 7
+ private var names = false
+ private var usePassword = false
+ private var password = SharePassword.make()
+ private var summaryInPreview = false
+ private val removed = HashSet<Int>()
+ private var dropNotes = false
+ private var views: Int? = null
+ private var confirmRevoke = false
+ private var copied: String? = null
+ private val box = ui.stack(0).apply { setPadding(ui.dp(8), 0, ui.dp(8), 0) }
+ private lateinit var dialog: android.app.Dialog
+
+ fun dismiss() { if (::dialog.isInitialized) dialog.dismiss() }
+
+ fun show() {
+ ShareStore.read(sessionId)?.takeIf { it.expiresAt.isAfter(Instant.now()) }?.let { step = Step.Done(it); loadViews(it) }
+ dialog = ui.sheet(activity, null, ScrollView(activity).apply { addView(box); isVerticalScrollBarEnabled = false })
+ render()
+ dialog.setOnDismissListener { if (open === this) open = null }
+ dialog.show()
+ open = this
+ }
+
+ private fun set(s: Step) { step = s; confirmRevoke = false; render() }
+
+ private fun render() {
+ box.removeAllViews()
+ when (val s = step) {
+ Step.Settings -> settings()
+ Step.Working -> working()
+ is Step.Blocked -> blocked(s.hits, s.kept)
+ is Step.Done -> done(s.record)
+ is Step.Failed -> failed(s.message)
+ }
+ }
+
+ private fun header(title: String) {
+ box.addView(ui.heading(title))
+ box.addView(ui.text(SessionStore.displayTitle(session), 13f, Palette.secondary, lines = 1), ui.lp(top = 2))
+ }
+
+ private fun label(text: String) = ui.text(text, 13f, Palette.secondary, medium = true)
+
+ private fun buttons(vararg b: View) = LinearLayout(activity).apply {
+ orientation = LinearLayout.HORIZONTAL
+ b.forEachIndexed { i, v -> addView(v, ui.weight().apply { if (i > 0) leftMargin = ui.dp(10) }) }
+ }
+
+ // MARK: Settings
+
+ private fun settings() {
+ header(L("分享这场会议"))
+ box.addView(label(L("内容")), ui.lp(top = 18))
+ for ((value, text) in listOf(ShareScope.Notes to L("只分享纪要"), ShareScope.Full to L("纪要和双语全文"))) {
+ val on = scope == value
+ val enabled = value == ShareScope.Full || hasNotes
+ box.addView(LinearLayout(activity).apply {
+ orientation = LinearLayout.HORIZONTAL
+ gravity = Gravity.CENTER_VERTICAL
+ minimumHeight = ui.dp(48)
+ setPadding(ui.dp(12), 0, ui.dp(12), 0)
+ addView(ui.text(text, 16f, Palette.ink, bold = on, lines = 2), ui.weight())
+ if (on) addView(ui.icon(R.drawable.i_check, 20, Palette.ink), LinearLayout.LayoutParams(ui.dp(20), ui.dp(20)))
+ contentDescription = text
+ isSelected = on
+ accessibilityDelegate = object : View.AccessibilityDelegate() {
+ override fun onInitializeAccessibilityNodeInfo(host: View, info: android.view.accessibility.AccessibilityNodeInfo) {
+ super.onInitializeAccessibilityNodeInfo(host, info)
+ info.className = "android.widget.RadioButton"; info.isCheckable = true; info.isChecked = on
+ }
+ }
+ if (enabled) ui.tappable(this, 14, if (on) ui.rounded(Palette.ground, 14) else null) { scope = value; render() }
+ else { alpha = 0.4f; isEnabled = false }
+ }, ui.lp(top = 4))
+ }
+ box.addView(label(L("有效期")), ui.lp(top = 16))
+ box.addView(ui.segmented(listOf("7" to L("7 天"), "30" to L("30 天"), "365" to L("1 年")), days.toString()) { days = it.toInt(); render() }, ui.lp(top = 8))
+ val toggles = ui.stack(0).apply { setPadding(0, ui.dp(8), 0, 0) }
+ toggles.addView(ui.switchRow(L("显示说话人名字"), null, names, titleLines = 2) { names = it }.apply { setPadding(ui.dp(4), paddingTop, ui.dp(4), paddingBottom) })
+ toggles.addView(ui.switchRow(L("用密码保护"), null, usePassword, titleLines = 2) { usePassword = it; render() }.apply { setPadding(ui.dp(4), paddingTop, ui.dp(4), paddingBottom) })
+ box.addView(toggles)
+ lateinit var go: View
+ if (usePassword) {
+ val field = EditText(activity).apply {
+ setText(password)
+ setSingleLine()
+ typeface = Typeface.MONOSPACE
+ setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f)
+ background = ui.rounded(Palette.ground, 14)
+ setPadding(ui.dp(14), 0, ui.dp(14), 0)
+ minHeight = ui.dp(48)
+ addTextChangedListener(object : TextWatcher {
+ override fun beforeTextChanged(s: CharSequence?, a: Int, b: Int, c: Int) {}
+ override fun onTextChanged(s: CharSequence?, a: Int, b: Int, c: Int) {}
+ override fun afterTextChanged(s: Editable?) {
+ password = s.toString()
+ go.alpha = if (password.length < 6) 0.4f else 1f
+ go.isEnabled = password.length >= 6
+ }
+ })
+ }
+ box.addView(LinearLayout(activity).apply {
+ orientation = LinearLayout.HORIZONTAL
+ gravity = Gravity.CENTER_VERTICAL
+ addView(field, ui.weight())
+ addView(ui.textButton(L("换一个")) { password = SharePassword.make(); field.setText(password) })
+ }, ui.lp(top = 4))
+ } else if (hasNotes) {
+ box.addView(ui.switchRow(L("预览卡显示摘要"), null, summaryInPreview, titleLines = 2) { summaryInPreview = it }.apply { setPadding(ui.dp(4), paddingTop, ui.dp(4), paddingBottom) })
+ }
+ box.addView(ui.text(if (usePassword) L("建议把链接和密码分两条消息发送。") else L("内容将上传至 cicada.indaloop.app,拿到链接的人都能看。"), 13f, Palette.tertiary), ui.lp(top = 10))
+ go = ui.button(L("生成链接"), "primary") { if (!usePassword || password.length >= 6) go() }
+ if (usePassword && password.length < 6) { go.alpha = 0.4f; go.isEnabled = false }
+ box.addView(buttons(ui.button(L("取消"), "quiet") { dialog.dismiss() }, go), ui.lp(top = 18))
+ }
+
+ private fun options() = ShareClient.Options(
+ scope = scope, days = days, names = names, password = if (usePassword) password.trim() else null,
+ summaryInPreview = !usePassword && summaryInPreview, removed = removed.toSet(), dropNotes = dropNotes)
+
+ private fun go() {
+ set(Step.Working)
+ val o = options()
+ app.background.execute {
+ val out = app.share.share(session, o)
+ app.main.post {
+ when (out) {
+ is ShareClient.Outcome.Shared -> { copy(out.record.url, "link"); views = 0; set(Step.Done(out.record)) }
+ is ShareClient.Outcome.Blocked -> set(Step.Blocked(out.hits, out.kept))
+ is ShareClient.Outcome.Failed -> set(Step.Failed(message(out.code)))
+ }
+ }
+ }
+ }
+
+ private fun working() {
+ header(L("分享这场会议"))
+ box.addView(LinearLayout(activity).apply {
+ orientation = LinearLayout.HORIZONTAL
+ gravity = Gravity.CENTER
+ minimumHeight = ui.dp(120)
+ addView(ProgressBar(activity).apply { isIndeterminate = true; indeterminateTintList = android.content.res.ColorStateList.valueOf(Palette.secondary) }, LinearLayout.LayoutParams(ui.dp(24), ui.dp(24)))
+ addView(ui.text(L("正在检查有没有敏感内容…"), 15f, Palette.secondary), LinearLayout.LayoutParams(-2, -2).apply { leftMargin = ui.dp(12) })
+ })
+ }
+
+ // MARK: Blocked
+
+ private fun blocked(hits: List<ShareHit>, kept: List<Int>) {
+ box.addView(LinearLayout(activity).apply {
+ orientation = LinearLayout.HORIZONTAL
+ gravity = Gravity.CENTER_VERTICAL
+ addView(ui.icon(R.drawable.i_info, 20, Palette.link), LinearLayout.LayoutParams(ui.dp(20), ui.dp(20)).apply { rightMargin = ui.dp(8) })
+ addView(ui.heading(L("检测到潜在敏感内容")), ui.weight())
+ })
+ box.addView(ui.text(L("链接尚未生成。请先核对以下内容:"), 13f, Palette.secondary), ui.lp(top = 6))
+ for (h in hits.take(5)) box.addView(hitRow(h, kept), ui.lp(top = 8))
+ if (hits.size > 5) box.addView(ui.text(LF("还有 %lld 处", hits.size - 5), 13f, Palette.secondary), ui.lp(top = 8))
+ val leftover = leftAfterRemoving(hits, kept)
+ box.addView(ui.text(if (leftover) L("去掉后再检查一次;你的记录不会改动。") else L("去掉这些内容后就没有可分享的了。"), 13f, Palette.tertiary), ui.lp(top = 12))
+ val back = ui.button(L("返回修改"), "quiet") { set(Step.Settings) }
+ box.addView(if (leftover) buttons(back, ui.button(L("去掉这些内容后分享"), "primary") {
+ removed.addAll(ShareHit.recordLines(hits, kept))
+ if (hits.any { it.part == "notes" }) dropNotes = true
+ go()
+ }) else buttons(back), ui.lp(top = 18))
+ }
+
+ /// 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 fun leftAfterRemoving(hits: List<ShareHit>, kept: List<Int>): Boolean {
+ val notesLeft = hasNotes && !dropNotes && hits.none { it.part == "notes" }
+ if (scope != ShareScope.Full) return notesLeft
+ val out = removed + ShareHit.recordLines(hits, kept)
+ return notesLeft || session.lines.indices.any { it !in out && session.lines[it].src.isNotEmpty() }
+ }
+
+ private fun hitRow(h: ShareHit, kept: List<Int>): View {
+ val what = h.questions.joinToString("、") { category(it) }
+ val place: String
+ val quote: String
+ if (h.part == "notes") {
+ place = L("纪要")
+ quote = session.notes?.summary ?: ""
+ } else {
+ val lines = ShareHit.recordLines(listOf(h), kept).sorted()
+ val a = lines.firstOrNull()?.let { Languages.clock(session.lines[it].t) } ?: ""
+ val b = lines.lastOrNull()?.let { Languages.clock(session.lines[it].t) } ?: ""
+ place = if (a == b) a else "$a–$b"
+ quote = lines.firstOrNull()?.let { session.lines[it].src } ?: ""
+ }
+ return ui.stack(3, ui.text("$what · $place", 13f, Palette.ink, bold = true), ui.text(quote, 13f, Palette.secondary, lines = 2)).apply {
+ background = ui.rounded(Palette.accentPale, 12)
+ setPadding(ui.dp(12), ui.dp(10), ui.dp(12), ui.dp(10))
+ }
+ }
+
+ // MARK: Done
+
+ private fun done(r: ShareRecord) {
+ header(if (copied == "link") L("链接已复制") else L("已分享"))
+ box.addView(field(r.url), ui.lp(top = 16))
+ box.addView(buttons(
+ ui.button(if (copied == "link") L("已复制") else L("复制链接"), "quiet", height = 48) { copy(r.url, "link"); render() },
+ ui.button(L("分享"), "primary", height = 48) {
+ // The link alone: the password goes in a message of its own.
+ activity.startActivity(Intent.createChooser(Intent(Intent.ACTION_SEND).setType("text/plain")
+ .putExtra(Intent.EXTRA_SUBJECT, SessionStore.displayTitle(session)).putExtra(Intent.EXTRA_TEXT, r.url), L("分享")))
+ }), ui.lp(top = 10))
+ r.password?.let { pw ->
+ box.addView(LinearLayout(activity).apply {
+ orientation = LinearLayout.HORIZONTAL
+ gravity = Gravity.CENTER_VERTICAL
+ addView(field(pw), ui.weight())
+ addView(ui.textButton(if (copied == "password") L("已复制") else L("复制密码")) { copy(pw, "password"); render() })
+ }, ui.lp(top = 12))
+ }
+ box.addView(ui.text(status(r), 13f, Palette.secondary), ui.lp(top = 12))
+ box.addView(View(activity).apply { setBackgroundColor(Palette.divider) }, LinearLayout.LayoutParams(-1, 1).apply { topMargin = ui.dp(14) })
+ if (confirmRevoke) {
+ box.addView(ui.text(L("取消后链接立即失效"), 15f, Palette.ink, bold = true), ui.lp(top = 14))
+ box.addView(ui.text(L("已查看过的人可能留有副本。"), 13f, Palette.tertiary), ui.lp(top = 2))
+ val stop = ui.button(L("取消分享"), "primary") {
+ app.background.execute {
+ val ok = app.share.revoke(r, sessionId)
+ app.main.post { if (ok) dialog.dismiss() else set(Step.Failed(message("network"))) }
+ }
+ }
+ stop.background = ui.ripple(ui.rounded(android.graphics.Color.parseColor("#B3261E"), 28), 28, dark = true)
+ box.addView(buttons(ui.button(L("暂不取消"), "quiet") { confirmRevoke = false; render() }, stop), ui.lp(top = 14))
+ } else {
+ box.addView(LinearLayout(activity).apply {
+ orientation = LinearLayout.HORIZONTAL
+ addView(ui.textButton(L("取消分享"), android.graphics.Color.parseColor("#B3261E")) { confirmRevoke = true; render() })
+ addView(ui.spacer())
+ addView(ui.textButton(L("在浏览器中打开")) {
+ try { activity.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(r.url))) } catch (_: Exception) {}
+ })
+ }, ui.lp(top = 6))
+ }
+ }
+
+ // One line, the middle left out when long (selectable text would wrap instead); 复制 copies it whole.
+ private fun field(text: String) = ui.text(text, 14f, Palette.ink).apply {
+ typeface = Typeface.MONOSPACE
+ isSingleLine = true
+ ellipsize = android.text.TextUtils.TruncateAt.MIDDLE
+ background = ui.rounded(Palette.ground, 12)
+ setPadding(ui.dp(12), ui.dp(10), ui.dp(12), ui.dp(10))
+ }
+
+ private fun status(r: ShareRecord): String {
+ // Ten minutes of slack: the server's clock, not the phone's, set the expiry.
+ val left = maxOf(1L, Math.ceil((r.expiresAt.epochSecond - Instant.now().epochSecond - 600) / 86400.0).toLong())
+ val expiry = LF("%lld 天后失效", left)
+ return views?.let { expiry + " · " + LF("打开 %lld 次", it) } ?: expiry
+ }
+
+ private fun loadViews(r: ShareRecord) {
+ app.background.execute {
+ val s = app.share.stats(listOf(r.id))[r.id] ?: return@execute
+ app.main.post {
+ if (s.state != "live") { ShareStore.remove(sessionId); set(Step.Settings) }
+ else { views = s.views; if (step is Step.Done) render() }
+ }
+ }
+ }
+
+ private fun failed(message: String) {
+ header(L("没有分享出去"))
+ box.addView(ui.text(message, 15f, Palette.ink), ui.lp(top = 14))
+ box.addView(buttons(ui.button(L("关闭"), "quiet") { dialog.dismiss() }, ui.button(L("重试"), "primary") { go() }), ui.lp(top = 18))
+ }
+
+ private fun copy(text: String, what: String) {
+ activity.getSystemService(android.content.ClipboardManager::class.java)
+ .setPrimaryClip(android.content.ClipData.newPlainText(if (what == "link") "link" else "password", text))
+ copied = what
+ }
+
+ companion object {
+ /// The sheet on screen, for the debug commands.
+ var open: ShareSheet? = null
+
+ /// Not while the meeting is still going, nor before an import has its text.
+ fun canShare(app: CicadaApp, s: Session) =
+ !(s.lines.isEmpty() && (s.notes?.isEmpty ?: true)) && app.store.liveId != s.id && s.importing != true
+
+ fun category(q: String) = when (q) {
+ "credential" -> L("密码或密钥")
+ "confidential" -> L("未公开的公司信息")
+ "crossborder" -> L("不宜跨境传输的信息")
+ "personal" -> L("个人身份信息")
+ "harmful" -> L("违法或危险内容")
+ else -> q
+ }
+
+ fun message(code: String) = when (code) {
+ "rate_limited", "too_many_shares" -> L("分享得太频繁了,请稍后再试。")
+ "review_unavailable" -> L("敏感内容检查暂时不可用,没有检查就不会分享。请稍后再试。")
+ "sharing_off" -> L("分享功能暂时关闭了。")
+ "update_required" -> L("请先更新知了。")
+ "too_large" -> L("这场会议太长,可以只分享纪要。")
+ "bad_document" -> L("这场会议没有可分享的内容。")
+ "network" -> L("连不上 cicada.indaloop.app,请检查网络。")
+ else -> L("服务器出了问题,请稍后再试。")
+ }
+ }
+}
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/Ui.kt b/android/app/src/main/kotlin/com/wquguru/cicada/Ui.kt
index fc5c587..1ff2f02 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/Ui.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/Ui.kt
@@ -108,7 +108,7 @@ class Ui(val context: Context) {
}
/// A row with a switch; the whole row toggles it.
- fun switchRow(label: String, helper: String, on: Boolean, changed: (Boolean) -> Unit): LinearLayout {
+ fun switchRow(label: String, helper: String?, on: Boolean, titleLines: Int = 1, changed: (Boolean) -> Unit): LinearLayout {
val sw = android.widget.Switch(context).apply {
isChecked = on
val states = arrayOf(intArrayOf(android.R.attr.state_checked), intArrayOf())
@@ -120,7 +120,7 @@ class Ui(val context: Context) {
isClickable = false
}
lateinit var row: LinearLayout
- row = listRow(label, helper, trailing = sw, chevron = false) {
+ row = listRow(label, helper, trailing = sw, chevron = false, titleView = text(label, 16f, Palette.ink, lines = titleLines)) {
sw.isChecked = !sw.isChecked
changed(sw.isChecked)
row.stateDescription = if (sw.isChecked) cicada.Strings.L("已开启") else cicada.Strings.L("已关闭")
diff --git a/android/app/src/main/res/xml/data_extraction_rules.xml b/android/app/src/main/res/xml/data_extraction_rules.xml
index b294e3e..427fc96 100644
--- a/android/app/src/main/res/xml/data_extraction_rules.xml
+++ b/android/app/src/main/res/xml/data_extraction_rules.xml
@@ -12,5 +12,8 @@
</cloud-backup>
<device-transfer>
<exclude domain="file" path="ling-api-key" />
+ <!-- 分享…: this phone's share identity and the links' manage tokens stay on this phone. -->
+ <exclude domain="file" path="share-device.json" />
+ <exclude domain="file" path="Shares" />
</device-transfer>
</data-extraction-rules>
diff --git a/android/cli/src/main/kotlin/cicada/cli/ShareTests.kt b/android/cli/src/main/kotlin/cicada/cli/ShareTests.kt
new file mode 100644
index 0000000..68d84e0
--- /dev/null
+++ b/android/cli/src/main/kotlin/cicada/cli/ShareTests.kt
@@ -0,0 +1,202 @@
+// 分享…: the Mac's ShareTests (the share document is a contract with the server and the other
+// apps: the same record gives the same bytes, Tests/fixtures/share), plus the crypto Android does
+// itself (Ed25519, PBKDF2) and the client's requests against a fake server.
+package cicada.cli
+
+import cicada.*
+import java.io.File
+import java.security.KeyFactory
+import java.security.Signature
+import java.security.spec.X509EncodedKeySpec
+
+object ShareTests {
+ val tests: List<Pair<String, () -> Unit>> = listOf(
+ "shareDocMatchesTheMacsBytes" to ::fixtureBytes,
+ "shareDocLeavesNothingPrivate" to ::nothingPrivateLeaves,
+ "shareDocNamesWhenAsked" to ::namesWhenAsked,
+ "shareDocNotesOnlyAndRemoved" to ::notesOnlyAndRemoved,
+ "shareDocSpeakerNumbersWithoutNames" to ::speakerNumbersWithoutNames,
+ "shareDocRoundsAndKeepsSlashes" to ::roundsAndKeepsSlashes,
+ "sharePasswordIsTheBrowsersPbkdf2" to ::password,
+ "shareBlockedHitsMapBack" to ::blockedHitsMapBack,
+ "ed25519MatchesRfc8032" to ::ed25519Vectors,
+ "ed25519VerifiesWithTheJdk" to ::ed25519Jdk,
+ "shareClientRegistersOnceAndSigns" to ::clientSigns,
+ )
+
+ private fun check(ok: Boolean, what: String) { if (!ok) throw AssertionError(what) }
+ private fun <T> equal(expected: T, actual: T, what: String) { if (expected != actual) throw AssertionError("$what: expected «$expected», got «$actual»") }
+
+ private val fixtures get() = File(resources, "../Tests/fixtures/share")
+ private fun session() = Session.read(File(fixtures, "session.json").readText())!!
+ private fun setUp() { loadStrings("zh-Hans"); SpeakerLabels.voices = true }
+ private fun hex(b: ByteArray) = ShareClient.hex(b)
+ private fun bytes(hex: String) = ByteArray(hex.length / 2) { hex.substring(it * 2, it * 2 + 2).toInt(16).toByte() }
+
+ private fun fixtureBytes() {
+ setUp()
+ val want = File(fixtures, "share-doc.json").readText().trim()
+ equal(want, ShareProjection.encode(ShareProjection.doc(session(), ShareScope.Full, names = false)), "the Mac's share document")
+ }
+
+ private fun nothingPrivateLeaves() {
+ setUp()
+ val text = ShareProjection.encode(ShareProjection.doc(session(), ShareScope.Full, names = false))
+ for (secret in listOf("/Users/someone", "Emma", "Kenji", "Emmer", "Sure, Emma")) check(!text.contains(secret), secret)
+ }
+
+ private fun namesWhenAsked() {
+ setUp()
+ val notes = ShareProjection.doc(session(), ShareScope.Full, names = true)["notes"].obj()!!
+ equal("Emma", notes["todos"].arr()[0].obj()!!["owner"], "to-do owner")
+ equal("Emma", notes["terms"].arr()[0].obj()!!["name"], "term")
+ }
+
+ private fun notesOnlyAndRemoved() {
+ setUp()
+ val s = session()
+ equal(0, ShareProjection.doc(s, ShareScope.Notes, names = false)["lines"].arr().size, "notes only has no lines")
+ val d = ShareProjection.doc(s, ShareScope.Full, names = false, removed = setOf(3), dropNotes = true)
+ equal(3, d["lines"].arr().size, "a line removed")
+ equal(null, d["notes"], "notes dropped")
+ equal(2, d["hidden"], "hidden counts both")
+ }
+
+ private fun speakerNumbersWithoutNames() {
+ setUp()
+ val s = session()
+ // Two voices with five substantive lines each get numbers; their names stay out.
+ s.lines = (0 until 10).map { i ->
+ TranscriptLine(id = "v$i", t = i.toDouble(), speaker = "them", src = "this is line number $i", dst = "第 $i 句话", srcLang = "en", dstLang = "zh", voice = if (i % 2 == 0) 3 else 7)
+ }.toMutableList()
+ equal(setOf("说话人 1", "说话人 2"), ShareProjection.doc(s, ShareScope.Full, names = false)["lines"].arr().map { it.obj()!!["who"] }.toSet(), "numbers")
+ equal(setOf("Emma", "Kenji"), ShareProjection.doc(s, ShareScope.Full, names = true)["lines"].arr().map { it.obj()!!["who"] }.toSet(), "names")
+ }
+
+ private fun roundsAndKeepsSlashes() {
+ setUp()
+ val s = session()
+ s.lines = mutableListOf(
+ TranscriptLine(id = "a", t = 12.25, src = "see https://example.com/a/b", dst = "see https://example.com/a/b", srcLang = "en-US", dstLang = "zh-Hans"),
+ TranscriptLine(id = "b", t = 0.05, src = "x", dst = "", srcLang = "en", dstLang = "zh"))
+ val text = ShareProjection.encode(ShareProjection.doc(s, ShareScope.Full, names = false))
+ check(text.contains("\"src\":\"see https://example.com/a/b\""), "slashes as they are")
+ check(!text.contains("\"dst\""), "no dst when the same as src or empty")
+ check(text.contains("\"t\":12.3") && text.contains("\"t\":0.1"), "halves round up like Swift: $text")
+ check(text.contains("\"langs\":[\"en\",\"zh\"]"), "base codes")
+ }
+
+ private fun password() {
+ val salt = ByteArray(16) { 1 }
+ // Same as the browser's crypto.subtle PBKDF2-SHA256, 32 bytes (server/test/api.test.mjs).
+ val v = SharePassword.verifier("ruby-41-lake", salt, 1000)
+ equal("eab69fcd00a0517794c156495dd76ad1fbfb036ea03df3d59a68a33519009c81", hex(v), "PBKDF2 vector")
+ check(!v.contentEquals(SharePassword.verifier("ruby-41-laka", salt, 1000)), "another password differs")
+ equal(3, SharePassword.make().split("-").size, "word-NN-word")
+ }
+
+ private fun blockedHitsMapBack() {
+ // The server counts lines of what was sent; the app maps them back to the record.
+ val hits = listOf(ShareHit("lines", 2, 3, listOf("credential")))
+ equal(setOf(4, 5), ShareHit.recordLines(hits, listOf(0, 1, 4, 5, 6)), "record lines")
+ }
+
+ private fun ed25519Vectors() {
+ // RFC 8032 §7.1, tests 1–3 and the 1023-byte message's key.
+ val cases = listOf(
+ Triple("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60", "",
+ "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b"),
+ Triple("4ccd089b28ff96da9db6c346ec114e0f5b8a319f35aba624da8cf6ed4fb8a6fb", "72",
+ "92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00"),
+ Triple("c5aa8df43f9f837bedb7442f31dcb7b166d38535076f094b85ce3a2e0b4458f7", "af82",
+ "6291d657deec24024827e69c3abe01a30ce548a284743a445e3680d7db5ac3ac18ff9b538d16f290ae67f760984dc6594a7c15e9716ed28dc027beceea1ec40a"),
+ )
+ val publics = listOf("d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a",
+ "3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c",
+ "fc51cd8e6218a1a38da47ed00230f0580816ed13ba3303ac5deb911548908025")
+ cases.forEachIndexed { i, (seed, msg, sig) ->
+ equal(publics[i], hex(Ed25519.publicKey(bytes(seed))), "public key $i")
+ equal(sig, hex(Ed25519.sign(bytes(seed), bytes(msg))), "signature $i")
+ }
+ }
+
+ private fun ed25519Jdk() {
+ // The JDK has Ed25519 (Android only from 13): it must accept ours for random keys and messages.
+ val random = java.util.Random(7)
+ repeat(8) { n ->
+ val seed = ByteArray(32).also(random::nextBytes)
+ val msg = ByteArray(n * 37).also(random::nextBytes)
+ val spec = X509EncodedKeySpec(bytes("302a300506032b6570032100") + Ed25519.publicKey(seed))
+ val v = Signature.getInstance("Ed25519")
+ v.initVerify(KeyFactory.getInstance("Ed25519").generatePublic(spec))
+ v.update(msg)
+ check(v.verify(Ed25519.sign(seed, msg)), "JDK verifies signature $n")
+ // Ed25519 is deterministic: the JDK's own signature is the same bytes.
+ val s = Signature.getInstance("Ed25519")
+ s.initSign(KeyFactory.getInstance("Ed25519").generatePrivate(java.security.spec.PKCS8EncodedKeySpec(bytes("302e020100300506032b657004220420") + seed)))
+ s.update(msg)
+ equal(hex(s.sign()), hex(Ed25519.sign(seed, msg)), "same signature as the JDK $n")
+ }
+ }
+
+ /// A fake server that checks what auth.js checks: the proof of work, then each signature.
+ private fun clientSigns() {
+ setUp()
+ val home = File(Paths.root, "share-test").apply { deleteRecursively(); mkdirs() }
+ val root = Paths.root
+ Paths.root = home
+ try {
+ var pub: ByteArray? = null
+ var registrations = 0
+ var forget = false
+ val calls = ArrayList<String>()
+ val transport = object : Transport {
+ override fun send(url: String, method: String, body: String?, headers: Map<String, String>, timeoutMs: Int): Transport.Response {
+ val path = url.removePrefix("https://test")
+ calls.add("$method $path")
+ check(headers["X-Cicada-Client"] == "android/1.5.1", "client header")
+ if (path == "/api/v1/devices") {
+ val o = Json.parseObject(body!!)!!
+ val key = java.util.Base64.getUrlDecoder().decode(o["key"].str())
+ val work = ShareClient.sha256(key + java.util.Base64.getUrlDecoder().decode(o["pow"].str()))
+ check(work[0].toInt() == 0 && work[1].toInt() == 0 && (work[2].toInt() and 0xF0) == 0, "20 zero bits")
+ equal("android", o["platform"], "platform")
+ pub = key; registrations++; forget = false
+ return Transport.Response(201, """{"device":"${"ab".repeat(16)}"}""")
+ }
+ if (forget) return Transport.Response(401, """{"code":"unknown_device"}""")
+ val message = "$method\n$path\n${headers["X-Cicada-Time"]}\n${headers["X-Cicada-Nonce"]}\n${hex(ShareClient.sha256((body ?: "").toByteArray()))}"
+ val v = Signature.getInstance("Ed25519")
+ v.initVerify(KeyFactory.getInstance("Ed25519").generatePublic(X509EncodedKeySpec(bytes("302a300506032b6570032100") + pub!!)))
+ v.update(message.toByteArray())
+ check(v.verify(java.util.Base64.getUrlDecoder().decode(headers["X-Cicada-Signature"])), "signed $method $path")
+ check(Regex("^[A-Za-z0-9_-]{16,64}$").matches(headers["X-Cicada-Nonce"]!!), "nonce shape")
+ return when {
+ method == "POST" && body!!.contains("Hk8!") -> Transport.Response(422, """{"code":"blocked","hits":[{"part":"lines","from":1,"to":1,"questions":["credential"]}]}""")
+ method == "POST" -> {
+ check(headers["Idempotency-Key"]!!.startsWith("20261106-140000-"), "idempotency key")
+ check(!body!!.contains("\\/"), "body keeps slashes")
+ Transport.Response(201, """{"id":"AAAAAAAAAAAAAAAAAAAAAA","url":"https://test/s/AAAAAAAAAAAAAAAAAAAAAA","token":"tok","expiresAt":1800000000}""")
+ }
+ method == "DELETE" -> { check(headers["Authorization"] == "Bearer tok", "manage token"); Transport.Response(204, "") }
+ else -> Transport.Response(200, """{"shares":[{"id":"AAAAAAAAAAAAAAAAAAAAAA","expiresAt":1800000000,"state":"live","views":3}]}""")
+ }
+ }
+ }
+ val client = ShareClient("android", "1.5.1", transport, "https://test")
+ val s = session()
+ val shared = client.share(s, ShareClient.Options(scope = ShareScope.Full, password = "ruby-41-lake")) as ShareClient.Outcome.Shared
+ equal("ruby-41-lake", ShareStore.read(s.id)?.password, "record kept, with its password")
+ equal(3, client.stats(listOf(shared.record.id))[shared.record.id]?.views, "stats")
+ equal(1, registrations, "registered once")
+ forget = true // the server lost this phone: registers again, once
+ check(client.revoke(shared.record, s.id), "revoked")
+ equal(2, registrations, "registered again after unknown_device")
+ equal(null, ShareStore.read(s.id), "record forgotten")
+ s.lines[1].src = "The prod database password is Hk8!vQ2#mZ, root account."
+ val blocked = client.share(s, ShareClient.Options(scope = ShareScope.Full)) as ShareClient.Outcome.Blocked
+ equal(setOf(1), ShareHit.recordLines(blocked.hits, blocked.kept), "blocked line")
+ check(!File(home, "share-device.json").readText().contains("tok"), "no token in the device file")
+ } finally { Paths.root = root }
+ }
+}
diff --git a/android/cli/src/main/kotlin/cicada/cli/Tests.kt b/android/cli/src/main/kotlin/cicada/cli/Tests.kt
index 26c0790..9bd100e 100644
--- a/android/cli/src/main/kotlin/cicada/cli/Tests.kt
+++ b/android/cli/src/main/kotlin/cicada/cli/Tests.kt
@@ -91,7 +91,7 @@ object Tests {
"notesPromptNamesTheVoices" to ::notesPromptNamesTheVoices,
"aHalfSentenceJoinsOnlyTheSameVoice" to ::aHalfSentenceJoinsOnlyTheSameVoice,
"slowVoiceprintsNeverHoldSubtitlesBack" to ::slowVoiceprintsNeverHoldSubtitlesBack,
- ) + ProviderTests.tests + AICheckTests.tests + FixTests.tests
+ ) + ProviderTests.tests + AICheckTests.tests + FixTests.tests + ShareTests.tests
var passed = 0; var failed = 0
for ((name, test) in tests) {
try { test(); passed++ } catch (e: Throwable) { failed++; println("FAIL $name: ${e.message ?: e.javaClass.simpleName}") }
diff --git a/android/core/src/main/kotlin/cicada/Ed25519.kt b/android/core/src/main/kotlin/cicada/Ed25519.kt
new file mode 100644
index 0000000..fd6c3b7
--- /dev/null
+++ b/android/core/src/main/kotlin/cicada/Ed25519.kt
@@ -0,0 +1,98 @@
+package cicada
+
+import java.math.BigInteger
+import java.security.MessageDigest
+
+/// Ed25519 signing (RFC 8032), for the share service's device key (ShareClient). Android has it
+/// built in only from Android 13 (API 33) and the app runs from Android 10, so this is the RFC's
+/// reference algorithm on BigInteger, with the platform's SHA-512: slow by crypto standards (tens
+/// of milliseconds a signature), which is nothing for one request. Signing only; the server
+/// verifies. Tested against RFC 8032's vectors and the JDK's own Ed25519 (cli Tests).
+/// Not constant-time: the key only names this phone to the share service (rate limits and owning
+/// its links), and nothing else on the phone can time the signing.
+object Ed25519 {
+ private val TWO = BigInteger.valueOf(2) // BigInteger.TWO is Android 13+
+ private val P = BigInteger.ONE.shiftLeft(255).subtract(BigInteger.valueOf(19))
+ private val Q = BigInteger.ONE.shiftLeft(252).add(BigInteger("27742317777372353535851937790883648493"))
+ private val D = BigInteger.valueOf(-121665).multiply(inv(BigInteger.valueOf(121666))).mod(P)
+ private val D2 = D.shiftLeft(1).mod(P)
+ private val SQRT_M1 = TWO.modPow(P.subtract(BigInteger.ONE).shiftRight(2), P)
+ private val G: Array<BigInteger> = run {
+ val y = BigInteger.valueOf(4).multiply(inv(BigInteger.valueOf(5))).mod(P)
+ val x = recoverX(y)
+ arrayOf(x, y, BigInteger.ONE, x.multiply(y).mod(P))
+ }
+
+ private fun inv(x: BigInteger) = x.modPow(P.subtract(TWO), P)
+
+ private fun recoverX(y: BigInteger): BigInteger {
+ val yy = y.multiply(y)
+ val x2 = yy.subtract(BigInteger.ONE).multiply(inv(D.multiply(yy).add(BigInteger.ONE))).mod(P)
+ var x = x2.modPow(P.add(BigInteger.valueOf(3)).shiftRight(3), P)
+ if (x.multiply(x).subtract(x2).mod(P).signum() != 0) x = x.multiply(SQRT_M1).mod(P)
+ return if (x.testBit(0)) P.subtract(x) else x // the base point's x is even
+ }
+
+ // Extended coordinates (X, Y, Z, T), x = X/Z, y = Y/Z, xy = T/Z.
+ private fun add(a: Array<BigInteger>, b: Array<BigInteger>): Array<BigInteger> {
+ val pa = a[1].subtract(a[0]).multiply(b[1].subtract(b[0])).mod(P)
+ val pb = a[1].add(a[0]).multiply(b[1].add(b[0])).mod(P)
+ val c = a[3].multiply(D2).multiply(b[3]).mod(P)
+ val d = a[2].shiftLeft(1).multiply(b[2]).mod(P)
+ val e = pb.subtract(pa); val f = d.subtract(c); val g = d.add(c); val h = pb.add(pa)
+ return arrayOf(e.multiply(f).mod(P), g.multiply(h).mod(P), f.multiply(g).mod(P), e.multiply(h).mod(P))
+ }
+
+ private fun mul(scalar: BigInteger, point: Array<BigInteger>): Array<BigInteger> {
+ var q = arrayOf(BigInteger.ZERO, BigInteger.ONE, BigInteger.ONE, BigInteger.ZERO)
+ var p = point
+ for (i in 0 until scalar.bitLength()) {
+ if (scalar.testBit(i)) q = add(q, p)
+ p = add(p, p)
+ }
+ return q
+ }
+
+ private fun compress(pt: Array<BigInteger>): ByteArray {
+ val z = inv(pt[2])
+ val x = pt[0].multiply(z).mod(P)
+ var y = pt[1].multiply(z).mod(P)
+ if (x.testBit(0)) y = y.setBit(255)
+ return little(y)
+ }
+
+ private fun little(n: BigInteger): ByteArray {
+ val big = n.toByteArray()
+ val out = ByteArray(32)
+ for (i in 0 until minOf(32, big.size)) out[i] = big[big.size - 1 - i]
+ return out
+ }
+
+ private fun number(b: ByteArray): BigInteger = BigInteger(1, b.reversedArray())
+
+ private fun sha512(vararg parts: ByteArray): ByteArray {
+ val md = MessageDigest.getInstance("SHA-512")
+ for (p in parts) md.update(p)
+ return md.digest()
+ }
+
+ private fun expand(seed: ByteArray): Pair<BigInteger, ByteArray> {
+ require(seed.size == 32) { "an Ed25519 seed is 32 bytes" }
+ val h = sha512(seed)
+ val a = number(h.copyOfRange(0, 32)).and(BigInteger.ONE.shiftLeft(254).subtract(BigInteger.valueOf(8))).setBit(254)
+ return a to h.copyOfRange(32, 64)
+ }
+
+ /// The 32-byte public key of a 32-byte private seed.
+ fun publicKey(seed: ByteArray): ByteArray = compress(mul(expand(seed).first, G))
+
+ /// A 64-byte signature of `message`.
+ fun sign(seed: ByteArray, message: ByteArray, publicKey: ByteArray = publicKey(seed)): ByteArray {
+ val (a, prefix) = expand(seed)
+ val r = number(sha512(prefix, message)).mod(Q)
+ val rs = compress(mul(r, G))
+ val h = number(sha512(rs, publicKey, message)).mod(Q)
+ val s = r.add(h.multiply(a)).mod(Q)
+ return rs + little(s)
+ }
+}
diff --git a/android/core/src/main/kotlin/cicada/Export.kt b/android/core/src/main/kotlin/cicada/Export.kt
index 8b26ae1..ad69df0 100644
--- a/android/core/src/main/kotlin/cicada/Export.kt
+++ b/android/core/src/main/kotlin/cicada/Export.kt
@@ -66,6 +66,24 @@ object SpeakerLabels {
fun label(number: Int, names: Map<Int, String>): String = names[number] ?: Strings.LF("说话人 %lld", number)
+ /// The notes with names: Ling wrote "说话人 6" before anyone named them (SpeakerLabels.named on
+ /// the Mac). A copy; the record keeps what Ling wrote.
+ fun named(notes: MeetingNotes, names: Map<Int, String>): MeetingNotes {
+ val n = MeetingNotes.from(notes.toJson())
+ if (names.isEmpty()) return n
+ fun swap(text: String): String {
+ if (!text.contains("说话人") && !text.contains("Speaker")) return text
+ var out = text
+ for ((k, name) in names.entries.sortedByDescending { it.key }) // 说话人 12 before 说话人 1
+ for (form in listOf("说话人 $k", "说话人$k", "Speaker $k")) out = out.replace(form, name)
+ return out
+ }
+ n.summary = swap(n.summary)
+ for (t in n.topics) { t.title = swap(t.title); t.summary = swap(t.summary); t.points = t.points.map(::swap).toMutableList() }
+ for (i in n.conclusions + n.todos) { i.text = swap(i.text); i.owner = i.owner?.let(::swap) }
+ return n
+ }
+
/// Who said a line: 你 · 同传 (said with 我说, so the other side heard its translation), a
/// speaker's name or number, else 对方 (未识别 once others have numbers).
fun speakerName(l: TranscriptLine, numbers: Map<String, Int>, names: Map<Int, String>): String {
diff --git a/android/core/src/main/kotlin/cicada/Json.kt b/android/core/src/main/kotlin/cicada/Json.kt
index 4f375ec..e71bb8d 100644
--- a/android/core/src/main/kotlin/cicada/Json.kt
+++ b/android/core/src/main/kotlin/cicada/Json.kt
@@ -117,16 +117,18 @@ object Json {
}
}
- fun write(value: Any?, pretty: Boolean = true): String {
+ /// `slashes = false` writes "/" as it is, like JSONEncoder's .withoutEscapingSlashes (the share
+ /// document, ShareProjection.swift).
+ fun write(value: Any?, pretty: Boolean = true, slashes: Boolean = true): String {
val b = StringBuilder()
- emit(b, value, pretty, 0)
+ emit(b, value, pretty, 0, slashes)
return b.toString()
}
- private fun emit(b: StringBuilder, v: Any?, pretty: Boolean, depth: Int) {
+ private fun emit(b: StringBuilder, v: Any?, pretty: Boolean, depth: Int, slashes: Boolean) {
when (v) {
null -> b.append("null")
- is String -> quote(b, v)
+ is String -> quote(b, v, slashes)
is Boolean -> b.append(if (v) "true" else "false")
is Int, is Long -> b.append(v.toString())
is Double -> b.append(number(v))
@@ -139,9 +141,9 @@ object Json {
entries.forEachIndexed { n, e ->
if (n > 0) b.append(',')
if (pretty) b.append('\n').append(" ".repeat(depth + 1))
- quote(b, e.key as String)
+ quote(b, e.key as String, slashes)
b.append(if (pretty) " : " else ":")
- emit(b, e.value, pretty, depth + 1)
+ emit(b, e.value, pretty, depth + 1, slashes)
}
if (pretty) b.append('\n').append(" ".repeat(depth))
b.append('}')
@@ -152,12 +154,12 @@ object Json {
v.forEachIndexed { n, x ->
if (n > 0) b.append(',')
if (pretty) b.append('\n').append(" ".repeat(depth + 1))
- emit(b, x, pretty, depth + 1)
+ emit(b, x, pretty, depth + 1, slashes)
}
if (pretty) b.append('\n').append(" ".repeat(depth))
b.append(']')
}
- else -> quote(b, v.toString())
+ else -> quote(b, v.toString(), slashes)
}
}
@@ -170,13 +172,13 @@ object Json {
return if (s.contains('E')) BigDecimal(s).stripTrailingZeros().toPlainString() else s
}
- private fun quote(b: StringBuilder, s: String) {
+ private fun quote(b: StringBuilder, s: String, slashes: Boolean) {
b.append('"')
for (c in s) {
when (c) {
'"' -> b.append("\\\"")
'\\' -> b.append("\\\\")
- '/' -> b.append("\\/")
+ '/' -> if (slashes) b.append("\\/") else b.append('/')
'\n' -> b.append("\\n")
'\r' -> b.append("\\r")
'\t' -> b.append("\\t")
diff --git a/android/core/src/main/kotlin/cicada/Share.kt b/android/core/src/main/kotlin/cicada/Share.kt
new file mode 100644
index 0000000..51e1a08
--- /dev/null
+++ b/android/core/src/main/kotlin/cicada/Share.kt
@@ -0,0 +1,362 @@
+package cicada
+
+import java.io.File
+import java.io.IOException
+import java.security.MessageDigest
+import java.security.SecureRandom
+import java.time.Instant
+import java.util.Base64
+import javax.crypto.Mac
+import javax.crypto.spec.SecretKeySpec
+
+// A meeting shared as a link on cicada.indaloop.app (ShareProjection.swift, ShareClient.swift).
+
+enum class ShareScope(val id: String) { Notes("notes"), Full("full") }
+
+/// The share document (v1): what goes to the share page, made from a meeting record. Only these
+/// fields leave the phone: never the record's file paths, 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 same bytes as the Mac (Tests/fixtures/share); server/src/doc.js reads them.
+object ShareProjection {
+ /// `removed`: indices into the record's lines the user took out; `dropNotes` leaves the notes out.
+ fun doc(s: Session, scope: ShareScope, names: Boolean, removed: Set<Int> = emptySet(), dropNotes: Boolean = false): Map<String, Any?> {
+ val numbers = SpeakerLabels.numbers(s.lines)
+ val nameMap = if (names) SpeakerLabels.names(s) else emptyMap()
+ fun who(l: TranscriptLine): String {
+ if (l.speaker == "me") return Strings.L("分享者")
+ val n = numbers[l.id] ?: return Strings.L("对方")
+ return if (names) SpeakerLabels.label(n, nameMap) else Strings.LF("说话人 %lld", n)
+ }
+ val lines = ArrayList<Map<String, Any?>>()
+ if (scope == ShareScope.Full) s.lines.forEachIndexed { i, l ->
+ if (i in removed || l.src.isEmpty()) return@forEachIndexed
+ val dst = l.dst?.takeIf { it.isNotEmpty() && it != l.src }
+ lines.add(mapOf("t" to round(l.t), "who" to who(l), "src" to l.src, "dst" to dst))
+ }
+ val raw = s.notes
+ val notes = if (dropNotes || raw == null || raw.isEmpty) null else {
+ val n = if (names) SpeakerLabels.named(raw, nameMap) else raw
+ mapOf(
+ "summary" to n.summary,
+ "topics" to n.topics.map { mapOf("start" to round(it.start), "title" to it.title, "summary" to it.summary, "points" to it.points) },
+ "conclusions" to n.conclusions.map { mapOf("text" to it.text, "t" to it.t?.let(::round)) },
+ "todos" to n.todos.map { mapOf("text" to it.text, "owner" to (if (names) it.owner else null), "t" to it.t?.let(::round)) },
+ "terms" to if (names) n.terms.map { mapOf("name" to it.name, "note" to it.note) } else emptyList(),
+ )
+ }
+ val hidden = (if (scope == ShareScope.Full) removed.size else 0) + (if (dropNotes && raw != null && !raw.isEmpty) 1 else 0)
+ return mapOf(
+ "v" to 1, "title" to SessionStore.displayTitle(s), "startedAt" to Iso8601.write(s.startedAt),
+ "duration" to Math.round(s.durationSeconds), "langs" to languages(s.lines),
+ "notes" to notes, "lines" to lines, "hidden" to hidden,
+ )
+ }
+
+ /// The meeting's usual direction ("en" → "zh"), by the most lines; ties go to the earliest.
+ fun languages(lines: List<TranscriptLine>): List<String> {
+ val count = LinkedHashMap<String, Int>()
+ for (l in lines) if (l.dst != null) {
+ val key = base(l.srcLang) + ">" + base(l.dstLang)
+ count[key] = (count[key] ?: 0) + 1
+ }
+ // LinkedHashMap keeps first-seen order, so the first of the most is the earliest.
+ val top = count.entries.fold(null as Map.Entry<String, Int>?) { best, e -> if (best == null || e.value > best.value) e else best } ?: return emptyList()
+ return top.key.split(">").filter { it.isNotEmpty() } // Swift's split drops empty parts
+ }
+
+ private fun base(code: String) = (code.split("-").firstOrNull { it.isNotEmpty() } ?: code).lowercase()
+
+ /// One decimal, halves away from zero as Swift's rounded(): the page shows seconds, and short
+ /// numbers keep the bytes the same on every platform.
+ fun round(t: Double): Double = Math.signum(t) * Math.floor(Math.abs(t) * 10 + 0.5) / 10
+
+ /// Compact, sorted keys, "/" unescaped: JSONEncoder's [.sortedKeys, .withoutEscapingSlashes].
+ fun encode(doc: Map<String, Any?>): String = Json.write(doc, pretty = false, slashes = false)
+}
+
+/// Where the review found a problem: the notes, or lines `from`…`to` of what was sent.
+data class ShareHit(val part: String, val from: Int?, val to: Int?, val questions: List<String>) {
+ companion object {
+ fun from(o: Map<String, Any?>) = ShareHit(o["part"].str() ?: "", o["from"].int(), o["to"].int(), o["questions"].arr().mapNotNull { it.str() })
+
+ /// The record's line indices behind the hits, given which record lines were sent (`kept`).
+ fun recordLines(hits: List<ShareHit>, kept: List<Int>): Set<Int> {
+ val out = HashSet<Int>()
+ for (h in hits) if (h.part == "lines") {
+ val a = h.from ?: continue; val b = h.to ?: continue
+ if (a > b) continue
+ for (i in a..b) if (i >= 0 && i < kept.size) out.add(kept[i])
+ }
+ return out
+ }
+ }
+}
+
+object SharePassword {
+ const val 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 never leaves either side. Written out over the
+ /// platform's HMAC-SHA256 (one block is all 32 bytes need) rather than SecretKeyFactory, whose
+ /// providers turn the password into bytes differently on Android and the JDK.
+ fun verifier(password: String, salt: ByteArray, iterations: Int = ITERATIONS): ByteArray {
+ val mac = Mac.getInstance("HmacSHA256")
+ mac.init(SecretKeySpec(password.toByteArray(Charsets.UTF_8).let { if (it.isEmpty()) ByteArray(1) else it }, "HmacSHA256"))
+ // An empty password can't be a SecretKeySpec; HMAC pads keys with zeros, so one zero byte is the same key.
+ var u = mac.doFinal(salt + byteArrayOf(0, 0, 0, 1))
+ val out = u.copyOf()
+ for (i in 1 until iterations) {
+ u = mac.doFinal(u)
+ for (k in out.indices) out[k] = (out[k].toInt() xor u[k].toInt()).toByte()
+ }
+ return out
+ }
+
+ /// "ruby-41-lake": easy to read out and type; the server limits how many can be tried.
+ fun make(random: java.util.Random = SecureRandom()): String {
+ val w = WORDS.split(" ")
+ return "${w[random.nextInt(w.size)]}-${10 + random.nextInt(90)}-${w[random.nextInt(w.size)]}"
+ }
+
+ private const val 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"
+}
+
+/// What the phone keeps about a shared meeting. The manage token (needed to turn the link off)
+/// lives only here, in the app's private files (Shares/<record id>.json), never in the record,
+/// exports or logs; so does the password, so it can be copied again.
+data class ShareRecord(
+ val id: String, val url: String, val token: String, val expiresAt: Instant,
+ val scope: String, val password: String?, val createdAt: Instant,
+) {
+ fun toJson(): Map<String, Any?> = mapOf(
+ "id" to id, "url" to url, "token" to token, "expiresAt" to Iso8601.write(expiresAt),
+ "scope" to scope, "password" to password, "createdAt" to Iso8601.write(createdAt),
+ )
+
+ companion object {
+ fun from(o: Map<String, Any?>): ShareRecord? {
+ val id = o["id"].str() ?: return null
+ return ShareRecord(id, o["url"].str() ?: return null, o["token"].str() ?: return null,
+ Iso8601.read(o["expiresAt"].str()) ?: return null, o["scope"].str() ?: "notes",
+ o["password"].str(), Iso8601.read(o["createdAt"].str()) ?: Instant.EPOCH)
+ }
+ }
+}
+
+/// Shares/<record id>.json and the device key, in the app's private folder (Paths.root), readable
+/// by this app only and left out of backups and device transfers (data_extraction_rules.xml).
+object ShareStore {
+ val folder get() = File(Paths.root, "Shares")
+ val deviceFile get() = File(Paths.root, "share-device.json")
+
+ fun read(sessionId: String): ShareRecord? =
+ try { Json.parseObject(File(folder, "$sessionId.json").readText())?.let(ShareRecord::from) } catch (_: Exception) { null }
+
+ fun save(r: ShareRecord, sessionId: String) = writePrivate(File(folder, "$sessionId.json"), Json.write(r.toJson()))
+
+ fun remove(sessionId: String) { File(folder, "$sessionId.json").delete() }
+
+ fun all(): Map<String, ShareRecord> =
+ (folder.listFiles() ?: emptyArray()).filter { it.name.endsWith(".json") }
+ .mapNotNull { f -> read(f.name.removeSuffix(".json"))?.let { f.name.removeSuffix(".json") to it } }.toMap()
+
+ fun writePrivate(f: File, text: String): Boolean = try {
+ f.parentFile?.mkdirs()
+ val tmp = File(f.path + ".tmp")
+ tmp.writeText(text)
+ tmp.setReadable(false, false); tmp.setReadable(true, true)
+ tmp.setWritable(false, false); tmp.setWritable(true, true)
+ if (!tmp.renameTo(f)) { f.writeText(text); tmp.delete() }
+ true
+ } catch (e: Exception) {
+ Log.d("share: could not write ${f.name} ${e.javaClass.simpleName}")
+ false
+ }
+}
+
+/// Talks to the share service on cicada.indaloop.app (server/). There are no accounts: this phone
+/// is an Ed25519 key made on first use (share-device.json), 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. Calls block: run
+/// them off the main thread.
+class ShareClient(
+ private val platform: String,
+ private val version: String,
+ private val transport: Transport = UrlTransport,
+ /// The dev build can point at a local Worker.
+ var base: String = "https://cicada.indaloop.app",
+) {
+ sealed class Outcome {
+ class Shared(val record: ShareRecord) : Outcome()
+ class Blocked(val hits: List<ShareHit>, val kept: List<Int>) : Outcome()
+ class Failed(val code: String, val retryAfter: Int?) : Outcome()
+ }
+
+ class Stats(val id: String, val expiresAt: Double, val state: String, val views: Int)
+
+ class Failure(val code: String, val retryAfter: Int? = null) : Exception(code)
+
+ data class Options(
+ val scope: ShareScope = ShareScope.Notes, val days: Int = 7, val names: Boolean = false,
+ val password: String? = null, val summaryInPreview: Boolean = false,
+ val removed: Set<Int> = emptySet(), val dropNotes: Boolean = false,
+ )
+
+ private val random = SecureRandom()
+ private val gate = Any()
+
+ private class Device(val seed: ByteArray, val pub: ByteArray, val id: String?, val server: String?)
+
+ private fun loadDevice(): Device {
+ val o = try { Json.parseObject(ShareStore.deviceFile.readText()) } catch (_: Exception) { null }
+ val seed = try { o?.get("key").str()?.let { Base64.getDecoder().decode(it) } } catch (_: Exception) { null }
+ if (o != null && seed != null && seed.size == 32) return Device(seed, Ed25519.publicKey(seed), o["device"].str(), o["server"].str())
+ val fresh = ByteArray(32).also(random::nextBytes)
+ saveDevice(fresh, null, null)
+ return Device(fresh, Ed25519.publicKey(fresh), null, null)
+ }
+
+ private fun saveDevice(seed: ByteArray, id: String?, server: String?) {
+ ShareStore.writePrivate(ShareStore.deviceFile, Json.write(mapOf("key" to Base64.getEncoder().encodeToString(seed), "device" to id, "server" to server)))
+ }
+
+ /// The device, registering this phone with the server first if needed (one at a time).
+ private fun device(force: Boolean = false): Device = synchronized(gate) {
+ val d = loadDevice()
+ if (!force && d.id != null && d.server == base) return d
+ val nonce = proofOfWork(d.pub)
+ val body = Json.write(mapOf("key" to b64url(d.pub), "pow" to b64url(nonce), "platform" to platform, "version" to version), pretty = false)
+ val r = send("POST", "/api/v1/devices", body, emptyMap(), null)
+ val id = Json.parseObject(r.body)?.get("device").str()
+ if (r.status != 201 || id == null) {
+ Log.d("share: register failed ${r.status} ${code(r.body) ?: "?"}")
+ throw Failure(code(r.body) ?: "register_failed", Json.parseObject(r.body)?.get("retryAfter").int())
+ }
+ saveDevice(d.seed, id, base)
+ Log.d("share: device registered")
+ return Device(d.seed, d.pub, id, base)
+ }
+
+ private fun send(method: String, path: String, body: String?, headers: Map<String, String>, signer: Device?): Transport.Response {
+ val h = LinkedHashMap<String, String>()
+ h["Content-Type"] = "application/json"
+ h["X-Cicada-Client"] = "$platform/$version"
+ h.putAll(headers)
+ if (signer != null) {
+ val time = (System.currentTimeMillis() / 1000).toString()
+ val nonce = b64url(ByteArray(16).also(random::nextBytes))
+ val bytes = (body ?: "").toByteArray(Charsets.UTF_8)
+ val message = "$method\n$path\n$time\n$nonce\n${hex(sha256(bytes))}"
+ h["X-Cicada-Device"] = signer.id!!
+ h["X-Cicada-Time"] = time
+ h["X-Cicada-Nonce"] = nonce
+ h["X-Cicada-Signature"] = b64url(Ed25519.sign(signer.seed, message.toByteArray(Charsets.UTF_8), signer.pub))
+ }
+ return try { transport.send(base + path, method, body, h, 90_000) } catch (e: IOException) { throw Failure("network") }
+ }
+
+ /// A signed call; registers again once if the server no longer knows this phone.
+ private fun signed(method: String, path: String, body: String? = null, headers: Map<String, String> = emptyMap()): Transport.Response {
+ var r = send(method, path, body, headers, device())
+ if (r.status == 401 && code(r.body) == "unknown_device") r = send(method, path, body, headers, device(force = true))
+ return r
+ }
+
+ fun share(s: Session, o: Options): Outcome {
+ val doc = ShareProjection.doc(s, o.scope, o.names, o.removed, o.dropNotes)
+ val kept = if (o.scope == ShareScope.Full) s.lines.indices.filter { it !in o.removed && s.lines[it].src.isNotEmpty() } else emptyList()
+ val encoded = ShareProjection.encode(doc)
+ val body = LinkedHashMap<String, Any?>()
+ body["doc"] = doc
+ body["scope"] = o.scope.id
+ body["days"] = o.days
+ body["summaryInPreview"] = o.summaryInPreview
+ o.password?.let { pw ->
+ val salt = ByteArray(16).also(random::nextBytes)
+ body["password"] = mapOf("salt" to b64url(salt), "iter" to SharePassword.ITERATIONS,
+ "hash" to b64url(sha256(SharePassword.verifier(pw, salt))))
+ }
+ return try {
+ // The same meeting, content and settings sent again (the answer was lost) gets the same
+ // link back; any other setting makes a new share.
+ val settings = "${o.scope.id}|${o.days}|${o.names}|${o.password ?: ""}|${o.summaryInPreview}"
+ val idem = s.id + "-" + hex(sha256(encoded.toByteArray(Charsets.UTF_8) + settings.toByteArray(Charsets.UTF_8)).copyOf(8))
+ val r = signed("POST", "/api/v1/shares", Json.write(body, pretty = false, slashes = false), mapOf("Idempotency-Key" to idem))
+ val obj = Json.parseObject(r.body) ?: emptyMap()
+ when (r.status) {
+ 200, 201 -> {
+ val id = obj["id"].str(); val url = obj["url"].str(); val token = obj["token"].str(); val exp = obj["expiresAt"].num()
+ if (id == null || url == null || token == null || exp == null) return Outcome.Failed("server_error", null)
+ ShareStore.read(s.id)?.takeIf { it.id != id }?.let { revoke(it, null) }
+ val rec = ShareRecord(id, url, token, Instant.ofEpochSecond(exp.toLong()), o.scope.id, o.password, Instant.now())
+ ShareStore.save(rec, s.id)
+ Log.d("share: ${s.id} shared (${o.scope.id}, ${o.days} days${if (o.password == null) "" else ", password"})")
+ Outcome.Shared(rec)
+ }
+ 422 -> {
+ val hits = obj["hits"].arr().mapNotNull { it.obj()?.let(ShareHit::from) }
+ Log.d("share: ${s.id} blocked " + hits.joinToString("; ") { h ->
+ h.part + (h.from?.let { " $it-${h.to ?: it}" } ?: "") + " " + h.questions.joinToString(",")
+ })
+ Outcome.Blocked(hits, kept)
+ }
+ else -> {
+ Log.d("share: ${s.id} failed ${r.status} ${obj["code"].str() ?: "?"}")
+ Outcome.Failed(obj["code"].str() ?: "server_error", obj["retryAfter"].int())
+ }
+ }
+ } catch (f: Failure) {
+ Outcome.Failed(f.code, f.retryAfter)
+ } catch (e: Exception) {
+ Log.d("share: failed ${e.javaClass.simpleName}")
+ Outcome.Failed("server_error", null)
+ }
+ }
+
+ /// Turns the link off on the server and forgets it here. `sessionId` null: the record is being replaced.
+ fun revoke(r: ShareRecord, sessionId: String?): Boolean {
+ val ok = try {
+ val res = signed("DELETE", "/api/v1/shares/${r.id}", headers = mapOf("Authorization" to "Bearer ${r.token}"))
+ // 404: already gone (or never ours); either way nothing to keep.
+ (res.status == 204 || res.status == 404).also { if (!it) Log.d("share: revoke ${r.id} failed ${res.status} ${code(res.body) ?: "?"}") }
+ } catch (e: Exception) {
+ Log.d("share: revoke ${r.id} failed ${e.message}")
+ false
+ }
+ if (ok && sessionId != null) ShareStore.remove(sessionId)
+ return ok
+ }
+
+ fun stats(ids: List<String>): Map<String, Stats> {
+ if (ids.isEmpty()) return emptyMap()
+ return try {
+ val r = signed("GET", "/api/v1/shares?ids=${ids.joinToString(",")}")
+ if (r.status != 200) return emptyMap()
+ Json.parseObject(r.body)?.get("shares").arr().mapNotNull { it.obj() }.mapNotNull { o ->
+ val id = o["id"].str() ?: return@mapNotNull null
+ id to Stats(id, o["expiresAt"].num() ?: 0.0, o["state"].str() ?: "", o["views"].int() ?: 0)
+ }.toMap()
+ } catch (_: Exception) { emptyMap() }
+ }
+
+ companion object {
+ /// 20 leading zero bits of sha256(public key ‖ 8-byte big-endian nonce): about a million hashes.
+ fun proofOfWork(pub: ByteArray): ByteArray {
+ val md = MessageDigest.getInstance("SHA-256")
+ val nonce = ByteArray(8)
+ var n = 0L
+ while (true) {
+ for (i in 0 until 8) nonce[i] = (n ushr (56 - 8 * i)).toByte()
+ md.update(pub); md.update(nonce)
+ val h = md.digest()
+ if (h[0].toInt() == 0 && h[1].toInt() == 0 && (h[2].toInt() and 0xFF) < 16) return nonce.copyOf()
+ n++
+ }
+ }
+
+ fun sha256(b: ByteArray): ByteArray = MessageDigest.getInstance("SHA-256").digest(b)
+ fun hex(b: ByteArray) = b.joinToString("") { "%02x".format(it.toInt() and 0xFF) }
+ fun b64url(b: ByteArray): String = Base64.getUrlEncoder().withoutPadding().encodeToString(b)
+ private fun code(body: String) = Json.parseObject(body)?.get("code").str()
+ }
+}