fm: /fmtransfer (Last.fm CSV to ListenBrainz), faster now-playing card
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
parent
62e8190d8f
commit
f53e84bd24
5 changed files with 399 additions and 21 deletions
|
|
@ -79,3 +79,8 @@ One entry per session, newest last, ≤ 15 lines: done, verified how, not done,
|
|||
- .env DASHBOARD_URL now ends in /dezio; dezio-bot restarted, active, no errors. GET /, /dezio/, /dezio/dashboard, /dezio/terms, /git/ all 200.
|
||||
- Owner still must do the Developer Portal steps (redirect URL, activity mapping, top.gg field).
|
||||
- Fix (2026-12-01): Tailscale strips the `/dezio` prefix, so `/dezio` (no slash) served the page and relative CSS/images broke. Mapping is now `tailscale funnel --bg --set-path /dezio http://127.0.0.1:8080/dezio`; `/dezio` gives 308 to `/dezio/`. Backup: /root/tailscale-serve.bak-2026-12-01b.json. Use `funnel`, not `serve` (serve turns Funnel off).
|
||||
|
||||
## 2026-12-03 — /fmtransfer and a faster /fm
|
||||
- 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 🧑.
|
||||
|
|
|
|||
|
|
@ -1,8 +1,11 @@
|
|||
//! The stats pictures, coloured from the album art so every song looks like itself.
|
||||
use crate::cardart::{blit, gradient, line, png, rounded_cover, tint, wash};
|
||||
use crate::cardart::{blit, gradient, jpeg, line, rounded_cover, tint, wash};
|
||||
use image::RgbaImage;
|
||||
|
||||
pub const FILE: &str = "lastfm.png";
|
||||
/// The now-playing card is mostly album photo: JPEG is ~5x smaller than PNG there, so it uploads in a fraction of the
|
||||
/// time on the server's ~100 KB/s line and still looks clean.
|
||||
pub const NOW_FILE: &str = "lastfm.jpg";
|
||||
|
||||
const W: i32 = 800;
|
||||
const PAD: i32 = 28;
|
||||
|
|
@ -48,7 +51,7 @@ pub fn now_playing(n: &Now) -> Vec<u8> {
|
|||
line(&mut img, "Before this", (x, 276), 14.0, false, SOFT, width);
|
||||
line(&mut img, p, (x, 296), 18.0, false, INK, width);
|
||||
}
|
||||
png(&img)
|
||||
jpeg(&img)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
|
@ -60,15 +63,17 @@ mod tests {
|
|||
|
||||
#[test]
|
||||
fn both_pictures_draw_with_the_album_colour() {
|
||||
let art = RgbaImage::from_fn(300, 300, |x, y| Rgba([180, (x / 2) as u8, (y / 3) as u8, 255]));
|
||||
// a real photo when there is one (PNG vs JPEG size only shows with real detail)
|
||||
let art = image::open("assets/images/banner.jpg").map(|i| i.to_rgba8()).unwrap_or_else(|_| RgbaImage::from_fn(300, 300, |x, y| Rgba([180, (x / 2) as u8, (y / 3) as u8, 255])));
|
||||
let now = now_playing(&Now { status: "Now playing · nightowl".into(), title: "Slow Drive Home".into(), artist: "Marlow Reed".into(), album: Some("Rear View".into()), accent: 0xB4502A, cover: Some(art.clone()), stats: vec![("Scrobbles".into(), "48,210".into()), ("Plays of this track".into(), "37".into())], previous: Some("Paper Lanterns by The Quiet Hours".into()) });
|
||||
let rows = (0..10).map(|i| Row { rank: i + 1, name: format!("Artist name {i}"), by: (i % 2 == 0).then(|| "Someone".to_string()), share: 1.0 - i as f32 * 0.09, value: format!("{} plays", 900 - i * 80) }).collect();
|
||||
let top = chart(&Chart { title: "Top albums · nightowl".into(), note: "Last 30 days".into(), accent: 0x2A7FB4, rows, cover: Some(Arc::new(art)), empty: String::new() });
|
||||
if std::env::var("DEZIO_DUMP").is_ok() {
|
||||
std::fs::write(std::env::temp_dir().join("dezio_fm_now.png"), &now).unwrap();
|
||||
std::fs::write(std::env::temp_dir().join("dezio_fm_now.jpg"), &now).unwrap();
|
||||
std::fs::write(std::env::temp_dir().join("dezio_fm_top.png"), &top).unwrap();
|
||||
}
|
||||
assert!(now.len() > 1000 && top.len() > 1000);
|
||||
assert!(now.len() < 150_000, "now-playing card is {} bytes", now.len());
|
||||
assert_ne!(wash(0xB4502A), wash(0x2A7FB4));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ mod api;
|
|||
mod extras;
|
||||
mod art;
|
||||
mod covers;
|
||||
mod transfer;
|
||||
mod views;
|
||||
|
||||
use self::api::{as_list, best_image, fm_url, Lb};
|
||||
|
|
@ -102,7 +103,7 @@ fn link_prompt(who: Option<u64>) -> Component {
|
|||
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 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, link it here, then bring your Last.fm history over with `/fmtransfer`.");
|
||||
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()
|
||||
|
|
@ -126,7 +127,9 @@ pub(crate) async fn link_account(state: &State, user: u64, username: &str) -> St
|
|||
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)))
|
||||
let count = info["playcount"].as_u64().unwrap_or(0);
|
||||
let hint = if count == 0 { "\n-# No listens yet? Bring your Last.fm history over with `/fmtransfer`." } else { "" };
|
||||
format!("✅ Linked to **{}** ({} listens).{hint}", escape(&name), crate::converters::thousands(count))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -156,7 +159,7 @@ async fn show(ctx: &Arc<Ctx>, mode: &str, user: Id<UserMarker>, kind: &str, peri
|
|||
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, Some(picture))) => ctx.reply_file(card, art::NOW_FILE, picture).await,
|
||||
Ok((card, None)) => ctx.reply(card).await,
|
||||
Err(e) => error(ctx, &e.to_string()).await,
|
||||
};
|
||||
|
|
@ -255,6 +258,8 @@ 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: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" => {
|
||||
let Some(user) = i.author() else { return };
|
||||
let name = interact::modal_values(d).get("username").map(|s| s.trim().to_string()).unwrap_or_default();
|
||||
|
|
@ -293,6 +298,8 @@ pub fn commands() -> Vec<Command> {
|
|||
.usage("<username>")
|
||||
.opt(Opt::opt("username", "Your ListenBrainz username", OptKind::String))
|
||||
.prefix_only(),
|
||||
Command::new("fmtransfer", "lastfm", "Move your Last.fm scrobbles to ListenBrainz: export a CSV, then upload it here.", |c| transfer::fmtransfer(c).boxed())
|
||||
.aliases(&["fmimport", "lastfmtransfer"]),
|
||||
]
|
||||
.into_iter()
|
||||
.chain(extras::commands())
|
||||
|
|
|
|||
356
src/commands/lastfm/transfer.rs
Normal file
356
src/commands/lastfm/transfer.rs
Normal file
|
|
@ -0,0 +1,356 @@
|
|||
//! `/fmtransfer`: bring a Last.fm history over to ListenBrainz.
|
||||
//!
|
||||
//! No linked account → how to make one. Linked → export from Last.fm with CrownNote's exporter (a CSV of
|
||||
//! `"Play count","Artist","Title"`), then "Upload CSV" opens a modal with a file box and a box for the ListenBrainz user
|
||||
//! token. The bot reads the file and sends the listens to ListenBrainz as an import.
|
||||
//!
|
||||
//! The CSV has play counts, not dates, so each play gets a made-up time: back from `ANCHOR`, `STEP` seconds apart, in
|
||||
//! file order. The same file always gives the same times, and ListenBrainz drops a listen it already has (same time
|
||||
//! and song), so sending the same file twice doesn't double anything.
|
||||
use super::api;
|
||||
use crate::cmd::Ctx;
|
||||
use crate::interact;
|
||||
use crate::state::State;
|
||||
use crate::ui::{button, escape, Card, GREEN, RED};
|
||||
use anyhow::Result;
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::HashSet;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
use twilight_model::application::interaction::modal::ModalInteractionData;
|
||||
use twilight_model::application::interaction::Interaction;
|
||||
use twilight_model::channel::message::component::{Button, ButtonStyle, Component, FileUpload, Label};
|
||||
use twilight_model::channel::message::EmojiReactionType;
|
||||
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/";
|
||||
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;
|
||||
/// Seconds between made-up plays: about one song.
|
||||
const STEP: i64 = 180;
|
||||
/// ListenBrainz refuses listens before 2002-10-01 (its `LISTEN_MINIMUM_TS`).
|
||||
const LB_MIN_TS: i64 = 1_033_430_400;
|
||||
const _: () = assert!(ANCHOR - (MAX_LISTENS as i64) * STEP > LB_MIN_TS);
|
||||
/// Listens per request. The API takes 1000; 500 is ~50 KB of JSON, well under a second on the server's ~100 KB/s line.
|
||||
const BATCH: usize = 500;
|
||||
/// At ~100 bytes a listen this is ~20 MB of upload, ~3.5 min at 100 KB/s: done well inside the 15 minutes an
|
||||
/// interaction token lives (progress and the result go through it). Also keeps every time above `LB_MIN_TS`.
|
||||
const MAX_LISTENS: u64 = 200_000;
|
||||
/// The file is read into memory; a 200k-play library as CSV is a few hundred KB, so 8 MiB is plenty.
|
||||
const MAX_FILE: u64 = 8 * 1024 * 1024;
|
||||
/// Sends per batch before giving up (rate limits, a dropped connection). Safe to repeat: ListenBrainz drops duplicates.
|
||||
const TRIES: usize = 3;
|
||||
/// Longest wait for a rate-limit window to reset.
|
||||
const MAX_RATE_WAIT: u64 = 60;
|
||||
/// Update the progress message every this many batches (~1 edit per 10k listens).
|
||||
const PROGRESS_EVERY: usize = 20;
|
||||
|
||||
/// One CSV row: `plays` listens of a song.
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub struct Row {
|
||||
pub plays: u64,
|
||||
pub artist: String,
|
||||
pub title: String,
|
||||
pub album: Option<String>,
|
||||
}
|
||||
|
||||
/// Split CSV text into records: commas, quoted fields with `""` escapes and newlines inside quotes.
|
||||
fn records(text: &str) -> Vec<Vec<String>> {
|
||||
let (mut out, mut rec, mut field, mut quoted) = (Vec::new(), Vec::new(), String::new(), false);
|
||||
let mut chars = text.trim_start_matches('\u{feff}').chars().peekable();
|
||||
while let Some(c) = chars.next() {
|
||||
match (c, quoted) {
|
||||
('"', true) if chars.peek() == Some(&'"') => {
|
||||
field.push('"');
|
||||
chars.next();
|
||||
}
|
||||
('"', _) => quoted = !quoted,
|
||||
(',', false) => rec.push(std::mem::take(&mut field)),
|
||||
('\r', false) => {}
|
||||
('\n', false) => {
|
||||
rec.push(std::mem::take(&mut field));
|
||||
out.push(std::mem::take(&mut rec));
|
||||
}
|
||||
_ => field.push(c),
|
||||
}
|
||||
}
|
||||
if !field.is_empty() || !rec.is_empty() {
|
||||
rec.push(field);
|
||||
out.push(rec);
|
||||
}
|
||||
out.retain(|r| r.iter().any(|f| !f.trim().is_empty()));
|
||||
out
|
||||
}
|
||||
|
||||
/// Rows from the export, and how many lines were skipped. Columns are found by their header (any order); without a
|
||||
/// play-count column each row is one play.
|
||||
pub fn parse(text: &str) -> Result<(Vec<Row>, usize), String> {
|
||||
let recs = records(text);
|
||||
let Some((head, body)) = recs.split_first() else { return Err("That file is empty.".into()) };
|
||||
let head: Vec<String> = head.iter().map(|h| h.trim().to_lowercase()).collect();
|
||||
let col = |names: &[&str]| head.iter().position(|h| names.contains(&h.as_str()));
|
||||
let (Some(artist), Some(title)) = (col(&["artist", "artist name"]), col(&["title", "track", "track name", "song", "name"])) else {
|
||||
return Err("I couldn't find the Artist and Title columns. Export the file with the CrownNote Last.fm exporter.".into());
|
||||
};
|
||||
let plays = col(&["play count", "plays", "playcount", "scrobbles", "count"]);
|
||||
let album = col(&["album", "album name"]);
|
||||
let (mut rows, mut skipped) = (Vec::new(), 0);
|
||||
for r in body {
|
||||
let get = |i: usize| r.get(i).map(|s| s.trim().to_string()).unwrap_or_default();
|
||||
let n = match plays {
|
||||
Some(i) => get(i).replace(',', "").parse::<u64>().ok(),
|
||||
None => Some(1),
|
||||
};
|
||||
let (a, t) = (get(artist), get(title));
|
||||
match n {
|
||||
Some(n) if n > 0 && !a.is_empty() && !t.is_empty() => {
|
||||
rows.push(Row { plays: n, artist: a, title: t, album: album.map(get).filter(|s| !s.is_empty()) })
|
||||
}
|
||||
_ => skipped += 1,
|
||||
}
|
||||
}
|
||||
if rows.is_empty() {
|
||||
return Err("I found no songs in that file.".into());
|
||||
}
|
||||
Ok((rows, skipped))
|
||||
}
|
||||
|
||||
/// Every play as a ListenBrainz listen, newest first from `ANCHOR`.
|
||||
fn listens(rows: &[Row]) -> impl Iterator<Item = Value> + '_ {
|
||||
rows.iter().flat_map(|r| std::iter::repeat_n(r, r.plays as usize)).enumerate().map(|(n, r)| {
|
||||
let mut meta = json!({"artist_name": r.artist, "track_name": r.title});
|
||||
if let Some(a) = &r.album {
|
||||
meta["release_name"] = json!(a);
|
||||
}
|
||||
json!({"listened_at": ANCHOR - n as i64 * STEP, "track_metadata": meta})
|
||||
})
|
||||
}
|
||||
|
||||
// ---- cards and the modal ------------------------------------------------------------------------------------------
|
||||
|
||||
fn url_button(label: &str, emoji: &str, url: &str) -> Button {
|
||||
Button { id: None, custom_id: None, disabled: false, emoji: Some(EmojiReactionType::Unicode { name: emoji.into() }), label: Some(label.into()), style: ButtonStyle::Link, url: Some(url.into()), sku_id: None }
|
||||
}
|
||||
|
||||
fn with_emoji(mut b: Button, emoji: &str) -> Button {
|
||||
b.emoji = Some(EmojiReactionType::Unicode { name: emoji.into() });
|
||||
b
|
||||
}
|
||||
|
||||
/// For someone with no linked ListenBrainz account: how to make one.
|
||||
fn signup_card() -> Component {
|
||||
let text = "### 🎧 Make a ListenBrainz account first\n\
|
||||
Dezio reads your music stats from ListenBrainz (free, no ads).\n\
|
||||
1. Open **Sign up** below and press **Sign in**, then **Create an account** (it's a MusicBrainz account).\n\
|
||||
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()
|
||||
}
|
||||
|
||||
/// For a linked account: export from Last.fm, then upload the file.
|
||||
fn transfer_card(username: &str, count: u64) -> Component {
|
||||
let state = if count == 0 {
|
||||
format!("**{}** has no listens yet. Bring your Last.fm history over:", escape(username))
|
||||
} else {
|
||||
format!("**{}** already has {} listens. You can still add your Last.fm history:", escape(username), crate::converters::thousands(count))
|
||||
};
|
||||
let text = format!(
|
||||
"### 📦 Transfer from Last.fm\n{state}\n\
|
||||
1. Open **Export Last.fm**, type your Last.fm username and download the CSV.\n\
|
||||
2. Open **Get token** and copy your **User token** (ListenBrainz settings).\n\
|
||||
3. Press **Upload CSV**, add the file and paste the token.\n\
|
||||
-# The file has play counts, not dates, so plays are dated back from 1 Jan 2025, 3 min apart: they count in all-time stats. \
|
||||
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()
|
||||
}
|
||||
|
||||
fn form() -> Vec<Component> {
|
||||
let file = FileUpload { id: None, custom_id: "file".into(), max_values: Some(1), min_values: Some(1), required: Some(true) };
|
||||
vec![
|
||||
Component::Label(Label { id: None, label: "Last.fm export (CSV)".into(), description: Some("The file from the CrownNote Last.fm exporter".into()), component: Box::new(Component::FileUpload(file)) }),
|
||||
interact::text_field("token", "ListenBrainz user token", Some("listenbrainz.org/settings → User token"), "", 64, false, Some("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx")),
|
||||
]
|
||||
}
|
||||
|
||||
pub async fn fmtransfer(ctx: Arc<Ctx>) -> Result<()> {
|
||||
let card = match api::linked(ctx.user_id.get()) {
|
||||
None => signup_card(),
|
||||
Some(name) => {
|
||||
ctx.defer_private().await?;
|
||||
let count = super::lfm(&ctx.state).user_info(&name).await.map(|i| i["playcount"].as_u64().unwrap_or(0)).unwrap_or(0);
|
||||
transfer_card(&name, count)
|
||||
}
|
||||
};
|
||||
if ctx.is_slash() { ctx.reply_private(card).await } else { ctx.reply(card).await }
|
||||
}
|
||||
|
||||
pub async fn open_form(state: &State, i: &Interaction) {
|
||||
interact::modal(state, i, "fm:xferform", "Transfer from Last.fm", form()).await;
|
||||
}
|
||||
|
||||
// ---- the import ------------------------------------------------------------------------------------------------------
|
||||
|
||||
/// People with an import running (one each: two at once would just race the same rate limit).
|
||||
fn running() -> &'static Mutex<HashSet<u64>> {
|
||||
static R: std::sync::OnceLock<Mutex<HashSet<u64>>> = std::sync::OnceLock::new();
|
||||
R.get_or_init(Default::default)
|
||||
}
|
||||
|
||||
async fn say(state: &State, i: &Interaction, text: &str) {
|
||||
if let Err(e) = state.http.interaction(state.app_id()).update_response(&i.token).content(Some(text)).await {
|
||||
tracing::warn!("fmtransfer progress edit failed: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The account a token belongs to.
|
||||
async fn token_owner(web: &reqwest::Client, token: &str) -> Result<String, String> {
|
||||
let r = web.get(format!("{API_URL}/validate-token")).header("Authorization", format!("Token {token}")).timeout(Duration::from_secs(15)).send().await;
|
||||
let v: Value = match r {
|
||||
Ok(r) if r.status().is_server_error() => return Err("ListenBrainz isn't responding right now — try again in a moment.".into()),
|
||||
Ok(r) => r.json().await.unwrap_or_default(),
|
||||
Err(_) => return Err("ListenBrainz isn't responding right now — try again in a moment.".into()),
|
||||
};
|
||||
match (v["valid"].as_bool(), v["user_name"].as_str()) {
|
||||
(Some(true), Some(name)) => Ok(name.to_string()),
|
||||
_ => Err(format!("That token isn't valid. Copy the **User token** from <{TOKEN_URL}>.")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Send one batch, waiting out rate limits. Err = a message for the user.
|
||||
async fn submit(web: &reqwest::Client, token: &str, batch: &[Value]) -> Result<(), String> {
|
||||
let body = json!({"listen_type": "import", "payload": batch});
|
||||
for attempt in 1..=TRIES {
|
||||
let r = web.post(format!("{API_URL}/submit-listens")).header("Authorization", format!("Token {token}")).json(&body).timeout(Duration::from_secs(60)).send().await;
|
||||
let wait = match r {
|
||||
Ok(r) if r.status().is_success() => {
|
||||
// nearly out of requests in this window: pause so the next batch isn't refused
|
||||
let h = |k: &str| r.headers().get(k).and_then(|v| v.to_str().ok()?.parse::<u64>().ok());
|
||||
if h("x-ratelimit-remaining") == Some(0) {
|
||||
tokio::time::sleep(Duration::from_secs(h("x-ratelimit-reset-in").unwrap_or(5).min(MAX_RATE_WAIT) + 1)).await;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
Ok(r) if r.status() == 429 => r.headers().get("x-ratelimit-reset-in").and_then(|v| v.to_str().ok()?.parse::<u64>().ok()).unwrap_or(10).min(MAX_RATE_WAIT) + 1,
|
||||
Ok(r) if r.status() == 401 => return Err(format!("ListenBrainz refused the token. Copy the **User token** from <{TOKEN_URL}>.")),
|
||||
Ok(r) if r.status().is_client_error() => {
|
||||
let msg = r.json::<Value>().await.ok().and_then(|v| v["error"].as_str().map(str::to_string)).unwrap_or_else(|| "unknown error".into());
|
||||
return Err(format!("ListenBrainz refused the listens: {}", escape(&msg)));
|
||||
}
|
||||
_ => 3 * attempt as u64,
|
||||
};
|
||||
if attempt < TRIES {
|
||||
tokio::time::sleep(Duration::from_secs(wait)).await;
|
||||
}
|
||||
}
|
||||
Err("ListenBrainz kept failing".into())
|
||||
}
|
||||
|
||||
async fn import(state: &State, i: &Interaction, d: &ModalInteractionData) -> Result<String, String> {
|
||||
let fields = interact::modal_values(d);
|
||||
let token = fields.get("token").map(|t| t.trim().to_string()).unwrap_or_default();
|
||||
let attachment = fields.get("file").and_then(|id| id.parse::<u64>().ok()).and_then(|id| d.resolved.as_ref()?.attachments.get(&Id::new_checked(id)?).cloned());
|
||||
let Some(file) = attachment else { return Err("Add the CSV file from the exporter.".into()) };
|
||||
if token.is_empty() {
|
||||
return Err(format!("Paste your ListenBrainz **User token** (from <{TOKEN_URL}>)."));
|
||||
}
|
||||
if file.size > MAX_FILE {
|
||||
return Err("That file is too big for a Last.fm export (8 MB max).".into());
|
||||
}
|
||||
let web = &state.web;
|
||||
let owner = token_owner(web, &token).await?;
|
||||
let text = match web.get(&file.url).timeout(Duration::from_secs(60)).send().await {
|
||||
Ok(r) if r.status().is_success() => r.text().await.map_err(|_| "I couldn't read that file.".to_string())?,
|
||||
_ => return Err("I couldn't download that file from Discord — try again.".into()),
|
||||
};
|
||||
let (rows, skipped) = parse(&text)?;
|
||||
let total: u64 = rows.iter().map(|r| r.plays).sum();
|
||||
if total > MAX_LISTENS {
|
||||
return Err(format!("That's {} plays; I can send up to {} at once. Split the file and upload the parts.", crate::converters::thousands(total), crate::converters::thousands(MAX_LISTENS)));
|
||||
}
|
||||
let who = escape(&owner);
|
||||
say(state, i, &format!("⏳ Sending {} plays ({} songs) to **{who}**…", crate::converters::thousands(total), rows.len())).await;
|
||||
let all: Vec<Value> = listens(&rows).collect();
|
||||
let mut sent = 0;
|
||||
for (n, batch) in all.chunks(BATCH).enumerate() {
|
||||
if let Err(e) = submit(web, &token, batch).await {
|
||||
return Err(format!("{e}. {} of {} plays were sent; upload the same file again to finish (sent plays won't double).", crate::converters::thousands(sent), crate::converters::thousands(total)));
|
||||
}
|
||||
sent += batch.len() as u64;
|
||||
if (n + 1) % PROGRESS_EVERY == 0 {
|
||||
say(state, i, &format!("⏳ Sending to **{who}**: {} / {} plays…", crate::converters::thousands(sent), crate::converters::thousands(total))).await;
|
||||
}
|
||||
}
|
||||
let user = i.author().map(|u| u.id.get());
|
||||
if let Some(u) = user.filter(|u| api::linked(*u).is_none()) {
|
||||
api::set_link(u, Some(&owner));
|
||||
}
|
||||
let skipped = if skipped > 0 { format!(" Skipped {skipped} line(s) with no artist, title or play count.") } else { String::new() };
|
||||
Ok(format!(
|
||||
"✅ Sent {} plays of {} songs to **{who}**.{skipped}\n-# ListenBrainz adds imports to your stats within a day; new listens show up right away in `/fm recent`.",
|
||||
crate::converters::thousands(total),
|
||||
rows.len()
|
||||
))
|
||||
}
|
||||
|
||||
pub async fn on_submit(state: &Arc<State>, i: &Interaction, d: &ModalInteractionData) {
|
||||
let Some(user) = i.author().map(|u| u.id.get()) else { return };
|
||||
if !running().lock().unwrap_or_else(|e| e.into_inner()).insert(user) {
|
||||
return interact::private_text(state, i, "Your last transfer is still running — wait for it to finish.").await;
|
||||
}
|
||||
interact::defer_private(state, i).await;
|
||||
let result = import(state, i, d).await;
|
||||
running().lock().unwrap_or_else(|e| e.into_inner()).remove(&user);
|
||||
match result {
|
||||
Ok(text) => say(state, i, &text).await,
|
||||
Err(text) => say(state, i, &format!("❌ {text}")).await,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn crownnote_export_parses() {
|
||||
let csv = "\u{feff}\"Play count\",\"Artist\",\"Title\"\r\n\"529\",\"System of a Down\",\"Question!\"\r\n\"3\",\"Linkin Park,\",\"Say \"\"Hi\"\"\"\n\"x\",\"A\",\"B\"\n\"2\",\"\",\"No artist\"\n";
|
||||
let (rows, skipped) = parse(csv).unwrap();
|
||||
assert_eq!(rows, vec![
|
||||
Row { plays: 529, artist: "System of a Down".into(), title: "Question!".into(), album: None },
|
||||
Row { plays: 3, artist: "Linkin Park,".into(), title: "Say \"Hi\"".into(), album: None },
|
||||
]);
|
||||
assert_eq!(skipped, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn columns_found_by_header_and_count_defaults_to_one() {
|
||||
let (rows, _) = parse("Track,Album,Artist\nSugar,Toxicity,System of a Down\n").unwrap();
|
||||
assert_eq!(rows, vec![Row { plays: 1, artist: "System of a Down".into(), title: "Sugar".into(), album: Some("Toxicity".into()) }]);
|
||||
assert!(parse("a,b\n1,2\n").is_err());
|
||||
assert!(parse("").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn listens_are_dated_back_from_the_anchor() {
|
||||
let rows = vec![Row { plays: 2, artist: "A".into(), title: "T".into(), album: None }, Row { plays: 1, artist: "B".into(), title: "U".into(), album: Some("R".into()) }];
|
||||
let l: Vec<Value> = listens(&rows).collect();
|
||||
assert_eq!(l.len(), 3);
|
||||
assert_eq!(l[0]["listened_at"], ANCHOR);
|
||||
assert_eq!(l[2]["listened_at"], ANCHOR - 2 * STEP);
|
||||
assert_eq!(l[2]["track_metadata"], json!({"artist_name": "B", "track_name": "U", "release_name": "R"}));
|
||||
}
|
||||
|
||||
/// The owner's real export: `DEZIO_FM_CSV=/path/to.csv cargo test fm_csv_file -- --ignored --nocapture`
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn fm_csv_file() {
|
||||
let path = std::env::var("DEZIO_FM_CSV").expect("set DEZIO_FM_CSV");
|
||||
let (rows, skipped) = parse(&std::fs::read_to_string(path).unwrap()).unwrap();
|
||||
println!("{} songs, {} plays, {skipped} skipped", rows.len(), rows.iter().map(|r| r.plays).sum::<u64>());
|
||||
}
|
||||
}
|
||||
|
|
@ -54,15 +54,19 @@ pub async fn now_playing(b: &Base) -> Result<(Component, Option<Vec<u8>>), Error
|
|||
let title = track["name"].as_str().unwrap_or("Unknown track");
|
||||
let album = track["album"]["#text"].as_str().filter(|a| !a.is_empty());
|
||||
let playing = track["@attr"]["nowplaying"].as_str() == Some("true");
|
||||
let found = b.api.plays(&b.username, "track", title, Some(artist), track["mbids"]["recording"].as_str()).await.ok().flatten();
|
||||
let plays = found.as_ref().map(|p| p.0).filter(|p| *p > 0);
|
||||
// some players send no album; Deezer knows which one the track is on
|
||||
let looked_up = match album {
|
||||
None => super::covers::album_name(&b.state, artist, title).await,
|
||||
Some(_) => None,
|
||||
// the play count, the album name and the cover are separate lookups: run them together
|
||||
let album_lookup = async {
|
||||
match album {
|
||||
// some players send no album; Deezer knows which one the track is on
|
||||
None => super::covers::album_name(&b.state, artist, title).await,
|
||||
Some(_) => None,
|
||||
}
|
||||
};
|
||||
let (found, looked_up, cover) = tokio::join!(b.api.plays(&b.username, "track", title, Some(artist), track["mbids"]["recording"].as_str()), album_lookup, super::covers::cover(&b.state, track));
|
||||
let found = found.ok().flatten();
|
||||
let plays = found.as_ref().map(|p| p.0).filter(|p| *p > 0);
|
||||
let album = album.or(looked_up.as_deref());
|
||||
let cover = match super::covers::cover(&b.state, track).await {
|
||||
let cover = match cover {
|
||||
Some(c) => Some(c),
|
||||
// their stats for the same track may carry a cover the listen doesn't
|
||||
None => match &found {
|
||||
|
|
@ -70,14 +74,15 @@ pub async fn now_playing(b: &Base) -> Result<(Component, Option<Vec<u8>>), Error
|
|||
None => None,
|
||||
},
|
||||
};
|
||||
let accent = colors::accent(&b.state, cover.as_deref(), GREEN).await;
|
||||
let art_image = match &cover {
|
||||
Some(url) => match crate::commands::media::fetch_limited(&b.state, url, 4 * 1024 * 1024).await {
|
||||
Some(bytes) => tokio::task::spawn_blocking(move || crate::pix::decode(&bytes)).await.ok().flatten(),
|
||||
None => None,
|
||||
},
|
||||
// one download for both the picture and its colour
|
||||
let bytes = match &cover {
|
||||
Some(url) => crate::commands::media::fetch_limited(&b.state, url, 4 * 1024 * 1024).await,
|
||||
None => None,
|
||||
};
|
||||
let (accent, art_image) = match bytes {
|
||||
Some(bytes) => tokio::task::spawn_blocking(move || (colors::pick(&bytes).unwrap_or(GREEN), crate::pix::decode(&bytes))).await.unwrap_or((GREEN, None)),
|
||||
None => (GREEN, None),
|
||||
};
|
||||
let status = if playing { format!("Now playing · {}", b.name) } else { format!("Last played · {}", b.name) };
|
||||
let mut stats = vec![("Listens".to_string(), thousands(num(&info, "playcount")))];
|
||||
if let Some(p) = plays {
|
||||
|
|
@ -97,7 +102,7 @@ pub async fn now_playing(b: &Base) -> Result<(Component, Option<Vec<u8>>), Error
|
|||
None => format!("-# {previous} Last played · {}", escape(&b.name)),
|
||||
}
|
||||
};
|
||||
let mut card = Card::new(Some(accent)).text(&heading).gallery(&[&format!("attachment://{}", super::art::FILE)]).footer(&links.join(" · "));
|
||||
let mut card = Card::new(Some(accent)).text(&heading).gallery(&[&format!("attachment://{}", super::art::NOW_FILE)]).footer(&links.join(" · "));
|
||||
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);
|
||||
|
|
|
|||
Loading…
Reference in a new issue