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,15 @@
|
||||
[package]
|
||||
name = "ookie-tx-meeting-core"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
description = "tmeet runner, join URL, and Doubao ASR framing. No GUI."
|
||||
license = "MIT"
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
tokio = { version = "1", features = ["rt-multi-thread", "sync", "time", "macros", "io-util", "process"] }
|
||||
tokio-tungstenite = { version = "0.26", default-features = false, features = ["connect", "rustls-tls-native-roots"] }
|
||||
futures-util = "0.3"
|
||||
flate2 = "1"
|
||||
uuid = { version = "1", features = ["v4"] }
|
||||
@@ -0,0 +1,497 @@
|
||||
//! Doubao streaming ASR (volcengine bigmodel_async).
|
||||
//!
|
||||
//! Wire format is the documented 4-byte header + big-endian payload size +
|
||||
//! gzip payload. Audio is pcm_s16le, 16 kHz, mono, about 200 ms per packet.
|
||||
//! Speaker ids returned here are Doubao clusters. They are not Tencent Meeting names.
|
||||
|
||||
use crate::error::{AppError, AppResult};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use flate2::write::GzEncoder;
|
||||
use flate2::read::GzDecoder;
|
||||
use flate2::Compression;
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use serde_json::{json, Value};
|
||||
use std::io::{Read, Write};
|
||||
use std::time::Duration;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
|
||||
use tokio_tungstenite::tungstenite::http::HeaderValue;
|
||||
use tokio_tungstenite::tungstenite::Message;
|
||||
use uuid::Uuid;
|
||||
|
||||
pub const SAMPLE_RATE: u32 = 16_000;
|
||||
|
||||
/// Speech settings the GUI stores in the OS keyring. The core crate only consumes them.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct SpeechSettings {
|
||||
pub auth_mode: String,
|
||||
pub api_key: String,
|
||||
pub app_key: String,
|
||||
pub access_key: String,
|
||||
pub resource_id: String,
|
||||
pub endpoint: String,
|
||||
pub hotwords: String,
|
||||
}
|
||||
|
||||
impl SpeechSettings {
|
||||
pub fn validate(&self) -> AppResult<()> {
|
||||
if !self.endpoint.starts_with("wss://") {
|
||||
return Err(AppError::new("invalid_endpoint", "endpoint 必须以 wss:// 开头"));
|
||||
}
|
||||
if self.resource_id.trim().is_empty() {
|
||||
return Err(AppError::new("invalid_resource", "资源 ID 不能为空"));
|
||||
}
|
||||
match self.auth_mode.as_str() {
|
||||
"new" if self.api_key.trim().is_empty() => {
|
||||
Err(AppError::new("credential_required", "新版控制台需要 API Key"))
|
||||
}
|
||||
"legacy" if self.app_key.trim().is_empty() || self.access_key.trim().is_empty() => {
|
||||
Err(AppError::new("credential_required", "旧版控制台需要 App Key 和 Access Key"))
|
||||
}
|
||||
"new" | "legacy" => Ok(()),
|
||||
_ => Err(AppError::new("invalid_auth_mode", "鉴权方式只能是 new 或 legacy")),
|
||||
}
|
||||
}
|
||||
}
|
||||
const PACKET_MS: u32 = 200;
|
||||
pub const PACKET_BYTES: usize = (SAMPLE_RATE as usize) * (PACKET_MS as usize) / 1000 * 2;
|
||||
|
||||
const MSG_FULL_CLIENT: u8 = 0b0001;
|
||||
const MSG_AUDIO_ONLY: u8 = 0b0010;
|
||||
const MSG_FULL_SERVER: u8 = 0b1001;
|
||||
const MSG_ERROR: u8 = 0b1111;
|
||||
|
||||
const FLAG_NONE: u8 = 0b0000;
|
||||
const FLAG_LAST: u8 = 0b0010;
|
||||
const SERIAL_JSON: u8 = 0b0001;
|
||||
const SERIAL_NONE: u8 = 0b0000;
|
||||
const COMPRESS_GZIP: u8 = 0b0001;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct TranscriptEvent {
|
||||
pub text: String,
|
||||
pub definite: bool,
|
||||
pub speaker_id: Option<String>,
|
||||
pub start_ms: Option<i64>,
|
||||
pub end_ms: Option<i64>,
|
||||
pub log_id: Option<String>,
|
||||
pub raw_error: Option<String>,
|
||||
}
|
||||
|
||||
pub fn hotwords(text: &str) -> Vec<Value> {
|
||||
text.lines()
|
||||
.map(str::trim)
|
||||
.filter(|line| !line.is_empty())
|
||||
.take(40)
|
||||
.map(|word| json!({ "word": word }))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn header_insert(
|
||||
headers: &mut tokio_tungstenite::tungstenite::http::HeaderMap,
|
||||
name: &'static str,
|
||||
value: &str,
|
||||
label: &str,
|
||||
) -> AppResult<()> {
|
||||
headers.insert(
|
||||
name,
|
||||
HeaderValue::from_str(value).map_err(|_| {
|
||||
AppError::new("invalid_credential", format!("{label} 含非法字符"))
|
||||
})?,
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn gzip(bytes: &[u8]) -> AppResult<Vec<u8>> {
|
||||
let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
|
||||
encoder
|
||||
.write_all(bytes)
|
||||
.map_err(|e| AppError::new("asr_frame_failed", e.to_string()))?;
|
||||
encoder
|
||||
.finish()
|
||||
.map_err(|e| AppError::new("asr_frame_failed", e.to_string()))
|
||||
}
|
||||
|
||||
fn gunzip(bytes: &[u8]) -> AppResult<Vec<u8>> {
|
||||
let mut decoder = GzDecoder::new(bytes);
|
||||
let mut out = Vec::new();
|
||||
decoder
|
||||
.read_to_end(&mut out)
|
||||
.map_err(|e| AppError::new("asr_frame_failed", e.to_string()))?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn header(message_type: u8, flags: u8, serialization: u8) -> [u8; 4] {
|
||||
[
|
||||
0b0001_0001, // version 1, header size 1 (4 bytes)
|
||||
(message_type << 4) | flags,
|
||||
(serialization << 4) | COMPRESS_GZIP,
|
||||
0,
|
||||
]
|
||||
}
|
||||
|
||||
fn frame(message_type: u8, flags: u8, serialization: u8, payload: &[u8]) -> AppResult<Vec<u8>> {
|
||||
let compressed = gzip(payload)?;
|
||||
let mut out = Vec::with_capacity(8 + compressed.len());
|
||||
out.extend_from_slice(&header(message_type, flags, serialization));
|
||||
out.extend_from_slice(&(compressed.len() as u32).to_be_bytes());
|
||||
out.extend_from_slice(&compressed);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn full_client_request(settings: &SpeechSettings) -> AppResult<Vec<u8>> {
|
||||
let words = hotwords(&settings.hotwords);
|
||||
let mut request = json!({
|
||||
"model_name": "bigmodel",
|
||||
"enable_itn": true,
|
||||
"enable_punc": true,
|
||||
"enable_ddc": false,
|
||||
"show_utterances": true,
|
||||
"enable_nonstream": true,
|
||||
"enable_speaker_info": true,
|
||||
"result_type": "full"
|
||||
});
|
||||
if !words.is_empty() {
|
||||
request["corpus"] = json!({
|
||||
"context": serde_json::to_string(&json!({ "hotwords": words })).unwrap_or_default()
|
||||
});
|
||||
}
|
||||
let payload = json!({
|
||||
"user": { "uid": "ookie-tx-meeting" },
|
||||
"audio": {
|
||||
"format": "pcm",
|
||||
"codec": "raw",
|
||||
"rate": SAMPLE_RATE,
|
||||
"bits": 16,
|
||||
"channel": 1
|
||||
},
|
||||
"request": request
|
||||
});
|
||||
frame(
|
||||
MSG_FULL_CLIENT,
|
||||
FLAG_NONE,
|
||||
SERIAL_JSON,
|
||||
payload.to_string().as_bytes(),
|
||||
)
|
||||
}
|
||||
|
||||
fn audio_frame(pcm: &[u8], last: bool) -> AppResult<Vec<u8>> {
|
||||
frame(
|
||||
MSG_AUDIO_ONLY,
|
||||
if last { FLAG_LAST } else { FLAG_NONE },
|
||||
SERIAL_NONE,
|
||||
pcm,
|
||||
)
|
||||
}
|
||||
|
||||
/// Parse one server frame. Returns None for frames that carry no transcript yet.
|
||||
pub fn parse_server_frame(bytes: &[u8]) -> AppResult<Option<TranscriptEvent>> {
|
||||
if bytes.len() < 8 {
|
||||
return Err(AppError::new("asr_frame_failed", "响应帧过短"));
|
||||
}
|
||||
let message_type = bytes[1] >> 4;
|
||||
let flags = bytes[1] & 0x0f;
|
||||
let compression = bytes[3] & 0x0f;
|
||||
let header_bytes = ((bytes[0] & 0x0f) as usize) * 4;
|
||||
|
||||
if message_type == MSG_ERROR {
|
||||
let code = if bytes.len() >= header_bytes + 4 {
|
||||
u32::from_be_bytes(bytes[header_bytes..header_bytes + 4].try_into().unwrap())
|
||||
} else {
|
||||
0
|
||||
};
|
||||
return Ok(Some(TranscriptEvent {
|
||||
text: String::new(),
|
||||
definite: true,
|
||||
speaker_id: None,
|
||||
start_ms: None,
|
||||
end_ms: None,
|
||||
log_id: None,
|
||||
raw_error: Some(format!("豆包返回错误 {code}")),
|
||||
}));
|
||||
}
|
||||
if message_type != MSG_FULL_SERVER {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let mut offset = header_bytes;
|
||||
if flags & 0b0001 != 0 {
|
||||
offset += 4; // sequence number
|
||||
}
|
||||
if offset + 4 > bytes.len() {
|
||||
return Err(AppError::new("asr_frame_failed", "响应帧缺少长度"));
|
||||
}
|
||||
let size = u32::from_be_bytes(bytes[offset..offset + 4].try_into().unwrap()) as usize;
|
||||
offset += 4;
|
||||
if offset + size > bytes.len() {
|
||||
return Err(AppError::new("asr_frame_failed", "响应帧长度不一致"));
|
||||
}
|
||||
let payload = &bytes[offset..offset + size];
|
||||
let json_bytes = if compression == COMPRESS_GZIP {
|
||||
gunzip(payload)?
|
||||
} else {
|
||||
payload.to_vec()
|
||||
};
|
||||
let value: Value = serde_json::from_slice(&json_bytes)
|
||||
.map_err(|e| AppError::new("asr_frame_failed", e.to_string()))?;
|
||||
Ok(event_from_payload(&value))
|
||||
}
|
||||
|
||||
fn event_from_payload(value: &Value) -> Option<TranscriptEvent> {
|
||||
let msg = value.get("payload_msg").unwrap_or(value);
|
||||
let result = msg.get("result")?;
|
||||
let text = result.get("text").and_then(Value::as_str).unwrap_or("").to_string();
|
||||
let log_id = result
|
||||
.pointer("/additions/log_id")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_string);
|
||||
let utterance = result
|
||||
.get("utterances")
|
||||
.and_then(Value::as_array)
|
||||
.and_then(|items| items.last());
|
||||
let definite = utterance
|
||||
.and_then(|u| u.get("definite"))
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false);
|
||||
let speaker_id = utterance
|
||||
.and_then(|u| u.pointer("/additions/speaker_id"))
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_string);
|
||||
let start_ms = utterance.and_then(|u| u.get("start_time")).and_then(Value::as_i64);
|
||||
let end_ms = utterance.and_then(|u| u.get("end_time")).and_then(Value::as_i64);
|
||||
if text.is_empty() && !definite {
|
||||
return None;
|
||||
}
|
||||
Some(TranscriptEvent {
|
||||
text,
|
||||
definite,
|
||||
speaker_id,
|
||||
start_ms,
|
||||
end_ms,
|
||||
log_id,
|
||||
raw_error: None,
|
||||
})
|
||||
}
|
||||
|
||||
pub struct AsrSession {
|
||||
pub events: mpsc::Receiver<TranscriptEvent>,
|
||||
audio: mpsc::Sender<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl AsrSession {
|
||||
pub async fn connect(settings: SpeechSettings) -> AppResult<Self> {
|
||||
settings.validate()?;
|
||||
let (audio_tx, audio_rx) = mpsc::channel::<Vec<u8>>(32);
|
||||
let (event_tx, event_rx) = mpsc::channel::<TranscriptEvent>(64);
|
||||
|
||||
let request = full_client_request(&settings)?;
|
||||
let url = settings.endpoint.clone();
|
||||
let resource_id = settings.resource_id.clone();
|
||||
let auth_mode = settings.auth_mode.clone();
|
||||
let api_key = settings.api_key.clone();
|
||||
let app_key = settings.app_key.clone();
|
||||
let access_key = settings.access_key.clone();
|
||||
|
||||
tokio::spawn(async move {
|
||||
if let Err(err) = drive(
|
||||
&url,
|
||||
&resource_id,
|
||||
&auth_mode,
|
||||
&api_key,
|
||||
&app_key,
|
||||
&access_key,
|
||||
request,
|
||||
audio_rx,
|
||||
event_tx.clone(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
let _ = event_tx
|
||||
.send(TranscriptEvent {
|
||||
text: String::new(),
|
||||
definite: true,
|
||||
speaker_id: None,
|
||||
start_ms: None,
|
||||
end_ms: None,
|
||||
log_id: None,
|
||||
raw_error: Some(err.detail),
|
||||
})
|
||||
.await;
|
||||
}
|
||||
});
|
||||
|
||||
Ok(Self {
|
||||
events: event_rx,
|
||||
audio: audio_tx,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn push(&self, pcm: Vec<u8>) -> AppResult<()> {
|
||||
self.audio
|
||||
.send(pcm)
|
||||
.await
|
||||
.map_err(|_| AppError::new("asr_closed", "识别连接已关闭"))
|
||||
}
|
||||
|
||||
pub fn finish(&self) {
|
||||
// Dropping the sender makes the driver send the final empty packet.
|
||||
}
|
||||
}
|
||||
|
||||
async fn drive(
|
||||
url: &str,
|
||||
resource_id: &str,
|
||||
auth_mode: &str,
|
||||
api_key: &str,
|
||||
app_key: &str,
|
||||
access_key: &str,
|
||||
first: Vec<u8>,
|
||||
mut audio_rx: mpsc::Receiver<Vec<u8>>,
|
||||
event_tx: mpsc::Sender<TranscriptEvent>,
|
||||
) -> AppResult<()> {
|
||||
let mut request = url
|
||||
.into_client_request()
|
||||
.map_err(|e| AppError::new("asr_connect_failed", e.to_string()))?;
|
||||
let headers = request.headers_mut();
|
||||
header_insert(headers, "X-Api-Resource-Id", resource_id, "资源 ID")?;
|
||||
header_insert(headers, "X-Api-Request-Id", &Uuid::new_v4().to_string(), "请求 ID")?;
|
||||
if auth_mode == "legacy" {
|
||||
header_insert(headers, "X-Api-App-Key", app_key, "App Key")?;
|
||||
header_insert(headers, "X-Api-Access-Key", access_key, "Access Key")?;
|
||||
} else {
|
||||
header_insert(headers, "X-Api-Key", api_key, "API Key")?;
|
||||
}
|
||||
|
||||
let (mut socket, response) = tokio::time::timeout(
|
||||
Duration::from_secs(15),
|
||||
tokio_tungstenite::connect_async(request),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| AppError::new("asr_connect_failed", "连接豆包超时"))?
|
||||
.map_err(|e| AppError::new("asr_connect_failed", e.to_string()))?;
|
||||
|
||||
let log_id = response
|
||||
.headers()
|
||||
.get("X-Tt-Logid")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.map(str::to_string);
|
||||
|
||||
socket
|
||||
.send(Message::Binary(first.into()))
|
||||
.await
|
||||
.map_err(|e| AppError::new("asr_send_failed", e.to_string()))?;
|
||||
|
||||
let mut pending = Vec::new();
|
||||
loop {
|
||||
tokio::select! {
|
||||
incoming = socket.next() => {
|
||||
match incoming {
|
||||
Some(Ok(Message::Binary(bytes))) => {
|
||||
if let Some(mut event) = parse_server_frame(&bytes)? {
|
||||
if event.log_id.is_none() {
|
||||
event.log_id = log_id.clone();
|
||||
}
|
||||
if event.raw_error.is_some() {
|
||||
let _ = event_tx.send(event).await;
|
||||
return Ok(());
|
||||
}
|
||||
let _ = event_tx.send(event).await;
|
||||
}
|
||||
}
|
||||
Some(Ok(Message::Close(_))) | None => break,
|
||||
Some(Err(e)) => return Err(AppError::new("asr_closed", e.to_string())),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
packet = audio_rx.recv() => {
|
||||
match packet {
|
||||
Some(pcm) => {
|
||||
pending.extend_from_slice(&pcm);
|
||||
while pending.len() >= PACKET_BYTES {
|
||||
let chunk: Vec<u8> = pending.drain(..PACKET_BYTES).collect();
|
||||
let frame = audio_frame(&chunk, false)?;
|
||||
socket.send(Message::Binary(frame.into())).await
|
||||
.map_err(|e| AppError::new("asr_send_failed", e.to_string()))?;
|
||||
}
|
||||
}
|
||||
None => {
|
||||
let frame = audio_frame(&pending, true)?;
|
||||
socket.send(Message::Binary(frame.into())).await
|
||||
.map_err(|e| AppError::new("asr_send_failed", e.to_string()))?;
|
||||
pending.clear();
|
||||
// Drain a little longer so the final utterance can arrive.
|
||||
let _ = tokio::time::timeout(Duration::from_secs(8), async {
|
||||
while let Some(msg) = socket.next().await {
|
||||
if let Ok(Message::Binary(bytes)) = msg {
|
||||
if let Ok(Some(event)) = parse_server_frame(&bytes) {
|
||||
let _ = event_tx.send(event).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}).await;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Resample interleaved s16le PCM to 16 kHz mono with linear interpolation.
|
||||
pub fn to_16k_mono(input: &[u8], channels: u16, rate: u32) -> Vec<u8> {
|
||||
if input.len() < 2 || channels == 0 || rate == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
let frame_bytes = channels as usize * 2;
|
||||
let frames = input.len() / frame_bytes;
|
||||
if frames == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut mono = Vec::with_capacity(frames);
|
||||
for i in 0..frames {
|
||||
let mut sum = 0i32;
|
||||
for c in 0..channels as usize {
|
||||
let off = i * frame_bytes + c * 2;
|
||||
let sample = i16::from_le_bytes([input[off], input[off + 1]]) as i32;
|
||||
sum += sample;
|
||||
}
|
||||
mono.push((sum / channels as i32) as i16);
|
||||
}
|
||||
if rate == SAMPLE_RATE {
|
||||
return mono.iter().flat_map(|s| s.to_le_bytes()).collect();
|
||||
}
|
||||
let out_len = ((mono.len() as u64) * SAMPLE_RATE as u64 / rate as u64) as usize;
|
||||
let mut out = Vec::with_capacity(out_len * 2);
|
||||
for i in 0..out_len {
|
||||
let src = (i as f64) * (rate as f64) / (SAMPLE_RATE as f64);
|
||||
let idx = src.floor() as usize;
|
||||
let frac = src - idx as f64;
|
||||
let a = mono[idx.min(mono.len() - 1)] as f64;
|
||||
let b = mono[(idx + 1).min(mono.len() - 1)] as f64;
|
||||
let sample = (a + (b - a) * frac).round() as i16;
|
||||
out.extend_from_slice(&sample.to_le_bytes());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn resamples_stereo_48k_down_to_16k_mono() {
|
||||
let mut stereo = Vec::new();
|
||||
for i in 0..48u16 {
|
||||
stereo.extend_from_slice(&(i as i16).to_le_bytes());
|
||||
stereo.extend_from_slice(&(i as i16).to_le_bytes());
|
||||
}
|
||||
let out = to_16k_mono(&stereo, 2, 48_000);
|
||||
assert_eq!(out.len(), 32); // 16 samples * 2 bytes
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_a_short_server_frame() {
|
||||
assert!(parse_server_frame(&[0, 1, 2]).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
use serde::Serialize;
|
||||
|
||||
/// Errors that cross the Tauri command boundary. The frontend only sees `code`.
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct AppError {
|
||||
pub code: String,
|
||||
pub detail: String,
|
||||
}
|
||||
|
||||
impl AppError {
|
||||
pub fn new(code: impl Into<String>, detail: impl Into<String>) -> Self {
|
||||
Self {
|
||||
code: code.into(),
|
||||
detail: detail.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for AppError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}: {}", self.code, self.detail)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<AppError> for String {
|
||||
fn from(value: AppError) -> Self {
|
||||
serde_json::to_string(&value).unwrap_or_else(|_| value.code.clone())
|
||||
}
|
||||
}
|
||||
|
||||
pub type AppResult<T> = Result<T, AppError>;
|
||||
@@ -0,0 +1,89 @@
|
||||
use crate::error::{AppError, AppResult};
|
||||
use serde::Serialize;
|
||||
use std::process::Command;
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct LaunchPlan {
|
||||
pub meeting_code: String,
|
||||
pub url: String,
|
||||
pub command: String,
|
||||
pub launched: bool,
|
||||
pub note: String,
|
||||
}
|
||||
|
||||
/// Personal-account join URL. This is a public client scheme, not an MCP call.
|
||||
/// Windows: `cmd /C start`, macOS: `open`. Other platforms only return the URL.
|
||||
pub fn client_url(meeting_code: &str) -> AppResult<String> {
|
||||
let digits: String = meeting_code.chars().filter(|c| c.is_ascii_digit()).collect();
|
||||
if digits.len() < 9 || digits.len() > 12 {
|
||||
return Err(AppError::new(
|
||||
"invalid_meeting_code",
|
||||
"会议号应为 9–12 位数字",
|
||||
));
|
||||
}
|
||||
Ok(format!("wemeet://page/inmeeting?meeting_code={digits}"))
|
||||
}
|
||||
|
||||
pub fn launch(meeting_code: &str) -> AppResult<LaunchPlan> {
|
||||
let url = client_url(meeting_code)?;
|
||||
let digits: String = meeting_code.chars().filter(|c| c.is_ascii_digit()).collect();
|
||||
|
||||
if cfg!(target_os = "linux") {
|
||||
return Ok(LaunchPlan {
|
||||
meeting_code: digits,
|
||||
url: url.clone(),
|
||||
command: format!("start \"\" \"{url}\""),
|
||||
launched: false,
|
||||
note: "当前是 Linux,无法唤起 PC/Mac 腾讯会议。把链接拿到已安装客户端的电脑上打开。".into(),
|
||||
});
|
||||
}
|
||||
|
||||
let mut command = if cfg!(windows) {
|
||||
let mut cmd = Command::new("cmd");
|
||||
cmd.args(["/C", "start", "", &url]);
|
||||
cmd
|
||||
} else {
|
||||
let mut cmd = Command::new("open");
|
||||
cmd.arg(&url);
|
||||
cmd
|
||||
};
|
||||
|
||||
match command.spawn() {
|
||||
Ok(child) => {
|
||||
drop(child);
|
||||
Ok(LaunchPlan {
|
||||
meeting_code: digits,
|
||||
url,
|
||||
command: if cfg!(windows) {
|
||||
"cmd /C start".into()
|
||||
} else {
|
||||
"open".into()
|
||||
},
|
||||
launched: true,
|
||||
note: "已请求系统打开腾讯会议。若客户端未安装或未登录,这次唤起不会入会。".into(),
|
||||
})
|
||||
}
|
||||
Err(e) => Err(AppError::new("launch_failed", e.to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Bring the installed client to the front before OAuth, so the user can confirm
|
||||
/// the personal account. Failure here is not fatal: auth still happens in the browser.
|
||||
pub fn focus_client() -> AppResult<String> {
|
||||
if cfg!(target_os = "linux") {
|
||||
return Ok("Linux 上无法拉起腾讯会议客户端。授权仍在浏览器完成。".into());
|
||||
}
|
||||
let url = "wemeet://page/home";
|
||||
let result = if cfg!(windows) {
|
||||
Command::new("cmd").args(["/C", "start", "", url]).spawn()
|
||||
} else {
|
||||
Command::new("open").arg(url).spawn()
|
||||
};
|
||||
match result {
|
||||
Ok(child) => {
|
||||
drop(child);
|
||||
Ok("已尝试拉起腾讯会议。请确认客户端登录的是个人账号,再回浏览器完成授权。".into())
|
||||
}
|
||||
Err(e) => Ok(format!("拉起客户端失败({e})。可直接在浏览器完成授权。")),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
pub mod asr;
|
||||
pub mod error;
|
||||
pub mod launch;
|
||||
pub mod tmeet;
|
||||
|
||||
pub use error::{AppError, AppResult};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::tmeet::not_logged_in;
|
||||
|
||||
#[test]
|
||||
fn logged_out_text_is_not_a_session() {
|
||||
assert!(not_logged_in(
|
||||
"Not logged in. Please use 'tmeet auth login' to authenticate.\n",
|
||||
""
|
||||
));
|
||||
assert!(not_logged_in(
|
||||
"",
|
||||
"Error: user config is empty, please use 'tmeet auth login'"
|
||||
));
|
||||
assert!(!not_logged_in(r#"{"open_id":"abc"}"#, ""));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
use crate::error::{AppError, AppResult};
|
||||
use serde_json::Value;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Stdio;
|
||||
use std::time::Duration;
|
||||
use tokio::io::{AsyncRead, AsyncReadExt};
|
||||
use tokio::process::Command;
|
||||
|
||||
const MAX_OUTPUT: usize = 4 * 1024 * 1024;
|
||||
|
||||
/// Locate the vendored tmeet binary.
|
||||
///
|
||||
/// Dev: `vendor/tmeet/<platform>/tmeet[.exe]`, walked up from the executable
|
||||
/// and from the current directory.
|
||||
/// Packaged: `tmeet[.exe]` beside the application executable.
|
||||
pub fn locate() -> AppResult<PathBuf> {
|
||||
let exe_name = if cfg!(windows) { "tmeet.exe" } else { "tmeet" };
|
||||
let platform_dir = platform_dir();
|
||||
|
||||
let mut candidates = Vec::new();
|
||||
if let Ok(exe) = std::env::current_exe() {
|
||||
if let Some(dir) = exe.parent() {
|
||||
candidates.push(dir.join(exe_name));
|
||||
candidates.push(dir.join("vendor").join("tmeet").join(platform_dir).join(exe_name));
|
||||
}
|
||||
}
|
||||
if let Ok(cwd) = std::env::current_dir() {
|
||||
candidates.push(cwd.join("vendor").join("tmeet").join(platform_dir).join(exe_name));
|
||||
let mut cursor = cwd.as_path();
|
||||
for _ in 0..4 {
|
||||
candidates.push(cursor.join("vendor").join("tmeet").join(platform_dir).join(exe_name));
|
||||
match cursor.parent() {
|
||||
Some(parent) => cursor = parent,
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
candidates
|
||||
.into_iter()
|
||||
.find(|path| path.is_file())
|
||||
.ok_or_else(|| {
|
||||
AppError::new(
|
||||
"tmeet_missing",
|
||||
"找不到内置的 tmeet。开发时它应在 vendor/tmeet/<平台>/ 下。",
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn platform_dir() -> &'static str {
|
||||
if cfg!(windows) {
|
||||
"windows-x86_64"
|
||||
} else if cfg!(target_os = "macos") {
|
||||
if cfg!(target_arch = "aarch64") {
|
||||
"macos-aarch64"
|
||||
} else {
|
||||
"macos-x86_64"
|
||||
}
|
||||
} else if cfg!(target_arch = "aarch64") {
|
||||
"linux-aarch64"
|
||||
} else {
|
||||
"linux-x86_64"
|
||||
}
|
||||
}
|
||||
|
||||
pub struct TmeetOutput {
|
||||
pub status: i32,
|
||||
pub stdout: String,
|
||||
pub stderr: String,
|
||||
pub json: Option<Value>,
|
||||
}
|
||||
|
||||
/// Run tmeet. `timeout` bounds the call; login uses a longer one because it
|
||||
/// waits for the browser OAuth round-trip (the CLI itself times out at 5 min).
|
||||
pub async fn run(args: &[&str], timeout: Duration) -> AppResult<TmeetOutput> {
|
||||
let bin = locate()?;
|
||||
run_at(&bin, args, timeout).await
|
||||
}
|
||||
|
||||
pub async fn run_at(bin: &Path, args: &[&str], timeout: Duration) -> AppResult<TmeetOutput> {
|
||||
let mut command = Command::new(bin);
|
||||
command
|
||||
.args(args)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.kill_on_drop(true);
|
||||
#[cfg(windows)]
|
||||
{
|
||||
command.creation_flags(0x08000000); // CREATE_NO_WINDOW
|
||||
}
|
||||
|
||||
let mut child = command
|
||||
.spawn()
|
||||
.map_err(|e| AppError::new("tmeet_spawn_failed", e.to_string()))?;
|
||||
|
||||
let mut stdout = child.stdout.take().ok_or_else(|| {
|
||||
AppError::new("tmeet_spawn_failed", "无法读取 tmeet 标准输出")
|
||||
})?;
|
||||
let mut stderr = child.stderr.take().ok_or_else(|| {
|
||||
AppError::new("tmeet_spawn_failed", "无法读取 tmeet 标准错误")
|
||||
})?;
|
||||
|
||||
let stdout_task = tokio::spawn(async move { read_capped(&mut stdout).await });
|
||||
let stderr_task = tokio::spawn(async move { read_capped(&mut stderr).await });
|
||||
|
||||
let status = tokio::time::timeout(timeout, child.wait())
|
||||
.await
|
||||
.map_err(|_| AppError::new("tmeet_timeout", "tmeet 超时未返回"))?
|
||||
.map_err(|e| AppError::new("tmeet_failed", e.to_string()))?;
|
||||
|
||||
let stdout = stdout_task
|
||||
.await
|
||||
.map_err(|e| AppError::new("tmeet_failed", e.to_string()))??;
|
||||
let stderr = stderr_task
|
||||
.await
|
||||
.map_err(|e| AppError::new("tmeet_failed", e.to_string()))??;
|
||||
|
||||
let json = parse_json(&stdout);
|
||||
Ok(TmeetOutput {
|
||||
status: status.code().unwrap_or(-1),
|
||||
stdout,
|
||||
stderr,
|
||||
json,
|
||||
})
|
||||
}
|
||||
|
||||
async fn read_capped(reader: &mut (impl AsyncRead + Unpin)) -> AppResult<String> {
|
||||
let mut buf = Vec::new();
|
||||
let mut chunk = [0u8; 8192];
|
||||
loop {
|
||||
let n = reader
|
||||
.read(&mut chunk)
|
||||
.await
|
||||
.map_err(|e| AppError::new("tmeet_failed", e.to_string()))?;
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
if buf.len() + n > MAX_OUTPUT {
|
||||
return Err(AppError::new("tmeet_output_limit", "tmeet 输出超过 4MB"));
|
||||
}
|
||||
buf.extend_from_slice(&chunk[..n]);
|
||||
}
|
||||
Ok(String::from_utf8_lossy(&buf).into_owned())
|
||||
}
|
||||
|
||||
pub fn not_logged_in(stdout: &str, stderr: &str) -> bool {
|
||||
let blob = format!("{stdout}\n{stderr}").to_ascii_lowercase();
|
||||
blob.contains("not logged in") || blob.contains("user config is empty")
|
||||
}
|
||||
|
||||
fn parse_json(stdout: &str) -> Option<Value> {
|
||||
let trimmed = stdout.trim();
|
||||
if trimmed.is_empty() {
|
||||
return None;
|
||||
}
|
||||
serde_json::from_str(trimmed).ok().or_else(|| {
|
||||
// Some commands print a hint after the JSON array. Take the first JSON value.
|
||||
let start = trimmed.find(['{', '['])?;
|
||||
let slice = &trimmed[start..];
|
||||
serde_json::from_str(slice).ok()
|
||||
})
|
||||
}
|
||||
|
||||
pub fn require_ok(output: TmeetOutput) -> AppResult<TmeetOutput> {
|
||||
if output.status != 0 {
|
||||
let detail = if !output.stderr.trim().is_empty() {
|
||||
output.stderr.trim().to_string()
|
||||
} else {
|
||||
output.stdout.trim().to_string()
|
||||
};
|
||||
return Err(AppError::new(
|
||||
"tmeet_failed",
|
||||
if detail.is_empty() {
|
||||
format!("tmeet 退出码 {}", output.status)
|
||||
} else {
|
||||
detail
|
||||
},
|
||||
));
|
||||
}
|
||||
Ok(output)
|
||||
}
|
||||
Reference in New Issue
Block a user