feat(qbzd): login subcommand, library scan, service files (68 endpoints)

qbzd login: interactive OAuth via system browser. Opens browser,
captures callback, exchanges code, saves token to keyring. Same
flow as desktop app. Daemon auto-logins on next start.

Library scan endpoint (POST /api/library/scan): discovers audio
files in registered folders. Full metadata extraction deferred
until MetadataExtractor moves to qbz-library crate.

Service files: systemd, OpenRC, runit + example qbzd.toml config.

cc
This commit is contained in:
vicrodh committed 2026-04-09 04:52:58 -06:00
1 parent 42a8ff5665
commit aacdeabe07
9 files changed
+284 -3

No files matched your search

+4
View File
@@ -38,6 +38,10 @@ serde_json = { workspace = true }
toml = "0.8"
clap = { version = "4", features = ["derive"] }
# Browser open + URL encoding (for OAuth login)
open = "5"
urlencoding = "2"
# System
dirs = "6"
log = { workspace = true }
+16
View File
@@ -0,0 +1,16 @@
#!/sbin/openrc-run
# QBZ Music Daemon - OpenRC service
name="QBZ Music Daemon"
description="Headless music player daemon for Qobuz"
command="/usr/bin/qbzd"
command_args="--config /etc/qbz/qbzd.toml"
command_user="qbz:audio"
pidfile="/run/qbzd.pid"
command_background=true
depend() {
need net
after sound
}
+3
View File
@@ -0,0 +1,3 @@
#!/bin/sh
# QBZ Music Daemon - runit service
exec chpst -u qbz:audio /usr/bin/qbzd --config /etc/qbz/qbzd.toml 2>&1
+23
View File
@@ -0,0 +1,23 @@
[Unit]
Description=QBZ Music Daemon
After=network-online.target sound.target
Wants=network-online.target
[Service]
Type=simple
ExecStart=/usr/bin/qbzd --config /etc/qbz/qbzd.toml
Restart=on-failure
RestartSec=5
User=qbz
Group=audio
Environment=RUST_LOG=info
Environment=XDG_RUNTIME_DIR=/run/user/%U
# Sandboxing
ProtectSystem=strict
ReadWritePaths=/var/lib/qbz /run/user
PrivateTmp=true
NoNewPrivileges=true
[Install]
WantedBy=multi-user.target
@@ -0,0 +1,42 @@
# QBZ Daemon Configuration
# Copy to ~/.config/qbz/qbzd.toml or /etc/qbz/qbzd.toml
[server]
bind = "0.0.0.0"
port = 8182
token = "auto" # "auto" generates on first run
[audio]
backend = "pipewire" # pipewire | alsa | pulse | system
device = "" # empty = default device
gapless = true
normalization = false
[cache]
memory_mb = 0 # 0 = auto-detect from RAM (recommended for SBCs)
disk_mb = 400 # persistent disk cache
prefetch_count = 2 # tracks to prefetch ahead
prefetch_concurrent = 1 # simultaneous track downloads
cmaf_concurrent_segments = 2 # parallel CMAF segments per track
[cache.auto]
enabled = true # auto-size memory cache from available RAM
# 1 GB RAM -> 100 MB, 4 GB -> 200 MB, 8+ GB -> 400 MB
[data]
dir = "" # empty = ~/.local/share/qbz (or /var/lib/qbz for system service)
[mpris]
enabled = true # D-Bus MPRIS media controls (Linux)
[qconnect]
enabled = true # Qobuz Connect (control from Qobuz mobile app)
device_name = "" # empty = hostname
[mdns]
enabled = true # LAN discovery via mDNS (_qbz._tcp)
name = "" # empty = hostname
[logging]
level = "info" # trace | debug | info | warn | error
journal = true # use systemd journal when available
+59
View File
@@ -114,6 +114,65 @@ pub async fn add_folder(
Ok(Json(serde_json::json!({"path": req.path, "status": "added"})))
}
/// Trigger a library scan on all registered folders.
/// Runs in background, returns immediately.
///
/// Note: Full metadata extraction requires the MetadataExtractor from
/// src-tauri/src/library/ which is not yet in the qbz-library crate.
/// This endpoint uses the scanner to find audio files and logs results.
/// Full metadata-aware scanning will be available when MetadataExtractor
/// is moved to the crate.
pub async fn start_scan(daemon: Arc<DaemonCore>) -> Result<Json<serde_json::Value>, String> {
let user = daemon.user.read().await;
let session = user.as_ref().ok_or("No active session")?;
let db_path = session.data_dir.join("library.db");
let db = qbz_library::LibraryDatabase::open(&db_path)
.map_err(|e| format!("Library DB error: {}", e))?;
let folders = db.get_folders()
.map_err(|e| format!("Failed to get folders: {}", e))?;
if folders.is_empty() {
return Ok(Json(serde_json::json!({"status": "no_folders", "message": "No folders configured. Add folders first."})));
}
let folder_count = folders.len();
// Spawn scan in background
tokio::task::spawn_blocking(move || {
let scanner = qbz_library::LibraryScanner::new();
let mut total_files = 0usize;
for folder in &folders {
let path = std::path::Path::new(folder);
if !path.exists() {
log::warn!("[qbzd] Scan: folder does not exist: {}", folder);
continue;
}
log::info!("[qbzd] Scanning: {}", folder);
match scanner.scan_directory(path) {
Ok(result) => {
let count = result.audio_files.len();
total_files += count;
log::info!(
"[qbzd] Scanned {}: {} audio files, {} CUE files",
folder, count, result.cue_files.len()
);
}
Err(e) => {
log::error!("[qbzd] Scan failed for {}: {}", folder, e);
}
}
}
log::info!("[qbzd] Library scan complete: {} audio files found", total_files);
});
Ok(Json(serde_json::json!({
"status": "scanning",
"folders": folder_count,
})))
}
#[derive(Deserialize)]
pub struct RemoveFolderRequest {
pub path: String,
+1
View File
@@ -413,6 +413,7 @@ fn build_router(daemon: Arc<DaemonCore>) -> axum::Router {
.route("/api/library/folders", get(with_daemon!(daemon, library::get_folders)))
.route("/api/library/folders", post(with_daemon!(daemon, library::add_folder, json)))
.route("/api/library/folders", delete(with_daemon!(daemon, library::remove_folder, json)))
.route("/api/library/scan", post(with_daemon!(daemon, library::start_scan)))
// Integrations
.route("/api/integrations/listenbrainz", get(with_daemon!(daemon, integrations::get_listenbrainz_status)))
.route("/api/integrations/listenbrainz/connect", post(with_daemon!(daemon, integrations::connect_listenbrainz, json)))
+131
View File
@@ -0,0 +1,131 @@
//! Interactive Qobuz login via system browser OAuth.
//!
//! Same flow as the desktop app's v2_start_system_browser_oauth:
//! 1. Extract bundle tokens (app_id, secrets, private_key)
//! 2. Start local HTTP server on random port
//! 3. Open system browser to Qobuz OAuth URL
//! 4. Capture authorization code from redirect
//! 5. Exchange code for session token
//! 6. Save token to system keyring
use qbz_qobuz::QobuzClient;
const OAUTH_TIMEOUT_SECS: u64 = 120;
pub async fn interactive_login() -> Result<(), String> {
println!("Initializing Qobuz client...");
// Create client and extract bundle tokens
let client = QobuzClient::new().map_err(|e| format!("Client error: {}", e))?;
client.init().await.map_err(|e| format!("Bundle extraction failed: {}", e))?;
let app_id = client.app_id().await.map_err(|e| format!("No app_id: {}", e))?;
// Bind to random available port
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.map_err(|e| format!("Failed to bind listener: {}", e))?;
let port = listener.local_addr().map_err(|e| e.to_string())?.port();
let redirect_url = format!("http://localhost:{}", port);
let oauth_url = format!(
"https://www.qobuz.com/signin/oauth?ext_app_id={}&redirect_url={}",
app_id,
urlencoding::encode(&redirect_url),
);
// Channel for the auth code
let (tx, mut rx) = tokio::sync::mpsc::channel::<String>(1);
// Local HTTP handler
let handler = axum::Router::new().route(
"/",
axum::routing::get(move |axum::extract::Query(params): axum::extract::Query<std::collections::HashMap<String, String>>| {
let tx = tx.clone();
async move {
if let Some(code) = params.get("code_autorisation").or_else(|| params.get("code")) {
let _ = tx.send(code.clone()).await;
axum::response::Html(
"<html><body style=\"font-family:system-ui;text-align:center;padding:60px\">\
<h2>Login successful!</h2>\
<p>You can close this tab and return to the terminal.</p>\
</body></html>"
)
} else {
axum::response::Html(
"<html><body style=\"font-family:system-ui;text-align:center;padding:60px\">\
<h2>Login failed</h2>\
<p>No authorization code received.</p>\
</body></html>"
)
}
}
}),
);
let server_handle = tokio::spawn(async move {
axum::serve(listener, handler).await.ok();
});
// Open system browser
println!("\nOpening browser for Qobuz login...");
println!("If the browser doesn't open, visit:\n {}\n", oauth_url);
if let Err(e) = open::that(&oauth_url) {
eprintln!("Failed to open browser: {}", e);
eprintln!("Please open this URL manually:\n {}\n", oauth_url);
}
println!("Waiting for login ({}s timeout)...", OAUTH_TIMEOUT_SECS);
// Wait for code
let code = tokio::time::timeout(
std::time::Duration::from_secs(OAUTH_TIMEOUT_SECS),
rx.recv(),
)
.await;
server_handle.abort();
let code = match code {
Ok(Some(c)) => c,
Ok(None) => return Err("Login cancelled".to_string()),
Err(_) => return Err(format!("Login timed out after {}s", OAUTH_TIMEOUT_SECS)),
};
println!("Authorization code received. Exchanging for session...");
// Exchange code for session via QobuzClient
let session = client
.login_with_oauth_code(&code)
.await
.map_err(|e| format!("OAuth exchange failed: {}", e))?;
println!(
"\nLogged in as: {} (user_id: {})",
session.display_name, session.user_id
);
println!("Subscription: {}", session.subscription_label);
// Save token to keyring
let token = session.user_auth_token.clone();
save_token_to_keyring(&token)?;
println!("\nCredentials saved. The daemon will auto-login on next start.");
Ok(())
}
/// Save OAuth token to system keyring (same service/key as desktop app).
fn save_token_to_keyring(token: &str) -> Result<(), String> {
const SERVICE: &str = "qbz-player";
const KEY: &str = "qobuz-oauth-token";
let entry = keyring::Entry::new(SERVICE, KEY)
.map_err(|e| format!("Keyring error: {}", e))?;
entry
.set_password(token)
.map_err(|e| format!("Failed to save to keyring: {}", e))?;
println!("Token saved to system keyring (service: {}, key: {})", SERVICE, KEY);
Ok(())
}
+5 -3
View File
@@ -2,6 +2,7 @@ mod api;
mod config;
mod daemon;
mod adapter;
mod login;
mod resources;
mod session;
@@ -96,9 +97,10 @@ async fn main() {
// Handle subcommands
match cli.command {
Some(Commands::Login) => {
log::info!("Starting interactive login...");
// TODO: Phase 1 — OAuth via system browser
eprintln!("Login not yet implemented. Use qbzd.toml to configure credentials.");
if let Err(e) = login::interactive_login().await {
eprintln!("Login failed: {}", e);
std::process::exit(1);
}
}
Some(Commands::Status) => {
println!("qbzd status: not running (status check requires daemon to be active)");