Tests / test (push) Canceled after 0s
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
The idea was "each person types their Apple Music username and their public playlists appear". Apple does not allow that, and it is worth writing down rather than discovering later: there is no API for another person's public playlists — their own developer forums answer that request with "you can't" (threads 692941 and 123894) — and a profile page is rendered by JavaScript with nothing behind it to call. MusicKit offers the catalog and the *signed-in* user's own library, and the second needs an Apple Developer Program membership for a developer token plus a Music-User-Token per person: a private key and a third-party secret in an app that holds none, to fetch something other than what was asked for. What a self-hosted app can do is the share link, which every playlist has: Music → Share → Copy Link. So the Música screen (next to Salud in Home's header, plus a section in Settings) keeps a list of them per profile, in the profile document like the routines — so they sync to the other devices and travel in a backup — and tapping one opens it in Apple Music on the iPhone. The username is a link to the person's public profile. The list is nicer than a column of URLs because the API reads each link's public page for a title, artwork and track count. That is scraping, so it is built to lose: a page that says nothing leaves the card showing the name its owner typed, and nothing on the screen depends on it. `POST /api/music/lookup` is host-allowlisted to Apple's music hosts — https only, checked again on the URL a redirect lands on — because the api container sits on the same network as everything else the owner runs, and a route that fetches whatever it is handed is a request-forgery lever. That boundary has its own tests, including the LAN addresses it must refuse. The parsing lives in api/music.js rather than in both halves: two copies of a parser kept in step by hand is a bomb, and this is the same shape as vitals.js. It is in the Dockerfile's COPY for the same reason vitals.js had to be.
82 lines
4.4 KiB
JavaScript
82 lines
4.4 KiB
JavaScript
/* 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(`<meta[^>]+(?:property|name)=["']${prop}["'][^>]+content=["']([^"']*)["']`, 'i').exec(text)
|
|
|| new RegExp(`<meta[^>]+content=["']([^"']*)["'][^>]+(?:property|name)=["']${prop}["']`, 'i').exec(text);
|
|
return m ? decode(m[1]) : null;
|
|
};
|
|
for (const m of text.matchAll(/<script[^>]+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;
|
|
}
|