音乐控制/解密
This commit is contained in:
1 parent
9e6d73e191
commit
ff1d5cd517
41 files changed
+10827
-4
No files matched your search
@@ -0,0 +1,610 @@
|
||||
//! 局域网服务:axum HTTP + WebSocket(MUSIC_REMOTE_PLAN §3.2 / §4.2 / §5.1 `server.rs`)。
|
||||
//!
|
||||
//! | 端点 | 用途 |
|
||||
//! |---|---|
|
||||
//! | `/ws` | 主通道:hello 鉴权、state 推送、cmd 控制、心跳 |
|
||||
//! | `/api/state` | REST 快照兜底(Bearer) |
|
||||
//! | `/cover/:hash` | 封面字节流(`<img>` 带不了 header → `?t=token`) |
|
||||
//! | `/pair` | 配对换 token(6 位码 + 限速) |
|
||||
//!
|
||||
//! 全部监听 `0.0.0.0`;实际端口在启动时按 26124→26139 探测(§3.2),
|
||||
//! 由 RemoteManager 写回 beacon 与配对二维码。
|
||||
|
||||
use std::net::SocketAddr;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use axum::extract::ws::{Message as AxumWs, WebSocket, WebSocketUpgrade};
|
||||
use axum::extract::{ConnectInfo, Path, Query, State};
|
||||
use axum::http::{header, HeaderMap, StatusCode};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum::routing::{get, post};
|
||||
use axum::{Json, Router};
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tauri::{AppHandle, Emitter, Manager};
|
||||
|
||||
use super::glsmtc;
|
||||
use super::pairing::{self, RemoteDeviceMeta};
|
||||
use super::proto::{
|
||||
CmdAction, CmdArgs, NowPlaying, WsMessage, PROTO_VER,
|
||||
};
|
||||
use super::RemoteManager;
|
||||
use crate::music::{AudioEngine, MusicManager};
|
||||
use crate::music::smtc::SMTC_BUTTON_EVENT;
|
||||
|
||||
/// WS 首条消息(hello)超时(§4.2 连接后首条)。
|
||||
const HELLO_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
/// 心跳周期(§4.2 30s 双向判活)。
|
||||
const HEARTBEAT: Duration = Duration::from_secs(30);
|
||||
/// 超过该时长无任何入站消息 → 判死断开(§5.4 心跳判活)。
|
||||
const IDLE_TIMEOUT: Duration = Duration::from_secs(90);
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AppState {
|
||||
pub app: AppHandle,
|
||||
}
|
||||
|
||||
/// 构建路由(§3.2 四个端点)。
|
||||
pub fn router(app: AppHandle) -> Router {
|
||||
Router::new()
|
||||
.route("/ws", get(ws_upgrade))
|
||||
.route("/api/state", get(api_state))
|
||||
.route("/cover/:hash", get(cover))
|
||||
.route("/pair", post(pair))
|
||||
.with_state(AppState { app })
|
||||
}
|
||||
|
||||
/// 启动服务:preferred=0 时从 26124 起,被占 +1 直至 26139(§3.2)。
|
||||
/// 成功返回(实际端口, serve 任务句柄);stop 时由 RemoteManager abort。
|
||||
pub async fn start(
|
||||
app: AppHandle,
|
||||
preferred: u16,
|
||||
) -> Result<(u16, tokio::task::JoinHandle<()>), String> {
|
||||
let from = if preferred == 0 { 26124 } else { preferred };
|
||||
let to = from.clamp(26124, 26139).min(26139);
|
||||
let mut bound: Option<(u16, tokio::net::TcpListener)> = None;
|
||||
for port in from..=to {
|
||||
match tokio::net::TcpListener::bind(("0.0.0.0", port)).await {
|
||||
Ok(l) => {
|
||||
bound = Some((port, l));
|
||||
break;
|
||||
}
|
||||
Err(e) => {
|
||||
crate::logger::log_warn(
|
||||
"music-remote",
|
||||
&format!("端口 {port} 绑定失败({e}),尝试下一个"),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
let (port, listener) = bound.ok_or_else(|| {
|
||||
format!("远程服务端口 {from}-{to} 全部不可用(被占用或无权限)")
|
||||
})?;
|
||||
|
||||
let router = router(app);
|
||||
let handle = tokio::task::spawn(async move {
|
||||
let svc = router.into_make_service_with_connect_info::<SocketAddr>();
|
||||
if let Err(e) = axum::serve(listener, svc).await {
|
||||
// abort 时 axum::serve 返回的错误走这里降级为日志(abort 本身另算)
|
||||
crate::logger::log_warn("music-remote", &format!("axum 服务结束: {e}"));
|
||||
}
|
||||
});
|
||||
Ok((port, handle))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 鉴权
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
fn bearer_token(headers: &HeaderMap) -> Option<String> {
|
||||
headers
|
||||
.get(header::AUTHORIZATION)?
|
||||
.to_str()
|
||||
.ok()?
|
||||
.strip_prefix("Bearer ")
|
||||
.map(|s| s.to_string())
|
||||
}
|
||||
|
||||
/// 校验设备 token → 设备信息;失败为 None(不做限速——限速由调用方按场景加)。
|
||||
fn validate_token(app: &AppHandle, token: &str) -> Option<RemoteDeviceMeta> {
|
||||
let music = app.state::<MusicManager>();
|
||||
let settings = music.load_settings();
|
||||
pairing::device_by_token(&settings.remote_devices, token)
|
||||
}
|
||||
|
||||
fn require_bearer(app: &AppHandle, headers: &HeaderMap) -> Result<RemoteDeviceMeta, StatusCode> {
|
||||
let token = bearer_token(headers).ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
validate_token(app, &token).ok_or(StatusCode::UNAUTHORIZED)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// REST:/api/state、/cover/:hash
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async fn api_state(
|
||||
State(st): State<AppState>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Json<NowPlaying>, StatusCode> {
|
||||
require_bearer(&st.app, &headers)?;
|
||||
let remote = st.app.state::<RemoteManager>();
|
||||
Ok(Json(remote.now_playing()))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct CoverQuery {
|
||||
/// 鉴权 token(`<img>` 无法带 Authorization header,§3.2)
|
||||
#[serde(rename = "t")]
|
||||
t: Option<String>,
|
||||
}
|
||||
|
||||
async fn cover(
|
||||
State(st): State<AppState>,
|
||||
Path(hash): Path<String>,
|
||||
Query(q): Query<CoverQuery>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Response, StatusCode> {
|
||||
let token = q.t.or_else(|| bearer_token(&headers));
|
||||
let token = token.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
validate_token(&st.app, &token).ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
|
||||
let remote = st.app.state::<RemoteManager>();
|
||||
let bytes = remote.covers.get(&hash).ok_or(StatusCode::NOT_FOUND)?;
|
||||
// 访问日志不打印 query(§3.2):logger 不记录请求行,天然满足;此处只管响应
|
||||
let ct = sniff_content_type(&bytes);
|
||||
Ok(([(header::CONTENT_TYPE, ct)], bytes).into_response())
|
||||
}
|
||||
|
||||
fn sniff_content_type(bytes: &[u8]) -> &'static str {
|
||||
if bytes.starts_with(&[0x89, b'P', b'N', b'G']) {
|
||||
"image/png"
|
||||
} else if bytes.starts_with(&[0xFF, 0xD8]) {
|
||||
"image/jpeg"
|
||||
} else if bytes.len() > 12 && &bytes[0..4] == b"RIFF" && &bytes[8..12] == b"WEBP" {
|
||||
"image/webp"
|
||||
} else {
|
||||
"application/octet-stream"
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// POST /pair(§3.4)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct PairRequest {
|
||||
pairing_code: String,
|
||||
device_name: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct PairResponse {
|
||||
token: String,
|
||||
device_id: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct HttpError {
|
||||
error: String,
|
||||
}
|
||||
|
||||
async fn pair(
|
||||
State(st): State<AppState>,
|
||||
ConnectInfo(addr): ConnectInfo<SocketAddr>,
|
||||
Json(req): Json<PairRequest>,
|
||||
) -> Result<(StatusCode, Json<PairResponse>), (StatusCode, Json<HttpError>)> {
|
||||
let ip = addr.ip().to_string();
|
||||
let remote = st.app.state::<RemoteManager>();
|
||||
|
||||
let denied = |msg: &str| {
|
||||
(
|
||||
StatusCode::TOO_MANY_REQUESTS,
|
||||
Json(HttpError {
|
||||
error: msg.to_string(),
|
||||
}),
|
||||
)
|
||||
};
|
||||
if !remote.auth.allowed(&ip) {
|
||||
return Err(denied("尝试过于频繁,60s 后再试"));
|
||||
}
|
||||
// 配对码校验:存在 + 未过期 + 匹配(一次性:成功即清除)
|
||||
match remote.take_pairing_if_match(&req.pairing_code) {
|
||||
Ok(()) => remote.auth.ok(&ip),
|
||||
Err(e) => {
|
||||
remote.auth.fail(&ip);
|
||||
return Err((
|
||||
StatusCode::FORBIDDEN,
|
||||
Json(HttpError { error: e }),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
let device_id = pairing::random_device_id();
|
||||
let token = pairing::random_token();
|
||||
// token 先入凭据库,成功才落设备表(§3.4-3 顺序)
|
||||
let key = pairing::token_key(&device_id);
|
||||
if let Err(e) = crate::secrets::secret_write(&key, &token) {
|
||||
crate::logger::log_error("music-remote", &format!("设备 token 写入凭据库失败: {e}"));
|
||||
return Err((
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(HttpError {
|
||||
error: "保存设备凭据失败".to_string(),
|
||||
}),
|
||||
));
|
||||
}
|
||||
|
||||
let name = if req.device_name.trim().is_empty() {
|
||||
format!("手机设备 {}", &device_id[..6])
|
||||
} else {
|
||||
req.device_name.trim().to_string()
|
||||
};
|
||||
let music = st.app.state::<MusicManager>();
|
||||
let mut settings = music.load_settings();
|
||||
settings.remote_devices.push(RemoteDeviceMeta {
|
||||
id: device_id.clone(),
|
||||
name,
|
||||
last_connected_ms: 0,
|
||||
});
|
||||
if let Err(e) = music.save_settings(&settings) {
|
||||
crate::logger::log_error("music-remote", &format!("设备表落盘失败: {e}"));
|
||||
}
|
||||
crate::logger::log_info(
|
||||
"music-remote",
|
||||
format!("设备配对成功: {device_id}({ip})").as_str(),
|
||||
);
|
||||
Ok((
|
||||
StatusCode::OK,
|
||||
Json(PairResponse { token, device_id }),
|
||||
))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// WebSocket(§4.2)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async fn ws_upgrade(
|
||||
State(st): State<AppState>,
|
||||
ConnectInfo(addr): ConnectInfo<SocketAddr>,
|
||||
upgrade: WebSocketUpgrade,
|
||||
) -> Response {
|
||||
// 升级阶段不鉴权:手机 WebSocket 无法带 Authorization header,
|
||||
// token 在升级后的首条 `hello` 消息里(§4.2)
|
||||
upgrade
|
||||
.on_upgrade(move |socket| handle_socket(st.app, addr, socket))
|
||||
.into_response()
|
||||
}
|
||||
|
||||
async fn handle_socket(app: AppHandle, addr: SocketAddr, socket: WebSocket) {
|
||||
let ip = addr.ip().to_string();
|
||||
let (mut sink, mut stream) = socket.split();
|
||||
|
||||
// 1) 首条必须是 hello(10s 超时)
|
||||
let hello = match tokio::time::timeout(HELLO_TIMEOUT, stream.next()).await {
|
||||
Ok(Some(Ok(AxumWs::Text(t)))) => match serde_json::from_str::<WsMessage>(&t) {
|
||||
Ok(WsMessage::Hello {
|
||||
token,
|
||||
device_name,
|
||||
..
|
||||
}) => (token, device_name),
|
||||
_ => {
|
||||
let _ = sink.send(AxumWs::Close(None)).await;
|
||||
return;
|
||||
}
|
||||
},
|
||||
_ => {
|
||||
let _ = sink.send(AxumWs::Close(None)).await;
|
||||
return;
|
||||
}
|
||||
};
|
||||
let (token, device_name) = hello;
|
||||
|
||||
let remote = app.state::<RemoteManager>();
|
||||
if !remote.auth.allowed(&ip) {
|
||||
let _ = sink.send(AxumWs::Close(None)).await;
|
||||
return;
|
||||
}
|
||||
let device = match validate_token(&app, &token) {
|
||||
Some(d) => {
|
||||
remote.auth.ok(&ip);
|
||||
d
|
||||
}
|
||||
None => {
|
||||
remote.auth.fail(&ip);
|
||||
crate::logger::log_warn("music-remote", &format!("hello 鉴权失败({ip})"));
|
||||
let _ = sink.send(AxumWs::Close(None)).await;
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
// 2) 上线登记 + 最后连接时间
|
||||
remote.mark_online(&device.id, true);
|
||||
touch_last_connected(&app, &device.id);
|
||||
|
||||
// 3) welcome + 首帧 state + 会话列表(§5.1 welcome → 全量;sessions 为 P1)
|
||||
let mut state_rx = remote.state_tx.subscribe();
|
||||
let mut sessions_rx = remote.sessions_rx();
|
||||
let mut queue_rx = remote.queue_rx();
|
||||
let mut rx = remote.shutdown_rx();
|
||||
let device_id = device.id.clone();
|
||||
let send_json = |msg: &WsMessage| -> String { serde_json::to_string(msg).unwrap_or_default() };
|
||||
|
||||
if sink
|
||||
.send(AxumWs::Text(send_json(&WsMessage::Welcome {
|
||||
device_id: device_id.clone(),
|
||||
device_name: device_name.clone(),
|
||||
proto_ver: PROTO_VER,
|
||||
})))
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
remote.mark_online(&device_id, false);
|
||||
return;
|
||||
}
|
||||
{
|
||||
let now = remote.now_playing();
|
||||
let _ = sink
|
||||
.send(AxumWs::Text(send_json(&WsMessage::State { now })))
|
||||
.await;
|
||||
}
|
||||
{
|
||||
let sessions = remote.sessions_snapshot();
|
||||
let _ = sink
|
||||
.send(AxumWs::Text(send_json(&WsMessage::Sessions { sessions })))
|
||||
.await;
|
||||
}
|
||||
{
|
||||
let q = remote.queue_snapshot();
|
||||
let _ = sink.send(AxumWs::Text(send_json(&queue_msg(&q)))).await;
|
||||
}
|
||||
|
||||
crate::logger::log_info(
|
||||
"music-remote",
|
||||
format!("WS 已连接: {device_name}({ip})").as_str(),
|
||||
);
|
||||
|
||||
// 4) 主循环:入站消息 / 状态变更推送 / 心跳
|
||||
let mut last_in = Instant::now();
|
||||
let mut beat = tokio::time::interval(HEARTBEAT);
|
||||
beat.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
// 心跳与判活(§4.2 / §5.4)
|
||||
_ = beat.tick() => {
|
||||
if last_in.elapsed() > IDLE_TIMEOUT {
|
||||
crate::logger::log_warn("music-remote", &format!("心跳超时,断开 {device_name}({ip})"));
|
||||
break;
|
||||
}
|
||||
if sink.send(AxumWs::Text(send_json(&WsMessage::Ping { ts: now_ms() }))).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// 服务停止
|
||||
_ = rx.changed() => {
|
||||
if *rx.borrow() { break; }
|
||||
}
|
||||
// 状态推送(watch:节流/Force 均已在监视线程收敛,§6.3)
|
||||
changed = state_rx.changed() => {
|
||||
if changed.is_err() { break; }
|
||||
let now = state_rx.borrow_and_update().clone();
|
||||
if sink.send(AxumWs::Text(send_json(&WsMessage::State { now }))).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// 会话列表变更(P1 多会话切换)
|
||||
changed = sessions_rx.changed() => {
|
||||
if changed.is_err() { break; }
|
||||
let sessions = sessions_rx.borrow_and_update().clone();
|
||||
if sink.send(AxumWs::Text(send_json(&WsMessage::Sessions { sessions }))).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Thing 本机队列变更(前端发布:切歌 / 增删队列)
|
||||
changed = queue_rx.changed() => {
|
||||
if changed.is_err() { break; }
|
||||
let snap = queue_rx.borrow_and_update().clone();
|
||||
if sink.send(AxumWs::Text(send_json(&queue_msg(&snap)))).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
incoming = stream.next() => {
|
||||
match incoming {
|
||||
Some(Ok(AxumWs::Text(t))) => {
|
||||
last_in = Instant::now();
|
||||
match serde_json::from_str::<WsMessage>(&t) {
|
||||
Ok(WsMessage::Cmd { id, action, args }) => {
|
||||
let res = dispatch_cmd(&app, action, args).await;
|
||||
let ack = WsMessage::CmdAck {
|
||||
id,
|
||||
ok: res.is_ok(),
|
||||
error: res.err(),
|
||||
};
|
||||
if sink.send(AxumWs::Text(send_json(&ack))).await.is_err() {
|
||||
break;
|
||||
}
|
||||
// cmd 触发的 state 立即帧由监视线程 Force 产生(§6.3 例外)
|
||||
}
|
||||
Ok(WsMessage::Ping { ts }) => {
|
||||
if sink.send(AxumWs::Text(send_json(&WsMessage::Pong { ts }))).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(WsMessage::Pong { .. }) => {}
|
||||
// 重复 hello / 非法消息:忽略(连接保持,状态以服务端为准)
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Some(Ok(AxumWs::Ping(p))) => {
|
||||
last_in = Instant::now();
|
||||
if sink.send(AxumWs::Pong(p)).await.is_err() { break; }
|
||||
}
|
||||
Some(Ok(AxumWs::Pong(_))) => { last_in = Instant::now(); }
|
||||
Some(Ok(AxumWs::Close(_))) | None => break,
|
||||
Some(Err(_)) => break,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
remote.mark_online(&device_id, false);
|
||||
crate::logger::log_info(
|
||||
"music-remote",
|
||||
format!("WS 已断开: {device_name}({ip})").as_str(),
|
||||
);
|
||||
let _ = sink.send(AxumWs::Close(None)).await;
|
||||
}
|
||||
|
||||
fn now_ms() -> i64 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_millis() as i64)
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// 队列快照 → WS 消息(`items`/`index`/`total` 展平成顶层字段)。
|
||||
fn queue_msg(q: &super::proto::QueueSnapshot) -> WsMessage {
|
||||
WsMessage::Queue {
|
||||
items: q.items.clone(),
|
||||
index: q.index,
|
||||
total: q.total,
|
||||
}
|
||||
}
|
||||
|
||||
fn touch_last_connected(app: &AppHandle, device_id: &str) {
|
||||
let music = app.state::<MusicManager>();
|
||||
let mut settings = music.load_settings();
|
||||
if let Some(d) = settings
|
||||
.remote_devices
|
||||
.iter_mut()
|
||||
.find(|d| d.id == device_id)
|
||||
{
|
||||
d.last_connected_ms = now_ms();
|
||||
if let Err(e) = music.save_settings(&settings) {
|
||||
crate::logger::log_warn("music-remote", &format!("更新最后连接时间失败: {e}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 执行一条控制指令(§5.1 数据流 + §5.2 兜底规则;P1 扩展 Volume/Select 与 isThing 直通)。
|
||||
async fn dispatch_cmd(
|
||||
app: &AppHandle,
|
||||
action: CmdAction,
|
||||
args: Option<CmdArgs>,
|
||||
) -> Result<(), String> {
|
||||
let remote = app.state::<RemoteManager>();
|
||||
let np = remote.now_playing();
|
||||
let gsmtc_ok = remote.gsmtc_ok.load(std::sync::atomic::Ordering::Relaxed);
|
||||
let a = args.clone().unwrap_or_default();
|
||||
|
||||
match action {
|
||||
// seek:Thing 自身直通 AudioEngine(SMTC 回环无 seek 通道);其他会话走 GSMTC
|
||||
CmdAction::Seek => {
|
||||
if args.is_none() || a.pos_sec < 0.0 || !a.pos_sec.is_finite() {
|
||||
return Err("seek 缺少/非法 args.posSec".into());
|
||||
}
|
||||
if np.is_thing {
|
||||
let engine = app.state::<AudioEngine>();
|
||||
let active = engine.state().active;
|
||||
crate::logger::log_info(
|
||||
"music-remote",
|
||||
&format!("远程 seek(Thing) pos={:.1} 引擎会话={active}", a.pos_sec),
|
||||
);
|
||||
// 引擎无会话(重启后只恢复了队列、还没起播)时 seek 是静默空转,
|
||||
// 手机端会白等保持窗口才回退——如实报错,让手机端立刻复位并提示
|
||||
if !active {
|
||||
return Err("电脑端播放器还没开始播放,先起播才能拖动进度".into());
|
||||
}
|
||||
engine.seek(a.pos_sec);
|
||||
} else if gsmtc_ok {
|
||||
gctl(np.session_id.clone(), action, args).await?;
|
||||
} else {
|
||||
return Err("当前模式不支持该会话的 seek".into());
|
||||
}
|
||||
}
|
||||
// 系统主音量(P1 §7):level>0 自动解除静音(volume::set 内处理)
|
||||
CmdAction::Volume => {
|
||||
let Some(_) = args else {
|
||||
return Err("volume 缺少 args.level".into());
|
||||
};
|
||||
if !a.level.is_finite() {
|
||||
return Err("volume args.level 非法".into());
|
||||
}
|
||||
let level = a.level;
|
||||
tokio::task::spawn_blocking(move || super::volume::set(level))
|
||||
.await
|
||||
.map_err(|e| format!("音量任务异常: {e}"))??;
|
||||
}
|
||||
// 目标会话切换(P1 §7):空 sessionId = 取消覆盖、跟随系统 current
|
||||
CmdAction::Select => {
|
||||
if args.is_none() {
|
||||
return Err("select 缺少 args.sessionId".into());
|
||||
}
|
||||
remote.set_selected(&a.session_id);
|
||||
}
|
||||
// 选歌(Thing 专属):队列在前端 store,事件交回前端执行
|
||||
CmdAction::Jump => {
|
||||
if !np.is_thing {
|
||||
return Err("只有 Thing 本机播放支持选歌".into());
|
||||
}
|
||||
if args.is_none() || a.index < 0 {
|
||||
return Err("jump 缺少 args.index".into());
|
||||
}
|
||||
let total = remote.queue_snapshot().total;
|
||||
if total > 0 && a.index >= total {
|
||||
return Err(format!("队列里没有第 {} 首(共 {total} 首)", a.index + 1));
|
||||
}
|
||||
app.emit(super::REMOTE_JUMP_EVENT, a.index)
|
||||
.map_err(|e| format!("派发到前端失败: {e}"))?;
|
||||
}
|
||||
// 按钮类:isThing 直通(P1 §7 跳过系统 SMTC 回环);其他会话 GSMTC;再退事件链兜底
|
||||
_ => {
|
||||
if np.is_thing {
|
||||
let name = button_name(action, np.status == super::proto::PlayStatus::Playing)?;
|
||||
app.emit(SMTC_BUTTON_EVENT, name)
|
||||
.map_err(|e| format!("派发到前端失败: {e}"))?;
|
||||
} else if gsmtc_ok {
|
||||
gctl(np.session_id.clone(), action, args).await?;
|
||||
} else {
|
||||
let name = button_name(action, np.status == super::proto::PlayStatus::Playing)?;
|
||||
app.emit(SMTC_BUTTON_EVENT, name)
|
||||
.map_err(|e| format!("派发到前端失败: {e}"))?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// cmd 触发立即推一帧(§6.3 例外)
|
||||
remote.notify_state_force();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 按钮动作 → music-smtc-button 事件载荷(与 smtc.rs 的映射一致)。
|
||||
fn button_name(action: CmdAction, playing: bool) -> Result<&'static str, String> {
|
||||
Ok(match action {
|
||||
CmdAction::Play => "play",
|
||||
CmdAction::Pause => "pause",
|
||||
CmdAction::Toggle => {
|
||||
if playing {
|
||||
"pause"
|
||||
} else {
|
||||
"play"
|
||||
}
|
||||
}
|
||||
CmdAction::Next => "next",
|
||||
CmdAction::Prev => "prev",
|
||||
CmdAction::Stop => "stop",
|
||||
_ => return Err("该动作不支持事件派发".into()),
|
||||
})
|
||||
}
|
||||
|
||||
/// GSMTC 控制:`.get()` 阻塞等待放 spawn_blocking(§3.1,绝不占 tokio worker/主线程)。
|
||||
async fn gctl(
|
||||
session_id: String,
|
||||
action: CmdAction,
|
||||
args: Option<CmdArgs>,
|
||||
) -> Result<(), String> {
|
||||
tokio::task::spawn_blocking(move || glsmtc::control(&session_id, action, args))
|
||||
.await
|
||||
.map_err(|e| format!("控制任务异常: {e}"))?
|
||||
}
|
||||
Reference in new issue
Block a user