From dc0184b0c00eef7db9ecb65fade792f30cb76933 Mon Sep 17 00:00:00 2001 From: NoLogicAlan Date: Tue, 19 May 2026 18:40:49 +0300 Subject: [PATCH] feat: add Last.fm URL support and improve track search accuracy - Add Last.fm URL parsing to %play command (e.g. %play https://last.fm/music/Drake/_/Make+Them+Cry) - Add freeform Last.fm search via %play lastfm: (e.g. %play lastfm:soda pop) - Pass trackMeta through Player.play() for accurate scrobbling from Last.fm results - Improve searchTrack() scoring to penalize non-song results (lyric videos, official videos, covers, remixes) - Penalize label/production company artists (e.g. "Sony Pictures Animation") in search results - Penalize quoted track names (e.g. "Soda Pop" Official Lyric Video) - Prefer clean /music/Artist/_/Track URL format in Last.fm search ranking --- commands/play.mjs | 190 +++++++++++++++++++++++++++++++++++++++++- commands/playnext.mjs | 2 +- commands/search.mjs | 2 +- src/LastFmManager.mjs | 133 +++++++++++++++++++++++++++++ src/Player.mjs | 6 +- 5 files changed, 327 insertions(+), 6 deletions(-) diff --git a/commands/play.mjs b/commands/play.mjs index bec7866..e442236 100644 --- a/commands/play.mjs +++ b/commands/play.mjs @@ -4,6 +4,65 @@ import { getGlobalColor } from "../src/MessageHandler.mjs"; import { PROVIDER_CHOICES } from "../src/constants/providers.mjs"; import { playLastFmCategory } from "./lastfm.mjs"; +/** + * Parse a Last.fm music URL and extract artist and track info. + * Supports: + * https://www.last.fm/music/Drake/ICEMAN/Make+Them+Cry + * https://www.last.fm/music/SAJA+BOYS/_/Soda+Pop + * https://www.last.fm/music/Drake/_/Make+Them+Cry ("_" = album placeholder) + * https://www.last.fm/music/Drake (artist only) + * + * @param {string} url + * @returns {{ artist: string, track: string|null, album: string|null, url: string } | null} + */ +function parseLastFmUrl(url) { + try { + const u = new URL(url); + if (!/^(?:www\.)?last\.fm$/i.test(u.hostname)) return null; + + // Path format: /music/Artist[/Album][/Track] + // Or: /music/Artist/_/Track (underscore = album placeholder) + const match = u.pathname.match(/^\/music\/([^/]+)(?:\/([^/]+))?(?:\/([^/]+))?/); + if (!match) return null; + + const artist = decodeURIComponent(match[1].replace(/\+/g, " ")); + const segment2 = match[2] ? decodeURIComponent(match[2].replace(/\+/g, " ")) : null; + const segment3 = match[3] ? decodeURIComponent(match[3].replace(/\+/g, " ")) : null; + + let track = null; + let album = null; + + if (segment3) { + // /music/Artist/Album/Track or /music/Artist/_/Track + album = segment2 === "_" ? null : segment2; + track = segment3; + } else if (segment2 && segment2 !== "_") { + // /music/Artist/Track (no album segment) + // Could be an album page or track page — treat as track if short enough + track = segment2; + } + + return { artist, track, album, url }; + } catch { + return null; + } +} + +/** + * Check if a string is a Last.fm music URL. + * @param {string} str + * @returns {boolean} + */ +function isLastFmUrl(str) { + if (!str || typeof str !== "string") return false; + try { + const u = new URL(str); + return /^(?:www\.)?last\.fm$/i.test(u.hostname) && /^\/music\//.test(u.pathname); + } catch { + return false; + } +} + // Last.fm provider keywords that trigger special play logic const LASTFM_PLAY_CATEGORIES = ["loved", "top", "recent", "albums"]; @@ -109,7 +168,9 @@ export const command = new CommandBuilder() "$prefixplay dz: get lucky", "$prefixplay -p yt take over league of legends", "$prefixplay https://open.spotify.com/track/...", + "$prefixplay https://www.last.fm/music/Drake/_/Make+Them+Cry", "$prefixplay lastfm:loved", + "$prefixplay lastfm:soda pop", "$prefixplay lastfm:td:top", "$prefixplay lastfm:sp", "$prefixplay lastfm:lf:loved", @@ -125,7 +186,7 @@ export const command = new CommandBuilder() .setDescription("The search provider. Default: YouTube Music. Or use inline prefix: sp:, dz:, am:, yt:, sc: etc.", "options.play.provider") .addFlagAliases("p", "u", "use") .addChoices(...PROVIDER_CHOICES) - .setDefault("yt") + .setDefault("ytm") , true) .addAlias("p"); @@ -135,6 +196,68 @@ export async function run(message, data) { const { provider: inlineProvider, query } = parseInlineProvider(rawQuery); const provider = inlineProvider ?? flagProvider ?? "ytm"; + // ── Last.fm URL detection ──────────────────────────────────────────────── + // If the raw query (or extracted query) is a Last.fm URL, parse it to get + // the artist and track name, then play it through the normal search pipeline + // with Last.fm metadata attached for accurate scrobbling. + // + // Examples: + // %play https://www.last.fm/music/Drake/ICEMAN/Make+Them+Cry + // %play https://www.last.fm/music/SAJA+BOYS/_/Soda+Pop + if (isLastFmUrl(rawQuery) || isLastFmUrl(query)) { + const lfUrl = isLastFmUrl(rawQuery) ? rawQuery : query; + const parsed = parseLastFmUrl(lfUrl); + + if (parsed && parsed.track) { + // We have artist + track — search using the combined query with Last.fm metadata + const lastfmTrackMeta = { + artist: parsed.artist, + name: parsed.track, + source: "lastfm", + url: parsed.url, + }; + + const p = await this.getPlayer(message, true, true, true); + if (!p) return; + + const searchEmbed = new EmbedBuilder() + .setColor(getGlobalColor()) + .setDescription(this.t(message, "responses.play.searching")); + let statusMsg = null; + try { statusMsg = await message.reply({ embeds: [searchEmbed] }); } catch {} + + const playQuery = `${parsed.track} ${parsed.artist}`.trim(); + const messages = p.play(playQuery, false, provider === "lastfm" || provider === "lf" ? "yt" : provider, lastfmTrackMeta); + messages.on("message", d => { + const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(d); + if (statusMsg) { statusMsg.edit({ embeds: [embed] }).catch(() => {}); } + else { message.reply({ embeds: [embed] }).catch(() => {}); } + }); + return; + } + + if (parsed && !parsed.track) { + // Artist-only URL (e.g. /music/Drake) — search for the artist + const p = await this.getPlayer(message, true, true, true); + if (!p) return; + + const searchEmbed = new EmbedBuilder() + .setColor(getGlobalColor()) + .setDescription(this.t(message, "responses.play.searching")); + let statusMsg = null; + try { statusMsg = await message.reply({ embeds: [searchEmbed] }); } catch {} + + const playQuery = parsed.artist; + const messages = p.play(playQuery, false, provider === "lastfm" || provider === "lf" ? "yt" : provider); + messages.on("message", d => { + const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(d); + if (statusMsg) { statusMsg.edit({ embeds: [embed] }).catch(() => {}); } + else { message.reply({ embeds: [embed] }).catch(() => {}); } + }); + return; + } + } + // ── Last.fm special provider: %play lastfm:loved / lastfm:top / lastfm:recent / lastfm:playlist 1 ── // Also supports sub-provider syntax: %play lastfm:td:top (play Last.fm top tracks, search on Tidal) // Bare provider defaults: %play lastfm:sp → top tracks on Spotify, %play lastfm:td → top tracks on Tidal @@ -183,6 +306,71 @@ export async function run(message, data) { resolveProvider, }); } + + // ── Freeform Last.fm search: %play lastfm:soda pop or %play lastfm:drake make them cry ── + // If the query after lastfm: is NOT a recognized category, treat it as a + // freeform track search on Last.fm. This uses Last.fm's track.search API + // to find the best match, then resolves it for playback. + if (lowerQuery && !LASTFM_PLAY_CATEGORIES.includes(lowerQuery) && !lowerQuery.startsWith("playlist")) { + const lastfm = this.lastfm; + if (lastfm && lastfm.enabled) { + // Try to parse as "track by artist" or "artist - track" first + const trackMeta = parseLastFmTrackQuery(query); + let searchResult; + + if (trackMeta) { + // Direct artist+track from the query — use it directly + searchResult = { artist: trackMeta.artist, name: trackMeta.name, url: "" }; + } else { + // Freeform query — search Last.fm for the best match + let statusMsg = null; + try { + statusMsg = await message.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription( + `🔍 Searching Last.fm for **${query}**...` + )] + }); + } catch {} + + try { + searchResult = await lastfm.searchTrack(query); + } catch {} + + if (!searchResult) { + const noResult = { embeds: [new EmbedBuilder().setColor("#ff0000").setDescription( + `❌ No results found on Last.fm for **${query}**.` + )] }; + if (statusMsg) statusMsg.edit(noResult).catch(() => message.reply(noResult)); + else message.reply(noResult); + return; + } + } + + // We have a Last.fm result — play it using the combined query with metadata + const lastfmTrackMeta = { + artist: searchResult.artist, + name: searchResult.name, + source: "lastfm", + url: searchResult.url ?? "", + }; + + const playProvider = resolveProvider && resolveProvider !== "lf" && resolveProvider !== "lastfm" + ? resolveProvider + : "yt"; + + const p = await this.getPlayer(message, true, true, true); + if (!p) return; + + const playQuery = `${searchResult.name} ${searchResult.artist}`.trim(); + const messages = p.play(playQuery, false, playProvider, lastfmTrackMeta); + messages.on("message", d => { + const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(d); + if (statusMsg) { statusMsg.edit({ embeds: [embed] }).catch(() => {}); } + else { message.reply({ embeds: [embed] }).catch(() => {}); } + }); + return; + } + } } const resolvedProvider = diff --git a/commands/playnext.mjs b/commands/playnext.mjs index 1fadc42..8e3eca8 100644 --- a/commands/playnext.mjs +++ b/commands/playnext.mjs @@ -33,7 +33,7 @@ export const command = new CommandBuilder() .setDescription("The search provider. Default: YouTube Music.", "options.playnext.provider") .addFlagAliases("p", "u", "use") .addChoices(...PROVIDER_CHOICES) - .setDefault("yt") + .setDefault("ytm") , true) .addAlias("pn"); diff --git a/commands/search.mjs b/commands/search.mjs index 4ed1a92..e357199 100644 --- a/commands/search.mjs +++ b/commands/search.mjs @@ -33,7 +33,7 @@ export const command = new CommandBuilder() o.setName("provider") .setDescription("The search provider. Default: YouTube Music.", "options.search.provider") .addChoices(...PROVIDER_CHOICES) - .setDefault("yt") + .setDefault("ytm") .addFlagAliases("p", "u", "use") , true) .addTextOption(o => diff --git a/src/LastFmManager.mjs b/src/LastFmManager.mjs index 8664294..3321a82 100644 --- a/src/LastFmManager.mjs +++ b/src/LastFmManager.mjs @@ -590,6 +590,8 @@ export class LastFmManager { const combined = `${artistNorm} ${nameNorm}`.trim(); let score = 0; + + // ── Positive matching ──────────────────────────────────────────────── if (combined === normalizedQuery) score += 50; if (combined.includes(normalizedQuery) && normalizedQuery) score += 25; if (normalizedQuery.includes(nameNorm) && nameNorm) score += 15; @@ -598,6 +600,79 @@ export class LastFmManager { const overlap = queryTokens.filter(token => combined.includes(token)).length; score += overlap * 4; + // ── Penalize non-song results ──────────────────────────────────────── + // Track names that contain these phrases are usually lyric videos, + // official videos, or other non-song entries that shouldn't be the + // top result when a user is searching for the actual song. + const nameLower = name.toLowerCase(); + const artistLower = artist.toLowerCase(); + const urlLower = String(track.url ?? "").toLowerCase(); + const fullText = `${nameLower} ${artistLower} ${urlLower}`; + + const negativePatterns = [ + /\bofficial (?:lyric|lyrics)\s*video\b/, + /\bofficial video\b/, + /\bofficial music video\b/, + /\blyric video\b/, + /\blyrics video\b/, + /\bmusic video\b/, + /\bofficial audio\b/, // some entries are titled "Official Audio" on last.fm + /\bvisuali[sz]er\b/, + /\bkaraoke\b/, + /\bcover\b/, + /\bremix\b/, + /\bacoustic\b/, + /\blive\b/, + /\bsped up\b/, + /\bslowed\b/, + /\breverb\b/, + /\bnightcore\b/, + /\b8d\b/, + /\bclip officiel\b/, // French official video + /\bvideo oficial\b/, // Spanish/Portuguese official video + /\bperformance\b/, + ]; + + for (const re of negativePatterns) { + if (re.test(fullText)) { + score -= 30; + break; // only penalize once per track + } + } + + // Penalize results where the artist is a label/production company + // instead of the actual artist (e.g. "Sony Pictures Animation") + const labelKeywords = [ + /\bpictures\b/i, + /\banimation\b/i, + /\brecords?\b/i, + /\bstudios?\b/i, + /\bentertainment\b/i, + /\bproductions?\b/i, + /\bmusic\s+(group|corp|inc|llc)\b/i, + /\brecordings?\b/i, + /\blabel\b/i, + ]; + for (const re of labelKeywords) { + if (re.test(artist)) { + score -= 20; + break; + } + } + + // Penalize results where the track name is wrapped in quotes + // (e.g. '"Soda Pop" Official Lyric Video' — the quotes indicate + // it's a video title, not the actual track name) + if (/^["""].*["""]$/.test(name) || /["""]/.test(name)) { + score -= 15; + } + + // Prefer results that have a clean /music/Artist/_/Track URL format + // (actual tracks) over /music/Artist/Track+Extra+Stuff (video entries) + if (urlLower.includes("/_/")) { + score += 5; // Clean track URL format + } + return { index, score, @@ -613,6 +688,64 @@ export class LastFmManager { return scored[0]?.track ?? null; } + /** + * Parse a Last.fm music URL and extract artist and track info. + * Supports: + * https://www.last.fm/music/Drake/ICEMAN/Make+Them+Cry + * https://www.last.fm/music/SAJA+BOYS/_/Soda+Pop + * https://www.last.fm/music/Drake/_/Make+Them+Cry ("_" = album placeholder) + * https://www.last.fm/music/Drake (artist only) + * + * @param {string} url + * @returns {{ artist: string, track: string|null, album: string|null, url: string } | null} + */ + parseLastFmUrl(url) { + try { + const u = new URL(url); + if (!/^(?:www\.)?last\.fm$/i.test(u.hostname)) return null; + + // Path format: /music/Artist[/Album][/Track] + // Or: /music/Artist/_/Track (underscore = album placeholder) + const match = u.pathname.match(/^\/music\/([^/]+)(?:\/([^/]+))?(?:\/([^/]+))?/); + if (!match) return null; + + const artist = decodeURIComponent(match[1].replace(/\+/g, " ")); + const segment2 = match[2] ? decodeURIComponent(match[2].replace(/\+/g, " ")) : null; + const segment3 = match[3] ? decodeURIComponent(match[3].replace(/\+/g, " ")) : null; + + let track = null; + let album = null; + + if (segment3) { + // /music/Artist/Album/Track or /music/Artist/_/Track + album = segment2 === "_" ? null : segment2; + track = segment3; + } else if (segment2 && segment2 !== "_") { + // /music/Artist/Track (no album segment) + track = segment2; + } + + return { artist, track, album, url }; + } catch { + return null; + } + } + + /** + * Check if a string is a Last.fm music URL. + * @param {string} str + * @returns {boolean} + */ + isLastFmUrl(str) { + if (!str || typeof str !== "string") return false; + try { + const u = new URL(str); + return /^(?:www\.)?last\.fm$/i.test(u.hostname) && /^\/music\//.test(u.pathname); + } catch { + return false; + } + } + /** * Get the user's Last.fm profile info. */ diff --git a/src/Player.mjs b/src/Player.mjs index b98d52f..f9d2cee 100644 --- a/src/Player.mjs +++ b/src/Player.mjs @@ -2030,11 +2030,11 @@ export default class Player extends EventEmitter { return res; } - playFirst(query, provider) { return this.play(query, true, provider); } + playFirst(query, provider, trackMeta) { return this.play(query, true, provider, trackMeta); } - play(query, top = false, provider) { + play(query, top = false, provider, trackMeta = null) { const events = new EventEmitter(); - this.workerJob("generalQuery", { query, provider }, (msg) => events.emit("message", msg)) + this.workerJob("generalQuery", { query, provider, trackMeta }, (msg) => events.emit("message", msg)) .then((data) => { if (!data) { logger.worker("[Player] Worker returned empty result");