musixmatch-inofficial/src/lib.rs
2026-06-11 17:59:45 +02:00

509 lines
16 KiB
Rust

#![doc = include_str!("../README.md")]
#![warn(missing_docs, clippy::todo)]
mod api_model;
mod apis;
mod error;
pub mod models;
pub mod storage;
use std::fmt::Debug;
use std::path::Path;
use std::sync::{Arc, RwLock};
pub use error::{Error, IdError};
use base64::Engine;
use hmac::{Hmac, KeyInit, Mac};
use log::{error, info, warn};
use rand::RngExt;
use reqwest::header::{self, HeaderMap};
use reqwest::{Client, ClientBuilder, Url};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use sha1::Sha1;
use storage::{FileStorage, SessionStorage};
use time::OffsetDateTime;
use time::format_description::well_known::Rfc3339;
use time::macros::format_description;
use tokio::sync::Mutex;
use crate::api_model::parse_body;
use crate::error::Result;
const YMD_FORMAT: &[time::format_description::FormatItem] =
format_description!("[year][month][day]");
const APP_ID: &str = "android-player-v1.0";
const API_URL: &str = "https://apic.musixmatch.com/ws/1.1/";
const SIGNATURE_SECRET: &[u8; 29] = b"mNdca@6W7TeEcFn6*3.s97sJ*yPMd";
const DEFAULT_UA: &str = "Dalvik/2.1.0 (Linux; U; Android 13; Pixel 6 Build/T3B2.230316.003)";
const DEFAULT_BRAND: &str = "Google";
const DEFAULT_DEVICE: &str = "Pixel 6";
/// Musixmatch API client
///
/// You do **not** have to wrap the client in an [`Rc`](std::rc::Rc) or [`Arc`] to reuse it,
/// because it already uses an [`Arc`] internally.
#[derive(Clone)]
pub struct Musixmatch {
inner: Arc<MusixmatchRef>,
}
/// Musixmatch API client builder
///
/// Used to construct a new [`Musixmatch`] client.#
#[derive(Default)]
pub struct MusixmatchBuilder {
user_agent: Option<String>,
brand: Option<String>,
device: Option<String>,
storage: DefaultOpt<Box<dyn SessionStorage>>,
credentials: Option<Credentials>,
}
#[derive(Default)]
enum DefaultOpt<T> {
Some(T),
None,
#[default]
Default,
}
impl<T> DefaultOpt<T> {
fn or_default<F: FnOnce() -> T>(self, f: F) -> Option<T> {
match self {
DefaultOpt::Some(x) => Some(x),
DefaultOpt::None => None,
DefaultOpt::Default => Some(f()),
}
}
}
struct MusixmatchRef {
http: Client,
storage: Option<Box<dyn SessionStorage>>,
credentials: RwLock<Option<Credentials>>,
brand: String,
device: String,
usertoken: Mutex<Option<String>>,
}
#[derive(Default, Clone)]
struct Credentials {
email: String,
password: String,
}
#[derive(Debug, Serialize, Deserialize)]
struct StoredSession {
usertoken: String,
}
impl MusixmatchBuilder {
/// Create a new Musixmatch client builder.
///
/// This is the same as `Musixmatch::builder()`
pub fn new() -> Self {
Self::default()
}
/// Set the Musixmatch credentials
///
/// The Musixmatch API required a free account on <https://www.musixmatch.com> to be
/// used. However, as of 2024, this requirement was removed.
///
/// The Musixmatch client can be constructed without any credentials.
/// In this case you rely on the stored session token to authenticate
/// yourself. If the token is missing or invalid, [`Error::MissingCredentials`]
/// is returned when attempting an API request.
///
/// In this case you can prompt the user to enter credentials, add them to the client
/// with the [`Musixmatch::set_credentials`] function and attempt another request.
///
/// This mode of operation is preferred for interactive applications since
/// it does not require storing credentials.
pub fn credentials<S: Into<String>, S2: Into<String>>(
mut self,
email: S,
password: S2,
) -> Self {
self.credentials = Some(Credentials {
email: email.into(),
password: password.into(),
});
self
}
/// Add a [`SessionStorage`] backend for persisting the Musixmatch session
/// token between requests.
///
/// **Default value**: [`FileStorage`] in `musixmatch_session.json`
pub fn storage(mut self, storage: Box<dyn SessionStorage>) -> Self {
self.storage = DefaultOpt::Some(storage);
self
}
/// Add a [`FileStorage`] backend for persisting the Musixmatch session
/// token between requests.
pub fn storage_file<P: AsRef<Path>>(self, path: P) -> Self {
self.storage(Box::from(FileStorage::new(path)))
}
/// Disable session token storage
///
/// This is not recommended, since the endpoint to generate new
/// session tokens is rate limited to 2 requests per minute.
pub fn no_storage(mut self) -> Self {
self.storage = DefaultOpt::None;
self
}
/// Set the user agent of the Musixmatch client
pub fn user_agent<S: Into<String>>(mut self, user_agent: S) -> Self {
self.user_agent = Some(user_agent.into());
self
}
/// Set the device brand of the Musixmatch client
pub fn device_brand<S: Into<String>>(mut self, device_brand: S) -> Self {
self.brand = Some(device_brand.into());
self
}
/// Set the device model of the Musixmatch client
pub fn device_model<S: Into<String>>(mut self, device_model: S) -> Self {
self.device = Some(device_model.into());
self
}
/// Returns a new, configured Musixmatch client
pub fn build(self) -> Result<Musixmatch> {
self.build_with_client(ClientBuilder::new())
}
/// Returns a new, configured Musixmatch client using a Reqwest client builder
pub fn build_with_client(self, client_builder: ClientBuilder) -> Result<Musixmatch> {
let storage = self.storage.or_default(|| Box::<FileStorage>::default());
let stored_session = Musixmatch::retrieve_session(&storage);
let mut headers = HeaderMap::new();
headers.insert(header::COOKIE, "AWSELBCORS=0; AWSELB=0".parse().unwrap());
let http = client_builder
.user_agent(self.user_agent.unwrap_or_else(|| DEFAULT_UA.to_owned()))
.gzip(true)
.default_headers(headers)
.build()?;
Ok(Musixmatch {
inner: MusixmatchRef {
http,
storage,
credentials: RwLock::new(self.credentials),
brand: self.brand.unwrap_or_else(|| DEFAULT_BRAND.to_owned()),
device: self.device.unwrap_or_else(|| DEFAULT_DEVICE.to_owned()),
usertoken: Mutex::new(stored_session.map(|s| s.usertoken)),
}
.into(),
})
}
}
impl Default for Musixmatch {
fn default() -> Self {
MusixmatchBuilder::new()
.build()
.expect("http client could not be constructed")
}
}
impl Musixmatch {
/// Create a new Musixmatch client builder
pub fn builder() -> MusixmatchBuilder {
MusixmatchBuilder::default()
}
async fn get_usertoken(&self, force_new: bool) -> Result<String> {
// Lock the session here to prevent concurrent tasks from obtaining sessions
let mut stored_usertoken = self.inner.usertoken.lock().await;
if !force_new && let Some(usertoken) = &mut *stored_usertoken {
return Ok(usertoken.clone());
}
let credentials = {
let c = self.inner.credentials.read().unwrap();
c.clone()
};
let now = OffsetDateTime::now_utc();
let guid = random_guid();
let adv_id = random_uuid();
// Get user token
// The get_token endpoint seems to be rate limited for 2 requests per minute
let mut url = Url::parse_with_params(
&format!("{API_URL}token.get"),
&[
("adv_id", adv_id.as_str()),
("root", "0"),
("sideloaded", "0"),
("app_id", "android-player-v1.0"),
// App version (7.9.5)
("build_number", "2022090901"),
("guid", guid.as_str()),
("lang", "en_US"),
("model", self.model_string().as_str()),
(
"timestamp",
now.format(&Rfc3339).unwrap_or_default().as_str(),
),
("format", "json"),
],
)
.unwrap();
sign_url_with_date(&mut url, now);
let resp = self.inner.http.get(url).send().await?.error_for_status()?;
let resp_txt = resp.text().await?;
let usertoken = parse_body::<api_model::GetToken>(&resp_txt)?.user_token;
info!("Received new usertoken: {}****", &usertoken[0..8]);
if let Some(credentials) = credentials {
let account = self.post_credentials(&usertoken, &credentials).await?;
info!("Logged in as {} ", account.name);
}
*stored_usertoken = Some(usertoken.to_owned());
self.store_session(&usertoken);
Ok(usertoken)
}
async fn post_credentials(
&self,
usertoken: &str,
credentials: &Credentials,
) -> Result<api_model::Account> {
let mut url = new_url_from_token("credential.post", usertoken);
sign_url_with_date(&mut url, OffsetDateTime::now_utc());
let api_credentials = api_model::Credentials {
credential_list: &[api_model::CredentialWrap {
credential: api_model::Credential {
action: "login",
email: &credentials.email,
password: &credentials.password,
typ: "mxm",
},
}],
};
let resp = self
.inner
.http
.post(url)
.json(&api_credentials)
.send()
.await?
.error_for_status()?;
let resp_txt = resp.text().await?;
let login = parse_body::<api_model::Login>(&resp_txt)?;
let credential = login
.0
.into_iter()
.next()
.ok_or(Error::InvalidData("no credentials returned".into()))?
.credential;
match credential {
api_model::LoginCredential::Account { account } => Ok(account),
api_model::LoginCredential::Error { error } => {
if error.status_code == 4004 {
Err(Error::WrongCredentials)
} else {
Err(Error::MusixmatchError {
status_code: error.status_code,
msg: error.description,
})
}
}
}
}
fn store_session(&self, usertoken: &str) {
if let Some(storage) = &self.inner.storage {
let to_store = StoredSession {
usertoken: usertoken.to_owned(),
};
match serde_json::to_string(&to_store) {
Ok(json) => storage.write(&json),
Err(e) => error!("Could not serialize session. Error: {e}"),
}
}
}
fn retrieve_session(storage: &Option<Box<dyn SessionStorage>>) -> Option<StoredSession> {
storage.as_ref().and_then(|storage| {
storage
.read()
.and_then(|json| match serde_json::from_str::<StoredSession>(&json) {
Ok(session) => Some(session),
Err(e) => {
error!("Could not deserialize session. Error: {e}");
None
}
})
})
}
fn model_string(&self) -> String {
// android.os.build (https://developer.android.com/reference/android/os/Build)
// "model", "manufacturer/" + Build.MANUFACTURER + " brand/" + Build.BRAND + " model/" + Build.MODEL
// manufacturer/Google brand/google model/Android SDK built for x86_64
format!(
"manufacturer/{0} brand/{0} model/{1}",
self.inner.brand, self.inner.device
)
}
fn new_url(&self, endpoint: &str) -> reqwest::Url {
Url::parse_with_params(
&format!("{API_URL}{endpoint}"),
&[("app_id", APP_ID), ("format", "json")],
)
.unwrap()
}
async fn finish_url(&self, url: &mut Url, force_new_session: bool) -> Result<()> {
let usertoken = self.get_usertoken(force_new_session).await?;
url.query_pairs_mut()
.append_pair("usertoken", &usertoken)
.finish();
sign_url_with_date(url, OffsetDateTime::now_utc());
Ok(())
}
async fn execute_get_request<T>(&self, url: &Url) -> Result<T>
where
T: DeserializeOwned,
{
let mut req_url = url.clone();
self.finish_url(&mut req_url, false).await?;
let resp = self
.inner
.http
.get(req_url)
.send()
.await?
.error_for_status()?;
let resp_txt = resp.text().await?;
match parse_body(&resp_txt) {
Ok(body) => Ok(body),
Err(Error::TokenExpired) => {
info!("Usertoken expired, getting a new one");
let mut req_url = url.clone();
self.finish_url(&mut req_url, true).await?;
let resp = self
.inner
.http
.get(req_url)
.send()
.await?
.error_for_status()?;
let resp_txt = resp.text().await?;
parse_body(&resp_txt)
}
Err(e) => Err(e),
}
}
/// Ensure the client has a login token
///
/// It is not neccessary to use this method, because the client
/// automatically obtains a token when executing requests.
pub async fn login(&self) -> Result<()> {
self.get_usertoken(false).await?;
Ok(())
}
/// Change the Musixmatch credentials
pub fn set_credentials<S: Into<String>, S2: Into<String>>(&self, email: S, password: S2) {
let mut c = self.inner.credentials.write().unwrap();
*c = Some(Credentials {
email: email.into(),
password: password.into(),
});
}
}
fn random_guid() -> String {
let mut rng = rand::rng();
let n = rng.random::<u64>();
format!("{n:016x}")
}
fn random_uuid() -> String {
let mut rng = rand::rng();
format!(
"{:08x}-{:04x}-{:04x}-{:04x}-{:012x}",
rng.random::<u32>(),
rng.random::<u16>(),
rng.random::<u16>(),
rng.random::<u16>(),
rng.random::<u64>() & 0xffffffffffff,
)
}
fn new_url_from_token(endpoint: &str, usertoken: &str) -> reqwest::Url {
Url::parse_with_params(
&format!("{API_URL}{endpoint}"),
&[
("app_id", APP_ID),
("usertoken", usertoken),
("format", "json"),
],
)
.unwrap()
}
fn sign_url_with_date(url: &mut Url, date: OffsetDateTime) {
let mut mac = Hmac::<Sha1>::new_from_slice(SIGNATURE_SECRET).unwrap();
mac.update(url.as_str().as_bytes());
mac.update(date.format(YMD_FORMAT).unwrap_or_default().as_bytes());
let sig = mac.finalize().into_bytes();
let sig_b64 = base64::engine::general_purpose::STANDARD.encode(sig) + "\n";
url.query_pairs_mut()
.append_pair("signature", &sig_b64)
.append_pair("signature_protocol", "sha1")
.finish();
}
#[cfg(test)]
mod tests {
use time::macros::datetime;
use super::*;
#[test]
fn t_sign_url() {
let mut url = Url::parse("https://apic.musixmatch.com/ws/1.1/track.subtitle.get?app_id=android-player-v1.0&usertoken=22092860c49e8d783b569a7bd847cd5b289bbec306f8a0bb2d3771&format=json&track_spotify_id=7Ga0ByppmSXWuKXdsD8JGL&subtitle_format=mxm").unwrap();
sign_url_with_date(&mut url, datetime!(2022-09-28 0:00 UTC));
assert_eq!(
url.as_str(),
"https://apic.musixmatch.com/ws/1.1/track.subtitle.get?app_id=android-player-v1.0&usertoken=22092860c49e8d783b569a7bd847cd5b289bbec306f8a0bb2d3771&format=json&track_spotify_id=7Ga0ByppmSXWuKXdsD8JGL&subtitle_format=mxm&signature=78ywxkeXlazpevI%2BbD8E3YluLPc%3D%0A&signature_protocol=sha1"
)
}
}