From e5d34ccee71d1ea4eaa7b80720488868b614a717 Mon Sep 17 00:00:00 2001 From: vicrodh <103399283+vicrodh@users.noreply.github.com> Date: Mon, 23 Feb 2026 14:45:30 -0600 Subject: [PATCH] feat(commands): add v2_start_oauth_login Tauri command with WebView browser login --- src-tauri/src/commands_v2.rs | 252 +++++++++++++++++++++++++++++++++++ src-tauri/src/lib.rs | 1 + 2 files changed, 253 insertions(+) diff --git a/src-tauri/src/commands_v2.rs b/src-tauri/src/commands_v2.rs index aacc18004..28856acfd 100644 --- a/src-tauri/src/commands_v2.rs +++ b/src-tauri/src/commands_v2.rs @@ -1006,6 +1006,258 @@ pub async fn v2_manual_login( }) } +/// OAuth login via embedded browser window. +/// +/// Opens a Qobuz sign-in page in a new WebView window. When Qobuz redirects +/// to play.qobuz.com/discover?code=..., the code is intercepted and exchanged +/// for a full user session without loading that page. +/// +/// Both the legacy client and CoreBridge are authenticated so all subsystems +/// work identically to a normal email/password login. +/// +/// Returns the same V2LoginResponse as v2_manual_login. +#[tauri::command] +pub async fn v2_start_oauth_login( + app: tauri::AppHandle, + runtime: State<'_, RuntimeManagerState>, + app_state: State<'_, AppState>, + core_bridge: State<'_, CoreBridgeState>, + legal_state: State<'_, LegalSettingsState>, +) -> Result { + let manager = runtime.manager(); + log::info!("[V2] v2_start_oauth_login starting..."); + + // ToS gate — same as v2_manual_login + if let Err((error_code, error)) = require_tos_accepted(&legal_state) { + return Ok(V2LoginResponse { + success: false, + user_name: None, + user_id: None, + subscription: None, + subscription_valid_until: None, + error: Some(error), + error_code: Some(error_code), + }); + } + + // Get app_id from initialized client + let app_id = { + let client = app_state.client.read().await; + client.app_id().await.map_err(|e| e.to_string())? + }; + + // Redirect URL that Qobuz will send the code to (play.qobuz.com/discover) + let redirect_url = "https://play.qobuz.com/discover"; + let oauth_url = format!( + "https://www.qobuz.com/signin/oauth?ext_app_id={}&redirect_url={}", + app_id, + urlencoding::encode(redirect_url), + ); + + // Shared state: code captured by the navigation callback + let code_holder: Arc>> = + Arc::new(std::sync::Mutex::new(None)); + let notify = Arc::new(tokio::sync::Notify::new()); + + let code_holder_nav = Arc::clone(&code_holder); + let notify_nav = Arc::clone(¬ify); + + // Build and open the OAuth WebView window + let parsed_url: tauri::Url = oauth_url + .parse() + .map_err(|e| format!("Invalid OAuth URL: {}", e))?; + + let oauth_window = tauri::WebviewWindowBuilder::new( + &app, + "qobuz-oauth", + tauri::WebviewUrl::External(parsed_url), + ) + .title("Qobuz Login") + .inner_size(520.0, 720.0) + .resizable(true) + .on_navigation(move |url| { + // Intercept redirect to play.qobuz.com/discover?code=... + if url.host_str() == Some("play.qobuz.com") { + for (key, value) in url.query_pairs() { + if key == "code" { + log::info!("[OAuth] Intercepted OAuth code from navigation"); + *code_holder_nav.lock().unwrap() = Some(value.to_string()); + notify_nav.notify_one(); + return false; // Block — we handle the code, don't load discover + } + } + } + true // Allow all other navigation (login form, CSRF redirects, etc.) + }) + .build() + .map_err(|e| format!("Failed to open OAuth window: {}", e))?; + + // Wait up to 5 minutes for the user to complete login + let timed_out = tokio::time::timeout( + std::time::Duration::from_secs(300), + notify.notified(), + ) + .await + .is_err(); + + // Always close the OAuth window + let _ = oauth_window.close(); + + if timed_out { + return Ok(V2LoginResponse { + success: false, + user_name: None, + user_id: None, + subscription: None, + subscription_valid_until: None, + error: Some("OAuth login timed out after 5 minutes".to_string()), + error_code: Some("oauth_timeout".to_string()), + }); + } + + // Extract code from shared state + let code = code_holder.lock().unwrap().clone(); + let code = match code { + Some(c) => c, + None => { + return Ok(V2LoginResponse { + success: false, + user_name: None, + user_id: None, + subscription: None, + subscription_valid_until: None, + error: Some("OAuth login cancelled".to_string()), + error_code: Some("oauth_cancelled".to_string()), + }); + } + }; + + log::info!("[V2] OAuth code received, exchanging for session..."); + + // Exchange code for UserSession via legacy client + let session = { + let client = app_state.client.read().await; + match client.login_with_oauth_code(&code).await { + Ok(s) => s, + Err(e) => { + return Ok(V2LoginResponse { + success: false, + user_name: None, + user_id: None, + subscription: None, + subscription_valid_until: None, + error: Some(e.to_string()), + error_code: Some("oauth_exchange_failed".to_string()), + }); + } + } + }; + + log::info!("[V2] OAuth session established for user {}", session.user_id); + manager.set_legacy_auth(true, Some(session.user_id)).await; + let _ = app.emit( + "runtime:event", + RuntimeEvent::AuthChanged { + logged_in: true, + user_id: Some(session.user_id), + }, + ); + + // Convert api::models::UserSession → qbz_models::UserSession for CoreBridge + // Both types are structurally identical; serde round-trip is safe. + let core_session: UserSession = match serde_json::to_value(&session) + .and_then(serde_json::from_value) + { + Ok(s) => s, + Err(e) => { + log::error!("[V2] Failed to convert session for CoreBridge: {}", e); + rollback_auth_state(&manager, &app).await; + return Ok(V2LoginResponse { + success: false, + user_name: None, + user_id: None, + subscription: None, + subscription_valid_until: None, + error: Some(format!("Session conversion error: {}", e)), + error_code: Some("internal_error".to_string()), + }); + } + }; + + // CoreBridge auth — inject session directly (OAuth has no email/password) + if let Some(bridge) = core_bridge.try_get().await { + match bridge.login_with_session(core_session).await { + Ok(_) => { + log::info!("[V2] CoreBridge session injected for OAuth user"); + manager.set_corebridge_auth(true).await; + } + Err(e) => { + log::error!("[V2] CoreBridge session injection failed: {}", e); + rollback_auth_state(&manager, &app).await; + let _ = app.emit( + "runtime:event", + RuntimeEvent::CoreBridgeAuthFailed { + error: e.to_string(), + }, + ); + return Ok(V2LoginResponse { + success: false, + user_name: Some(session.display_name), + user_id: Some(session.user_id), + subscription: Some(session.subscription_label), + subscription_valid_until: session.subscription_valid_until, + error: Some(format!("V2 authentication failed: {}", e)), + error_code: Some("v2_auth_failed".to_string()), + }); + } + } + } else { + log::error!("[V2] CoreBridge not initialized for OAuth login"); + rollback_auth_state(&manager, &app).await; + return Ok(V2LoginResponse { + success: false, + user_name: Some(session.display_name), + user_id: Some(session.user_id), + subscription: Some(session.subscription_label), + subscription_valid_until: session.subscription_valid_until, + error: Some("V2 CoreBridge not initialized".to_string()), + error_code: Some("v2_not_initialized".to_string()), + }); + } + + // Activate per-user session (same as manual login) + if let Err(e) = crate::session_lifecycle::activate_session(&app, session.user_id).await { + log::error!("[V2] Session activation failed after OAuth: {}", e); + rollback_auth_state(&manager, &app).await; + return Ok(V2LoginResponse { + success: false, + user_name: Some(session.display_name.clone()), + user_id: Some(session.user_id), + subscription: Some(session.subscription_label.clone()), + subscription_valid_until: session.subscription_valid_until.clone(), + error: Some(format!("Session activation failed: {}", e)), + error_code: Some("session_activation_failed".to_string()), + }); + } + + let _ = app.emit( + "runtime:event", + RuntimeEvent::RuntimeReady { + user_id: session.user_id, + }, + ); + + Ok(V2LoginResponse { + success: true, + user_name: Some(session.display_name), + user_id: Some(session.user_id), + subscription: Some(session.subscription_label), + subscription_valid_until: session.subscription_valid_until, + error: None, + error_code: None, + }) +} + // ==================== Prefetch (V2) ==================== /// Number of Qobuz tracks to prefetch (not total tracks, just Qobuz) diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index c3001b75a..8d22b0ed1 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -931,6 +931,7 @@ pub fn run() { commands_v2::v2_init_client, commands_v2::v2_auto_login, commands_v2::v2_manual_login, + commands_v2::v2_start_oauth_login, commands_v2::v2_get_user_info, commands_v2::v2_save_credentials, commands_v2::v2_clear_saved_credentials,