Dezio/src/commands/lastfm/mod.rs
astar76 ef26f7ff12 Covers and artist photos with fallbacks, tag IDs first
Covers come from the release in the player's own tags (Cover Art
Archive), then ListenBrainz's match, the release group, Deezer and
iTunes. Deezer and iTunes results count only when the artist and title
match. Artist photos come from Deezer, then MusicBrainz/Wikimedia.
Missing album names are looked up on Deezer. Play counts and Who Knows
match by MusicBrainz ID before names.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-01 15:44:39 -06:00

324 lines
15 KiB
Rust

//! Listening stats (from ListenBrainz since Last.fm's API went Pro-only; see api.rs): now playing, recent & top stats,
//! WhoKnows, album charts, Pixel Jumble and lyrics.
//!
//! Prefix: `D!fm [top|recent|profile] [@user]` · `D!ta` / `D!tab` / `D!tt` · `D!recent` · `D!fmprofile` · `D!fmset <username>`
//! `D!wk` / `D!wkt` / `D!wka` · `D!chart [size] [period]` · `D!px` · `D!lyrics`
//! Slash: `/fm [user] [mode] [kind] [period]` · `/whoknows` · `/chart` · `/pixel` · `/lyrics`
//!
//! Every card is public; only the person who ran the command can flip pages or switch views. The now-playing card has
//! "Go to song" (the track's page on the Last.fm website) and "Listen to song" (anyone can press it: they get the song from YouTube as a
//! 96 kbit/s Opus file in a message only they can see, which deletes itself after ~14 minutes).
mod api;
mod extras;
mod art;
mod covers;
mod views;
use self::api::{as_list, best_image, fm_url, Lb};
use super::info::display_name_of;
use crate::bail_user;
use crate::cmd::{Command, Ctx, Opt, OptKind, Origin};
use crate::converters::find_member;
use crate::interact;
use crate::state::State;
use crate::ui::{button, escape, truncate, Card, GREEN, RED};
use anyhow::Result;
use futures::FutureExt;
use serde_json::Value;
use std::sync::Arc;
use twilight_model::application::interaction::{Interaction, InteractionData};
use twilight_model::channel::message::component::{ButtonStyle, Component};
use twilight_model::id::marker::UserMarker;
use twilight_model::id::Id;
pub const PLAYING_EMOJI: &str = "<a:playing:1393315200869994536>";
/// Keys from Last.fm (old commands and slash choices use them); `api::range_of` maps them to ListenBrainz ranges, and
/// the labels say what those ranges cover.
pub const PERIODS: [(&str, &str); 6] = [("overall", "All time"), ("7day", "Last week"), ("1month", "Last month"), ("3month", "Last quarter"), ("6month", "Last half-year"), ("12month", "This year")];
pub fn period_label(key: &str) -> &'static str {
PERIODS.iter().find(|p| p.0 == key).map_or("All time", |p| p.1)
}
pub fn period_of(word: &str) -> Option<&'static str> {
let w = word.to_lowercase();
if let Some(p) = PERIODS.iter().find(|p| p.0 == w) {
return Some(p.0);
}
Some(match w.as_str() {
"alltime" | "all" => "overall",
"7d" | "week" | "weekly" => "7day",
"1m" | "month" | "monthly" => "1month",
"3m" | "quarterly" => "3month",
"6m" => "6month",
"12m" | "year" | "yearly" => "12month",
_ => return None,
})
}
pub fn kind_of(word: &str) -> Option<&'static str> {
Some(match word.to_lowercase().as_str() {
"artists" | "artist" | "ar" | "a" => "artists",
"albums" | "album" | "al" | "ab" => "albums",
"tracks" | "track" | "songs" | "song" | "t" => "tracks",
_ => return None,
})
}
pub fn link(text: &str, url: Option<&str>) -> String {
let t = escape(text).replace('[', "(").replace(']', ")");
match url {
Some(u) if !u.is_empty() => format!("[{t}](<{u}>)"),
_ => t,
}
}
pub fn normalise_title(title: &str) -> String {
let lower = title.to_lowercase();
let no_brackets = regex::Regex::new(r"[\(\[][^)\]]*[\)\]]").unwrap().replace_all(&lower, "").to_string();
let no_suffix = regex::Regex::new(r"\s+-\s+(single|ep|remaster.*|deluxe.*)$").unwrap().replace(&no_brackets, "").to_string();
regex::Regex::new(r"[^\w\s]").unwrap().replace_all(&no_suffix, "").trim().to_string()
}
fn lfm(state: &State) -> Arc<Lb> {
Lb::get(state)
}
async fn error(ctx: &Ctx, text: &str) -> Result<()> {
ctx.reply_private(Card::new(Some(RED)).text(&format!("❌ {text}")).build()).await
}
/// The linked ListenBrainz name (for the dashboard).
pub fn linked_name(user: u64) -> Option<String> {
api::linked(user)
}
pub fn unlink(user: u64) {
api::set_link(user, None);
}
fn link_prompt(who: Option<u64>) -> Component {
let text = match who {
None => "You haven't linked a ListenBrainz account yet.".to_string(),
Some(u) => format!("<@{u}> hasn't linked a ListenBrainz account yet."),
};
let text = format!("{text}\n-# Dezio reads your stats from [ListenBrainz](<https://listenbrainz.org>) now: Last.fm's API costs money since December. Make a free account there, connect Last.fm in its settings to bring your history and new scrobbles, then link it here.");
let mut b = button("fm:link", "Link ListenBrainz", ButtonStyle::Success);
b.emoji = Some(twilight_model::channel::message::EmojiReactionType::Unicode { name: "🔗".into() });
Card::new(Some(RED)).text(&format!("### ❌ ListenBrainz not linked\n{text}")).row(vec![b]).build()
}
/// The ListenBrainz name for a person, or None after showing a "link your account" prompt.
async fn username_or_prompt(ctx: &Ctx, user: Id<UserMarker>) -> Result<Option<String>> {
if let Some(n) = api::linked(user.get()) {
return Ok(Some(n));
}
let own = user == ctx.user_id;
let card = link_prompt(if own { None } else { Some(user.get()) });
if own && ctx.is_slash() { ctx.reply_private(card).await? } else { ctx.reply(card).await? }
Ok(None)
}
pub(crate) async fn link_account(state: &State, user: u64, username: &str) -> String {
match Lb::get(state).user_info(username).await {
Err(api::Error::NotFound(_)) => format!("❌ There's no ListenBrainz user called **{}**.", escape(username)),
Err(e) => format!("❌ {e}"),
Ok(info) => {
let name = info["name"].as_str().unwrap_or(username).to_string();
api::set_link(user, Some(&name));
format!("✅ Linked to **{}** ({} listens).", escape(&name), crate::converters::thousands(info["playcount"].as_u64().unwrap_or(0)))
}
}
}
async fn who_is(ctx: &Ctx, text: &str) -> Result<Id<UserMarker>> {
if text.trim().is_empty() {
return Ok(ctx.reply_to.unwrap_or(ctx.user_id));
}
if let Some(u) = ctx.guild_id.and_then(|g| find_member(&ctx.state.cache, g, text.trim())) {
return Ok(u);
}
match crate::converters::parse_id(text.trim()).and_then(Id::new_checked) {
Some(u) => Ok(u),
None => bail_user!("I couldn't find `{}`.", escape(&truncate(text, 50))),
}
}
// ---- /fm and friends -------------------------------------------------------------------------------------------
async fn show(ctx: &Arc<Ctx>, mode: &str, user: Id<UserMarker>, kind: &str, period: &str) -> Result<()> {
let state = &ctx.state;
let api = lfm(state);
let Some(username) = username_or_prompt(ctx, user).await? else { return Ok(()) };
ctx.defer().await?;
let name = display_name_of(state, ctx.guild_id, user).await;
let avatar = super::media::avatar(state, user, 256).await;
let base = views::Base { state: state.clone(), api: api.clone(), owner: ctx.user_id.get(), user: user.get(), name, avatar, username: username.clone() };
if mode == "nowplaying" {
return match views::now_playing(&base).await {
Ok((card, Some(picture))) => ctx.reply_file(card, art::FILE, picture).await,
Ok((card, None)) => ctx.reply(card).await,
Err(e) => error(ctx, &e.to_string()).await,
};
}
let game = match mode {
"top" => views::Top::load(base, kind.to_string(), period.to_string()).await.map(|g| Box::new(g) as Box<dyn super::games::Game>),
"recent" => views::Recent::load(base).await.map(|g| Box::new(g) as Box<dyn super::games::Game>),
_ => views::Profile::load(base).await.map(|g| Box::new(g) as Box<dyn super::games::Game>),
};
match game {
Ok(g) => super::games::launch(ctx, g, None).await,
Err(e) => error(ctx, &e.to_string()).await,
}
}
async fn prefix_mode(ctx: &Arc<Ctx>, mode: &str, args: &str) -> Result<()> {
let (mut kind, mut period, mut rest) = ("artists", "overall", Vec::new());
for word in args.split_whitespace() {
if mode == "top" {
if let Some(k) = kind_of(word) {
kind = k;
continue;
}
if let Some(p) = period_of(word) {
period = p;
continue;
}
}
rest.push(word);
}
let user = who_is(ctx, &rest.join(" ")).await?;
show(ctx, mode, user, kind, period).await
}
async fn fm(ctx: Arc<Ctx>) -> Result<()> {
if ctx.is_slash() {
let mode = ctx.args.str("mode").unwrap_or("nowplaying").to_string();
if mode == "link" {
return open_link_modal(&ctx).await;
}
let user = ctx.args.user("user").unwrap_or(ctx.user_id);
return show(&ctx, &mode, user, ctx.args.str("kind").unwrap_or("artists"), ctx.args.str("period").unwrap_or("overall")).await;
}
let args = ctx.args.str("args").unwrap_or("").to_string();
let (first, rest) = args.split_once(char::is_whitespace).map_or((args.as_str(), ""), |(a, b)| (a, b));
let mode = match first.to_lowercase().as_str() {
"top" | "t" => Some("top"),
"recent" | "rc" | "r" => Some("recent"),
"profile" | "p" | "me" => Some("profile"),
"np" => Some("nowplaying"),
_ => None,
};
match mode {
Some(m) => prefix_mode(&ctx, m, rest).await,
None => prefix_mode(&ctx, "nowplaying", &args).await,
}
}
async fn shortcut(ctx: Arc<Ctx>) -> Result<()> {
let args = ctx.args.str("args").unwrap_or("").to_string();
match ctx.invoked {
"ta" => prefix_mode(&ctx, "top", &format!("artists {args}")).await,
"tab" => prefix_mode(&ctx, "top", &format!("albums {args}")).await,
"tt" => prefix_mode(&ctx, "top", &format!("tracks {args}")).await,
"recent" => prefix_mode(&ctx, "recent", &args).await,
_ => prefix_mode(&ctx, "profile", &args).await,
}
}
fn link_form() -> Vec<Component> {
vec![interact::text_field("username", "ListenBrainz username", None, "", 64, false, Some("e.g. rob"))]
}
async fn open_link_modal(ctx: &Ctx) -> Result<()> {
let Origin::Interaction { id, token, responded, .. } = &ctx.origin else { bail_user!("Use `/fm mode:link`.") };
responded.store(true, std::sync::atomic::Ordering::SeqCst);
use twilight_model::http::interaction::{InteractionResponse, InteractionResponseData, InteractionResponseType};
let data = InteractionResponseData { custom_id: Some("fm:linkform".into()), title: Some("Link your ListenBrainz".into()), components: Some(link_form()), ..Default::default() };
ctx.state.http.interaction(ctx.state.app_id()).create_response(*id, token, &InteractionResponse { kind: InteractionResponseType::Modal, data: Some(data) }).await?;
Ok(())
}
async fn fmset(ctx: Arc<Ctx>) -> Result<()> {
let Some(name) = ctx.args.str("username").map(str::to_string) else {
if let Some(current) = api::linked(ctx.user_id.get()) {
return ctx.say(&format!("Linked to **{}**. Use `{}fmset <username>` to change it.", escape(&current), ctx.state.prefix(ctx.guild_id))).await;
}
return ctx.reply(link_prompt(None)).await;
};
ctx.defer().await?;
let text = link_account(&ctx.state, ctx.user_id.get(), &name).await;
ctx.say(&text).await
}
pub async fn on_component(state: &Arc<State>, i: &Interaction) {
match i.data.as_ref() {
Some(InteractionData::MessageComponent(d)) if d.custom_id == "fm:link" => interact::modal(state, i, "fm:linkform", "Link your ListenBrainz", link_form()).await,
Some(InteractionData::MessageComponent(d)) if d.custom_id == "fm:listen" => extras::listen_button(state, i).await,
Some(InteractionData::ModalSubmit(d)) if d.custom_id == "fm:linkform" => {
let Some(user) = i.author() else { return };
let name = interact::modal_values(d).get("username").map(|s| s.trim().to_string()).unwrap_or_default();
if name.len() < 2 {
return interact::private_text(state, i, "Type your ListenBrainz username.").await;
}
interact::defer_private(state, i).await;
let text = link_account(state, user.id.get(), &name).await;
interact::followup_text(state, i, &text).await;
}
_ => {}
}
}
// ---- registration -----------------------------------------------------------------------------------------------------
pub fn commands() -> Vec<Command> {
let periods: &'static [&'static str] = Box::leak(PERIODS.iter().map(|p| p.0).collect::<Vec<_>>().into_boxed_slice());
let modes: &'static [&'static str] = &["nowplaying", "top", "recent", "profile", "link"];
let who = |c: Command| c.opt(Opt::opt("args", "A user, and for top lists a kind and period", OptKind::String).prefix_only());
vec![
Command::new("fm", "lastfm", "What you (or someone) are listening to. `fm top albums monthly`, `fm recent`, `fm profile @friend` for stats — reply to someone with `fm` to see theirs.", |c| fm(c).boxed())
.usage("[top|recent|profile] [artists|albums|tracks] [weekly|monthly|…] [@user]")
.opt(Opt::opt("args", "What to show and for whom", OptKind::String).prefix_only())
.opt(Opt::opt("user", "Whose profile (defaults to you)", OptKind::User).slash_only())
.opt(Opt::opt("mode", "What to show — or 'link' to connect your account", OptKind::String).choices(modes).slash_only())
.opt(Opt::opt("kind", "Top list: artists, albums or tracks", OptKind::String).choices(&["artists", "albums", "tracks"]).slash_only())
.opt(Opt::opt("period", "Top list: time period", OptKind::String).choices(periods).slash_only()),
who(Command::new("ta", "lastfm", "Your top artists.", |c| shortcut(c).boxed()).aliases(&["topartists"]).usage("[period] [@user]").prefix_only()),
who(Command::new("tab", "lastfm", "Your top albums.", |c| shortcut(c).boxed()).aliases(&["topalbums"]).usage("[period] [@user]").prefix_only()),
who(Command::new("tt", "lastfm", "Your top tracks.", |c| shortcut(c).boxed()).aliases(&["toptracks"]).usage("[period] [@user]").prefix_only()),
who(Command::new("recent", "lastfm", "Your last 50 listens.", |c| shortcut(c).boxed()).aliases(&["rc", "recenttracks"]).usage("[@user]").prefix_only()),
who(Command::new("fmprofile", "lastfm", "Listening profile: listens, library size, daily average and this week's favourites.", |c| shortcut(c).boxed()).aliases(&["fmp", "fmstats"]).usage("[@user]").prefix_only()),
Command::new("fmset", "lastfm", "Link your ListenBrainz account: `D!fmset <username>`.", |c| fmset(c).boxed())
.aliases(&["fmlogin", "setfm"])
.usage("<username>")
.opt(Opt::opt("username", "Your ListenBrainz username", OptKind::String))
.prefix_only(),
]
.into_iter()
.chain(extras::commands())
.collect()
}
pub use self::api::as_list as _as_list;
#[allow(dead_code)]
fn _unused(_: &Value) {
let _ = (as_list, best_image, fm_url, GREEN);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn words_map_to_periods_and_kinds() {
assert_eq!((period_of("weekly"), period_of("12m"), period_of("alltime"), period_of("nope")), (Some("7day"), Some("12month"), Some("overall"), None));
assert_eq!((kind_of("songs"), kind_of("al"), kind_of("x")), (Some("tracks"), Some("albums"), None));
}
#[test]
fn album_names_are_compared_without_noise() {
assert_eq!(normalise_title("Abbey Road (Remastered 2019)"), "abbey road");
assert_eq!(normalise_title("Thriller - Deluxe Edition"), "thriller");
assert_eq!(normalise_title("OK Computer [Special]"), "ok computer");
}
}