Building up a little db of "similar artists"

This commit is contained in:
Connor Johnstone
2026-03-02 22:01:43 -05:00
parent 16e8962be1
commit 4a388c6637
8 changed files with 395 additions and 79 deletions

View File

@@ -1,12 +1,9 @@
use std::collections::HashMap;
use serde::Deserialize;
const BASE_URL: &str = "https://ws.audioscrobbler.com/2.0/";
pub struct LastfmClient {
api_key: String,
artist_cache: HashMap<String, Vec<SimilarArtist>>,
}
pub struct SimilarArtist {
@@ -18,6 +15,7 @@ pub struct SimilarArtist {
// Last.fm returns {"error": N, "message": "..."} on failure
#[derive(Deserialize)]
struct ApiError {
#[allow(dead_code)]
error: u32,
message: String,
}
@@ -44,46 +42,37 @@ struct ArtistEntry {
impl LastfmClient {
pub fn new(api_key: String) -> Self {
Self {
api_key,
artist_cache: HashMap::new(),
}
Self { api_key }
}
pub fn get_similar_artists(
&mut self,
&self,
artist_mbid: &str,
) -> Result<&[SimilarArtist], Box<dyn std::error::Error>> {
if !self.artist_cache.contains_key(artist_mbid) {
let url = format!(
"{}?method=artist.getSimilar&mbid={}&api_key={}&format=json",
BASE_URL, artist_mbid, self.api_key
);
let body: String = ureq::get(&url).call()?.body_mut().read_to_string()?;
) -> Result<Vec<SimilarArtist>, Box<dyn std::error::Error>> {
let url = format!(
"{}?method=artist.getSimilar&mbid={}&api_key={}&format=json",
BASE_URL, artist_mbid, self.api_key
);
let body: String = ureq::get(&url).call()?.body_mut().read_to_string()?;
let artists = if let Ok(err) = serde_json::from_str::<ApiError>(&body) {
eprintln!(" Last.fm: {}", err.message);
Vec::new()
} else {
let resp: SimilarArtistsResponse = serde_json::from_str(&body)?;
resp.similarartists
.artist
.into_iter()
.map(|a| {
let mbid = a.mbid.filter(|s| !s.is_empty());
SimilarArtist {
name: a.name,
mbid,
match_score: a.match_score.parse().unwrap_or(0.0),
}
})
.collect()
};
self.artist_cache.insert(artist_mbid.to_string(), artists);
if let Ok(err) = serde_json::from_str::<ApiError>(&body) {
eprintln!(" Last.fm: {}", err.message);
return Ok(Vec::new());
}
Ok(self.artist_cache.get(artist_mbid).unwrap())
let resp: SimilarArtistsResponse = serde_json::from_str(&body)?;
Ok(resp
.similarartists
.artist
.into_iter()
.map(|a| {
let mbid = a.mbid.filter(|s| !s.is_empty());
SimilarArtist {
name: a.name,
mbid,
match_score: a.match_score.parse().unwrap_or(0.0),
}
})
.collect())
}
}