// NAME: RateYourMusic Integration
// AUTHOR: yusufaf
// x-release-please-start-version
// VERSION: 1.2.0
// x-release-please-end-version
// DESCRIPTION: Display RateYourMusic links for your Spotify albums
(function () {
// Marketplace and the Extensions folder can both load this file; only the first copy runs.
if (window.__rymActive) {
console.info('RYM Extension: Another copy is already running; skipping this one.');
return;
}
window.__rymActive = true;
//#region Type Definitions
/**
* @typedef {Object} AlbumInfo
* @property {string} artist - Primary artist name
* @property {string} album - Album name
* @property {string} albumUri - Spotify album URI
* @property {number|null} releaseDate - Release year
* @property {string|null} albumType - Spotify album type: "album", "single", "compilation"
* @property {number|null} totalTracks - Total track count
*/
//#endregion
//#region Constants
/** RYM base URL */
const RYM_BASE_URL = 'https://rateyourmusic.com';
/** Container element ID */
const CONTAINER_ID = 'rym-container';
/** Now Playing panel root (Spotify 1.3.3+). Attribute-based so it survives class-hash changes. */
const SELECTOR_NPV_ROOT = '[data-npv-root]';
/** Scroll viewport of the Now Playing panel. Excludes the panel header, whose context link can also point at the album. */
const SELECTOR_NPV_VIEWPORT = `${SELECTOR_NPV_ROOT} [data-overlayscrollbars-viewport]`;
/** Legacy selector for the album art/info grid (Spotify < 1.3.3, relies on a Spicetify css-map class) */
const SELECTOR_RIGHT_SIDEBAR_CONTENT = '.main-nowPlayingView-nowPlayingGrid';
/** Legacy alternative selector for right sidebar */
const SELECTOR_RIGHT_SIDEBAR_ALT = '[data-testid="NPV_Panel_OpenDiv"]';
/** LocalStorage key for extension configuration */
const CONFIG_KEY = 'rym-extension-config';
/** Gear/settings icon SVG path (16x16 viewBox, Bootstrap Icons gear-fill) */
const GEAR_SVG_PATH = 'M9.405 1.05c-.413-1.4-2.397-1.4-2.81 0l-.1.34a1.464 1.464 0 0 1-2.105.872l-.31-.17c-1.283-.698-2.686.705-1.987 1.987l.169.311c.446.82.023 1.841-.872 2.105l-.34.1c-1.4.413-1.4 2.397 0 2.81l.34.1a1.464 1.464 0 0 1 .872 2.105l-.17.31c-.698 1.283.705 2.686 1.987 1.987l.311-.169a1.464 1.464 0 0 1 2.105.872l.1.34c.413 1.4 2.397 1.4 2.81 0l.1-.34a1.464 1.464 0 0 1 2.105-.872l.31.17c1.283.698 2.686-.705 1.987-1.987l-.169-.311a1.464 1.464 0 0 1 .872-2.105l.34-.1c1.4-.413 1.4-2.397 0-2.81l-.34-.1a1.464 1.464 0 0 1-.872-2.105l.17-.31c.698-1.283-.705-2.686-1.987-1.987l-.311.169a1.464 1.464 0 0 1-2.105-.872zM8 10.93a2.929 2.929 0 1 1 0-5.858 2.929 2.929 0 0 1 0 5.858z';
/** Read by the shared footer. release-please keeps `version` in sync with the VERSION banner. */
const EXT = {
name: 'RateYourMusic Integration',
slug: 'rym',
// x-release-please-start-version
version: '1.2.0',
// x-release-please-end-version
footerPrefix: 'rym-modal',
};
// @shared footer.js start — edit shared/footer.js, then run pnpm sync
/**
* Settings footer shared by every extension: version, Docs, More extensions and a
* report-an-issue link. Reads the file's EXT config; class names are built from
* EXT.footerPrefix (`${footerPrefix}-footer`, `-footer-links`, `-version`, `-github-link`, `-github-icon`).
*/
const SHARED_HUB_URL = 'https://spicetify.yusufaf.dev/';
/** GitHub mark icon path (16x16 viewBox, Bootstrap Icons github, MIT) */
const SHARED_GITHUB_ICON_PATH = 'M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8z';
/** @param {{ name: string, slug: string, version: string, footerPrefix: string }} ext */
function sharedFooterHtml(ext) {
const p = ext.footerPrefix;
const issueUrl = `https://github.com/yusufaf/spicetify-extensions/issues/new?template=${ext.slug}.yml`;
return `
`;
}
/**
* CSS for sharedFooterHtml, to append to the extension's own stylesheet.
* `sticky` pins the footer to the bottom of Spicetify's PopupModal while the content scrolls.
* @param {{ footerPrefix: string }} ext
* @param {{ sticky?: boolean }} [options]
*/
function sharedFooterCss(ext, { sticky = false } = {}) {
const p = ext.footerPrefix;
const stickyRules = sticky
? `
position: sticky;
bottom: 0;
padding: 10px 0 2px;
/* Matches Spicetify's popup container, so the sticky footer blends in under any theme */
background: var(--spice-player, var(--background-elevated-base, #121212));`
: '';
return `
.${p}-footer {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
border-top: 1px solid rgba(255, 255, 255, 0.1);${stickyRules}
}
.${p}-version {
color: var(--spice-subtext, #b3b3b3);
font-size: 0.75rem;
}
.${p}-footer-links {
display: inline-flex;
align-items: center;
gap: 12px;
flex-shrink: 0;
white-space: nowrap;
}
.${p}-footer a[href] {
display: inline-flex;
align-items: center;
color: var(--spice-subtext, #b3b3b3);
font-size: 0.75rem;
text-decoration: none;
}
.${p}-footer a[href]:hover {
color: var(--spice-text, #fff);
text-decoration: underline;
}
.${p}-footer a[href]:focus-visible {
outline: 2px solid var(--spice-text, #fff);
outline-offset: 2px;
border-radius: 2px;
}
.${p}-github-icon {
width: 16px;
height: 16px;
fill: currentColor;
}
`;
}
// @shared footer.js end
/**
* Marker appended to outgoing album links when the companion API is configured.
* The capture userscript reads `sid` off the URL, which ties a RYM page back to
* an exact Spotify album with no name matching involved.
*/
const RYM_LINK_SOURCE = 'spicetify';
/**
* Give up on the companion API after this long. The card is fully rendered
* before the request is even sent, so a slow or dead server costs nothing
* except the upgrade it would have provided.
*/
const API_TIMEOUT_MS = 4000;
/** Spotify base-62 album ids are 22 characters. */
const SPOTIFY_ALBUM_ID_PATTERN = /^[A-Za-z0-9]{22}$/;
/** Default configuration */
const DEFAULT_CONFIG = {
position: 'below-album-info',
showAlbumLink: true,
showArtistLink: true,
showSearchLink: true,
compactMode: false,
showTooltips: true,
// Companion API (spicetify-music-api), off until both fields are filled in.
// With no configuration the extension makes zero network requests, which is a
// property worth keeping deliberate rather than incidental.
apiBaseUrl: '',
apiToken: '',
// Whether to show the rating and genres you captured yourself. Only has an
// effect once the API above is configured.
showRymData: true
};
//#endregion
//#region State
/** @type {HTMLElement|null} Shared tooltip element */
let tooltipElement = null;
/** @type {string|null} Currently displayed album URI */
let currentAlbumUri = null;
/** @type {HTMLElement|null} Card for the current album, kept so it can be re-inserted when Spotify re-renders the panel */
let rymCard = null;
/** @type {string|null} Why the last companion API lookup failed, cleared by the next one that succeeds */
let lastApiError = null;
/**
* @type {Map} spotifyAlbumId -> companion API response.
* Session-scoped and only holds responses that carried something to show. An
* album with no capture yet is not cached, so the ✓ appears on the next
* album change after you capture it rather than after a Spotify restart.
*/
const albumDataCache = new Map();
/** Bounds the cache for very long listening sessions. */
const ALBUM_CACHE_LIMIT = 300;
//#endregion
//#region Utilities
/**
* Characters NFD does not decompose, which the special-character strip would
* otherwise delete outright (Ágætis byrjun → "agtis-byrjun" instead of
* "agaetis-byrjun"). Applied after toLowerCase(), so lowercase keys suffice.
*
* Verified against live RYM URLs: æ (sigur-ros/agaetis-byrjun, kaelan-mikla),
* ø (artist/slotface). The rest follow the same transliteration convention but
* are unverified — check against a real RYM URL before relying on them.
*/
const SLUG_TRANSLITERATIONS = {
'æ': 'ae',
'œ': 'oe',
'ø': 'o',
'ß': 'ss',
'đ': 'd',
'ð': 'd',
'ł': 'l',
'þ': 'th',
'ı': 'i',
'ŋ': 'n'
};
/** @type {RegExp} Matches any key of SLUG_TRANSLITERATIONS */
const SLUG_TRANSLITERATION_PATTERN = new RegExp(
`[${Object.keys(SLUG_TRANSLITERATIONS).join('')}]`,
'g'
);
/**
* Slugifies string for RYM URLs (lowercase, hyphens, remove special chars)
* Handles accented characters by converting them to ASCII equivalents
* @param {string} str - Input string
* @returns {string} Slugified string
*/
function slugify(str) {
return str
.normalize('NFD') // Decompose accented characters (é → e + ́)
.replace(/[\u0300-\u036f]/g, '') // Remove diacritical marks
.toLowerCase()
.trim()
// Unicode dashes are not \w and would be deleted, silently joining the words
// either side (JAŸ-Z spelled with U+2010 would slug to "jayz" and 404)
.replace(/[‐-―−]/g, '-')
// Expand ligatures NFD leaves intact, before they get stripped below
.replace(SLUG_TRANSLITERATION_PATTERN, (ch) => SLUG_TRANSLITERATIONS[ch])
.replace(/[$/]/g, '_') // RYM maps $ and / to _ (AWAKE/ASLEEP → awake_asleep)
.replace(/[^\w\s-]/g, '') // Remove remaining special characters
.replace(/\s+/g, '-') // Replace spaces with hyphens (preserve underscores)
.replace(/-+/g, '-') // Collapse multiple hyphens
.replace(/^-+|-+$|_+$/g, ''); // Trim hyphens from ends and trailing underscores
}
/**
* Creates or returns the shared tooltip element
* @returns {HTMLElement} Tooltip element
*/
function getTooltip() {
if (!tooltipElement) {
tooltipElement = document.createElement('div');
tooltipElement.className = 'rym-tooltip';
document.body.appendChild(tooltipElement);
}
return tooltipElement;
}
/**
* Shows tooltip near the target element with the given text
* @param {HTMLElement} target - Element to position near
* @param {string} text - Text to display
*/
function showTooltip(target, text) {
const tooltip = getTooltip();
tooltip.textContent = text;
const rect = target.getBoundingClientRect();
const tooltipRect = tooltip.getBoundingClientRect();
// Position below the target, aligned to left
let left = rect.left;
let top = rect.bottom + 8;
// Adjust if tooltip would go off right edge
if (left + 300 > window.innerWidth) {
left = window.innerWidth - 310;
}
// Adjust if tooltip would go off bottom edge
if (top + 40 > window.innerHeight) {
top = rect.top - 40;
tooltip.style.setProperty('--arrow-top', 'auto');
tooltip.style.setProperty('--arrow-bottom', '-5px');
}
tooltip.style.left = `${left}px`;
tooltip.style.top = `${top}px`;
tooltip.classList.add('visible');
}
/**
* Hides the tooltip
*/
function hideTooltip() {
if (tooltipElement) {
tooltipElement.classList.remove('visible');
}
}
/**
* Attaches tooltip behavior to a link element
* @param {HTMLElement} link - Link element
* @param {string} url - URL to show in tooltip
*/
function attachTooltip(link, url) {
link.addEventListener('mouseenter', () => showTooltip(link, url));
link.addEventListener('mouseleave', hideTooltip);
}
/**
* Determines RYM release type from Spotify metadata
* @param {AlbumInfo} albumInfo - Album information from Spotify
* @returns {string} RYM release type: "album", "ep", "single", "comp", "mixtape"
*/
function determineRYMReleaseType(albumInfo) {
const { album, albumType, totalTracks } = albumInfo;
const albumLower = (album || '').toLowerCase();
// Priority 1: Album name patterns (highest confidence)
if (albumLower.includes('mixtape') || albumLower.includes('mix tape')) {
return 'mixtape';
}
if (albumLower.match(/\bep\b|e\.p\./i)) {
return 'ep';
}
if (albumLower.includes('compilation') || albumLower.includes('greatest hits')) {
return 'comp';
}
// Priority 2: Spotify album_type + track count
if (albumType === 'compilation') {
return 'comp';
}
if (albumType === 'single') {
if (totalTracks && totalTracks >= 4 && totalTracks <= 6) {
return 'ep';
}
return 'single';
}
if (albumType === 'album') {
if (totalTracks && totalTracks >= 4 && totalTracks <= 6) {
return 'ep';
}
return 'album';
}
// Priority 3: Default fallback
return 'album';
}
/**
* Extracts current album info from Spicetify player
* @returns {AlbumInfo|null} Album information or null
*/
function getCurrentAlbumInfo() {
const data = Spicetify.Player.data;
if (!data || !data.item || !data.context) {
return null;
}
// Use correct property paths from actual Spicetify data structure
const albumType = data.context.metadata?.albumType?.toLowerCase() || null;
const totalTracks = parseInt(data.context.metadata?.playlist_number_of_tracks) || null;
const releaseDate = data.context.metadata?.releaseDate || data.item.album?.date?.year || null;
return {
album: data.item.album?.name || '',
albumType: albumType,
albumUri: data.item.album?.uri || '',
artist: data.item.artists?.[0]?.name || '',
releaseDate: releaseDate,
totalTracks: totalTracks
};
}
/**
* Loads configuration from LocalStorage
* @returns {Object} Configuration object with position property
*/
function loadConfig() {
try {
const stored = Spicetify.LocalStorage.get(CONFIG_KEY);
if (stored) {
// Merge with defaults to handle new settings added in updates
return { ...DEFAULT_CONFIG, ...JSON.parse(stored) };
}
return DEFAULT_CONFIG;
} catch (e) {
console.warn('RYM Extension: Failed to load config, using defaults', e);
return DEFAULT_CONFIG;
}
}
/**
* Saves configuration to LocalStorage
* @param {Object} config - Configuration object to save
* @returns {void}
*/
function saveConfig(config) {
Spicetify.LocalStorage.set(CONFIG_KEY, JSON.stringify(config));
}
/**
* Whether the companion API is usable. Both fields are required, so a partly
* filled-in settings form never results in a request.
* @param {Object} config - Configuration object
* @returns {boolean} True when the API should be contacted
*/
function isApiConfigured(config) {
return Boolean(config.apiBaseUrl && config.apiToken);
}
/**
* Extracts the bare album id from a Spotify URI ("spotify:album:").
* @param {string|null} albumUri - Spotify album URI
* @returns {string|null} The 22-character id, or null if the URI is unusable
*/
function spotifyAlbumIdFromUri(albumUri) {
if (typeof albumUri !== 'string') return null;
const id = albumUri.split(':').pop();
return SPOTIFY_ALBUM_ID_PATTERN.test(id) ? id : null;
}
/**
* Appends the correlation marker to an outgoing RYM link.
* @param {string} url - RYM URL
* @param {string|null} spotifyAlbumId - Album id to correlate with
* @returns {string} URL with the marker, or the original when there is no id
*/
function withCorrelation(url, spotifyAlbumId) {
if (!spotifyAlbumId) return url;
const separator = url.includes('?') ? '&' : '?';
return `${url}${separator}src=${RYM_LINK_SOURCE}&sid=${spotifyAlbumId}`;
}
/**
* Checks a URL is genuinely a RateYourMusic page before it becomes an href.
*
* The API validates this on write, but pooled links originate from other users'
* captures, so the value arriving here is not something this extension has ever
* verified itself. Re-checking on read is cheap and keeps a bad row in the
* shared table from turning into a link the user clicks.
*
* @param {string} url - Candidate URL
* @returns {boolean} True when the URL is an https rateyourmusic.com URL
*/
function isSafeRymUrl(url) {
if (typeof url !== 'string') return false;
try {
const parsed = new URL(url);
return parsed.protocol === 'https:' && parsed.hostname === 'rateyourmusic.com';
} catch (e) {
return false;
}
}
/**
* Fetches stored RYM data for an album from the companion API.
*
* Never throws and never rejects: every failure path returns null, because the
* card is already rendered by the time this runs and a dead server must be
* indistinguishable from having no server configured.
*
* @param {string} spotifyAlbumId - Spotify album id
* @param {Object} config - Configuration object
* @returns {Promise