feat: add cli support for ncm

This commit is contained in:
鲁树人 2024-09-14 16:16:20 +01:00
parent abd4549da3
commit 208461e089
9 changed files with 140 additions and 10 deletions

1
Cargo.lock generated
View File

@ -434,6 +434,7 @@ dependencies = [
"anyhow", "anyhow",
"clap", "clap",
"umc_kuwo", "umc_kuwo",
"umc_ncm",
"umc_qmc", "umc_qmc",
"umc_utils", "umc_utils",
] ]

View File

@ -8,4 +8,5 @@ anyhow = "1.0.86"
clap = { version = "4.5.17", features = ["derive"] } clap = { version = "4.5.17", features = ["derive"] }
umc_kuwo = { path = "../um_crypto/kuwo" } umc_kuwo = { path = "../um_crypto/kuwo" }
umc_qmc = { path = "../um_crypto/qmc" } umc_qmc = { path = "../um_crypto/qmc" }
umc_ncm = { path = "../um_crypto/ncm" }
umc_utils = { path = "../um_crypto/utils" } umc_utils = { path = "../um_crypto/utils" }

View File

@ -1,5 +1,6 @@
use clap::Subcommand; use clap::Subcommand;
pub mod ncm;
pub mod qmc1; pub mod qmc1;
pub mod qmc2; pub mod qmc2;
@ -9,4 +10,6 @@ pub enum Commands {
QMCv1(qmc1::ArgsQMCv1), QMCv1(qmc1::ArgsQMCv1),
#[command(name = "qmc2")] #[command(name = "qmc2")]
QMCv2(qmc2::ArgsQMCv2), QMCv2(qmc2::ArgsQMCv2),
#[command(name = "ncm")]
NCM(ncm::ArgsNCM),
} }

90
um_cli/src/cmd/ncm.rs Normal file
View File

@ -0,0 +1,90 @@
use crate::Cli;
use clap::Args;
use std::fs::File;
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::PathBuf;
use umc_ncm::header::NCMFile;
/// Decrypt a NCM file (NetEase Cloud Music)
#[derive(Args)]
pub struct ArgsNCM {
/// Path to output file, e.g. /export/Music/song.flac
#[arg(short, long)]
output: Option<PathBuf>,
/// Path to input file, e.g. /export/Music/song.ncm
#[arg(name = "input")]
input: PathBuf,
/// Path to export cover image. Could be either JPG or PNG.
/// File will not be created if not found.
#[arg(short)]
cover: Option<PathBuf>,
/// Path to export metadata. JSON string.
#[arg(short)]
metadata: Option<PathBuf>,
}
impl ArgsNCM {
fn write_metadata(&self, cli: &Cli, ncm: &NCMFile) -> anyhow::Result<()> {
if let Some(metadata_path) = &self.metadata {
if !ncm.metadata.is_empty() {
let metadata = ncm.get_metadata()?;
File::create(metadata_path)?.write_all(&metadata)?;
if cli.verbose {
let metadata_path = metadata_path.display();
let len = metadata.len();
println!("metadata written to {metadata_path} ({len} bytes)");
}
} else {
println!("metadata is empty, skip.");
}
}
Ok(())
}
fn write_cover(&self, cli: &Cli, ncm: &NCMFile) -> anyhow::Result<()> {
if let Some(cover_path) = &self.cover {
if let Some(cover) = &ncm.image1 {
File::create(cover_path)?.write_all(&cover)?;
if cli.verbose {
let cover_path = cover_path.display();
let len = cover.len();
println!("cover written to {cover_path} ({len} bytes)");
}
} else {
println!("cover#1 is empty, skip.");
}
}
Ok(())
}
pub fn run(&self, cli: &Cli) -> anyhow::Result<i32> {
let mut file_input = File::open(&self.input)?;
let ncm = NCMFile::new_from_readable(&mut file_input)?;
self.write_metadata(cli, &ncm)?;
self.write_cover(cli, &ncm)?;
if let Some(output_path) = &self.output {
file_input.seek(SeekFrom::Start(ncm.audio_data_offset as u64))?;
let mut file_output = File::create(output_path)?;
let mut offset = 0usize;
let mut buffer = vec![0u8; cli.buffer_size].into_boxed_slice();
while let Ok(n) = file_input.read(&mut buffer) {
if n == 0 {
break;
}
ncm.decrypt(&mut buffer[..n], offset);
file_output.write_all(&buffer[..n])?;
offset += n;
}
}
Ok(0)
}
}

View File

@ -5,7 +5,7 @@ use std::fs::File;
use std::io::{Read, Write}; use std::io::{Read, Write};
use std::path::PathBuf; use std::path::PathBuf;
/// Decrypt a QMCv1 file /// Decrypt a QMCv1 file (QQMusic)
#[derive(Args)] #[derive(Args)]
pub struct ArgsQMCv1 { pub struct ArgsQMCv1 {
/// Path to output file, e.g. /export/Music/song.flac /// Path to output file, e.g. /export/Music/song.flac

View File

@ -8,7 +8,7 @@ use std::path::PathBuf;
use umc_qmc::{footer, QMCv2Cipher}; use umc_qmc::{footer, QMCv2Cipher};
use umc_utils::base64; use umc_utils::base64;
/// Decrypt a QMCv2 file /// Decrypt a QMCv2 file (QQMusic)
#[derive(Args)] #[derive(Args)]
pub struct ArgsQMCv2 { pub struct ArgsQMCv2 {
/// Path to output file, e.g. /export/Music/song.flac /// Path to output file, e.g. /export/Music/song.flac

View File

@ -29,6 +29,7 @@ fn run_command(cli: &Cli) -> Result<i32> {
match &cli.command { match &cli.command {
Some(Commands::QMCv1(cmd)) => cmd.run(&cli), Some(Commands::QMCv1(cmd)) => cmd.run(&cli),
Some(Commands::QMCv2(cmd)) => cmd.run(&cli), Some(Commands::QMCv2(cmd)) => cmd.run(&cli),
Some(Commands::NCM(cmd)) => cmd.run(&cli),
None => { None => {
// https://github.com/clap-rs/clap/issues/3857#issuecomment-1161796261 // https://github.com/clap-rs/clap/issues/3857#issuecomment-1161796261
todo!("implement a sensible default command, similar to um/cli"); todo!("implement a sensible default command, similar to um/cli");

View File

@ -1,5 +1,7 @@
use crate::{content_key, metadata, NetEaseCryptoError as Error}; use crate::{content_key, metadata, NetEaseCryptoError as Error, NetEaseCryptoError};
use byteorder::{ByteOrder, LE}; use byteorder::{ByteOrder, LE};
use std::cmp::max;
use std::io::Read;
const CRC32: crc::Crc<u32> = crc::Crc::<u32>::new(&crc::CRC_32_ISO_HDLC); const CRC32: crc::Crc<u32> = crc::Crc::<u32>::new(&crc::CRC_32_ISO_HDLC);
@ -97,10 +99,10 @@ impl NCMFile {
let offset = offset + 1; let offset = offset + 1;
let cover_frame_len = LE::read_u32(&header[offset..offset + 4]) as usize; let cover_frame_len = LE::read_u32(&header[offset..offset + 4]) as usize;
let offset = offset + 4;
if header.len() < offset + cover_frame_len + 4 { if header.len() < offset + cover_frame_len + 4 {
Err(Error::HeaderTooSmall(offset + cover_frame_len + 4))?; Err(Error::HeaderTooSmall(offset + cover_frame_len + 4))?;
} }
let offset = offset + 4;
let image1_len = LE::read_u32(&header[offset..offset + 4]) as usize; let image1_len = LE::read_u32(&header[offset..offset + 4]) as usize;
if image1_len > cover_frame_len { if image1_len > cover_frame_len {
@ -110,6 +112,7 @@ impl NCMFile {
})?; })?;
} }
let offset = offset + 4; let offset = offset + 4;
let image2_len = cover_frame_len - image1_len; let image2_len = cover_frame_len - image1_len;
let image1 = match image1_len { let image1 = match image1_len {
0 => None, 0 => None,
@ -135,6 +138,36 @@ impl NCMFile {
}) })
} }
pub fn new_from_readable<T>(file: &mut T) -> Result<Self, Error>
where
T: Read + ?Sized,
{
let mut total_bytes_read = 0;
let mut next_read_len = 4096;
let mut header = vec![];
let ncm = loop {
header.resize(total_bytes_read + next_read_len, 0);
let this_read = file
.read(&mut header[total_bytes_read..])
.map_err(NetEaseCryptoError::FileIOError)?;
if this_read == 0 {
Err(NetEaseCryptoError::FileIOErrorReadZero)?;
}
total_bytes_read += this_read;
match NCMFile::new(&header) {
Ok(ncm) => break ncm,
Err(NetEaseCryptoError::HeaderTooSmall(expected_len)) => {
next_read_len = max(expected_len - total_bytes_read, 4096);
}
Err(err) => Err(err)?,
};
};
Ok(ncm)
}
pub fn get_metadata(&self) -> Result<Vec<u8>, Error> { pub fn get_metadata(&self) -> Result<Vec<u8>, Error> {
metadata::decrypt(&self.metadata) metadata::decrypt(&self.metadata)
} }
@ -145,18 +178,14 @@ impl NCMFile {
/// ///
/// * `data`: The data to decrypt /// * `data`: The data to decrypt
/// * `offset`: Offset of the data in file, subtract `self.audio_data_offset` /// * `offset`: Offset of the data in file, subtract `self.audio_data_offset`
/// pub fn decrypt<T>(&self, data: &mut T, offset: usize)
/// returns: Result<(), NetEaseCryptoError>
pub fn decrypt<T>(&self, data: &mut T, offset: usize) -> Result<(), Error>
where where
T: AsMut<[u8]>, T: AsMut<[u8]> + ?Sized,
{ {
let key_stream = self.audio_rc4_key_stream.iter().cycle().skip(offset & 0xff); let key_stream = self.audio_rc4_key_stream.iter().cycle().skip(offset & 0xff);
for (datum, &key) in data.as_mut().iter_mut().zip(key_stream) { for (datum, &key) in data.as_mut().iter_mut().zip(key_stream) {
*datum ^= key; *datum ^= key;
} }
Ok(())
} }
} }

View File

@ -11,6 +11,11 @@ pub enum NetEaseCryptoError {
#[error("Header need at least {0} more bytes")] #[error("Header need at least {0} more bytes")]
HeaderTooSmall(usize), HeaderTooSmall(usize),
#[error("File I/O Error: {0}")]
FileIOError(std::io::Error),
#[error("File I/O Error: Read 0 bytes")]
FileIOErrorReadZero,
#[error("Not a NCM file")] #[error("Not a NCM file")]
NotNCMFile, NotNCMFile,
#[error("Invalid NCM checksum. Expected {expected:08x}, actual: {expected:08x}")] #[error("Invalid NCM checksum. Expected {expected:08x}, actual: {expected:08x}")]