Skip to content

Commit 07cfad2

Browse files
unhappychoiceclaude
andcommitted
feat(fetcher): add lastfm_scrobbles_today + lastfm family scaffold
Introduces the `lastfm_*` family with the first sibling: today's scrobbles for a Last.fm user, surfacing the currently-playing track when one is in flight. Shared infrastructure for the family is split into two modules so the subsequent `lastfm_top_*` and `lastfm_charts` siblings can reuse it without churn: - `lastfm/client.rs`: fixed-host HTTP (`ws.audioscrobbler.com`), API key resolution from `LASTFM_API_KEY`, and a `get_json` helper that detects Last.fm's HTTP-200 error envelope (`{"error":N,"message":...}`) before handing bytes to the caller's deserializer. - `lastfm/common.rs`: image-URL picking that filters the well-known placeholder hash so `ImageLinkedList` rows don't all share the same gray square, plus count parsing and `k/M` formatting helpers. `lastfm_scrobbles_today` accepts a required `user` and an optional `limit` (1..=50, default 10), reads `user.getRecentTracks?from=midnight-UTC-today`, and emits 8 shapes: LinkedTextBlock (default) / ImageLinkedList / TextBlock / Text / MarkdownTextBlock / Entries / Badge / Timeline. Refresh interval is 5 minutes so the splash reflects "what I'm playing now" within a coffee break. Ratio / NumberSeries / PointSeries / Bars / Image / Calendar / Heatmap deliberately rejected: no natural denominator, no chronological-ranking contract, and the "top tracks today" Bars angle is the territory of the follow-up `lastfm_top_tracks` sibling. Safety: `Safety::Safe`. Same model as `github_*` — the host never moves; `user` only picks which resource within `ws.audioscrobbler.com` is queried. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
1 parent 04d8ce5 commit 07cfad2

5 files changed

Lines changed: 1256 additions & 0 deletions

File tree

‎src/fetcher/lastfm/client.rs‎

Lines changed: 193 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,193 @@
1+
//! Shared HTTP client + auth for the `lastfm_*` fetcher family.
2+
//!
3+
//! Every request targets `ws.audioscrobbler.com` — the host is hardcoded, so the API key
4+
//! never leaves to an attacker-controlled origin. Same `Safety::Safe` model as `github_*`:
5+
//! config-provided fields (`user`, `period`, …) only change which resource within the fixed
6+
//! host is queried.
7+
//!
8+
//! Auth: `LASTFM_API_KEY` (free, https://www.last.fm/api/account/create).
9+
//! Last.fm signals errors with HTTP 200 + `{"error": <code>, "message": <msg>}` rather than a
10+
//! non-2xx status, so [`get_json`] inspects the JSON envelope before deserializing into the
11+
//! caller's target type.
12+
13+
use std::sync::OnceLock;
14+
use std::time::Duration;
15+
16+
use reqwest::Client;
17+
use serde::de::DeserializeOwned;
18+
19+
use crate::fetcher::FetchError;
20+
21+
const API_BASE: &str = "https://ws.audioscrobbler.com/2.0/";
22+
const USER_AGENT: &str = concat!("splashboard/", env!("CARGO_PKG_VERSION"));
23+
const REQUEST_TIMEOUT: Duration = Duration::from_secs(10);
24+
const MAX_BYTES: usize = 5 * 1024 * 1024;
25+
26+
pub fn http() -> &'static Client {
27+
static CLIENT: OnceLock<Client> = OnceLock::new();
28+
CLIENT.get_or_init(|| {
29+
Client::builder()
30+
.user_agent(USER_AGENT)
31+
.timeout(REQUEST_TIMEOUT)
32+
.gzip(true)
33+
.build()
34+
.expect("reqwest client should build with default config")
35+
})
36+
}
37+
38+
pub fn resolve_api_key() -> Result<String, FetchError> {
39+
std::env::var("LASTFM_API_KEY").map_err(|_| FetchError::Failed("LASTFM_API_KEY not set".into()))
40+
}
41+
42+
/// `GET https://ws.audioscrobbler.com/2.0/?method=<method>&api_key=<key>&format=json&<params>`
43+
/// then deserialize into `T`. Caller passes additional query pairs as `(key, value)` slices;
44+
/// `method`, `api_key`, and `format` are appended unconditionally.
45+
pub async fn get_json<T: DeserializeOwned>(
46+
method: &str,
47+
params: &[(&str, &str)],
48+
) -> Result<T, FetchError> {
49+
let key = resolve_api_key()?;
50+
let url = build_url(method, &key, params);
51+
let res = http()
52+
.get(&url)
53+
.send()
54+
.await
55+
.map_err(|e| FetchError::Failed(format!("lastfm request failed: {e}")))?;
56+
parse_json(res).await
57+
}
58+
59+
fn build_url(method: &str, api_key: &str, params: &[(&str, &str)]) -> String {
60+
let mut url = url::Url::parse(API_BASE).expect("static API_BASE parses");
61+
{
62+
let mut q = url.query_pairs_mut();
63+
q.append_pair("method", method);
64+
q.append_pair("api_key", api_key);
65+
q.append_pair("format", "json");
66+
for (k, v) in params {
67+
q.append_pair(k, v);
68+
}
69+
}
70+
url.into()
71+
}
72+
73+
async fn parse_json<T: DeserializeOwned>(res: reqwest::Response) -> Result<T, FetchError> {
74+
let status = res.status();
75+
let bytes = res
76+
.bytes()
77+
.await
78+
.map_err(|e| FetchError::Failed(format!("lastfm read body: {e}")))?;
79+
if bytes.len() > MAX_BYTES {
80+
return Err(FetchError::Failed(format!(
81+
"lastfm response too large ({} bytes, cap {MAX_BYTES})",
82+
bytes.len()
83+
)));
84+
}
85+
if !status.is_success() {
86+
return Err(FetchError::Failed(format!("lastfm {status}")));
87+
}
88+
// Last.fm tunnels errors through a 200 + `{"error":N,"message":...}` envelope, so we
89+
// detect that before handing bytes to the caller's deserializer.
90+
if let Some(err) = parse_api_error(&bytes) {
91+
return Err(err);
92+
}
93+
serde_json::from_slice(&bytes)
94+
.map_err(|e| FetchError::Failed(format!("lastfm json parse: {e}")))
95+
}
96+
97+
fn parse_api_error(bytes: &[u8]) -> Option<FetchError> {
98+
let value: serde_json::Value = serde_json::from_slice(bytes).ok()?;
99+
let code = value.get("error").and_then(|v| v.as_i64())?;
100+
let message = value
101+
.get("message")
102+
.and_then(|v| v.as_str())
103+
.unwrap_or("(no message)");
104+
Some(FetchError::Failed(format!(
105+
"lastfm error {code}: {message}"
106+
)))
107+
}
108+
109+
#[cfg(test)]
110+
mod tests {
111+
use super::*;
112+
113+
#[test]
114+
fn build_url_includes_method_api_key_and_format() {
115+
let url = build_url(
116+
"user.getRecentTracks",
117+
"secret",
118+
&[("user", "rj"), ("limit", "5")],
119+
);
120+
assert!(url.starts_with("https://ws.audioscrobbler.com/2.0/?"));
121+
assert!(url.contains("method=user.getRecentTracks"));
122+
assert!(url.contains("api_key=secret"));
123+
assert!(url.contains("format=json"));
124+
assert!(url.contains("user=rj"));
125+
assert!(url.contains("limit=5"));
126+
}
127+
128+
#[test]
129+
fn build_url_percent_encodes_param_values() {
130+
// Last.fm usernames are ASCII but reserved characters in artist / track query params
131+
// (slashes, ampersands, plus, …) must encode so we don't smuggle extra query pairs.
132+
let url = build_url("artist.search", "k", &[("artist", "AC/DC & Friends")]);
133+
assert!(
134+
url.contains("artist=AC%2FDC+%26+Friends")
135+
|| url.contains("artist=AC%2FDC%20%26%20Friends")
136+
);
137+
}
138+
139+
#[test]
140+
fn resolve_api_key_fails_with_clear_message_when_unset() {
141+
let _lock = crate::paths::TEST_ENV_LOCK
142+
.lock()
143+
.unwrap_or_else(|e| e.into_inner());
144+
let prev = std::env::var("LASTFM_API_KEY").ok();
145+
unsafe { std::env::remove_var("LASTFM_API_KEY") };
146+
let err = resolve_api_key().unwrap_err();
147+
assert!(matches!(err, FetchError::Failed(m) if m == "LASTFM_API_KEY not set"));
148+
if let Some(v) = prev {
149+
unsafe { std::env::set_var("LASTFM_API_KEY", v) };
150+
}
151+
}
152+
153+
#[test]
154+
fn resolve_api_key_reads_env() {
155+
let _lock = crate::paths::TEST_ENV_LOCK
156+
.lock()
157+
.unwrap_or_else(|e| e.into_inner());
158+
let prev = std::env::var("LASTFM_API_KEY").ok();
159+
unsafe { std::env::set_var("LASTFM_API_KEY", "abc123") };
160+
assert_eq!(resolve_api_key().unwrap(), "abc123");
161+
match prev {
162+
Some(v) => unsafe { std::env::set_var("LASTFM_API_KEY", v) },
163+
None => unsafe { std::env::remove_var("LASTFM_API_KEY") },
164+
}
165+
}
166+
167+
#[test]
168+
fn parse_api_error_surfaces_lastfm_error_envelope() {
169+
let bytes = br#"{"error":6,"message":"User not found"}"#;
170+
let err = parse_api_error(bytes).expect("error envelope must be detected");
171+
let FetchError::Failed(msg) = err else {
172+
panic!("expected FetchError::Failed");
173+
};
174+
assert!(msg.contains("lastfm error 6"));
175+
assert!(msg.contains("User not found"));
176+
}
177+
178+
#[test]
179+
fn parse_api_error_returns_none_on_success_bodies() {
180+
let bytes = br#"{"recenttracks":{"track":[]}}"#;
181+
assert!(parse_api_error(bytes).is_none());
182+
}
183+
184+
#[test]
185+
fn parse_api_error_returns_none_on_unparseable_bytes() {
186+
assert!(parse_api_error(b"not-json").is_none());
187+
}
188+
189+
#[test]
190+
fn http_reuses_the_same_client() {
191+
assert!(std::ptr::eq(http(), http()));
192+
}
193+
}

‎src/fetcher/lastfm/common.rs‎

Lines changed: 155 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,155 @@
1+
//! Cross-cutting helpers for the `lastfm_*` family: image-URL picking, count parsing,
2+
//! human-readable formatting.
3+
4+
use serde::Deserialize;
5+
6+
/// Per-row image descriptor returned by Last.fm. The JSON shape is `{"#text": "...",
7+
/// "size": "..."}`; sizes are `small | medium | large | extralarge | mega`. Entries are
8+
/// almost always present even when the underlying entity has no artwork — in that case
9+
/// Last.fm serves a known placeholder hash that [`best_image`] filters out.
10+
#[derive(Debug, Clone, Deserialize)]
11+
pub struct ImageEntry {
12+
#[serde(rename = "#text", default)]
13+
pub url: String,
14+
#[serde(default)]
15+
pub size: String,
16+
}
17+
18+
/// Largest non-placeholder image URL, or `None` when every entry is empty or the placeholder.
19+
///
20+
/// Last.fm tags artwork-less entities (track / artist / album) with a fixed gray-square hash
21+
/// `2a96cbd8b46e442fc41c2b86b821562f`. Without filtering, an `ImageLinkedList` of those rows
22+
/// would surface the same placeholder thumbnail on every row, which is worse than no
23+
/// thumbnails at all.
24+
pub fn best_image(images: &[ImageEntry]) -> Option<String> {
25+
const PLACEHOLDER: &str = "2a96cbd8b46e442fc41c2b86b821562f";
26+
const PRIORITY: &[&str] = &["mega", "extralarge", "large", "medium", "small"];
27+
PRIORITY
28+
.iter()
29+
.find_map(|size| {
30+
images.iter().find(|img| {
31+
img.size == *size && !img.url.is_empty() && !img.url.contains(PLACEHOLDER)
32+
})
33+
})
34+
.map(|img| img.url.clone())
35+
}
36+
37+
/// Parse a Last.fm count field. Counts come back as JSON strings (`"42"`) for historical
38+
/// reasons; anything that can't parse silently collapses to zero rather than failing the
39+
/// entire fetch.
40+
pub fn parse_count(raw: &str) -> u64 {
41+
raw.parse().unwrap_or(0)
42+
}
43+
44+
/// Human-readable count: `1234` -> `"1.2k"`, `2_100_000` -> `"2.1M"`. Mirrors the
45+
/// `huggingface_trending` convention so the catalog reads consistently.
46+
pub fn format_count(n: u64) -> String {
47+
if n >= 1_000_000 {
48+
format!("{:.1}M", n as f64 / 1_000_000.0)
49+
} else if n >= 1_000 {
50+
format!("{:.1}k", n as f64 / 1_000.0)
51+
} else {
52+
n.to_string()
53+
}
54+
}
55+
56+
/// `"play"` vs `"plays"` — small enough that inlining at every call site would obscure intent.
57+
pub fn plays_word(n: u64) -> &'static str {
58+
if n == 1 { "play" } else { "plays" }
59+
}
60+
61+
#[cfg(test)]
62+
mod tests {
63+
use super::*;
64+
65+
fn img(size: &str, url: &str) -> ImageEntry {
66+
ImageEntry {
67+
url: url.into(),
68+
size: size.into(),
69+
}
70+
}
71+
72+
#[test]
73+
fn best_image_prefers_mega_over_smaller_sizes() {
74+
let imgs = vec![
75+
img("small", "https://example.com/small.png"),
76+
img("mega", "https://example.com/mega.png"),
77+
img("large", "https://example.com/large.png"),
78+
];
79+
assert_eq!(
80+
best_image(&imgs),
81+
Some("https://example.com/mega.png".into())
82+
);
83+
}
84+
85+
#[test]
86+
fn best_image_falls_back_through_priority_chain() {
87+
let imgs = vec![
88+
img("medium", "https://example.com/medium.png"),
89+
img("small", "https://example.com/small.png"),
90+
];
91+
assert_eq!(
92+
best_image(&imgs),
93+
Some("https://example.com/medium.png".into())
94+
);
95+
}
96+
97+
#[test]
98+
fn best_image_skips_placeholder_hash() {
99+
let imgs = vec![
100+
img(
101+
"mega",
102+
"https://lastfm.freetls.fastly.net/i/u/300x300/2a96cbd8b46e442fc41c2b86b821562f.png",
103+
),
104+
img("large", "https://example.com/real.png"),
105+
];
106+
assert_eq!(
107+
best_image(&imgs),
108+
Some("https://example.com/real.png".into())
109+
);
110+
}
111+
112+
#[test]
113+
fn best_image_returns_none_when_only_placeholder_or_empty() {
114+
let imgs = vec![
115+
img(
116+
"mega",
117+
"https://lastfm.freetls.fastly.net/i/u/300x300/2a96cbd8b46e442fc41c2b86b821562f.png",
118+
),
119+
img("large", ""),
120+
];
121+
assert!(best_image(&imgs).is_none());
122+
}
123+
124+
#[test]
125+
fn best_image_returns_none_on_empty_input() {
126+
assert!(best_image(&[]).is_none());
127+
}
128+
129+
#[test]
130+
fn parse_count_reads_numeric_strings() {
131+
assert_eq!(parse_count("42"), 42);
132+
assert_eq!(parse_count("0"), 0);
133+
}
134+
135+
#[test]
136+
fn parse_count_collapses_garbage_to_zero() {
137+
assert_eq!(parse_count("not-a-number"), 0);
138+
assert_eq!(parse_count(""), 0);
139+
}
140+
141+
#[test]
142+
fn format_count_picks_unit_by_magnitude() {
143+
assert_eq!(format_count(0), "0");
144+
assert_eq!(format_count(950), "950");
145+
assert_eq!(format_count(1_500), "1.5k");
146+
assert_eq!(format_count(1_200_000), "1.2M");
147+
}
148+
149+
#[test]
150+
fn plays_word_pluralises_only_for_non_singular() {
151+
assert_eq!(plays_word(0), "plays");
152+
assert_eq!(plays_word(1), "play");
153+
assert_eq!(plays_word(2), "plays");
154+
}
155+
}

‎src/fetcher/lastfm/mod.rs‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
//! Last.fm fetchers — user listening statistics (recent scrobbles, top artists / tracks /
2+
//! albums) plus global charts.
3+
//!
4+
//! Every request targets the fixed host `ws.audioscrobbler.com`. Config-provided fields
5+
//! (`user`, `period`, …) only change which resource on that host is queried; the API key
6+
//! never leaves to an attacker-controlled origin. Classified as `Safety::Safe`, same model
7+
//! as the `github_*` family.
8+
//!
9+
//! Auth: `LASTFM_API_KEY` — create one at https://www.last.fm/api/account/create and put it
10+
//! in `$HOME/.splashboard/secrets.toml`.
11+
12+
mod client;
13+
mod common;
14+
mod scrobbles_today;
15+
16+
use std::sync::Arc;
17+
18+
use crate::fetcher::Fetcher;
19+
20+
pub fn fetchers() -> Vec<Arc<dyn Fetcher>> {
21+
vec![Arc::new(scrobbles_today::LastfmScrobblesToday)]
22+
}
23+
24+
#[cfg(test)]
25+
mod tests {
26+
use super::*;
27+
28+
#[test]
29+
fn fetchers_entry_point_registers_the_batch_under_lastfm_prefix() {
30+
let names: Vec<String> = fetchers().iter().map(|f| f.name().to_string()).collect();
31+
for name in &names {
32+
assert!(
33+
name.starts_with("lastfm_"),
34+
"{name} must use the `lastfm_` family prefix"
35+
);
36+
}
37+
assert!(names.contains(&"lastfm_scrobbles_today".to_string()));
38+
}
39+
}

0 commit comments

Comments
 (0)