/* music.js — what a public Apple Music page says about itself. * * This is the API half of the Música screen. The client keeps the links (frontend/src/lib/music.js * owns reading and validating those); this fetches one and reads its title, artwork and track count * so the list looks like a list of playlists instead of a column of URLs. * * It lives beside server.js, exported and tested on its own, for the reason vitals.js does: it is * the only part of the route with logic in it, and it is much easier to test against real markup * than to watch a phone do it. server.js owns the socket, this owns the parsing. * * ── Two things that are not negotiable here ────────────────────────────────────────────────── * * HOST-ALLOWLISTED. The URL comes from a signed-in user and the request is made from the api * container, which sits on the same network as everything else the owner runs — so a route that * fetches whatever it is handed is a request-forgery lever. Only Apple's own music hosts are * reachable, which is a set nobody can point at the LAN. `hostAllowed` is used both before the * request and again on the final URL, because a redirect must not be a way around it. * * BEST EFFORT. Apple's markup is theirs to change; a page that yields nothing costs the reader the * artwork and the track count, never the playlist (the card falls back to the name its owner * typed). Apple publishes a schema.org MusicPlaylist block for previews to read, which is the part * this leans on; the Open Graph tags are the fallback. */ export const MUSIC_HOSTS = new Set(['music.apple.com', 'itunes.apple.com', 'geo.music.apple.com']); export const MUSIC_TIMEOUT_MS = 8000; export const MUSIC_MAX_HTML = 1024 * 1024; // a playlist page is a few hundred KB; more is not one /** Is this URL one we are willing to fetch? https, and one of Apple's music hosts. */ export function hostAllowed(url) { try { const u = new URL(String(url)); return u.protocol === 'https:' && MUSIC_HOSTS.has(u.hostname.toLowerCase()); } catch { return false } } /** Read at most `max` bytes of a response, as text. */ export async function readCapped(res, max = MUSIC_MAX_HTML) { const chunks = []; let size = 0; for await (const chunk of res.body || []) { size += chunk.length; if (size > max) break; chunks.push(chunk); } return Buffer.concat(chunks).toString('utf8'); } const decode = s => String(s || '') .replace(/"/g, '"').replace(/�?39;/g, "'").replace(/'/g, "'") .replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/ /g, ' '); /** @returns {{title:string|null, artwork:string|null, tracks:number|null, curator:string|null}} */ export function parseMusicPage(html) { const text = String(html || ''); const out = { title: null, artwork: null, tracks: null, curator: null }; const meta = prop => { const m = new RegExp(`]+(?:property|name)=["']${prop}["'][^>]+content=["']([^"']*)["']`, 'i').exec(text) || new RegExp(`]+content=["']([^"']*)["'][^>]+(?:property|name)=["']${prop}["']`, 'i').exec(text); return m ? decode(m[1]) : null; }; for (const m of text.matchAll(/]+application\/ld\+json[^>]*>([\s\S]*?)<\/script>/gi)) { let data; try { data = JSON.parse(m[1].trim()); } catch { continue } for (const node of Array.isArray(data) ? data : [data]) { if (!node || node['@type'] !== 'MusicPlaylist') continue; if (node.name) out.title = decode(node.name); if (typeof node.numTracks === 'number') out.tracks = node.numTracks; const img = node.image; if (typeof img === 'string') out.artwork = img; else if (img && typeof img === 'object' && img.url) out.artwork = img.url; const by = node.byArtist || node.author || node.creator; if (by && typeof by === 'object' && by.name) out.curator = decode(by.name); } } if (!out.title) out.title = meta('og:title') || meta('twitter:title'); if (!out.artwork) out.artwork = meta('og:image') || meta('twitter:image'); // Apple serves the preview image at whatever size it likes; asking their own CDN template for a // bigger one is a string substitution, and harmless when the path does not match. if (out.artwork) out.artwork = out.artwork.replace(/\/\d+x\d+(bb)?\.(jpg|png|webp)$/i, '/600x600bb.jpg'); return out; }