feat(musicbrainz): add MusicBrainz integration engine (Stage 1)

- Add MusicBrainz client with rate limiting (1 req/sec)
- Add SQLite cache with TTL for recordings, artists, releases
- Add Tauri commands for entity resolution
- Support ISRC, UPC/barcode, and name-based lookups
- Include artist relationship extraction (Stage 3 prep)

cc
This commit is contained in:
vicrodh committed 2026-01-25 06:33:35 -06:00
1 parent 8602493331
commit 55693e66ba
7 files changed
+1627

No files matched your search

+2
View File
@@ -9,6 +9,7 @@ pub mod cache;
pub mod credits;
pub mod favorites;
pub mod lastfm;
pub mod musicbrainz;
pub mod notification;
pub mod playback;
pub mod playback_context;
@@ -26,6 +27,7 @@ pub use cache::*;
pub use credits::*;
pub use favorites::*;
pub use lastfm::*;
pub use musicbrainz::*;
pub use notification::*;
pub use playback::*;
pub use playback_context::*;
+431
View File
@@ -0,0 +1,431 @@
//! MusicBrainz Tauri commands
//!
//! Exposes MusicBrainz entity resolution to the frontend
use tauri::State;
use crate::musicbrainz::{
ArtistRelationships, CacheStats, MatchConfidence, MusicBrainzSharedState, ResolvedArtist,
ResolvedRelease, ResolvedTrack,
};
/// Resolve a track to MusicBrainz by ISRC
#[tauri::command]
pub async fn musicbrainz_resolve_track(
isrc: Option<String>,
title: String,
artist: String,
state: State<'_, MusicBrainzSharedState>,
) -> Result<ResolvedTrack, String> {
if !state.client.is_enabled().await {
return Ok(ResolvedTrack::empty());
}
// Check cache first (short lock)
if let Some(ref isrc_val) = isrc {
let cached = {
let cache = state.cache.lock().await;
cache.get_recording(isrc_val).ok().flatten()
};
if let Some(cached) = cached {
log::debug!("MusicBrainz cache hit for ISRC: {}", isrc_val);
return Ok(cached);
}
}
// Try ISRC lookup
if let Some(ref isrc_val) = isrc {
match state.client.search_recording_by_isrc(isrc_val).await {
Ok(response) => {
if let Some(recording) = response.recordings.first() {
let resolved = recording_to_resolved(recording);
// Cache the result (short lock)
{
let cache = state.cache.lock().await;
let _ = cache.set_recording(isrc_val, &resolved);
}
return Ok(resolved);
}
}
Err(e) => {
log::warn!("MusicBrainz ISRC lookup failed: {}", e);
}
}
}
// Fallback to title+artist search
match state.client.search_recording(&title, &artist).await {
Ok(response) => {
if let Some(recording) = response
.recordings
.iter()
.find(|r| r.score.unwrap_or(0) >= 80)
{
let resolved = recording_to_resolved(recording);
// Cache by ISRC if available
if let Some(ref isrc_val) = isrc {
let cache = state.cache.lock().await;
let _ = cache.set_recording(isrc_val, &resolved);
}
return Ok(resolved);
}
}
Err(e) => {
log::warn!("MusicBrainz recording search failed: {}", e);
}
}
// Cache negative result
if let Some(ref isrc_val) = isrc {
let empty = ResolvedTrack::empty();
let cache = state.cache.lock().await;
let _ = cache.set_recording(isrc_val, &empty);
}
Ok(ResolvedTrack::empty())
}
/// Resolve an artist to MusicBrainz by name
#[tauri::command]
pub async fn musicbrainz_resolve_artist(
name: String,
state: State<'_, MusicBrainzSharedState>,
) -> Result<ResolvedArtist, String> {
if !state.client.is_enabled().await {
return Ok(ResolvedArtist::empty());
}
// Check cache first
let cached = {
let cache = state.cache.lock().await;
cache.get_artist(&name).ok().flatten()
};
if let Some(cached) = cached {
log::debug!("MusicBrainz cache hit for artist: {}", name);
return Ok(cached);
}
match state.client.search_artist(&name).await {
Ok(response) => {
if let Some(artist) = response
.artists
.iter()
.find(|a| a.score.unwrap_or(0) >= 90)
{
let resolved = artist_to_resolved(artist);
// Cache the result
{
let cache = state.cache.lock().await;
let _ = cache.set_artist(&name, &resolved);
}
return Ok(resolved);
}
}
Err(e) => {
log::warn!("MusicBrainz artist search failed: {}", e);
}
}
// Cache negative result
let empty = ResolvedArtist::empty();
{
let cache = state.cache.lock().await;
let _ = cache.set_artist(&name, &empty);
}
Ok(empty)
}
/// Resolve a release to MusicBrainz by UPC/barcode
#[tauri::command]
pub async fn musicbrainz_resolve_release(
upc: Option<String>,
title: String,
artist: String,
state: State<'_, MusicBrainzSharedState>,
) -> Result<ResolvedRelease, String> {
if !state.client.is_enabled().await {
return Ok(ResolvedRelease::empty());
}
// Check cache first
if let Some(ref upc_val) = upc {
let cached = {
let cache = state.cache.lock().await;
cache.get_release(upc_val).ok().flatten()
};
if let Some(cached) = cached {
log::debug!("MusicBrainz cache hit for UPC: {}", upc_val);
return Ok(cached);
}
}
// Try barcode lookup
if let Some(ref upc_val) = upc {
match state.client.search_release_by_barcode(upc_val).await {
Ok(response) => {
if let Some(release) = response.releases.first() {
let resolved = release_to_resolved(release);
// Cache the result
{
let cache = state.cache.lock().await;
let _ = cache.set_release(upc_val, &resolved);
}
return Ok(resolved);
}
}
Err(e) => {
log::warn!("MusicBrainz barcode lookup failed: {}", e);
}
}
}
// Fallback to title+artist search
match state.client.search_release(&title, &artist).await {
Ok(response) => {
if let Some(release) = response
.releases
.iter()
.find(|r| r.score.unwrap_or(0) >= 80)
{
let resolved = release_to_resolved(release);
// Cache by UPC if available
if let Some(ref upc_val) = upc {
let cache = state.cache.lock().await;
let _ = cache.set_release(upc_val, &resolved);
}
return Ok(resolved);
}
}
Err(e) => {
log::warn!("MusicBrainz release search failed: {}", e);
}
}
// Cache negative result
if let Some(ref upc_val) = upc {
let empty = ResolvedRelease::empty();
let cache = state.cache.lock().await;
let _ = cache.set_release(upc_val, &empty);
}
Ok(ResolvedRelease::empty())
}
/// Get artist relationships by MBID (for Stage 3)
#[tauri::command]
pub async fn musicbrainz_get_artist_relationships(
mbid: String,
state: State<'_, MusicBrainzSharedState>,
) -> Result<ArtistRelationships, String> {
if !state.client.is_enabled().await {
return Ok(ArtistRelationships::empty());
}
// Check cache first
let cached = {
let cache = state.cache.lock().await;
cache.get_artist_relations(&mbid).ok().flatten()
};
if let Some(cached) = cached {
log::debug!("MusicBrainz cache hit for artist relations: {}", mbid);
return Ok(cached);
}
match state.client.get_artist_with_relations(&mbid).await {
Ok(response) => {
let relations = extract_relationships(&response);
// Cache the result
{
let cache = state.cache.lock().await;
let _ = cache.set_artist_relations(&mbid, &relations);
}
Ok(relations)
}
Err(e) => {
log::warn!("MusicBrainz artist relations lookup failed: {}", e);
// Cache negative result
let empty = ArtistRelationships::empty();
{
let cache = state.cache.lock().await;
let _ = cache.set_artist_relations(&mbid, &empty);
}
Ok(empty)
}
}
}
/// Check if MusicBrainz integration is enabled
#[tauri::command]
pub async fn musicbrainz_is_enabled(
state: State<'_, MusicBrainzSharedState>,
) -> Result<bool, String> {
Ok(state.client.is_enabled().await)
}
/// Enable or disable MusicBrainz integration
#[tauri::command]
pub async fn musicbrainz_set_enabled(
enabled: bool,
state: State<'_, MusicBrainzSharedState>,
) -> Result<(), String> {
state.client.set_enabled(enabled).await;
log::info!(
"MusicBrainz integration {}",
if enabled { "enabled" } else { "disabled" }
);
Ok(())
}
/// Get MusicBrainz cache statistics
#[tauri::command]
pub async fn musicbrainz_get_cache_stats(
state: State<'_, MusicBrainzSharedState>,
) -> Result<CacheStats, String> {
let cache = state.cache.lock().await;
cache.get_stats()
}
/// Clear MusicBrainz cache
#[tauri::command]
pub async fn musicbrainz_clear_cache(
state: State<'_, MusicBrainzSharedState>,
) -> Result<(), String> {
let cache = state.cache.lock().await;
cache.clear_all()
}
/// Cleanup expired cache entries
#[tauri::command]
pub async fn musicbrainz_cleanup_cache(
state: State<'_, MusicBrainzSharedState>,
) -> Result<usize, String> {
let cache = state.cache.lock().await;
cache.cleanup_expired()
}
// ============ Helper functions ============
use crate::musicbrainz::models::{
ArtistFullResponse, ArtistResult, RecordingResult, RelatedArtist, ReleaseResult, Period,
};
fn recording_to_resolved(recording: &RecordingResult) -> ResolvedTrack {
let artist_credit = recording.artist_credit.as_ref().map(|credits| {
credits
.iter()
.map(|c| {
format!(
"{}{}",
c.name.as_deref().unwrap_or(&c.artist.name),
c.joinphrase.as_deref().unwrap_or("")
)
})
.collect::<Vec<_>>()
.join("")
});
let artist_mbids = recording
.artist_credit
.as_ref()
.map(|credits| credits.iter().map(|c| c.artist.id.clone()).collect());
let (release_mbid, release_title) = recording
.releases
.as_ref()
.and_then(|releases| releases.first())
.map(|r| (Some(r.id.clone()), r.title.clone()))
.unwrap_or((None, None));
ResolvedTrack {
mbid: Some(recording.id.clone()),
title: recording.title.clone(),
artist_credit,
artist_mbids,
release_mbid,
release_title,
confidence: MatchConfidence::from_score(recording.score),
}
}
fn artist_to_resolved(artist: &ArtistResult) -> ResolvedArtist {
use crate::musicbrainz::ArtistType;
ResolvedArtist {
mbid: Some(artist.id.clone()),
name: Some(artist.name.clone()),
sort_name: artist.sort_name.clone(),
artist_type: Some(ArtistType::from(artist.artist_type.as_deref())),
country: artist.country.clone(),
disambiguation: artist.disambiguation.clone(),
confidence: MatchConfidence::from_score(artist.score),
}
}
fn release_to_resolved(release: &ReleaseResult) -> ResolvedRelease {
let (label, catalog_number) = release
.label_info
.as_ref()
.and_then(|info| info.first())
.map(|li| (li.label.as_ref().map(|l| l.name.clone()), li.catalog_number.clone()))
.unwrap_or((None, None));
ResolvedRelease {
mbid: Some(release.id.clone()),
title: Some(release.title.clone()),
release_group_mbid: release.release_group.as_ref().map(|rg| rg.id.clone()),
label,
catalog_number,
country: release.country.clone(),
date: release.date.clone(),
confidence: MatchConfidence::from_score(release.score),
}
}
fn extract_relationships(artist: &ArtistFullResponse) -> ArtistRelationships {
let mut members = Vec::new();
let mut past_members = Vec::new();
let mut groups = Vec::new();
let mut collaborators = Vec::new();
if let Some(relations) = &artist.relations {
for relation in relations {
let Some(related_artist) = &relation.artist else {
continue;
};
let related = RelatedArtist {
mbid: related_artist.id.clone(),
name: related_artist.name.clone(),
role: relation.attributes.as_ref().and_then(|a| a.first().cloned()),
period: Some(Period {
begin: relation.begin.clone(),
end: relation.end.clone(),
}),
};
match relation.relation_type.as_str() {
"member of band" => {
if relation.direction.as_deref() == Some("backward") {
groups.push(related);
} else if relation.ended == Some(true) {
past_members.push(related);
} else {
members.push(related);
}
}
"collaboration" => {
collaborators.push(related);
}
_ => {}
}
}
}
ArtistRelationships {
members,
past_members,
groups,
collaborators,
}
}
+15
View File
@@ -17,6 +17,7 @@ pub mod lastfm;
pub mod library;
pub mod lyrics;
pub mod media_controls;
pub mod musicbrainz;
pub mod network;
pub mod offline;
pub mod playback_context;
@@ -192,6 +193,9 @@ pub fn run() {
// Initialize subscription validity tracking (for offline download compliance)
let subscription_state = config::create_subscription_state()
.expect("Failed to initialize subscription state");
// Initialize MusicBrainz integration state
let musicbrainz_state = musicbrainz::MusicBrainzSharedState::new()
.expect("Failed to initialize MusicBrainz state");
// Read saved audio device and settings for player initialization
let (saved_device, audio_settings) = audio_settings_state
@@ -401,6 +405,7 @@ pub fn run() {
.manage(playback_prefs_state)
.manage(favorites_prefs_state)
.manage(tray_settings_state)
.manage(musicbrainz_state)
.invoke_handler(tauri::generate_handler![
// Auth commands
commands::init_client,
@@ -740,6 +745,16 @@ pub fn run() {
config::tray_settings::set_enable_tray,
config::tray_settings::set_minimize_to_tray,
config::tray_settings::set_close_to_tray,
// MusicBrainz integration commands
commands::musicbrainz_resolve_track,
commands::musicbrainz_resolve_artist,
commands::musicbrainz_resolve_release,
commands::musicbrainz_get_artist_relationships,
commands::musicbrainz_is_enabled,
commands::musicbrainz_set_enabled,
commands::musicbrainz_get_cache_stats,
commands::musicbrainz_clear_cache,
commands::musicbrainz_cleanup_cache,
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
+391
View File
@@ -0,0 +1,391 @@
//! MusicBrainz cache layer
//!
//! SQLite-based cache for MusicBrainz lookups with TTL expiration
use rusqlite::{params, Connection, OptionalExtension};
use std::path::Path;
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
use tokio::sync::Mutex;
use super::models::*;
/// TTL for recording cache (30 days)
const RECORDING_TTL_SECS: i64 = 30 * 24 * 60 * 60;
/// TTL for artist cache (7 days)
const ARTIST_TTL_SECS: i64 = 7 * 24 * 60 * 60;
/// TTL for release cache (30 days)
const RELEASE_TTL_SECS: i64 = 30 * 24 * 60 * 60;
/// TTL for artist relationships cache (7 days)
const RELATIONS_TTL_SECS: i64 = 7 * 24 * 60 * 60;
/// MusicBrainz cache state shared across commands
pub struct MusicBrainzCacheState {
pub cache: Arc<Mutex<MusicBrainzCache>>,
}
impl MusicBrainzCacheState {
pub fn new() -> Result<Self, String> {
let data_dir = dirs::data_dir()
.ok_or("Could not determine data directory")?
.join("qbz")
.join("cache");
std::fs::create_dir_all(&data_dir)
.map_err(|e| format!("Failed to create cache directory: {}", e))?;
let db_path = data_dir.join("musicbrainz_cache.db");
let cache = MusicBrainzCache::new(&db_path)?;
log::info!("MusicBrainz cache initialized at {:?}", db_path);
Ok(Self {
cache: Arc::new(Mutex::new(cache)),
})
}
}
/// MusicBrainz SQLite cache
pub struct MusicBrainzCache {
conn: Connection,
}
impl MusicBrainzCache {
pub fn new(path: &Path) -> Result<Self, String> {
let conn = Connection::open(path)
.map_err(|e| format!("Failed to open MusicBrainz cache: {}", e))?;
// Enable WAL mode for better concurrency
conn.execute_batch("PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;")
.map_err(|e| format!("Failed to set pragmas: {}", e))?;
let cache = Self { conn };
cache.init()?;
Ok(cache)
}
fn init(&self) -> Result<(), String> {
self.conn
.execute_batch(
r#"
-- Recordings indexed by ISRC
CREATE TABLE IF NOT EXISTS mb_recordings (
isrc TEXT PRIMARY KEY,
data TEXT NOT NULL,
fetched_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_mb_recordings_fetched ON mb_recordings(fetched_at);
-- Artists indexed by normalized name
CREATE TABLE IF NOT EXISTS mb_artists (
name_normalized TEXT PRIMARY KEY,
data TEXT NOT NULL,
fetched_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_mb_artists_fetched ON mb_artists(fetched_at);
-- Releases indexed by UPC/barcode
CREATE TABLE IF NOT EXISTS mb_releases (
barcode TEXT PRIMARY KEY,
data TEXT NOT NULL,
fetched_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_mb_releases_fetched ON mb_releases(fetched_at);
-- Artist relationships indexed by MBID
CREATE TABLE IF NOT EXISTS mb_artist_relations (
mbid TEXT PRIMARY KEY,
data TEXT NOT NULL,
fetched_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_mb_relations_fetched ON mb_artist_relations(fetched_at);
"#,
)
.map_err(|e| format!("Failed to initialize MusicBrainz cache: {}", e))?;
Ok(())
}
fn current_timestamp() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0)
}
/// Normalize artist name for consistent cache keys
pub fn normalize_name(name: &str) -> String {
name.to_lowercase()
.trim()
.replace(['\'', '"', '.', ','], "")
.split_whitespace()
.collect::<Vec<_>>()
.join(" ")
}
// ============ Recording Cache ============
/// Get cached recording by ISRC
pub fn get_recording(&self, isrc: &str) -> Result<Option<ResolvedTrack>, String> {
let min_fetched_at = Self::current_timestamp() - RECORDING_TTL_SECS;
let result: Option<String> = self
.conn
.query_row(
"SELECT data FROM mb_recordings WHERE isrc = ? AND fetched_at > ?",
params![isrc, min_fetched_at],
|row| row.get(0),
)
.optional()
.map_err(|e| format!("Failed to query recording cache: {}", e))?;
if let Some(data) = result {
serde_json::from_str(&data)
.map(Some)
.map_err(|e| format!("Failed to parse cached recording: {}", e))
} else {
Ok(None)
}
}
/// Cache a resolved recording
pub fn set_recording(&self, isrc: &str, data: &ResolvedTrack) -> Result<(), String> {
let fetched_at = Self::current_timestamp();
let json = serde_json::to_string(data)
.map_err(|e| format!("Failed to serialize recording: {}", e))?;
self.conn
.execute(
"INSERT OR REPLACE INTO mb_recordings (isrc, data, fetched_at) VALUES (?, ?, ?)",
params![isrc, json, fetched_at],
)
.map_err(|e| format!("Failed to cache recording: {}", e))?;
Ok(())
}
// ============ Artist Cache ============
/// Get cached artist by name
pub fn get_artist(&self, name: &str) -> Result<Option<ResolvedArtist>, String> {
let normalized = Self::normalize_name(name);
let min_fetched_at = Self::current_timestamp() - ARTIST_TTL_SECS;
let result: Option<String> = self
.conn
.query_row(
"SELECT data FROM mb_artists WHERE name_normalized = ? AND fetched_at > ?",
params![normalized, min_fetched_at],
|row| row.get(0),
)
.optional()
.map_err(|e| format!("Failed to query artist cache: {}", e))?;
if let Some(data) = result {
serde_json::from_str(&data)
.map(Some)
.map_err(|e| format!("Failed to parse cached artist: {}", e))
} else {
Ok(None)
}
}
/// Cache a resolved artist
pub fn set_artist(&self, name: &str, data: &ResolvedArtist) -> Result<(), String> {
let normalized = Self::normalize_name(name);
let fetched_at = Self::current_timestamp();
let json = serde_json::to_string(data)
.map_err(|e| format!("Failed to serialize artist: {}", e))?;
self.conn
.execute(
"INSERT OR REPLACE INTO mb_artists (name_normalized, data, fetched_at) VALUES (?, ?, ?)",
params![normalized, json, fetched_at],
)
.map_err(|e| format!("Failed to cache artist: {}", e))?;
Ok(())
}
// ============ Release Cache ============
/// Get cached release by barcode
pub fn get_release(&self, barcode: &str) -> Result<Option<ResolvedRelease>, String> {
let min_fetched_at = Self::current_timestamp() - RELEASE_TTL_SECS;
let result: Option<String> = self
.conn
.query_row(
"SELECT data FROM mb_releases WHERE barcode = ? AND fetched_at > ?",
params![barcode, min_fetched_at],
|row| row.get(0),
)
.optional()
.map_err(|e| format!("Failed to query release cache: {}", e))?;
if let Some(data) = result {
serde_json::from_str(&data)
.map(Some)
.map_err(|e| format!("Failed to parse cached release: {}", e))
} else {
Ok(None)
}
}
/// Cache a resolved release
pub fn set_release(&self, barcode: &str, data: &ResolvedRelease) -> Result<(), String> {
let fetched_at = Self::current_timestamp();
let json = serde_json::to_string(data)
.map_err(|e| format!("Failed to serialize release: {}", e))?;
self.conn
.execute(
"INSERT OR REPLACE INTO mb_releases (barcode, data, fetched_at) VALUES (?, ?, ?)",
params![barcode, json, fetched_at],
)
.map_err(|e| format!("Failed to cache release: {}", e))?;
Ok(())
}
// ============ Artist Relations Cache ============
/// Get cached artist relationships by MBID
pub fn get_artist_relations(&self, mbid: &str) -> Result<Option<ArtistRelationships>, String> {
let min_fetched_at = Self::current_timestamp() - RELATIONS_TTL_SECS;
let result: Option<String> = self
.conn
.query_row(
"SELECT data FROM mb_artist_relations WHERE mbid = ? AND fetched_at > ?",
params![mbid, min_fetched_at],
|row| row.get(0),
)
.optional()
.map_err(|e| format!("Failed to query relations cache: {}", e))?;
if let Some(data) = result {
serde_json::from_str(&data)
.map(Some)
.map_err(|e| format!("Failed to parse cached relations: {}", e))
} else {
Ok(None)
}
}
/// Cache artist relationships
pub fn set_artist_relations(&self, mbid: &str, data: &ArtistRelationships) -> Result<(), String> {
let fetched_at = Self::current_timestamp();
let json = serde_json::to_string(data)
.map_err(|e| format!("Failed to serialize relations: {}", e))?;
self.conn
.execute(
"INSERT OR REPLACE INTO mb_artist_relations (mbid, data, fetched_at) VALUES (?, ?, ?)",
params![mbid, json, fetched_at],
)
.map_err(|e| format!("Failed to cache relations: {}", e))?;
Ok(())
}
// ============ Maintenance ============
/// Clear expired entries from all tables
pub fn cleanup_expired(&self) -> Result<usize, String> {
let now = Self::current_timestamp();
let mut total_deleted = 0;
total_deleted += self
.conn
.execute(
"DELETE FROM mb_recordings WHERE fetched_at <= ?",
params![now - RECORDING_TTL_SECS],
)
.map_err(|e| format!("Failed to cleanup recordings: {}", e))?;
total_deleted += self
.conn
.execute(
"DELETE FROM mb_artists WHERE fetched_at <= ?",
params![now - ARTIST_TTL_SECS],
)
.map_err(|e| format!("Failed to cleanup artists: {}", e))?;
total_deleted += self
.conn
.execute(
"DELETE FROM mb_releases WHERE fetched_at <= ?",
params![now - RELEASE_TTL_SECS],
)
.map_err(|e| format!("Failed to cleanup releases: {}", e))?;
total_deleted += self
.conn
.execute(
"DELETE FROM mb_artist_relations WHERE fetched_at <= ?",
params![now - RELATIONS_TTL_SECS],
)
.map_err(|e| format!("Failed to cleanup relations: {}", e))?;
if total_deleted > 0 {
log::info!("MusicBrainz cache cleanup: removed {} expired entries", total_deleted);
}
Ok(total_deleted)
}
/// Clear all cached data
pub fn clear_all(&self) -> Result<(), String> {
self.conn
.execute_batch(
r#"
DELETE FROM mb_recordings;
DELETE FROM mb_artists;
DELETE FROM mb_releases;
DELETE FROM mb_artist_relations;
"#,
)
.map_err(|e| format!("Failed to clear MusicBrainz cache: {}", e))?;
log::info!("MusicBrainz cache cleared");
Ok(())
}
/// Get cache statistics
pub fn get_stats(&self) -> Result<CacheStats, String> {
let recordings: i64 = self
.conn
.query_row("SELECT COUNT(*) FROM mb_recordings", [], |row| row.get(0))
.unwrap_or(0);
let artists: i64 = self
.conn
.query_row("SELECT COUNT(*) FROM mb_artists", [], |row| row.get(0))
.unwrap_or(0);
let releases: i64 = self
.conn
.query_row("SELECT COUNT(*) FROM mb_releases", [], |row| row.get(0))
.unwrap_or(0);
let relations: i64 = self
.conn
.query_row("SELECT COUNT(*) FROM mb_artist_relations", [], |row| row.get(0))
.unwrap_or(0);
Ok(CacheStats {
recordings: recordings as u64,
artists: artists as u64,
releases: releases as u64,
relations: relations as u64,
})
}
}
/// Cache statistics
#[derive(Debug, Clone, serde::Serialize)]
pub struct CacheStats {
pub recordings: u64,
pub artists: u64,
pub releases: u64,
pub relations: u64,
}
+378
View File
@@ -0,0 +1,378 @@
//! MusicBrainz API client
//!
//! HTTP client with rate limiting and proper User-Agent handling
//! Uses Cloudflare Workers proxy for consistent rate limiting
use reqwest::Client;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::Mutex;
use super::models::*;
/// Proxy URL for MusicBrainz requests
const MUSICBRAINZ_PROXY_URL: &str = "https://qbz-api-proxy.blitzkriegfc.workers.dev/musicbrainz";
/// Direct MusicBrainz API URL (fallback)
const MUSICBRAINZ_API_URL: &str = "https://musicbrainz.org/ws/2";
/// Rate limiter for MusicBrainz API (1 request per second)
pub struct RateLimiter {
last_request: Mutex<Instant>,
min_interval: Duration,
}
impl RateLimiter {
pub fn new() -> Self {
Self {
// Start in the past so first request doesn't wait
last_request: Mutex::new(Instant::now() - Duration::from_secs(2)),
min_interval: Duration::from_millis(1100), // Slightly over 1 second for safety
}
}
pub async fn wait(&self) {
let mut last = self.last_request.lock().await;
let elapsed = last.elapsed();
if elapsed < self.min_interval {
tokio::time::sleep(self.min_interval - elapsed).await;
}
*last = Instant::now();
}
}
impl Default for RateLimiter {
fn default() -> Self {
Self::new()
}
}
/// MusicBrainz API client configuration
#[derive(Debug, Clone)]
pub struct MusicBrainzConfig {
/// Whether MusicBrainz integration is enabled
pub enabled: bool,
/// Use proxy instead of direct API
pub use_proxy: bool,
}
impl Default for MusicBrainzConfig {
fn default() -> Self {
Self {
enabled: true,
use_proxy: true,
}
}
}
/// MusicBrainz API client
pub struct MusicBrainzClient {
client: Client,
rate_limiter: Arc<RateLimiter>,
config: Arc<Mutex<MusicBrainzConfig>>,
}
impl Default for MusicBrainzClient {
fn default() -> Self {
Self::new()
}
}
impl MusicBrainzClient {
pub fn new() -> Self {
Self::with_config(MusicBrainzConfig::default())
}
pub fn with_config(config: MusicBrainzConfig) -> Self {
let version = env!("CARGO_PKG_VERSION");
let user_agent = format!(
"QBZ/{} (https://github.com/vicrodh/qbz; qbz@vicrodh.dev)",
version
);
let client = Client::builder()
.user_agent(&user_agent)
.timeout(Duration::from_secs(10))
.build()
.unwrap_or_else(|_| Client::new());
Self {
client,
rate_limiter: Arc::new(RateLimiter::new()),
config: Arc::new(Mutex::new(config)),
}
}
/// Check if MusicBrainz integration is enabled
pub async fn is_enabled(&self) -> bool {
self.config.lock().await.enabled
}
/// Enable or disable MusicBrainz integration
pub async fn set_enabled(&self, enabled: bool) {
self.config.lock().await.enabled = enabled;
}
/// Get the base URL based on configuration
async fn base_url(&self) -> &'static str {
if self.config.lock().await.use_proxy {
MUSICBRAINZ_PROXY_URL
} else {
MUSICBRAINZ_API_URL
}
}
/// Search recordings by ISRC
pub async fn search_recording_by_isrc(&self, isrc: &str) -> Result<RecordingSearchResponse, String> {
if !self.is_enabled().await {
return Err("MusicBrainz integration is disabled".to_string());
}
self.rate_limiter.wait().await;
let base_url = self.base_url().await;
let url = format!(
"{}/recording?query=isrc:{}&fmt=json&limit=5",
base_url, isrc
);
log::debug!("MusicBrainz recording search by ISRC: {}", isrc);
let response = self
.client
.get(&url)
.send()
.await
.map_err(|e| format!("MusicBrainz request failed: {}", e))?;
if !response.status().is_success() {
let status = response.status();
let text = response.text().await.unwrap_or_default();
return Err(format!("MusicBrainz API error {}: {}", status, text));
}
response
.json::<RecordingSearchResponse>()
.await
.map_err(|e| format!("Failed to parse MusicBrainz response: {}", e))
}
/// Search recordings by title and artist
pub async fn search_recording(
&self,
title: &str,
artist: &str,
) -> Result<RecordingSearchResponse, String> {
if !self.is_enabled().await {
return Err("MusicBrainz integration is disabled".to_string());
}
self.rate_limiter.wait().await;
let base_url = self.base_url().await;
let query = format!(
"recording:\"{}\" AND artist:\"{}\"",
Self::escape_query(title),
Self::escape_query(artist)
);
let url = format!(
"{}/recording?query={}&fmt=json&limit=5",
base_url,
urlencoding::encode(&query)
);
log::debug!("MusicBrainz recording search: {} - {}", artist, title);
let response = self
.client
.get(&url)
.send()
.await
.map_err(|e| format!("MusicBrainz request failed: {}", e))?;
if !response.status().is_success() {
let status = response.status();
let text = response.text().await.unwrap_or_default();
return Err(format!("MusicBrainz API error {}: {}", status, text));
}
response
.json::<RecordingSearchResponse>()
.await
.map_err(|e| format!("Failed to parse MusicBrainz response: {}", e))
}
/// Search artists by name
pub async fn search_artist(&self, name: &str) -> Result<ArtistSearchResponse, String> {
if !self.is_enabled().await {
return Err("MusicBrainz integration is disabled".to_string());
}
self.rate_limiter.wait().await;
let base_url = self.base_url().await;
let query = format!("artist:\"{}\"", Self::escape_query(name));
let url = format!(
"{}/artist?query={}&fmt=json&limit=5",
base_url,
urlencoding::encode(&query)
);
log::debug!("MusicBrainz artist search: {}", name);
let response = self
.client
.get(&url)
.send()
.await
.map_err(|e| format!("MusicBrainz request failed: {}", e))?;
if !response.status().is_success() {
let status = response.status();
let text = response.text().await.unwrap_or_default();
return Err(format!("MusicBrainz API error {}: {}", status, text));
}
response
.json::<ArtistSearchResponse>()
.await
.map_err(|e| format!("Failed to parse MusicBrainz response: {}", e))
}
/// Get artist details with relationships
pub async fn get_artist_with_relations(&self, mbid: &str) -> Result<ArtistFullResponse, String> {
if !self.is_enabled().await {
return Err("MusicBrainz integration is disabled".to_string());
}
self.rate_limiter.wait().await;
let base_url = self.base_url().await;
let url = format!(
"{}/artist/{}?inc=artist-rels&fmt=json",
base_url, mbid
);
log::debug!("MusicBrainz artist lookup with relations: {}", mbid);
let response = self
.client
.get(&url)
.send()
.await
.map_err(|e| format!("MusicBrainz request failed: {}", e))?;
if !response.status().is_success() {
let status = response.status();
let text = response.text().await.unwrap_or_default();
return Err(format!("MusicBrainz API error {}: {}", status, text));
}
response
.json::<ArtistFullResponse>()
.await
.map_err(|e| format!("Failed to parse MusicBrainz response: {}", e))
}
/// Search releases by barcode (UPC/EAN)
pub async fn search_release_by_barcode(&self, barcode: &str) -> Result<ReleaseSearchResponse, String> {
if !self.is_enabled().await {
return Err("MusicBrainz integration is disabled".to_string());
}
self.rate_limiter.wait().await;
let base_url = self.base_url().await;
let url = format!(
"{}/release?query=barcode:{}&fmt=json&limit=5",
base_url, barcode
);
log::debug!("MusicBrainz release search by barcode: {}", barcode);
let response = self
.client
.get(&url)
.send()
.await
.map_err(|e| format!("MusicBrainz request failed: {}", e))?;
if !response.status().is_success() {
let status = response.status();
let text = response.text().await.unwrap_or_default();
return Err(format!("MusicBrainz API error {}: {}", status, text));
}
response
.json::<ReleaseSearchResponse>()
.await
.map_err(|e| format!("Failed to parse MusicBrainz response: {}", e))
}
/// Search releases by title and artist
pub async fn search_release(
&self,
title: &str,
artist: &str,
) -> Result<ReleaseSearchResponse, String> {
if !self.is_enabled().await {
return Err("MusicBrainz integration is disabled".to_string());
}
self.rate_limiter.wait().await;
let base_url = self.base_url().await;
let query = format!(
"release:\"{}\" AND artist:\"{}\"",
Self::escape_query(title),
Self::escape_query(artist)
);
let url = format!(
"{}/release?query={}&fmt=json&limit=5",
base_url,
urlencoding::encode(&query)
);
log::debug!("MusicBrainz release search: {} - {}", artist, title);
let response = self
.client
.get(&url)
.send()
.await
.map_err(|e| format!("MusicBrainz request failed: {}", e))?;
if !response.status().is_success() {
let status = response.status();
let text = response.text().await.unwrap_or_default();
return Err(format!("MusicBrainz API error {}: {}", status, text));
}
response
.json::<ReleaseSearchResponse>()
.await
.map_err(|e| format!("Failed to parse MusicBrainz response: {}", e))
}
/// Escape special characters in Lucene queries
fn escape_query(s: &str) -> String {
s.replace('\\', "\\\\")
.replace('"', "\\\"")
.replace(':', "\\:")
.replace('(', "\\(")
.replace(')', "\\)")
.replace('[', "\\[")
.replace(']', "\\]")
.replace('{', "\\{")
.replace('}', "\\}")
.replace('^', "\\^")
.replace('~', "\\~")
.replace('*', "\\*")
.replace('?', "\\?")
.replace('!', "\\!")
.replace('+', "\\+")
.replace('-', "\\-")
.replace('&', "\\&")
.replace('|', "\\|")
}
}
+45
View File
@@ -0,0 +1,45 @@
//! MusicBrainz integration module
//!
//! Provides entity resolution and caching for MusicBrainz lookups.
//! This module operates as a background semantic engine - it enriches
//! data without affecting the UI directly (Stage 1).
//!
//! ## Architecture
//!
//! - `client.rs`: HTTP client with rate limiting (1 req/sec)
//! - `models.rs`: API response types and resolved entity types
//! - `cache.rs`: SQLite-based cache with TTL expiration
//!
//! ## Usage
//!
//! The module is accessed via Tauri commands in `commands/musicbrainz.rs`.
pub mod cache;
pub mod client;
pub mod models;
pub use cache::{CacheStats, MusicBrainzCache, MusicBrainzCacheState};
pub use client::{MusicBrainzClient, MusicBrainzConfig};
pub use models::{
ArtistRelationships, ArtistType, MatchConfidence, Period, RelatedArtist, ResolvedArtist,
ResolvedRelease, ResolvedTrack,
};
use std::sync::Arc;
use tokio::sync::Mutex;
/// Shared state wrapper for Tauri
pub struct MusicBrainzSharedState {
pub client: Arc<MusicBrainzClient>,
pub cache: Arc<Mutex<MusicBrainzCache>>,
}
impl MusicBrainzSharedState {
pub fn new() -> Result<Self, String> {
let cache_state = MusicBrainzCacheState::new()?;
Ok(Self {
client: Arc::new(MusicBrainzClient::new()),
cache: cache_state.cache,
})
}
}
+365
View File
@@ -0,0 +1,365 @@
//! MusicBrainz API response models
//!
//! Types for deserializing MusicBrainz JSON responses
use serde::{Deserialize, Serialize};
/// Match confidence levels for MusicBrainz lookups
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum MatchConfidence {
Exact, // ISRC/UPC exact match
High, // Score >= 95
Medium, // Score >= 80
Low, // Score >= 60
None, // No match found
}
impl MatchConfidence {
pub fn from_score(score: Option<i32>) -> Self {
match score {
Some(s) if s >= 100 => Self::Exact,
Some(s) if s >= 95 => Self::High,
Some(s) if s >= 80 => Self::Medium,
Some(s) if s >= 60 => Self::Low,
_ => Self::None,
}
}
}
/// Artist type classification
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ArtistType {
Person,
Group,
Orchestra,
Choir,
Character,
Other,
}
impl Default for ArtistType {
fn default() -> Self {
Self::Other
}
}
impl From<Option<&str>> for ArtistType {
fn from(s: Option<&str>) -> Self {
match s.map(|s| s.to_lowercase()).as_deref() {
Some("person") => Self::Person,
Some("group") => Self::Group,
Some("orchestra") => Self::Orchestra,
Some("choir") => Self::Choir,
Some("character") => Self::Character,
_ => Self::Other,
}
}
}
// ============ API Response Types ============
/// Recording search response
#[derive(Debug, Deserialize)]
pub struct RecordingSearchResponse {
pub created: Option<String>,
pub count: i32,
pub offset: i32,
pub recordings: Vec<RecordingResult>,
}
/// Single recording in search results
#[derive(Debug, Deserialize)]
pub struct RecordingResult {
pub id: String,
pub score: Option<i32>,
pub title: Option<String>,
pub length: Option<i64>,
#[serde(rename = "artist-credit")]
pub artist_credit: Option<Vec<ArtistCredit>>,
pub isrcs: Option<Vec<String>>,
pub releases: Option<Vec<ReleaseRef>>,
}
/// Artist credit entry
#[derive(Debug, Deserialize)]
pub struct ArtistCredit {
pub name: Option<String>,
pub joinphrase: Option<String>,
pub artist: ArtistRef,
}
/// Reference to an artist
#[derive(Debug, Deserialize)]
pub struct ArtistRef {
pub id: String,
pub name: String,
#[serde(rename = "sort-name")]
pub sort_name: Option<String>,
pub disambiguation: Option<String>,
}
/// Reference to a release (album)
#[derive(Debug, Deserialize)]
pub struct ReleaseRef {
pub id: String,
pub title: Option<String>,
pub status: Option<String>,
pub date: Option<String>,
pub country: Option<String>,
#[serde(rename = "release-group")]
pub release_group: Option<ReleaseGroupRef>,
}
/// Reference to a release group
#[derive(Debug, Deserialize)]
pub struct ReleaseGroupRef {
pub id: String,
#[serde(rename = "primary-type")]
pub primary_type: Option<String>,
}
/// Artist search response
#[derive(Debug, Deserialize)]
pub struct ArtistSearchResponse {
pub created: Option<String>,
pub count: i32,
pub offset: i32,
pub artists: Vec<ArtistResult>,
}
/// Single artist in search results
#[derive(Debug, Deserialize)]
pub struct ArtistResult {
pub id: String,
pub score: Option<i32>,
pub name: String,
#[serde(rename = "sort-name")]
pub sort_name: Option<String>,
#[serde(rename = "type")]
pub artist_type: Option<String>,
pub country: Option<String>,
pub disambiguation: Option<String>,
pub aliases: Option<Vec<Alias>>,
#[serde(rename = "life-span")]
pub life_span: Option<LifeSpan>,
}
/// Artist alias
#[derive(Debug, Deserialize)]
pub struct Alias {
pub name: String,
#[serde(rename = "sort-name")]
pub sort_name: Option<String>,
#[serde(rename = "type")]
pub alias_type: Option<String>,
pub locale: Option<String>,
pub primary: Option<bool>,
}
/// Life span for an artist
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct LifeSpan {
pub begin: Option<String>,
pub end: Option<String>,
pub ended: Option<bool>,
}
/// Full artist response (with includes)
#[derive(Debug, Deserialize)]
pub struct ArtistFullResponse {
pub id: String,
pub name: String,
#[serde(rename = "sort-name")]
pub sort_name: Option<String>,
#[serde(rename = "type")]
pub artist_type: Option<String>,
pub country: Option<String>,
pub disambiguation: Option<String>,
#[serde(rename = "life-span")]
pub life_span: Option<LifeSpan>,
pub relations: Option<Vec<Relation>>,
}
/// Relation between entities
#[derive(Debug, Deserialize)]
pub struct Relation {
#[serde(rename = "type")]
pub relation_type: String,
#[serde(rename = "type-id")]
pub type_id: Option<String>,
pub direction: Option<String>,
pub begin: Option<String>,
pub end: Option<String>,
pub ended: Option<bool>,
pub attributes: Option<Vec<String>>,
pub artist: Option<ArtistRef>,
}
/// Release search response
#[derive(Debug, Deserialize)]
pub struct ReleaseSearchResponse {
pub created: Option<String>,
pub count: i32,
pub offset: i32,
pub releases: Vec<ReleaseResult>,
}
/// Single release in search results
#[derive(Debug, Deserialize)]
pub struct ReleaseResult {
pub id: String,
pub score: Option<i32>,
pub title: String,
pub status: Option<String>,
pub date: Option<String>,
pub country: Option<String>,
pub barcode: Option<String>,
#[serde(rename = "label-info")]
pub label_info: Option<Vec<LabelInfo>>,
#[serde(rename = "release-group")]
pub release_group: Option<ReleaseGroupRef>,
#[serde(rename = "artist-credit")]
pub artist_credit: Option<Vec<ArtistCredit>>,
}
/// Label information
#[derive(Debug, Deserialize)]
pub struct LabelInfo {
#[serde(rename = "catalog-number")]
pub catalog_number: Option<String>,
pub label: Option<LabelRef>,
}
/// Reference to a label
#[derive(Debug, Deserialize)]
pub struct LabelRef {
pub id: String,
pub name: String,
}
// ============ Resolved Types (Output) ============
/// Resolved track with MusicBrainz data
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResolvedTrack {
pub mbid: Option<String>,
pub title: Option<String>,
pub artist_credit: Option<String>,
pub artist_mbids: Option<Vec<String>>,
pub release_mbid: Option<String>,
pub release_title: Option<String>,
pub confidence: MatchConfidence,
}
impl ResolvedTrack {
pub fn empty() -> Self {
Self {
mbid: None,
title: None,
artist_credit: None,
artist_mbids: None,
release_mbid: None,
release_title: None,
confidence: MatchConfidence::None,
}
}
}
/// Resolved artist with MusicBrainz data
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResolvedArtist {
pub mbid: Option<String>,
pub name: Option<String>,
pub sort_name: Option<String>,
pub artist_type: Option<ArtistType>,
pub country: Option<String>,
pub disambiguation: Option<String>,
pub confidence: MatchConfidence,
}
impl ResolvedArtist {
pub fn empty() -> Self {
Self {
mbid: None,
name: None,
sort_name: None,
artist_type: None,
country: None,
disambiguation: None,
confidence: MatchConfidence::None,
}
}
}
/// Resolved release with MusicBrainz data
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResolvedRelease {
pub mbid: Option<String>,
pub title: Option<String>,
pub release_group_mbid: Option<String>,
pub label: Option<String>,
pub catalog_number: Option<String>,
pub country: Option<String>,
pub date: Option<String>,
pub confidence: MatchConfidence,
}
impl ResolvedRelease {
pub fn empty() -> Self {
Self {
mbid: None,
title: None,
release_group_mbid: None,
label: None,
catalog_number: None,
country: None,
date: None,
confidence: MatchConfidence::None,
}
}
}
/// Related artist (for relationships)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RelatedArtist {
pub mbid: String,
pub name: String,
pub role: Option<String>,
pub period: Option<Period>,
}
/// Time period for a relationship
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Period {
pub begin: Option<String>,
pub end: Option<String>,
}
/// Artist relationships
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ArtistRelationships {
pub members: Vec<RelatedArtist>,
pub past_members: Vec<RelatedArtist>,
pub groups: Vec<RelatedArtist>,
pub collaborators: Vec<RelatedArtist>,
}
impl ArtistRelationships {
pub fn empty() -> Self {
Self {
members: Vec::new(),
past_members: Vec::new(),
groups: Vec::new(),
collaborators: Vec::new(),
}
}
pub fn is_empty(&self) -> bool {
self.members.is_empty()
&& self.past_members.is_empty()
&& self.groups.is_empty()
&& self.collaborators.is_empty()
}
}