Files
Thing/src-tauri/src/music/decrypt/common.rs
T
2026-09-28 00:21:12 +08:00

267 lines
9.5 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.
//! 本地解密的**统一错误类型与公共格式探测**。
//!
//! 两个引擎([`super::ncm`] 网易云 / [`super::qmc`] QQ音乐)各自的内部错误不同,
//! 但调度层只关心「可读的中文原因」,因此都收敛到 [`DecryptError`]。
//!
//! 输出扩展名统一由 [`detect_format`] 按**音频首帧魔数**判定——
//! 两个平台都不信任容器里声明的格式字段(详见 `MUSIC_DECRYPT_PLAN.md` §3.1⑥ / §3.2 末)。
use std::fmt;
use std::path::PathBuf;
/// 解密失败原因。全部经 `to_string()` 上报为 per-file 失败,**不 panic**
/// (否则一个坏文件会带走整批任务)。
#[derive(Debug)]
pub enum DecryptError {
Io(String),
/// 文件不属于本引擎认得的加密格式
NotEncrypted(String),
/// 容器/尾部结构残缺
Broken(String),
/// 缺少解密密钥(QQ QMC2 的 ekey 情况),文案要能给用户下一步动作
KeyRequired(String),
/// 输出失败
Output(String),
}
impl fmt::Display for DecryptError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
DecryptError::Io(e) => write!(f, "读取失败:{e}"),
DecryptError::NotEncrypted(e) => write!(f, "{e}"),
DecryptError::Broken(e) => write!(f, "文件结构损坏:{e}"),
DecryptError::KeyRequired(e) => write!(f, "{e}"),
DecryptError::Output(e) => write!(f, "输出失败:{e}"),
}
}
}
impl std::error::Error for DecryptError {}
impl From<std::io::Error> for DecryptError {
fn from(e: std::io::Error) -> Self {
DecryptError::Io(e.to_string())
}
}
pub type Result<T> = std::result::Result<T, DecryptError>;
/// 解密产物(两引擎统一形状)
#[derive(Debug, Clone)]
pub struct Outcome {
pub output: PathBuf,
/// 落盘用的扩展名(由首帧魔数判定)
pub format: String,
/// 单独落盘的封面(没有则为 None)
pub cover: Option<PathBuf>,
/// 音频明文字节数
pub audio_bytes: u64,
/// 给 UI 的一行备注(平台 / 密钥形态 / 元数据摘要)。
///
/// 结构化元数据目前只用来拼这一行——P2 做标签回填时再把 `NcmMeta` 提升到
/// `Outcome` 上,不要提前加一个没人读的字段。
pub note: String,
}
/// 按音频首帧魔数判定输出扩展名。
///
/// **这是权威来源**:ncm 的 `format` 字段、QMC 的输入后缀都只是声明,
/// 不可信(QKKDecrypt 同样以内容探测为准)。
pub fn detect_format(head: &[u8]) -> &'static str {
detect_format_opt(head).unwrap_or("flac")
}
/// 同上,但认不出时返回 `None`(调用方可据此决定是否回退到后缀/声明格式)。
pub fn detect_format_opt(head: &[u8]) -> Option<&'static str> {
let starts = |m: &[u8]| head.len() >= m.len() && &head[..m.len()] == m;
if starts(b"fLaC") {
Some("flac")
} else if starts(b"OggS") {
Some("ogg")
} else if starts(b"ID3") || (head.len() >= 2 && head[0] == 0xFF && head[1] & 0xE0 == 0xE0) {
// ID3 标签,或无标签 MP3 的帧同步字(0xFFEx / 0xFFFx)
Some("mp3")
} else if starts(b"RIFF") && head.len() >= 12 && &head[8..12] == b"WAVE" {
Some("wav")
} else if head.len() >= 12 && &head[4..8] == b"ftyp" {
Some("m4a")
} else if starts(b"wvpk") {
Some("wv")
} else {
None
}
}
/// 图片扩展名(按魔数)
pub fn image_ext(data: &[u8]) -> &'static str {
const PNG: &[u8] = &[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
if data.len() >= 8 && &data[..8] == PNG {
"png"
} else {
"jpg"
}
}
/// 确保输出目录存在并返回「按相对目录展开后」的目标目录。
///
/// 文件夹批量模式要保留原目录结构(`Pop/a.mflac` → `out/Pop/a.flac`),
/// 否则不同子目录的同名文件会在输出根目录里互相挤兑(虽然去重逻辑会让位成
/// `_1`,但产物与源的对应关系就丢了)。
pub fn ensure_subdir(
dir: &std::path::Path,
rel_parent: Option<&std::path::Path>,
) -> Result<PathBuf> {
let target = match rel_parent {
Some(rel) if !rel.as_os_str().is_empty() => dir.join(rel),
_ => dir.to_path_buf(),
};
std::fs::create_dir_all(&target)?;
Ok(target)
}
/// 在 `dir` 下为 `stem` + `ext` 找一个不冲突的输出路径。
///
/// 不同来源的同名文件若直接扁平落盘会**互相覆盖**,故占用时追加 `_1`/`_2`…
/// `reserved` 是本批次内已占用的名字(磁盘上尚不存在的也算)。
pub fn unique_output(
dir: &std::path::Path,
stem: &str,
ext: &str,
reserved: &mut std::collections::HashSet<String>,
) -> Result<PathBuf> {
let mut candidate = dir.join(format!("{stem}.{ext}"));
let mut n = 1;
loop {
let key = candidate.to_string_lossy().to_lowercase();
if !candidate.exists() && !reserved.contains(&key) {
reserved.insert(key);
return Ok(candidate);
}
candidate = dir.join(format!("{stem}_{n}.{ext}"));
n += 1;
if n > 9999 {
return Err(DecryptError::Output(format!(
"无法为 {stem} 找到不冲突的输出名"
)));
}
}
}
/// 读满 `buf` 或读到 EOF,返回实际字节数。
///
/// 与 `Read::read` 的关键区别:**只有 EOF 才会提前返回**,不会因为底层缓冲的
/// 短读而返回半个块。流密码解密的块边界必须与加密侧严格一致,
/// 否则相位错位、文件中途变噪声(`MUSIC_DECRYPT_PLAN.md` §6.24)。
pub fn read_full(r: &mut impl std::io::Read, buf: &mut [u8]) -> Result<usize> {
let mut filled = 0usize;
while filled < buf.len() {
match r.read(&mut buf[filled..]) {
Ok(0) => break,
Ok(n) => filled += n,
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
Err(e) => return Err(DecryptError::Io(e.to_string())),
}
}
Ok(filled)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn detect_format_by_magic() {
assert_eq!(detect_format(b"fLaC\x00\x00\x00\x22"), "flac");
assert_eq!(detect_format(b"OggS\x00\x02"), "ogg");
assert_eq!(detect_format(b"ID3\x04\x00"), "mp3");
assert_eq!(detect_format(&[0xFF, 0xFB, 0x90, 0x00]), "mp3");
assert_eq!(detect_format(b"RIFF\x00\x00\x00\x00WAVEfmt "), "wav");
assert_eq!(detect_format(b"\x00\x00\x00\x20ftypM4A "), "m4a");
assert_eq!(detect_format(b"wvpk\x00\x00"), "wv");
assert_eq!(detect_format(b"\x00\x01\x02\x03"), "flac");
}
#[test]
fn image_ext_by_magic() {
assert_eq!(
image_ext(&[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]),
"png"
);
assert_eq!(image_ext(&[0xFF, 0xD8, 0xFF, 0xE0]), "jpg");
}
#[test]
fn unique_output_appends_suffix_on_collision() {
let dir = std::env::temp_dir().join(format!("dec_unique_{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let mut reserved = std::collections::HashSet::new();
let a = unique_output(&dir, "song", "flac", &mut reserved).unwrap();
assert_eq!(a.file_name().unwrap(), "song.flac");
let b = unique_output(&dir, "song", "flac", &mut reserved).unwrap();
assert_eq!(b.file_name().unwrap(), "song_1.flac");
let c = unique_output(&dir, "song", "mp3", &mut reserved).unwrap();
assert_eq!(c.file_name().unwrap(), "song.mp3");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn ensure_subdir_preserves_relative_structure() {
let root = std::env::temp_dir().join(format!("dec_subdir_{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(&root).unwrap();
// 无相对目录 → 输出根
let flat = ensure_subdir(&root, None).unwrap();
assert_eq!(flat, root);
// 有相对目录 → 逐级创建
let nested = ensure_subdir(
&root,
Some(std::path::Path::new("Pop").join("2026").as_path()),
)
.unwrap();
assert!(nested.is_dir());
assert!(nested.ends_with("Pop/2026") || nested.ends_with(r"Pop\2026"));
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn read_full_returns_whole_buffer() {
// 一个每次只吐 3 字节的 reader:read_full 必须凑满整个 buf
struct Drip {
data: Vec<u8>,
pos: usize,
}
impl std::io::Read for Drip {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
if self.pos >= self.data.len() {
return Ok(0);
}
let n = buf.len().min(3).min(self.data.len() - self.pos);
buf[..n].copy_from_slice(&self.data[self.pos..self.pos + n]);
self.pos += n;
Ok(n)
}
}
let src: Vec<u8> = (0..100u8).collect();
let mut r = Drip {
data: src.clone(),
pos: 0,
};
let mut buf = [0u8; 64];
let n = read_full(&mut r, &mut buf).unwrap();
assert_eq!(n, 64, "短读 reader 也必须凑满整块");
assert_eq!(&buf[..], &src[..64]);
// 末尾不足一块时返回实际长度
let n2 = read_full(&mut r, &mut buf).unwrap();
assert_eq!(n2, 36);
let n3 = read_full(&mut r, &mut buf).unwrap();
assert_eq!(n3, 0, "EOF 返回 0");
}
}