Files
Thing/src-tauri/src/music/feiniu/proxy.rs
T
2026-09-15 17:17:16 +08:00

237 lines
7.9 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! 飞牛音乐本地流代理(axum)。
//!
//! 原生 `/track/stream`、`/static/cover` 需要 `Cookie: music-token=<token>`,而
//! WebView 的 `<audio>/<img>` 无法设置 Cookie。本模块绑定 `127.0.0.1:<动态端口>`,
//! 转发请求时注入 Cookie 与可选的安全码头,前端直接用本地地址播放/显示,天然支持 Range/seek。
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use axum::{
extract::{Query, State},
http::{header, HeaderMap, StatusCode},
response::{IntoResponse, Response},
routing::get,
Router,
};
use lofty::file::TaggedFileExt;
use super::conn::normalize_base_url;
/// 由 Feiniu 运行期与代理 handler 共享的连接配置(登录更新、登出置空)。
#[derive(Clone, Default)]
pub struct ProxyCfg {
pub base_url: String,
pub token: String,
pub access_code: String,
/// FnConnect 中继链路:所有请求需携带 `Cookie: mode=relay`
pub relay: bool,
}
#[derive(Clone)]
pub struct ProxyShared {
pub client: reqwest::Client,
pub cfg: Arc<Mutex<ProxyCfg>>,
}
/// 启动本地流代理,绑定到 `127.0.0.1:0`(动态空闲端口),返回实际端口。
/// 代理以独立 tokio 任务常驻应用存活期;token 变化经共享 `ProxyCfg` 即时生效,无需重启。
pub async fn start(shared: ProxyShared) -> Result<u16, String> {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.map_err(|e| format!("绑定本地端口失败: {e}"))?;
let port = listener
.local_addr()
.map_err(|e| e.to_string())?
.port();
let app = Router::new()
.route("/feiniu/stream", get(proxy_stream))
.route("/feiniu/cover", get(proxy_cover))
.route("/feiniu/local-cover", get(proxy_local_cover))
.with_state(shared);
tokio::spawn(async move {
if let Err(e) = axum::serve(listener, app).await {
crate::logger::log_error("music", &format!("飞牛流代理异常: {e}"));
}
});
Ok(port)
}
/// 本地音频文件的内嵌封面:`GET /feiniu/local-cover?path=<绝对路径>`。
///
/// 供「本地曲库」列表显示封面(无需 NAS 登录)。只接受音频扩展名,且必须
/// 能被 lofty 解析出内嵌图片——非音频文件在这里必然 404,不构成任意文件读取。
/// 响应带 immutable 缓存头:path 不变时 WebView 直接复用。
async fn proxy_local_cover(Query(q): Query<HashMap<String, String>>) -> Response {
const AUDIO_EXTS: [&str; 7] = ["mp3", "flac", "wav", "m4a", "aac", "ogg", "ape"];
let Some(path) = q.get("path") else {
return (StatusCode::BAD_REQUEST, "missing path").into_response();
};
let p = std::path::Path::new(path);
let ext_ok = p
.extension()
.and_then(|e| e.to_str())
.map(|e| AUDIO_EXTS.contains(&e.to_lowercase().as_str()))
.unwrap_or(false);
if !ext_ok || !p.is_file() {
return StatusCode::NOT_FOUND.into_response();
}
let picture = lofty::read_from_path(p).ok().and_then(|tagged| {
tagged
.primary_tag()
.or_else(|| tagged.first_tag())
.and_then(|t| t.pictures().first())
.cloned()
});
let Some(pic) = picture else {
return StatusCode::NOT_FOUND.into_response();
};
// lofty 0.22 的 mime_type 返回 Option<MimeType>
let mime = pic
.mime_type()
.map(|m| m.to_string())
.unwrap_or_else(|| "image/jpeg".to_string());
let mut resp = ([(header::CONTENT_TYPE, mime)], pic.data().to_vec()).into_response();
resp.headers_mut().insert(
header::CACHE_CONTROL,
header::HeaderValue::from_static("public, max-age=2592000, immutable"),
);
resp
}
async fn proxy_stream(
State(s): State<ProxyShared>,
Query(q): Query<HashMap<String, String>>,
headers: HeaderMap,
) -> Response {
let guid = q.get("guid").cloned().unwrap_or_default().trim().to_string();
if guid.is_empty() {
return (StatusCode::BAD_REQUEST, "missing guid").into_response();
}
forward(
&s,
"/music/api/v1/track/stream",
vec![("guid".to_string(), guid)],
&headers,
)
.await
}
async fn proxy_cover(
State(s): State<ProxyShared>,
Query(q): Query<HashMap<String, String>>,
headers: HeaderMap,
) -> Response {
let cover_id = q
.get("coverId")
.cloned()
.unwrap_or_default()
.trim()
.to_string();
if cover_id.is_empty() {
return (StatusCode::BAD_REQUEST, "missing coverId").into_response();
}
let size = q.get("size").cloned().unwrap_or_else(|| "320".into());
forward(
&s,
"/music/api/v1/static/cover",
vec![
("coverId".to_string(), cover_id),
("size".to_string(), size),
],
&headers,
)
.await
}
/// 统一转发:向 NAS 发起上游 GET,注入 Cookie/安全码,透传 Range 与响应头,流式回传 body。
async fn forward(
s: &ProxyShared,
path: &str,
query: Vec<(String, String)>,
headers: &HeaderMap,
) -> Response {
let cfg = match s.cfg.lock() {
Ok(g) => g.clone(),
Err(e) => e.into_inner().clone(),
};
if cfg.base_url.is_empty() || cfg.token.is_empty() {
return (StatusCode::UNAUTHORIZED, "飞牛音乐未登录").into_response();
}
let base = normalize_base_url(&cfg.base_url);
let url = format!("{base}{path}");
let qrefs: Vec<(&str, &str)> = query.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();
let mut rb = s.client.get(&url).query(&qrefs);
// 中继链路必须带 mode=relay,网关据此转发到 NAS(与 music-token 合并进同一个 Cookie 头)。
rb = rb.header(
"cookie",
if cfg.relay {
format!("music-token={}; mode=relay", cfg.token)
} else {
format!("music-token={}", cfg.token)
},
);
if !cfg.access_code.is_empty() {
use base64::Engine;
rb = rb
.header(
"x-access-code",
base64::engine::general_purpose::STANDARD.encode(cfg.access_code.as_bytes()),
)
.header("x-access-source", "app");
}
if let Some(range) = headers.get(header::RANGE) {
rb = rb.header(header::RANGE, range.clone());
}
drop(cfg);
let resp = match rb.send().await {
Ok(r) => r,
Err(e) => return (StatusCode::BAD_GATEWAY, format!("上游错误: {e}")).into_response(),
};
let status = resp.status();
let ct = resp.headers().get(header::CONTENT_TYPE).cloned();
let cl = resp.headers().get(header::CONTENT_LENGTH).cloned();
let cr = resp.headers().get(header::CONTENT_RANGE).cloned();
let ar = resp.headers().get(header::ACCEPT_RANGES).cloned();
// 缓存头必须透传:NAS 的封面接口带 `public, max-age=2592000, immutable`,
// 丢掉它就等于告诉 WebView「这个响应不可缓存」——每次进曲库页都要重新下载全部封面。
let cc = resp.headers().get(header::CACHE_CONTROL).cloned();
let et = resp.headers().get(header::ETAG).cloned();
let lm = resp.headers().get(header::LAST_MODIFIED).cloned();
let ex = resp.headers().get(header::EXPIRES).cloned();
let body = axum::body::Body::from_stream(resp.bytes_stream());
let mut out = Response::new(body);
*out.status_mut() = status;
let h = out.headers_mut();
if let Some(v) = ct {
h.insert(header::CONTENT_TYPE, v);
}
if let Some(v) = cl {
h.insert(header::CONTENT_LENGTH, v);
}
if let Some(v) = cr {
h.insert(header::CONTENT_RANGE, v);
}
if let Some(v) = ar {
h.insert(header::ACCEPT_RANGES, v);
}
if let Some(v) = cc {
h.insert(header::CACHE_CONTROL, v);
}
if let Some(v) = et {
h.insert(header::ETAG, v);
}
if let Some(v) = lm {
h.insert(header::LAST_MODIFIED, v);
}
if let Some(v) = ex {
h.insert(header::EXPIRES, v);
}
out
}