/* The radio sources, tested without a network: everything here is a filter or a parse, and the filters are the point. A station that cannot be played is worse than no station — a row that does nothing when tapped, on a screen whose whole job is to make sound. The three rules that are load-bearing: HTTPS (an http stream is blocked by the browser on an https page, silently), no HLS (Chrome and Android need a library, and this project does not add one for a station), and nothing fetched from a host that is not on our own list. */ import { test } from 'node:test'; import assert from 'node:assert/strict'; import { GENRES, genreList, genreOf, PARADISE, parsePls, pickPlaylist, somaStation, rbStations, nowFrom, allowedHost, get, streamFor, stationsFor, nowPlaying, RADIO_HOSTS, clearRadioCache, searchStations, rbSearch, normQuery, relevance, rankStations } from '../radio.js'; const pls = 'https://api.somafm.com/beatblender.pls'; const channel = (over = {}) => ({ id: 'beatblender', title: 'Beat Blender', genre: 'electronic', description: 'A late night blend of deep-house and downtempo chill.', playlists: [ { url: pls, format: 'mp3', quality: 'highest' }, { url: 'https://api.somafm.com/beatblender130.pls', format: 'aac', quality: 'highest' } ], ...over }); test('the genres the screen offers are the ones a person asked for', () => { const keys = genreList().map(g => g.key); for (const want of ['workout', 'techno', 'rnb', 'latin', 'hiphop', 'reggae', 'chill', 'jazz', 'rock', 'electronic']) { assert.ok(keys.includes(want), want + ' is offered'); } // Every genre names at least one SomaFM channel or one tag: a chip that shows nothing is a chip // that should not be there. for (const g of GENRES) assert.ok(g.soma.length + g.tags.length > 0, g.key + ' has a source'); assert.equal(genreOf('nope'), null); assert.equal(genreOf('rnb').label, 'R&B / Soul'); }); test('a .pls gives the stream, and anything else gives nothing', () => { const text = [ '[playlist]', 'numberofentries=2', 'File1=https://ice2.somafm.com/beatblender-128-mp3', 'Title1=SomaFM: Beat Blender', 'Length1=-1', 'File2=https://ice6.somafm.com/beatblender-128-mp3', 'Version=2' ].join('\n'); assert.equal(parsePls(text), 'https://ice2.somafm.com/beatblender-128-mp3', 'the first mirror'); // An http stream would be blocked by the browser on an https page, so it is not a stream here. assert.equal(parsePls('[playlist]\nFile1=http://ice2.somafm.com/x'), null); assert.equal(parsePls('nope'), null); assert.equal(parsePls(null), null); assert.equal(parsePls(''), null); }); test('the playlist chosen is the best one that plays everywhere', () => { assert.equal(pickPlaylist(channel()), pls, 'mp3 highest wins over aac highest'); assert.equal(pickPlaylist(channel({ playlists: [ { url: 'https://api.somafm.com/x256.pls', format: 'mp3', quality: 'highest' }, { url: 'https://api.somafm.com/x.pls', format: 'mp3', quality: 'high' } ] })), 'https://api.somafm.com/x256.pls'); assert.equal(pickPlaylist(channel({ playlists: [{ url: 'https://api.somafm.com/x130.pls', format: 'aac', quality: 'highest' }] })), 'https://api.somafm.com/x130.pls', 'aac is the fallback, not nothing'); assert.equal(pickPlaylist(channel({ playlists: [{ url: 'http://api.somafm.com/x.pls', format: 'mp3' }] })), null); assert.equal(pickPlaylist(channel({ playlists: [] })), null); }); test('a SomaFM channel becomes a station, and a broken one does not', () => { const s = somaStation(channel()); assert.equal(s.src, 'soma'); assert.equal(s.id, 'beatblender'); assert.equal(s.pls, pls); assert.equal(s.detail, 'A late night blend of deep-house and downtempo chill.'); assert.equal(somaStation(channel({ id: '' })), null); assert.equal(somaStation(channel({ title: ' ' })), null); assert.equal(somaStation(channel({ playlists: [] })), null); assert.equal(somaStation(null), null); }); test('the directory is filtered down to what can be played', () => { const rows = [ { stationuuid: 'a', name: 'Techno One', url_resolved: 'https://x.example/stream', codec: 'MP3', bitrate: 192, country: 'Germany', tags: 'techno,dance' }, { stationuuid: 'b', name: 'Plain HTTP', url_resolved: 'http://x.example/stream', codec: 'MP3' }, { stationuuid: 'c', name: 'HLS only', url_resolved: 'https://x.example/live.m3u8', codec: 'AAC' }, { stationuuid: 'd', name: 'Unknown codec', url_resolved: 'https://x.example/wm', codec: 'WMAL' }, { stationuuid: 'e', name: 'Wild', url_resolved: 'https://x.example/wm2' }, { stationuuid: 'f', name: 'Techno One', url_resolved: 'https://x.example/stream', codec: 'MP3' }, { stationuuid: 'g', name: ' ', url_resolved: 'https://x.example/blank', codec: 'MP3' }, { stationuuid: 'h', name: 'AAC+ Latin', url_resolved: 'https://y.example/aac', codec: 'AAC+', bitrate: 64, country: 'Colombia' } ]; const out = rbStations(rows); // "Wild" has no codec at all, and that is kept on purpose: a blank codec means the directory did // not say, which is common, rather than that the station is unplayable. The ones it *does* name // and that no browser plays (WMAL), and the HLS ones, are the ones dropped. assert.deepEqual(out.map(s => s.name), ['Techno One', 'Wild', 'AAC+ Latin'], 'only what is known to be unplayable is dropped'); assert.equal(out[0].detail, 'Germany · MP3 · 192 kbps'); assert.equal(out[0].genre, 'techno, dance'); assert.equal(out[2].detail, 'Colombia · AAC+ · 64 kbps'); assert.equal(rbStations('nope').length, 0); assert.equal(rbStations([{ name: 'no url' }]).length, 0); }); test('what is playing is read from the two stations that publish it, and invented for nobody', () => { assert.deepEqual(nowFrom('soma', { songs: [{ title: 'Cuban Nights', artist: 'Miguel Migs', albumArt: 'https://cdn.example/a.jpg' }] }), { artist: 'Miguel Migs', title: 'Cuban Nights', cover: 'https://cdn.example/a.jpg' }); assert.deepEqual(nowFrom('paradise', { artist: 'Yes', title: 'I have seen all good people', cover: 'https://img.example/c.jpg' }), { artist: 'Yes', title: 'I have seen all good people', cover: 'https://img.example/c.jpg' }); // No song playing, no cover, or a source that publishes nothing: null, never a placeholder. assert.equal(nowFrom('soma', { songs: [] }), null); assert.equal(nowFrom('soma', null), null); assert.equal(nowFrom('rb', { title: 'x' }), null); assert.equal(nowFrom('paradise', {}), null); const noArt = nowFrom('soma', { songs: [{ title: 'x' }] }); assert.equal(noArt.artist, null); assert.equal(noArt.cover, null); }); test('only our own hosts may be fetched, over https', () => { assert.equal(allowedHost('https://somafm.com/channels.json'), true); assert.equal(allowedHost('https://api.somafm.com/beatblender.pls'), true); assert.equal(allowedHost('https://all.api.radio-browser.info/json/stations'), true); assert.equal(allowedHost('https://api.radioparadise.com/api/now_playing?chan=0'), true); // The stream hosts are reached by the browser, never by this process — so they are not here. assert.equal(allowedHost('https://ice2.somafm.com/beatblender-128-mp3'), false); assert.equal(allowedHost('http://somafm.com/channels.json'), false, 'https only'); assert.equal(allowedHost('https://evil.example/somafm.com'), false); assert.equal(allowedHost('https://somafm.com.evil.example/x'), false); assert.equal(allowedHost('not a url'), false); assert.equal(allowedHost('https://somafm.com/', ['example.com']), false, 'the list is the argument'); assert.ok(RADIO_HOSTS.every(h => h === h.toLowerCase())); }); /* The gate itself, and the one test that can see it: `get` is the only place this module makes an outgoing call, so an off-list URL must die there — not at a caller that might forget. */ test('get refuses an off-list url without calling fetch at all', async () => { let calls = 0; const fetchImpl = async () => { calls++; return { ok: true, text: async () => 'x' }; }; for (const url of ['https://evil.example/x', 'http://somafm.com/channels.json', 'https://somafm.com.evil.example/x', 'not a url']) { assert.equal(await get(url, { fetchImpl }), null, url); } assert.equal(calls, 0, 'nothing left this process'); // ...and an on-list one does go out, so the test above is not passing because get never works. assert.equal(await get('https://somafm.com/channels.json', { fetchImpl }), 'x'); assert.equal(calls, 1); }); test('resolving a stream never fetches anything outside the allowlist', async () => { clearRadioCache(); const calls = []; const fetchImpl = async (url) => { calls.push(String(url)); if (String(url).includes('evil')) throw new Error('should not be called'); return { ok: true, text: async () => '[playlist]\nFile1=https://ice2.somafm.com/beatblender-128-mp3\n' }; }; const url = await streamFor({ src: 'soma', id: 'beatblender', pls }, { fetchImpl }); assert.equal(url, 'https://ice2.somafm.com/beatblender-128-mp3'); assert.deepEqual(calls, [pls]); // Cached: a second press does not ask SomaFM again. assert.equal(await streamFor({ src: 'soma', id: 'beatblender', pls }, { fetchImpl }), url); assert.equal(calls.length, 1); // A directory station carries its own stream: nothing is fetched, and an http one is refused. assert.equal(await streamFor({ src: 'rb', id: 'x', url: 'https://y.example/aac' }, { fetchImpl }), 'https://y.example/aac'); assert.equal(await streamFor({ src: 'rb', id: 'x', url: 'http://y.example/aac' }, { fetchImpl }), null); assert.equal(await streamFor(null, { fetchImpl }), null); // A SomaFM station whose playlist points off the list is refused rather than followed. assert.equal(await streamFor({ src: 'soma', id: 'x', pls: 'https://evil.example/x.pls' }, { fetchImpl }), null); assert.equal(calls.length, 1); }); test('a genre list puts the curated channels first and the directory last', async () => { clearRadioCache(); const fetchImpl = async (url) => { const u = String(url); if (u.includes('channels.json')) { return { ok: true, text: async () => JSON.stringify({ channels: [ channel(), channel({ id: 'bossa', title: 'Bossa Beyond' }), channel({ id: 'reggae', title: 'Heavyweight Reggae' }) ] }) }; } if (u.includes('api.somafm.com')) { // The channel's own playlist, which is what turns a channel into something playable. return { ok: true, text: async () => '[playlist]\nFile1=https://ice2.somafm.com/x-128-mp3\n' }; } if (u.includes('radio-browser')) { return { ok: true, text: async () => JSON.stringify([ { stationuuid: 'z1', name: 'Salsa Dura', url_resolved: 'https://z.example/salsa', codec: 'MP3', country: 'Colombia', tags: 'salsa' }, { stationuuid: 'z2', name: 'Dead', url_resolved: 'http://z.example/dead', codec: 'MP3' } ]) }; } return { ok: false, text: async () => '' }; }; // The curated channels come back with their stream already resolved (`fetchImpl` answers the // `.pls` above), and a channel whose stream cannot be resolved is not listed at all. const { genre, stations } = await stationsFor('latin', { fetchImpl }); assert.equal(genre.key, 'latin'); const names = stations.map(s => s.name); // The no-advertising stations first — that is what the order is for. assert.deepEqual(names.slice(0, 3), ['Bossa Beyond', 'Heavyweight Reggae', 'Radio Paradise · Global']); assert.ok(names.includes('Salsa Dura'), 'and the directory fills in the genres SomaFM does not carry'); assert.ok(stations.every(s => /^https:\/\//.test(s.url || '')), 'every row can be played when it is tapped'); assert.equal(names.includes('Dead'), false); // An unknown genre falls back to the first one rather than showing a blank screen. const fallback = await stationsFor('nope', { fetchImpl }); assert.equal(fallback.genre.key, 'workout'); }); test('what is playing is asked for at the right address, per source', async () => { const calls = []; const fetchImpl = async (url) => { calls.push(String(url)); if (String(url).includes('somafm')) return { ok: true, text: async () => JSON.stringify({ songs: [{ title: 'T', artist: 'A' }] }) }; return { ok: true, text: async () => JSON.stringify({ title: 'Paradise Song', artist: 'PR' }) }; }; const soma = await nowPlaying({ src: 'soma', id: 'beatblender' }, { fetchImpl }); assert.equal(soma.title, 'T'); assert.match(calls[0], /somafm\.com\/songs\/beatblender\.json/); const para = await nowPlaying({ src: 'paradise', id: 'rock' }, { fetchImpl }); assert.equal(para.artist, 'PR'); assert.match(calls[1], /chan=2/, 'the third mix is chan=2'); // A directory station publishes nothing, so nothing is asked and nothing is shown. assert.equal(await nowPlaying({ src: 'rb', id: 'x', url: 'https://y.example/aac' }, { fetchImpl }), null); assert.equal(calls.length, 2); assert.equal(PARADISE.length, 4); }); /* ---------- search ---------- */ test('a query has to be a query: trimmed, lowered, and at least two characters', () => { assert.equal(normQuery(' Jazz '), 'jazz'); assert.equal(normQuery('Deep HOUSE'), 'deep house'); assert.equal(normQuery('j'), '', 'one letter matches everything and costs a request to say so'); assert.equal(normQuery(''), ''); assert.equal(normQuery(null), ''); assert.equal(normQuery('x'.repeat(200)).length, 60, 'a wall of text is truncated, not refused'); }); test('the best answer to "techno" is a station called Techno Something', () => { // The directory matches substrings anywhere, so a chart station with "techno" in its tags used to // come back ahead of every station actually named after the genre. This is the ordering that fixes // it: the name is the answer, and where in the name it appears is the ranking. assert.equal(relevance({ name: 'Techno' }, 'techno'), 0); assert.equal(relevance({ name: 'Techno: Live' }, 'techno'), 1); assert.equal(relevance({ name: 'TechnoFM' }, 'techno'), 2); assert.equal(relevance({ name: 'Radio Techno Club' }, 'techno'), 3); assert.equal(relevance({ name: '# TOP 100 CLUB CHARTS - DANCE & DJ MIX' }, 'techno'), 4); assert.equal(relevance({ name: '' }, 'techno'), 4); const ranked = rankStations([ { name: 'Radio Techno Club' }, { name: '# TOP 100 CLUB CHARTS' }, { name: 'Techno' }, { name: 'TechnoFM' } ], 'techno').map(s => s.name); assert.deepEqual(ranked, ['Techno', 'TechnoFM', 'Radio Techno Club', '# TOP 100 CLUB CHARTS']); // Ties fall back to the shorter name, then to the order the directory gave: a 90-character // marketing string is noise next to "Jazz 24". assert.deepEqual(rankStations([{ name: 'Jazz FM 106.9 Yerevan Radio Station' }, { name: 'Jazz 24' }], 'jazz').map(s => s.name), ['Jazz 24', 'Jazz FM 106.9 Yerevan Radio Station']); assert.deepEqual(rankStations(null, 'jazz'), []); }); test('a search asks the directory by name, https only, and the curated channels come first', async () => { clearRadioCache(); const asked = []; const fetchImpl = async (url) => { asked.push(url); if (url.includes('channels.json')) return { ok: true, text: async () => JSON.stringify({ channels: [ channel({ id: 'sonicuniverse', title: 'Sonic Universe', genre: 'jazz', playlists: [{ url: 'https://api.somafm.com/sonicuniverse.pls', format: 'mp3', quality: 'highest' }] }), channel({ id: 'beatblender', title: 'Beat Blender', genre: 'electronic' }) // not a jazz hit ] }) }; // As the directory answers: the noisy name first — which is exactly the problem the ranking // exists for. It matches "jazz" inside a marketing string; "Jazz 24" starts with it. if (url.includes('/stations/search')) return { ok: true, text: async () => JSON.stringify([ { name: 'Smooth Jazz Worldwide Radio Charts Network', codec: 'MP3', country: 'Germany', url_resolved: 'https://x/noisy', stationuuid: 'a' }, { name: 'Jazz 24', codec: 'MP3', country: 'Switzerland', url_resolved: 'https://x/jazz24', stationuuid: 'b' }, { name: 'Jazz 24 dup', codec: 'MP3', country: 'Switzerland', url_resolved: 'https://x/jazz24', stationuuid: 'c' }, { name: 'Jazz FM', codec: 'MP3', country: 'United Kingdom', url_resolved: 'http://x/jazzfm', stationuuid: 'd' } ]) }; if (url.includes('sonicuniverse.pls')) return { ok: true, text: async () => '[playlist]\nFile1=https://ice2.somafm.com/sonicuniverse-128-mp3' }; return { ok: false, status: 404, text: async () => '' }; }; const stations = await searchStations('jazz', { fetchImpl }); // The curated channel is the first answer: no advertising, and a stream known to work. assert.equal(stations[0].src, 'soma'); assert.equal(stations[0].id, 'sonicuniverse'); assert.equal(stations[0].url, 'https://ice2.somafm.com/sonicuniverse-128-mp3'); const search = asked.find(u => u.includes('/stations/search')); assert.ok(search, 'the directory was asked'); const q = new URL(search).searchParams; assert.equal(q.get('name'), 'jazz'); assert.equal(q.get('hidebroken'), 'true'); assert.equal(q.get('is_https'), 'true', 'an http stream is a row the browser will refuse to play'); assert.equal(q.get('order'), 'clickcount', 'ordered by what people actually listen to'); // The http station never makes it, the duplicate never makes it, the noisy name does not outrank // the station actually called Jazz, and nothing from the directory outranks the curated channel. assert.deepEqual(stations.map(s => s.name), ['Sonic Universe', 'Jazz 24', 'Smooth Jazz Worldwide Radio Charts Network']); assert.ok(stations.every(s => /^https:\/\//.test(s.url))); }); test('a one-letter search answers nothing and asks nobody', async () => { clearRadioCache(); let called = 0; const fetchImpl = async () => { called++; return { ok: true, text: async () => '[]' } }; assert.deepEqual(await searchStations('j', { fetchImpl }), []); assert.deepEqual(await searchStations(' ', { fetchImpl }), []); assert.equal(called, 0); }); test('the same query twice is one request to the directory', async () => { clearRadioCache(); let called = 0; const fetchImpl = async url => { if (url.includes('/stations/search')) { called++; return { ok: true, text: async () => JSON.stringify([{ name: 'Jazz', codec: 'MP3', url_resolved: 'https://x/1', stationuuid: 'a' }]) } } if (url.includes('channels.json')) return { ok: true, text: async () => JSON.stringify({ channels: [] }) }; return { ok: false, status: 404, text: async () => '' }; }; await rbSearch('jazz', { fetchImpl }); await rbSearch('jazz', { fetchImpl }); assert.equal(called, 1); });