feat(api): add private_key extraction, OAUTH_CALLBACK path, and login_with_oauth_code to legacy client
This commit is contained in:
3 files changed
+115
-2
No files matched your search
@@ -16,9 +16,11 @@ const BUNDLE_BASE_URL: &str = "https://play.qobuz.com";
|
||||
pub struct BundleTokens {
|
||||
pub app_id: String,
|
||||
pub secrets: Vec<String>,
|
||||
/// OAuth private key for the /oauth/callback exchange (newer bundles).
|
||||
pub private_key: Option<String>,
|
||||
}
|
||||
|
||||
/// Extract app_id and secrets from Qobuz bundle
|
||||
/// Extract app_id, secrets, and OAuth private_key from Qobuz bundle
|
||||
pub async fn extract_bundle_tokens(client: &Client) -> Result<BundleTokens> {
|
||||
// Step 1: Get login page to find bundle URL
|
||||
let login_page = client.get(LOGIN_PAGE_URL).send().await?.text().await?;
|
||||
@@ -41,7 +43,10 @@ pub async fn extract_bundle_tokens(client: &Client) -> Result<BundleTokens> {
|
||||
));
|
||||
}
|
||||
|
||||
Ok(BundleTokens { app_id, secrets })
|
||||
// Step 5: Extract OAuth private_key (optional)
|
||||
let private_key = extract_private_key(&bundle_content);
|
||||
|
||||
Ok(BundleTokens { app_id, secrets, private_key })
|
||||
}
|
||||
|
||||
fn extract_bundle_url(html: &str) -> Result<String> {
|
||||
@@ -180,6 +185,14 @@ fn extract_secrets(bundle: &str) -> Result<Vec<String>> {
|
||||
Ok(secrets)
|
||||
}
|
||||
|
||||
fn extract_private_key(bundle: &str) -> Option<String> {
|
||||
let re = Regex::new(r#"privateKey:\s*"(?P<key>[A-Za-z0-9]{6,30})""#)
|
||||
.expect("Invalid regex");
|
||||
re.captures(bundle)
|
||||
.and_then(|caps| caps.name("key"))
|
||||
.map(|m| m.as_str().to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -174,6 +174,105 @@ impl QobuzClient {
|
||||
*self.session.write().await = None;
|
||||
}
|
||||
|
||||
/// Inject an already-authenticated session (e.g. obtained via OAuth flow).
|
||||
pub async fn set_session(&self, session: UserSession) {
|
||||
*self.session.write().await = Some(session);
|
||||
}
|
||||
|
||||
/// Exchange an OAuth code for a full user session.
|
||||
///
|
||||
/// Step 1: GET /oauth/callback?code=CODE&private_key=KEY → { token }
|
||||
/// Step 2: POST /user/login with X-User-Auth-Token: token, body=extra=partner
|
||||
pub async fn login_with_oauth_code(&self, code: &str) -> Result<UserSession> {
|
||||
use reqwest::header::{HeaderMap, HeaderValue};
|
||||
|
||||
let tokens = self.tokens.read().await;
|
||||
let tokens = tokens.as_ref().ok_or_else(|| {
|
||||
ApiError::BundleExtractionError("Client not initialized".to_string())
|
||||
})?;
|
||||
let app_id = tokens.app_id.clone();
|
||||
let private_key = tokens.private_key.clone().ok_or_else(|| {
|
||||
ApiError::BundleExtractionError(
|
||||
"OAuth private key not available — bundle may be outdated".to_string(),
|
||||
)
|
||||
})?;
|
||||
drop(tokens);
|
||||
|
||||
// Step 1: Exchange code for token via /oauth/callback
|
||||
let callback_url = endpoints::build_url(paths::OAUTH_CALLBACK);
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
"X-App-Id",
|
||||
HeaderValue::from_str(&app_id).map_err(|_| ApiError::InvalidAppId)?,
|
||||
);
|
||||
|
||||
log::info!("[OAuth] Exchanging code at /oauth/callback");
|
||||
let resp = self
|
||||
.http
|
||||
.get(&callback_url)
|
||||
.headers(headers)
|
||||
.query(&[("code", code), ("private_key", &private_key)])
|
||||
.send()
|
||||
.await?;
|
||||
|
||||
if !resp.status().is_success() {
|
||||
return Err(ApiError::ApiResponse(format!(
|
||||
"OAuth callback failed: {}",
|
||||
resp.status()
|
||||
)));
|
||||
}
|
||||
|
||||
let json: Value = resp.json().await?;
|
||||
let token = json["token"]
|
||||
.as_str()
|
||||
.ok_or_else(|| {
|
||||
ApiError::ApiResponse("No token in OAuth callback response".to_string())
|
||||
})?
|
||||
.to_string();
|
||||
|
||||
log::info!("[OAuth] Token received, fetching session via /user/login");
|
||||
|
||||
// Step 2: GET /user/login with X-User-Auth-Token to fetch full profile
|
||||
let user_login_url = endpoints::build_url(paths::USER_LOGIN);
|
||||
let mut auth_headers = HeaderMap::new();
|
||||
auth_headers.insert(
|
||||
"X-App-Id",
|
||||
HeaderValue::from_str(&app_id).map_err(|_| ApiError::InvalidAppId)?,
|
||||
);
|
||||
auth_headers.insert(
|
||||
"X-User-Auth-Token",
|
||||
HeaderValue::from_str(&token).map_err(|_| {
|
||||
ApiError::AuthenticationError("Invalid OAuth token format".into())
|
||||
})?,
|
||||
);
|
||||
|
||||
let login_resp = self
|
||||
.http
|
||||
.post(&user_login_url)
|
||||
.headers(auth_headers)
|
||||
.header("Content-Type", "text/plain;charset=UTF-8")
|
||||
.body("extra=partner")
|
||||
.send()
|
||||
.await?;
|
||||
|
||||
match login_resp.status() {
|
||||
StatusCode::OK => {
|
||||
let login_json: Value = login_resp.json().await?;
|
||||
let session = parse_login_response(&login_json)?;
|
||||
*self.session.write().await = Some(session.clone());
|
||||
log::info!("[OAuth] Session established for user {}", session.user_id);
|
||||
Ok(session)
|
||||
}
|
||||
StatusCode::UNAUTHORIZED => Err(ApiError::AuthenticationError(
|
||||
"OAuth token rejected".to_string(),
|
||||
)),
|
||||
status => Err(ApiError::ApiResponse(format!(
|
||||
"user/login OAuth step failed: {}",
|
||||
status
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Get current user info (display name, subscription, and expiry if available)
|
||||
pub async fn get_user_info(&self) -> Option<(String, String, Option<String>)> {
|
||||
self.session.read().await.as_ref().map(|s| {
|
||||
|
||||
@@ -6,6 +6,7 @@ pub const BASE_URL: &str = "https://www.qobuz.com/api.json/0.2";
|
||||
pub mod paths {
|
||||
// User
|
||||
pub const USER_LOGIN: &str = "/user/login";
|
||||
pub const OAUTH_CALLBACK: &str = "/oauth/callback";
|
||||
pub const PURCHASE_GET_USER_PURCHASES: &str = "/purchase/getUserPurchases";
|
||||
pub const PURCHASE_GET_USER_PURCHASES_IDS: &str = "/purchase/getUserPurchasesIds";
|
||||
pub const DYNAMIC_SUGGEST: &str = "/dynamic/suggest";
|
||||
|
||||
Reference in new issue
Block a user