Add a personal-account Tencent Meeting interview test bench.
The Tauri app vendors tmeet for browser OAuth, lists and creates meetings, launches the desktop client, and sends local playback audio to Doubao streaming ASR.
This commit is contained in:
@@ -0,0 +1,150 @@
|
||||
//! Loopback capture of the default playback device.
|
||||
//!
|
||||
//! Windows uses WASAPI loopback: open the render endpoint, then initialize a
|
||||
//! capture client on it. That is "what you hear", not a single process.
|
||||
//! macOS has no system loopback. Linux has no Tencent Meeting client to capture.
|
||||
|
||||
use ookie_tx_meeting_core::asr::{to_16k_mono, AsrSession, SAMPLE_RATE};
|
||||
use ookie_tx_meeting_core::error::{AppError, AppResult};
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
pub fn platform_note() -> &'static str {
|
||||
if cfg!(windows) {
|
||||
"Windows:采集默认播放设备。腾讯会议的声音和其他正在播放的声音都会进去。面试时不要放别的音频。"
|
||||
} else if cfg!(target_os = "macos") {
|
||||
"macOS 没有系统回环。请先安装 BlackHole,把腾讯会议的输出指到它。本原型不假装能直接采。"
|
||||
} else {
|
||||
"当前是 Linux,没有可采集的腾讯会议播放输出。用「测试识别」跑 fixture,或在 Windows 真机上采集。"
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn capture_to(session: AsrSession, stop: mpsc::Receiver<()>) -> AppResult<()> {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
capture_wasapi(session, stop).await
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
let _ = (session, stop);
|
||||
Err(AppError::new("capture_unavailable", platform_note()))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
async fn capture_wasapi(session: AsrSession, mut stop: mpsc::Receiver<()>) -> AppResult<()> {
|
||||
let (tx, mut rx) = mpsc::channel::<Vec<u8>>(16);
|
||||
let (ready_tx, ready_rx) = tokio::sync::oneshot::channel::<Result<(), String>>();
|
||||
|
||||
std::thread::spawn(move || {
|
||||
let result = wasapi_thread(tx);
|
||||
let _ = ready_tx.send(result);
|
||||
});
|
||||
|
||||
match ready_rx.await {
|
||||
Ok(Ok(())) => {}
|
||||
Ok(Err(detail)) => return Err(AppError::new("capture_failed", detail)),
|
||||
Err(_) => return Err(AppError::new("capture_failed", "采集线程退出")),
|
||||
}
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
packet = rx.recv() => {
|
||||
match packet {
|
||||
Some(pcm) => session.push(pcm).await?,
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
_ = stop.recv() => break,
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn wasapi_thread(tx: mpsc::Sender<Vec<u8>>) -> Result<(), String> {
|
||||
use wasapi::{DeviceCollection, Direction, SampleType, StreamMode, WaveFormat};
|
||||
|
||||
let hr = wasapi::initialize_mta();
|
||||
if hr.is_err() {
|
||||
return Err(format!("COM 初始化失败: {hr:?}"));
|
||||
}
|
||||
// 0.19 has no DeviceEnumerator. The first active render device is the default output.
|
||||
let collection = DeviceCollection::new(&Direction::Render).map_err(|e| e.to_string())?;
|
||||
let device = collection
|
||||
.get_device_at_index(0)
|
||||
.map_err(|e| format!("找不到播放设备: {e}"))?;
|
||||
let mut audio_client = device.get_iaudioclient().map_err(|e| format!("无法打开播放设备: {e}"))?;
|
||||
let mix = audio_client.get_mixformat().map_err(|e| format!("无法读取混音格式: {e}"))?;
|
||||
let channels = mix.get_nchannels();
|
||||
let rate = mix.get_samplespersec();
|
||||
let sample_type = mix.get_subformat().map_err(|e| format!("无法识别采样格式: {e}"))?;
|
||||
let desired = WaveFormat::new(
|
||||
mix.get_bitspersample() as usize,
|
||||
mix.get_validbitspersample() as usize,
|
||||
&sample_type,
|
||||
rate as usize,
|
||||
channels as usize,
|
||||
None,
|
||||
);
|
||||
let (default_period, _) = audio_client.get_device_period().map_err(|e| e.to_string())?;
|
||||
let mode = StreamMode::EventsShared {
|
||||
autoconvert: true,
|
||||
buffer_duration_hns: default_period.max(200_000),
|
||||
};
|
||||
audio_client
|
||||
.initialize_client(&desired, &Direction::Capture, &mode)
|
||||
.map_err(|e| format!("初始化回环失败: {e}"))?;
|
||||
let capture = audio_client.get_audiocaptureclient().map_err(|e| e.to_string())?;
|
||||
let event = audio_client.set_get_eventhandle().map_err(|e| e.to_string())?;
|
||||
audio_client.start_stream().map_err(|e| format!("无法开始采集: {e}"))?;
|
||||
|
||||
let mut acc = Vec::new();
|
||||
let mut scratch = vec![0u8; 64 * 1024];
|
||||
loop {
|
||||
if tx.is_closed() {
|
||||
break;
|
||||
}
|
||||
if event.wait_for_event(500).is_err() {
|
||||
if tx.is_closed() {
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let (frames, _) = match capture.read_from_device(&mut scratch) {
|
||||
Ok(read) => read,
|
||||
Err(_) => break,
|
||||
};
|
||||
let byte_count = frames as usize * mix.get_blockalign() as usize;
|
||||
if frames == 0 || byte_count == 0 || byte_count > scratch.len() {
|
||||
continue;
|
||||
}
|
||||
let chunk = &scratch[..byte_count];
|
||||
let pcm = if sample_type == SampleType::Float {
|
||||
f32_bytes_to_s16(chunk, channels, rate)
|
||||
} else {
|
||||
to_16k_mono(chunk, channels, rate)
|
||||
};
|
||||
acc.extend_from_slice(&pcm);
|
||||
let packet = (SAMPLE_RATE as usize) * 2 / 5; // 200 ms
|
||||
while acc.len() >= packet {
|
||||
let send: Vec<u8> = acc.drain(..packet).collect();
|
||||
if tx.blocking_send(send).is_err() {
|
||||
let _ = audio_client.stop_stream();
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
let _ = audio_client.stop_stream();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn f32_bytes_to_s16(input: &[u8], channels: u16, rate: u32) -> Vec<u8> {
|
||||
let mut s16 = Vec::with_capacity(input.len() / 2);
|
||||
for frame in input.chunks_exact(4) {
|
||||
let sample = f32::from_le_bytes([frame[0], frame[1], frame[2], frame[3]]);
|
||||
let clipped = (sample.clamp(-1.0, 1.0) * i16::MAX as f32) as i16;
|
||||
s16.extend_from_slice(&clipped.to_le_bytes());
|
||||
}
|
||||
to_16k_mono(&s16, channels, rate)
|
||||
}
|
||||
@@ -0,0 +1,372 @@
|
||||
use crate::capture;
|
||||
use crate::settings;
|
||||
use ookie_tx_meeting_core::asr::SpeechSettings;
|
||||
use ookie_tx_meeting_core::asr::{AsrSession, TranscriptEvent};
|
||||
use ookie_tx_meeting_core::error::{AppError, AppResult};
|
||||
use ookie_tx_meeting_core::launch;
|
||||
use ookie_tx_meeting_core::tmeet;
|
||||
use serde::Serialize;
|
||||
use serde_json::{json, Value};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::Duration;
|
||||
use tauri::{AppHandle, Emitter, State};
|
||||
use tokio::sync::{mpsc, Mutex};
|
||||
|
||||
pub struct AppState {
|
||||
pub capturing: AtomicBool,
|
||||
stop_capture: Mutex<Option<mpsc::Sender<()>>>,
|
||||
}
|
||||
|
||||
impl Default for AppState {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
capturing: AtomicBool::new(false),
|
||||
stop_capture: Mutex::new(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn emit_transcript(app: &AppHandle, event: &TranscriptEvent, source: &str) {
|
||||
let _ = app.emit(
|
||||
"transcript",
|
||||
json!({
|
||||
"source": source,
|
||||
"text": event.text,
|
||||
"definite": event.definite,
|
||||
"speakerId": event.speaker_id,
|
||||
"startMs": event.start_ms,
|
||||
"endMs": event.end_ms,
|
||||
"logId": event.log_id,
|
||||
"error": event.raw_error,
|
||||
"speakerNote": "豆包的说话人编号不是腾讯会议里的人名"
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async fn forward_events(app: AppHandle, mut events: mpsc::Receiver<TranscriptEvent>, source: String) {
|
||||
while let Some(event) = events.recv().await {
|
||||
emit_transcript(&app, &event, &source);
|
||||
}
|
||||
let _ = app.emit("transcript-closed", json!({ "source": source }));
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct AuthView {
|
||||
pub logged_in: bool,
|
||||
pub summary: String,
|
||||
pub raw: Value,
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn app_info() -> Value {
|
||||
json!({
|
||||
"name": "OOKIE 腾讯会议测试台",
|
||||
"account": "个人版",
|
||||
"limits": [
|
||||
"个人版没有会中实时转写 API,字幕来自本机播放声音 + 豆包",
|
||||
"个人版没有直播在线花名册,会中只能看到受邀人和等候室记录",
|
||||
"豆包说话人编号对不上腾讯会议人名",
|
||||
"授权在浏览器完成,拉起客户端只用来核对登录账号"
|
||||
],
|
||||
"capture": capture::platform_note()
|
||||
})
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn tmeet_status() -> AppResult<AuthView> {
|
||||
let output = tmeet::run(&["--format", "json", "auth", "status"], Duration::from_secs(20)).await?;
|
||||
// v1.1.0 prints "Not logged in" and still exits 0. Do not trust the exit code alone.
|
||||
let logged_in = output.status == 0 && !tmeet::not_logged_in(&output.stdout, &output.stderr);
|
||||
Ok(AuthView {
|
||||
logged_in,
|
||||
summary: if logged_in {
|
||||
"已登录".into()
|
||||
} else {
|
||||
"未登录".into()
|
||||
},
|
||||
raw: output.json.unwrap_or(json!({ "stdout": output.stdout, "stderr": output.stderr })),
|
||||
})
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn tmeet_login() -> AppResult<Value> {
|
||||
let focus = launch::focus_client()?;
|
||||
// The CLI blocks until the browser flow finishes or its own 5-minute timer fires.
|
||||
let output = tmeet::run(
|
||||
&["--format", "json", "auth", "login"],
|
||||
Duration::from_secs(330),
|
||||
)
|
||||
.await?;
|
||||
if output.status != 0 {
|
||||
return Err(AppError::new(
|
||||
"login_failed",
|
||||
format!(
|
||||
"{}\n{}",
|
||||
output.stderr.trim(),
|
||||
output.stdout.trim()
|
||||
),
|
||||
));
|
||||
}
|
||||
Ok(json!({
|
||||
"focus": focus,
|
||||
"stdout": output.stdout,
|
||||
"stderr": output.stderr
|
||||
}))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn tmeet_logout() -> AppResult<Value> {
|
||||
let output = tmeet::require_ok(
|
||||
tmeet::run(&["--format", "json", "auth", "logout"], Duration::from_secs(30)).await?,
|
||||
)?;
|
||||
Ok(output.json.unwrap_or(json!({ "stdout": output.stdout })))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn meeting_list() -> AppResult<Value> {
|
||||
let output = tmeet::require_ok(
|
||||
tmeet::run(
|
||||
&["--format", "json", "meeting", "list", "--page-size", "20"],
|
||||
Duration::from_secs(30),
|
||||
)
|
||||
.await?,
|
||||
)?;
|
||||
Ok(output.json.unwrap_or(json!({ "stdout": output.stdout })))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn meeting_create(subject: String, start: String, end: String) -> AppResult<Value> {
|
||||
if subject.trim().is_empty() || subject.chars().count() > 80 {
|
||||
return Err(AppError::new("invalid_subject", "主题不能为空,且不超过 80 字"));
|
||||
}
|
||||
if !looks_like_iso(&start) || !looks_like_iso(&end) {
|
||||
return Err(AppError::new(
|
||||
"invalid_time",
|
||||
"时间用 ISO 8601,例如 2026-11-14T15:00:00+08:00",
|
||||
));
|
||||
}
|
||||
let output = tmeet::require_ok(
|
||||
tmeet::run(
|
||||
&[
|
||||
"--format",
|
||||
"json",
|
||||
"meeting",
|
||||
"create",
|
||||
"--subject",
|
||||
subject.trim(),
|
||||
"--start",
|
||||
start.trim(),
|
||||
"--end",
|
||||
end.trim(),
|
||||
],
|
||||
Duration::from_secs(40),
|
||||
)
|
||||
.await?,
|
||||
)?;
|
||||
Ok(output.json.unwrap_or(json!({ "stdout": output.stdout })))
|
||||
}
|
||||
|
||||
fn looks_like_iso(value: &str) -> bool {
|
||||
let v = value.trim();
|
||||
v.len() >= 16 && v.len() <= 40 && v.contains('T') && !v.contains(['\n', '\r', '"'])
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn meeting_get(meeting_code: String) -> AppResult<Value> {
|
||||
let code = digits(&meeting_code)?;
|
||||
let output = tmeet::require_ok(
|
||||
tmeet::run(
|
||||
&["--format", "json", "meeting", "get", "--meeting-code", &code],
|
||||
Duration::from_secs(30),
|
||||
)
|
||||
.await?,
|
||||
)?;
|
||||
Ok(output.json.unwrap_or(json!({ "stdout": output.stdout })))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn meeting_cancel(meeting_id: String) -> AppResult<Value> {
|
||||
let id = meeting_id.trim();
|
||||
if id.is_empty() || id.len() > 64 || id.contains([' ', '\n', '"']) {
|
||||
return Err(AppError::new("invalid_meeting_id", "会议 ID 不合法"));
|
||||
}
|
||||
let output = tmeet::require_ok(
|
||||
tmeet::run(
|
||||
&["--format", "json", "meeting", "cancel", "--meeting-id", id],
|
||||
Duration::from_secs(30),
|
||||
)
|
||||
.await?,
|
||||
)?;
|
||||
Ok(output.json.unwrap_or(json!({ "stdout": output.stdout })))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn meeting_launch(meeting_code: String) -> AppResult<launch::LaunchPlan> {
|
||||
launch::launch(&meeting_code)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn meeting_people(meeting_id: String) -> AppResult<Value> {
|
||||
let id = meeting_id.trim();
|
||||
if id.is_empty() || id.len() > 64 || id.contains([' ', '\n', '"']) {
|
||||
return Err(AppError::new("invalid_meeting_id", "会议 ID 不合法"));
|
||||
}
|
||||
let invitees = tmeet::run(
|
||||
&[
|
||||
"--format",
|
||||
"json",
|
||||
"meeting",
|
||||
"invitees-list",
|
||||
"--meeting-id",
|
||||
id,
|
||||
],
|
||||
Duration::from_secs(30),
|
||||
)
|
||||
.await?;
|
||||
let participants = tmeet::run(
|
||||
&[
|
||||
"--format",
|
||||
"json",
|
||||
"report",
|
||||
"participants",
|
||||
"--meeting-id",
|
||||
id,
|
||||
],
|
||||
Duration::from_secs(30),
|
||||
)
|
||||
.await?;
|
||||
let waiting = tmeet::run(
|
||||
&[
|
||||
"--format",
|
||||
"json",
|
||||
"report",
|
||||
"waiting-room-log",
|
||||
"--meeting-id",
|
||||
id,
|
||||
],
|
||||
Duration::from_secs(30),
|
||||
)
|
||||
.await?;
|
||||
Ok(json!({
|
||||
"invitees": invitees.json.unwrap_or(json!({ "stdout": invitees.stdout, "stderr": invitees.stderr, "status": invitees.status })),
|
||||
"participants": participants.json.unwrap_or(json!({ "stdout": participants.stdout, "stderr": participants.stderr, "status": participants.status })),
|
||||
"waitingRoom": waiting.json.unwrap_or(json!({ "stdout": waiting.stdout, "stderr": waiting.stderr, "status": waiting.status })),
|
||||
"note": "参会明细是入会/离会记录,不是直播在线花名册。会还没开始时为空是正常的。"
|
||||
}))
|
||||
}
|
||||
|
||||
fn digits(value: &str) -> AppResult<String> {
|
||||
let code: String = value.chars().filter(|c| c.is_ascii_digit()).collect();
|
||||
if code.len() < 9 || code.len() > 12 {
|
||||
return Err(AppError::new("invalid_meeting_code", "会议号应为 9–12 位数字"));
|
||||
}
|
||||
Ok(code)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn speech_get() -> Value {
|
||||
serde_json::to_value(settings::view(&settings::load())).unwrap_or(json!({}))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn speech_save(incoming: SpeechSettings) -> AppResult<Value> {
|
||||
let previous = settings::load();
|
||||
let next = settings::merge_secrets(incoming, &previous);
|
||||
settings::save(&next)?;
|
||||
Ok(serde_json::to_value(settings::view(&next)).unwrap_or(json!({})))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn speech_test(app: AppHandle) -> AppResult<Value> {
|
||||
let settings = settings::load();
|
||||
settings.validate()?;
|
||||
let pcm = fixture_pcm()?;
|
||||
let mut session = AsrSession::connect(settings).await?;
|
||||
let events = std::mem::replace(&mut session.events, mpsc::channel(1).1);
|
||||
tokio::spawn(forward_events(app, events, "fixture".into()));
|
||||
session.push(pcm).await?;
|
||||
session.finish();
|
||||
Ok(json!({
|
||||
"started": true,
|
||||
"note": "fixture 是 1.6 秒 220Hz 正弦,不是人声。豆包可能返回空或无意义文本,这只证明链路通了。"
|
||||
}))
|
||||
}
|
||||
|
||||
fn fixture_pcm() -> AppResult<Vec<u8>> {
|
||||
let path = fixture_path()?;
|
||||
let bytes = std::fs::read(&path)
|
||||
.map_err(|e| AppError::new("fixture_missing", format!("{}: {e}", path.display())))?;
|
||||
// Standard 44-byte PCM WAV header. The fixture is written that way.
|
||||
if bytes.len() < 44 || &bytes[0..4] != b"RIFF" {
|
||||
return Err(AppError::new("fixture_invalid", "fixture 不是 WAV"));
|
||||
}
|
||||
Ok(bytes[44..].to_vec())
|
||||
}
|
||||
|
||||
fn fixture_path() -> AppResult<std::path::PathBuf> {
|
||||
let mut candidates = Vec::new();
|
||||
if let Ok(cwd) = std::env::current_dir() {
|
||||
candidates.push(cwd.join("fixtures").join("sample.wav"));
|
||||
if let Some(parent) = cwd.parent() {
|
||||
candidates.push(parent.join("fixtures").join("sample.wav"));
|
||||
}
|
||||
}
|
||||
if let Ok(exe) = std::env::current_exe() {
|
||||
if let Some(dir) = exe.parent() {
|
||||
candidates.push(dir.join("fixtures").join("sample.wav"));
|
||||
}
|
||||
}
|
||||
candidates
|
||||
.into_iter()
|
||||
.find(|path| path.is_file())
|
||||
.ok_or_else(|| AppError::new("fixture_missing", "找不到 fixtures/sample.wav"))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn capture_start(app: AppHandle, state: State<'_, AppState>) -> AppResult<Value> {
|
||||
if state.capturing.swap(true, Ordering::SeqCst) {
|
||||
return Err(AppError::new("already_capturing", "已经在采集"));
|
||||
}
|
||||
let started = capture_start_inner(app, &state).await;
|
||||
if started.is_err() {
|
||||
state.capturing.store(false, Ordering::SeqCst);
|
||||
}
|
||||
started
|
||||
}
|
||||
|
||||
async fn capture_start_inner(app: AppHandle, state: &AppState) -> AppResult<Value> {
|
||||
let settings = settings::load();
|
||||
settings.validate()?;
|
||||
let session = AsrSession::connect(settings).await?;
|
||||
let (stop_tx, stop_rx) = mpsc::channel(1);
|
||||
*state.stop_capture.lock().await = Some(stop_tx);
|
||||
let mut session = session;
|
||||
let events = std::mem::replace(&mut session.events, mpsc::channel(1).1);
|
||||
let app_for_task = app.clone();
|
||||
tokio::spawn(async move {
|
||||
if let Err(err) = capture::capture_to(session, stop_rx).await {
|
||||
let _ = app_for_task.emit(
|
||||
"transcript",
|
||||
json!({ "source": "loopback", "error": err.detail, "text": "", "definite": true }),
|
||||
);
|
||||
}
|
||||
});
|
||||
let app2 = app.clone();
|
||||
tokio::spawn(async move {
|
||||
forward_events(app2, events, "loopback".into()).await;
|
||||
});
|
||||
Ok(json!({
|
||||
"started": true,
|
||||
"note": capture::platform_note(),
|
||||
"privacy": "候选人的声音会发到你在设置里填写的豆包服务。开始前需要已告知对方。"
|
||||
}))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn capture_stop(state: State<'_, AppState>) -> AppResult<Value> {
|
||||
state.capturing.store(false, Ordering::SeqCst);
|
||||
if let Some(stop) = state.stop_capture.lock().await.take() {
|
||||
let _ = stop.send(()).await;
|
||||
}
|
||||
Ok(json!({ "stopped": true }))
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||
|
||||
mod capture;
|
||||
mod commands;
|
||||
mod settings;
|
||||
|
||||
fn main() {
|
||||
tauri::Builder::default()
|
||||
.manage(commands::AppState::default())
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
commands::app_info,
|
||||
commands::tmeet_status,
|
||||
commands::tmeet_login,
|
||||
commands::tmeet_logout,
|
||||
commands::meeting_list,
|
||||
commands::meeting_create,
|
||||
commands::meeting_get,
|
||||
commands::meeting_cancel,
|
||||
commands::meeting_launch,
|
||||
commands::meeting_people,
|
||||
commands::speech_get,
|
||||
commands::speech_save,
|
||||
commands::speech_test,
|
||||
commands::capture_start,
|
||||
commands::capture_stop,
|
||||
])
|
||||
.run(tauri::generate_context!())
|
||||
.expect("腾讯会议测试台启动失败");
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
use ookie_tx_meeting_core::asr::SpeechSettings;
|
||||
use ookie_tx_meeting_core::error::{AppError, AppResult};
|
||||
use serde::Serialize;
|
||||
|
||||
pub const KEYRING_SERVICE: &str = "school.oops.ookie.tx-meeting";
|
||||
const KEYRING_USER: &str = "doubao-asr";
|
||||
|
||||
pub fn default_settings() -> SpeechSettings {
|
||||
SpeechSettings {
|
||||
auth_mode: "new".into(),
|
||||
api_key: String::new(),
|
||||
app_key: String::new(),
|
||||
access_key: String::new(),
|
||||
resource_id: "volc.seedasr.sauc.duration".into(),
|
||||
endpoint: "wss://openspeech.bytedance.com/api/v3/sauc/bigmodel_async".into(),
|
||||
hotwords: String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct SpeechSettingsView {
|
||||
pub auth_mode: String,
|
||||
pub api_key_set: bool,
|
||||
pub api_key_hint: String,
|
||||
pub app_key: String,
|
||||
pub access_key_set: bool,
|
||||
pub access_key_hint: String,
|
||||
pub resource_id: String,
|
||||
pub endpoint: String,
|
||||
pub hotwords: String,
|
||||
}
|
||||
|
||||
pub fn view(settings: &SpeechSettings) -> SpeechSettingsView {
|
||||
SpeechSettingsView {
|
||||
auth_mode: settings.auth_mode.clone(),
|
||||
api_key_set: !settings.api_key.is_empty(),
|
||||
api_key_hint: hint(&settings.api_key),
|
||||
app_key: settings.app_key.clone(),
|
||||
access_key_set: !settings.access_key.is_empty(),
|
||||
access_key_hint: hint(&settings.access_key),
|
||||
resource_id: settings.resource_id.clone(),
|
||||
endpoint: settings.endpoint.clone(),
|
||||
hotwords: settings.hotwords.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn hint(secret: &str) -> String {
|
||||
let n = secret.chars().count();
|
||||
if n == 0 {
|
||||
return String::new();
|
||||
}
|
||||
if n <= 4 {
|
||||
return "••••".into();
|
||||
}
|
||||
let tail: String = secret.chars().skip(n - 4).collect();
|
||||
format!("••••{tail}")
|
||||
}
|
||||
|
||||
pub fn load() -> SpeechSettings {
|
||||
let Ok(entry) = keyring::Entry::new(KEYRING_SERVICE, KEYRING_USER) else {
|
||||
return default_settings();
|
||||
};
|
||||
match entry.get_password() {
|
||||
Ok(raw) => serde_json::from_str(&raw).unwrap_or_else(|_| default_settings()),
|
||||
Err(_) => default_settings(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn save(settings: &SpeechSettings) -> AppResult<()> {
|
||||
settings.validate()?;
|
||||
let entry = keyring::Entry::new(KEYRING_SERVICE, KEYRING_USER)
|
||||
.map_err(|e| AppError::new("keyring_failed", e.to_string()))?;
|
||||
let raw = serde_json::to_string(settings)
|
||||
.map_err(|e| AppError::new("settings_invalid", e.to_string()))?;
|
||||
entry
|
||||
.set_password(&raw)
|
||||
.map_err(|e| AppError::new("keyring_failed", e.to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Empty secret fields keep the previously stored secret. Non-secret fields always overwrite.
|
||||
pub fn merge_secrets(incoming: SpeechSettings, previous: &SpeechSettings) -> SpeechSettings {
|
||||
let mut next = incoming;
|
||||
if next.api_key.trim().is_empty() {
|
||||
next.api_key = previous.api_key.clone();
|
||||
}
|
||||
if next.access_key.trim().is_empty() {
|
||||
next.access_key = previous.access_key.clone();
|
||||
}
|
||||
next
|
||||
}
|
||||
Reference in New Issue
Block a user