fm: suggest /fmtransfer on low-listen /fm cards, how to connect apps

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
astar76 2026-12-03 10:58:17 -06:00
commit b3b436dba2
4 changed files with 53 additions and 6 deletions

View file

@ -84,3 +84,4 @@ One entry per session, newest last, ≤ 15 lines: done, verified how, not done,
- Done: `/fmtransfer` (`D!fmtransfer`, `src/commands/lastfm/transfer.rs`). No linked account → how to make one + Link button. Linked → steps with buttons to the CrownNote Last.fm exporter, the ListenBrainz token page, and "Upload CSV" (modal: file + user token). Plays are sent as an import in 500-listen batches; made-up times back from 2025-01-01, 3 min apart, so the same file sent twice doesn't double. Token never stored or logged. Linking an empty account hints at `/fmtransfer`.
- /fm now playing: JPEG instead of PNG (~47 KB with a real photo), cover downloaded once (accent from the same bytes), play count / album / cover lookups run together.
- Verified: unit tests (CSV parse, dates, picture size); owner's export parses (700 songs, 51,584 plays). Not checked in Discord 🧑.
- Later same day: your own /fm card with no listens or under 500 (`transfer::LOW_LISTENS`) shows a `/fmtransfer` hint and a "Transfer from Last.fm" button (steps shown privately). Transfer and sign-up cards now say how to connect apps (Spotify, Web Scrobbler, Pano Scrobbler, ListenBrainz's add-data list).

View file

@ -12,7 +12,7 @@ mod api;
mod extras;
mod art;
mod covers;
mod transfer;
pub(crate) mod transfer;
mod views;
use self::api::{as_list, best_image, fm_url, Lb};
@ -258,6 +258,7 @@ 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::MessageComponent(d)) if d.custom_id == "fm:xferinfo" => transfer::show_info(state, i).await,
Some(InteractionData::MessageComponent(d)) if d.custom_id == "fm:xfer" => transfer::open_form(state, i).await,
Some(InteractionData::ModalSubmit(d)) if d.custom_id == "fm:xferform" => transfer::on_submit(state, i, d).await,
Some(InteractionData::ModalSubmit(d)) if d.custom_id == "fm:linkform" => {

View file

@ -26,6 +26,14 @@ use twilight_model::id::Id;
pub const EXPORTER_URL: &str = "https://www.crownnote.com/tools/lastfm-exporter";
const TOKEN_URL: &str = "https://listenbrainz.org/settings/";
const SIGNUP_URL: &str = "https://listenbrainz.org/login/";
/// ListenBrainz's own list of every app and player that can send it listens.
const APPS_URL: &str = "https://listenbrainz.org/add-data/";
/// How new listens get to ListenBrainz: the common cases, then the full list.
const APPS: &str = "**Keep it updated:** connect what you listen with so new plays show up.\n\
- **Spotify:** ListenBrainz → Settings → Connect services → Spotify.\n\
- **Browser** (YouTube, YouTube Music, SoundCloud, Deezer, Tidal…): the **Web Scrobbler** extension, ListenBrainz in its settings.\n\
- **Android:** **Pano Scrobbler**, add ListenBrainz under accounts.\n\
- Anything else (foobar2000, MusicBee, Jellyfin, Navidrome…): **Connect apps** lists them.";
const API_URL: &str = "https://api.listenbrainz.org/1";
/// 2025-01-01 00:00 UTC. Fixed (not "now") so a second upload of the same file lands on the same times.
const ANCHOR: i64 = 1_735_689_600;
@ -48,6 +56,16 @@ const MAX_RATE_WAIT: u64 = 60;
/// Update the progress message every this many batches (~1 edit per 10k listens).
const PROGRESS_EVERY: usize = 20;
/// Below this many listens, your own `/fm` card suggests `/fmtransfer`: a new account, or one that only has the last
/// few weeks (a few hundred plays) and is missing its Last.fm years.
pub const LOW_LISTENS: u64 = 500;
pub const HINT: &str = "-# 📦 Moving from Last.fm? Bring your scrobbles over with `/fmtransfer`.";
/// The button under a `/fm` card that shows the transfer steps (only to whoever presses it).
pub fn hint_button() -> Button {
with_emoji(button("fm:xferinfo", "Transfer from Last.fm", ButtonStyle::Secondary), "📦")
}
/// One CSV row: `plays` listens of a song.
#[derive(Debug, PartialEq)]
pub struct Row {
@ -148,7 +166,8 @@ fn signup_card() -> Component {
2. Confirm your email and sign in to ListenBrainz with it.\n\
3. Press **Link ListenBrainz** here and type your username.\n\
4. Run `/fmtransfer` again to bring your Last.fm scrobbles over.";
Card::new(Some(RED)).text(text).row(vec![url_button("Sign up", "🌐", SIGNUP_URL), with_emoji(button("fm:link", "Link ListenBrainz", ButtonStyle::Success), "🔗")]).build()
let buttons = vec![url_button("Sign up", "🌐", SIGNUP_URL), with_emoji(button("fm:link", "Link ListenBrainz", ButtonStyle::Success), "🔗"), url_button("Connect apps", "📱", APPS_URL)];
Card::new(Some(RED)).text(text).text(APPS).row(buttons).build()
}
/// For a linked account: export from Last.fm, then upload the file.
@ -167,7 +186,7 @@ fn transfer_card(username: &str, count: u64) -> Component {
Uploading the same file again adds nothing twice. Your token is used once and never saved."
);
let upload = with_emoji(button("fm:xfer", "Upload CSV", ButtonStyle::Primary), "📤");
Card::new(Some(GREEN)).text(&text).row(vec![url_button("Export Last.fm", "📥", EXPORTER_URL), url_button("Get token", "🔑", TOKEN_URL), upload]).build()
Card::new(Some(GREEN)).text(&text).row(vec![url_button("Export Last.fm", "📥", EXPORTER_URL), url_button("Get token", "🔑", TOKEN_URL), upload]).text(APPS).row(vec![url_button("Connect apps", "📱", APPS_URL)]).build()
}
fn form() -> Vec<Component> {
@ -190,6 +209,19 @@ pub async fn fmtransfer(ctx: Arc<Ctx>) -> Result<()> {
if ctx.is_slash() { ctx.reply_private(card).await } else { ctx.reply(card).await }
}
/// `hint_button`: the steps for whoever pressed it, privately.
pub async fn show_info(state: &State, i: &Interaction) {
let Some(user) = i.author().map(|u| u.id.get()) else { return };
let card = match api::linked(user) {
None => signup_card(),
Some(name) => {
let count = super::lfm(state).user_info(&name).await.map(|i| i["playcount"].as_u64().unwrap_or(0)).unwrap_or(0);
transfer_card(&name, count)
}
};
interact::private_card(state, i, card).await;
}
pub async fn open_form(state: &State, i: &Interaction) {
interact::modal(state, i, "fm:xferform", "Transfer from Last.fm", form()).await;
}

View file

@ -1,7 +1,7 @@
//! The stats cards: now playing, top lists, recent tracks and profile (paged, switchable, owner-only).
use super::super::games::{btn, Game, Rendered, Reply};
use super::api::{best_image, fm_url, profile_url, track_from_url, Error, Lb};
use super::{link, period_label, PERIODS, PLAYING_EMOJI};
use super::{link, period_label, transfer, PERIODS, PLAYING_EMOJI};
use crate::cardart::{chart, Chart, Row};
use crate::colors;
use crate::converters::thousands;
@ -48,7 +48,8 @@ pub async fn now_playing(b: &Base) -> Result<(Component, Option<Vec<u8>>), Error
let (tracks, info) = tokio::join!(b.api.recent(&b.username, 2), b.api.user_info(&b.username));
let (tracks, info) = (tracks?, info?);
let Some(track) = tracks.first() else {
return Ok((Card::new(Some(RED)).text(&format!("### No listens yet\n{} hasn't listened to anything yet.", escape(&b.username))).build(), None));
let card = Card::new(Some(RED)).text(&format!("### No listens yet\n{} hasn't listened to anything yet.", escape(&b.username)));
return Ok((if b.owner == b.user { card.text(transfer::HINT).row(vec![transfer::hint_button()]) } else { card }.build(), None));
};
let artist = track["artist"]["#text"].as_str().unwrap_or("Unknown artist");
let title = track["name"].as_str().unwrap_or("Unknown track");
@ -103,11 +104,23 @@ pub async fn now_playing(b: &Base) -> Result<(Component, Option<Vec<u8>>), Error
}
};
let mut card = Card::new(Some(accent)).text(&heading).gallery(&[&format!("attachment://{}", super::art::NOW_FILE)]).footer(&links.join(" · "));
// your own card with only a few listens: probably new here, with the history still on Last.fm
let low = b.owner == b.user && num(&info, "playcount") < transfer::LOW_LISTENS;
if low {
card = card.text(transfer::HINT);
}
let mut row = Vec::new();
if let Some(url) = track["url"].as_str().filter(|u| track_from_url(u).is_some()) {
let go = twilight_model::channel::message::component::Button { id: None, custom_id: None, disabled: false, emoji: Some(twilight_model::channel::message::EmojiReactionType::Unicode { name: "🎵".into() }), label: Some("Go to song".into()), style: ButtonStyle::Link, url: Some(url.into()), sku_id: None };
let mut listen = button("fm:listen", "Listen to song", ButtonStyle::Primary);
listen.emoji = Some(twilight_model::channel::message::EmojiReactionType::Unicode { name: "🎧".into() });
card = card.row(vec![go, listen]);
row = vec![go, listen];
}
if low {
row.push(transfer::hint_button());
}
if !row.is_empty() {
card = card.row(row);
}
Ok((card.build(), Some(picture)))
}