feat: reddit -> spotify/bandcamp artist linker MVP (extension + resolver service)
Firefox MV2 content script that detects artist/band names in reddit comment threads and rewrites them inline into Spotify + Bandcamp links, backed by a tiny zero-dependency Node resolver that confirms each candidate against the Spotify Web API (direct links) or MusicBrainz (zero-setup, search links). Includes build + install instructions in the README. Source: project/reddit-spotify-linker (user 2026-06-12) + user message 2026-06-14 "Full vibe code, small service, minimal code." Closes task/resolver-service, closes task/firefox-extension, closes task/docs-and-publish (plan/mvp-build, objective/ship-mvp-linker). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
+14
@@ -0,0 +1,14 @@
|
||||
# secrets / local config
|
||||
.env
|
||||
*.env
|
||||
!.env.example
|
||||
|
||||
# node
|
||||
node_modules/
|
||||
npm-debug.log*
|
||||
|
||||
# editor / os
|
||||
.DS_Store
|
||||
*.swp
|
||||
.idea/
|
||||
.vscode/
|
||||
@@ -0,0 +1,118 @@
|
||||
# Reddit → Spotify / Bandcamp linker
|
||||
|
||||
A Firefox extension that, while you browse a Reddit thread, finds **artist / band
|
||||
names** in the comments (and the post body) and turns them into inline links to
|
||||
**Spotify** and **Bandcamp** — so a recommendation thread like
|
||||
[this one](https://www.reddit.com/r/SlamDeathMetal/comments/1txh2r1/) becomes a
|
||||
list of clickable artists instead of names you have to copy-paste into search.
|
||||
|
||||
The hard part is *"which words are artists and which aren't?"*. Rather than guess
|
||||
with client-side rules, the extension hands candidate names to a tiny local
|
||||
**resolver service** that checks each one against a real music database and only
|
||||
links the names that actually match an artist.
|
||||
|
||||
```
|
||||
reddit page content script resolver service
|
||||
─────────── ────────────── ────────────────
|
||||
comment text ──extract──> candidate names ──POST /resolve──> Spotify API (direct links)
|
||||
or
|
||||
<a> links <──rewrite── confirmed links <───────────────── MusicBrainz (zero-setup)
|
||||
```
|
||||
|
||||
## Layout
|
||||
|
||||
```
|
||||
service/ tiny Node.js resolver (one file, zero npm deps)
|
||||
resolver.js
|
||||
package.json
|
||||
.env.example
|
||||
extension/ Firefox MV2 extension (content script only)
|
||||
manifest.json
|
||||
content.js
|
||||
styles.css
|
||||
```
|
||||
|
||||
## 1. Run the resolver service
|
||||
|
||||
Requirements: **Node 18+** (uses the built-in `fetch`). No `npm install` needed —
|
||||
there are no dependencies.
|
||||
|
||||
```sh
|
||||
cd service
|
||||
node resolver.js
|
||||
# resolver listening on http://localhost:8787 (provider: musicbrainz)
|
||||
```
|
||||
|
||||
That's it. With no configuration the resolver validates names against
|
||||
**MusicBrainz** (no account required) and links to Spotify/Bandcamp **search**
|
||||
pages.
|
||||
|
||||
### Optional: direct Spotify links
|
||||
|
||||
For **direct artist links** (instead of Spotify search), give the service Spotify
|
||||
API credentials:
|
||||
|
||||
1. Create a free app at <https://developer.spotify.com/dashboard> and copy its
|
||||
**Client ID** and **Client Secret**.
|
||||
2. `cp .env.example .env` and fill them in (the `.env` file is gitignored):
|
||||
|
||||
```
|
||||
SPOTIFY_CLIENT_ID=your_id
|
||||
SPOTIFY_CLIENT_SECRET=your_secret
|
||||
```
|
||||
3. Restart the service. It will report `provider: spotify` on startup.
|
||||
|
||||
(Bandcamp has no public API, so Bandcamp links are always a search URL.)
|
||||
|
||||
Quick check that it works:
|
||||
|
||||
```sh
|
||||
curl -s localhost:8787/resolve \
|
||||
-H 'content-type: application/json' \
|
||||
-d '{"candidates":["Cerebral Bore","Devourment","Notarealband Xyzzy"]}'
|
||||
# {"Cerebral Bore":{...},"Devourment":{...},"Notarealband Xyzzy":null}
|
||||
```
|
||||
|
||||
## 2. Install the extension in Firefox
|
||||
|
||||
The extension is unpacked / unsigned, so load it as a **temporary add-on**:
|
||||
|
||||
1. Open `about:debugging#/runtime/this-firefox`.
|
||||
2. **Load Temporary Add-on…**
|
||||
3. Select `extension/manifest.json`.
|
||||
|
||||
It's now active until you restart Firefox. (To keep it permanently you'd sign it
|
||||
via [AMO](https://addons.mozilla.org/developers/) or use Firefox Developer/ESR
|
||||
with `xpinstall.signatures.required = false`.)
|
||||
|
||||
## 3. Use it
|
||||
|
||||
1. Make sure the resolver service is running.
|
||||
2. Open any Reddit comments thread (a URL with `/comments/` in it).
|
||||
3. Artist names in the comments become links: the name links to **Spotify**, with
|
||||
a small superscript **`bc`** link to **Bandcamp** beside it. New comments loaded
|
||||
as you scroll are linked automatically.
|
||||
|
||||
## Configuration
|
||||
|
||||
The resolver URL is the constant `RESOLVER_URL` at the top of
|
||||
`extension/content.js` (default `http://localhost:8787`). If you change the host
|
||||
or port, update **both** that constant **and** the matching entry in
|
||||
`extension/manifest.json` → `permissions` (Firefox needs the host listed there to
|
||||
let the content script reach it).
|
||||
|
||||
## Limitations (MVP)
|
||||
|
||||
- **Detection is capitalization-based.** Names written in lowercase, or split
|
||||
across formatting (e.g. **bold** in the middle of a name), can be missed. The
|
||||
resolver's exact-name match keeps false *positives* low; the trade-off is some
|
||||
false *negatives*.
|
||||
- **Bandcamp links are searches**, not direct artist pages (no public API).
|
||||
- The resolver caches results in memory; it resets when you restart it.
|
||||
- Without Spotify credentials the MusicBrainz path is rate-limited to ~1 lookup/
|
||||
second, so the first scan of a large thread fills in gradually (cached after).
|
||||
- Built and tested as a Firefox MV2 extension.
|
||||
|
||||
## License
|
||||
|
||||
Personal project — do as you like.
|
||||
@@ -0,0 +1,193 @@
|
||||
// Reddit -> Spotify/Bandcamp linker (content script).
|
||||
//
|
||||
// On a reddit thread page it: pulls candidate artist names out of comment text,
|
||||
// asks the local resolver service which ones are real artists, and rewrites those
|
||||
// occurrences in place into links. The resolver does the hard "is this an artist"
|
||||
// part; this script only handles extraction + DOM rewriting.
|
||||
|
||||
(() => {
|
||||
"use strict";
|
||||
|
||||
// If you run the resolver on a different host/port, change this AND the matching
|
||||
// host entry in manifest.json `permissions`.
|
||||
const RESOLVER_URL = "http://localhost:8787";
|
||||
|
||||
// ---- candidate extraction -------------------------------------------------
|
||||
// A token is a Capitalized or ALL-CAPS word; a candidate is 1-4 tokens joined by
|
||||
// spaces, with a few lowercase connectors allowed inside ("Signs of the Swarm").
|
||||
const TOKEN = "[A-Z][A-Za-z0-9'’.&\\-]*";
|
||||
const CAND_RE = new RegExp(`${TOKEN}(?:[ ]+(?:${TOKEN}|of|the|and|&|in|on|to|for|a|an)){0,3}`, "g");
|
||||
const CONNECTORS = new Set(["of", "the", "and", "&", "in", "on", "to", "for", "a", "an"]);
|
||||
|
||||
// Common capitalized words that are almost never the artist being recommended.
|
||||
// Deliberately small: the resolver's exact-name match is the real filter, so we
|
||||
// avoid stoplisting plausible one-word band names (Yes, Love, Tool, ...).
|
||||
const STOP = new Set([
|
||||
"I", "A", "An", "The", "And", "But", "Or", "Nor", "So", "Yet", "For", "If", "As",
|
||||
"At", "By", "In", "On", "To", "Of", "Up", "Off", "Out", "It", "He", "She", "We",
|
||||
"They", "You", "Me", "Him", "Her", "Us", "Them", "My", "Your", "His", "Its", "Our",
|
||||
"Their", "This", "That", "These", "Those", "Is", "Are", "Was", "Were", "Be", "Been",
|
||||
"Am", "Do", "Does", "Did", "Has", "Have", "Had", "Will", "Would", "Can", "Could",
|
||||
"Should", "Not", "No", "Yeah", "Ok", "Okay", "Lol", "Imo", "Imho", "Tbh", "Edit",
|
||||
"Reddit", "Spotify", "Bandcamp", "Youtube", "Google", "Apple", "Album", "Albums",
|
||||
"Band", "Bands", "Song", "Songs", "Track", "Tracks", "Ep", "Lp", "Cd", "Op", "Vol",
|
||||
]);
|
||||
|
||||
function matchesIn(text) {
|
||||
const out = [];
|
||||
CAND_RE.lastIndex = 0;
|
||||
let m;
|
||||
while ((m = CAND_RE.exec(text))) {
|
||||
let str = m[0].replace(/[.,;:!?’'")\]]+$/u, ""); // trim trailing punctuation
|
||||
let parts = str.split(/\s+/);
|
||||
while (parts.length && CONNECTORS.has(parts[parts.length - 1].toLowerCase())) parts.pop();
|
||||
str = parts.join(" ");
|
||||
if (!str) continue;
|
||||
const single = parts.length === 1;
|
||||
if (single && (STOP.has(str) || str.length < 2 || /^\d+$/.test(str))) continue;
|
||||
out.push({ name: str, index: m.index, length: str.length }); // only trailing trimmed -> index unchanged
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---- DOM walking ----------------------------------------------------------
|
||||
const SKIP_TAGS = new Set([
|
||||
"A", "SCRIPT", "STYLE", "CODE", "PRE", "TEXTAREA", "INPUT", "BUTTON", "TIME", "NOSCRIPT", "SVG", "SELECT",
|
||||
]);
|
||||
|
||||
function inSkippable(node) {
|
||||
for (let el = node.parentElement; el; el = el.parentElement) {
|
||||
if (SKIP_TAGS.has(el.tagName)) return true;
|
||||
if (el.classList && el.classList.contains("rsl-link")) return true;
|
||||
if (el.isContentEditable) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function collectTextNodes(root) {
|
||||
const nodes = [];
|
||||
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {
|
||||
acceptNode(node) {
|
||||
const v = node.nodeValue;
|
||||
if (!v || v.length > 5000 || !/[A-Za-z]/.test(v)) return NodeFilter.FILTER_REJECT;
|
||||
if (inSkippable(node)) return NodeFilter.FILTER_REJECT;
|
||||
return NodeFilter.FILTER_ACCEPT;
|
||||
},
|
||||
});
|
||||
let n;
|
||||
while ((n = walker.nextNode())) nodes.push(n);
|
||||
return nodes;
|
||||
}
|
||||
|
||||
// ---- link building / rewriting --------------------------------------------
|
||||
function makeLink(label, links) {
|
||||
const frag = document.createDocumentFragment();
|
||||
const a = document.createElement("a");
|
||||
a.className = "rsl-link";
|
||||
a.textContent = label;
|
||||
a.href = links.spotify;
|
||||
a.target = "_blank";
|
||||
a.rel = "noopener noreferrer";
|
||||
a.title = "Open on Spotify";
|
||||
frag.appendChild(a);
|
||||
if (links.bandcamp) {
|
||||
const sup = document.createElement("sup");
|
||||
sup.className = "rsl-sup";
|
||||
const b = document.createElement("a");
|
||||
b.className = "rsl-bc";
|
||||
b.textContent = "bc";
|
||||
b.href = links.bandcamp;
|
||||
b.target = "_blank";
|
||||
b.rel = "noopener noreferrer";
|
||||
b.title = "Search on Bandcamp";
|
||||
sup.appendChild(b);
|
||||
frag.appendChild(sup);
|
||||
}
|
||||
return frag;
|
||||
}
|
||||
|
||||
function wrapNode(node) {
|
||||
const text = node.nodeValue;
|
||||
const ms = matchesIn(text).filter((m) => {
|
||||
const links = resolved.get(m.name);
|
||||
return links && links.spotify;
|
||||
});
|
||||
if (!ms.length) return;
|
||||
const frag = document.createDocumentFragment();
|
||||
let last = 0;
|
||||
for (const m of ms) {
|
||||
if (m.index < last) continue; // skip overlaps
|
||||
if (m.index > last) frag.appendChild(document.createTextNode(text.slice(last, m.index)));
|
||||
frag.appendChild(makeLink(text.substr(m.index, m.length), resolved.get(m.name)));
|
||||
last = m.index + m.length;
|
||||
}
|
||||
if (last < text.length) frag.appendChild(document.createTextNode(text.slice(last)));
|
||||
node.parentNode && node.parentNode.replaceChild(frag, node);
|
||||
}
|
||||
|
||||
// ---- resolver client ------------------------------------------------------
|
||||
const resolved = new Map(); // candidate string -> { spotify, bandcamp } | null
|
||||
|
||||
async function resolve(names) {
|
||||
try {
|
||||
const r = await fetch(`${RESOLVER_URL}/resolve`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ candidates: names }),
|
||||
});
|
||||
if (!r.ok) throw new Error(`http ${r.status}`);
|
||||
return await r.json();
|
||||
} catch (e) {
|
||||
console.warn("[rsl] resolver unreachable:", e.message);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- scan orchestration ---------------------------------------------------
|
||||
function getRoot() {
|
||||
return (
|
||||
document.querySelector("main, .content[role='main'], shreddit-comment-tree, .commentarea") ||
|
||||
document.body
|
||||
);
|
||||
}
|
||||
|
||||
async function scan() {
|
||||
const nodes = collectTextNodes(getRoot());
|
||||
if (!nodes.length) return;
|
||||
|
||||
const seen = new Set();
|
||||
for (const node of nodes) for (const m of matchesIn(node.nodeValue)) seen.add(m.name);
|
||||
|
||||
const ask = [...seen].filter((c) => !resolved.has(c));
|
||||
if (ask.length) {
|
||||
const res = await resolve(ask);
|
||||
if (res) for (const c of ask) resolved.set(c, res[c] || null); // negative-cache misses
|
||||
}
|
||||
for (const node of nodes) if (node.isConnected) wrapNode(node);
|
||||
}
|
||||
|
||||
// serialize scans; coalesce overlapping triggers
|
||||
let running = false;
|
||||
let pending = false;
|
||||
function schedule() {
|
||||
if (running) { pending = true; return; }
|
||||
running = true;
|
||||
scan()
|
||||
.catch((e) => console.warn("[rsl]", e))
|
||||
.finally(() => {
|
||||
running = false;
|
||||
if (pending) { pending = false; setTimeout(schedule, 300); }
|
||||
});
|
||||
}
|
||||
|
||||
function debounce(fn, ms) {
|
||||
let t;
|
||||
return () => { clearTimeout(t); t = setTimeout(fn, ms); };
|
||||
}
|
||||
|
||||
const onThread = () => /\/comments\//.test(location.pathname);
|
||||
|
||||
if (onThread()) schedule();
|
||||
new MutationObserver(debounce(() => { if (onThread()) schedule(); }, 600))
|
||||
.observe(document.documentElement, { childList: true, subtree: true });
|
||||
})();
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"manifest_version": 2,
|
||||
"name": "Reddit → Spotify/Bandcamp linker",
|
||||
"version": "0.1.0",
|
||||
"description": "Turns artist/album names in reddit comments into Spotify and Bandcamp links.",
|
||||
"browser_specific_settings": {
|
||||
"gecko": {
|
||||
"id": "reddit-spotify-linker@paul.yapplesauce.com",
|
||||
"strict_min_version": "109.0"
|
||||
}
|
||||
},
|
||||
"permissions": [
|
||||
"http://localhost:8787/*",
|
||||
"http://127.0.0.1:8787/*"
|
||||
],
|
||||
"content_scripts": [
|
||||
{
|
||||
"matches": ["*://*.reddit.com/*"],
|
||||
"js": ["content.js"],
|
||||
"css": ["styles.css"],
|
||||
"run_at": "document_idle"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
/* Injected links — kept subtle so reddit comments stay readable. */
|
||||
.rsl-link {
|
||||
text-decoration: underline dotted #1db954 !important; /* spotify green */
|
||||
text-underline-offset: 2px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.rsl-link:hover {
|
||||
text-decoration: underline solid #1db954 !important;
|
||||
}
|
||||
.rsl-sup {
|
||||
font-size: 0.7em;
|
||||
margin-left: 1px;
|
||||
vertical-align: super;
|
||||
line-height: 0;
|
||||
}
|
||||
.rsl-bc {
|
||||
color: #629aa9 !important; /* bandcamp teal */
|
||||
text-decoration: none !important;
|
||||
font-weight: 600;
|
||||
}
|
||||
.rsl-bc:hover {
|
||||
text-decoration: underline !important;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
# Copy to `.env` (it is gitignored). All values are OPTIONAL.
|
||||
#
|
||||
# Without Spotify credentials the resolver validates names against MusicBrainz and links
|
||||
# to Spotify/Bandcamp SEARCH pages — works with zero setup.
|
||||
#
|
||||
# With credentials it uses the Spotify Web API for DIRECT artist links.
|
||||
# Create a (free) app at https://developer.spotify.com/dashboard to get these.
|
||||
SPOTIFY_CLIENT_ID=
|
||||
SPOTIFY_CLIENT_SECRET=
|
||||
|
||||
# Port the resolver listens on (default 8787). If you change it, also update
|
||||
# RESOLVER_URL in extension/content.js and the host in extension/manifest.json.
|
||||
PORT=8787
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"name": "reddit-spotify-linker-resolver",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "Tiny resolver service: candidate names -> confirmed-artist links (Spotify/Bandcamp).",
|
||||
"engines": { "node": ">=18" },
|
||||
"scripts": {
|
||||
"start": "node resolver.js"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
// Tiny resolver service: candidate names -> artist links, for CONFIRMED artists only.
|
||||
//
|
||||
// Zero npm deps; Node 18+ (built-in fetch). The "which words are real artists" problem
|
||||
// is delegated to a music API rather than guessed client-side:
|
||||
// * with SPOTIFY_CLIENT_ID/SECRET set -> Spotify Web API (client-credentials) for
|
||||
// DIRECT artist links;
|
||||
// * without creds -> MusicBrainz validation + Spotify/Bandcamp SEARCH links (zero setup).
|
||||
// Either way a candidate only resolves when an artist's name matches it case-insensitively
|
||||
// (the precision lever that keeps random capitalized words from being linked).
|
||||
|
||||
import { createServer } from "node:http";
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
// --- minimal .env loader (no dependency) ------------------------------------
|
||||
try {
|
||||
const env = readFileSync(new URL("./.env", import.meta.url), "utf8");
|
||||
for (const line of env.split("\n")) {
|
||||
const m = line.match(/^\s*([\w.-]+)\s*=\s*(.*?)\s*$/);
|
||||
if (m && !(m[1] in process.env)) process.env[m[1]] = m[2].replace(/^["']|["']$/g, "");
|
||||
}
|
||||
} catch { /* no .env -> use real env / defaults */ }
|
||||
|
||||
const PORT = Number(process.env.PORT) || 8787;
|
||||
const SPOTIFY_ID = process.env.SPOTIFY_CLIENT_ID;
|
||||
const SPOTIFY_SECRET = process.env.SPOTIFY_CLIENT_SECRET;
|
||||
const USE_SPOTIFY = Boolean(SPOTIFY_ID && SPOTIFY_SECRET);
|
||||
const UA = "reddit-spotify-linker/0.1 (https://git.yapplesauce.com/paul/linker)";
|
||||
const MAX_CANDIDATES = 100;
|
||||
|
||||
const norm = (s) => String(s).normalize("NFKC").trim().toLowerCase();
|
||||
const bandcampSearch = (n) => `https://bandcamp.com/search?q=${encodeURIComponent(n)}&item_type=b`;
|
||||
const spotifySearch = (n) => `https://open.spotify.com/search/${encodeURIComponent(n)}`;
|
||||
|
||||
const cache = new Map(); // norm(name) -> { spotify, bandcamp, name } | null (negatives cached too)
|
||||
|
||||
// --- Spotify (optional) -----------------------------------------------------
|
||||
let spToken = null;
|
||||
let spTokenExp = 0;
|
||||
async function spotifyToken() {
|
||||
if (spToken && Date.now() < spTokenExp) return spToken;
|
||||
const auth = Buffer.from(`${SPOTIFY_ID}:${SPOTIFY_SECRET}`).toString("base64");
|
||||
const r = await fetch("https://accounts.spotify.com/api/token", {
|
||||
method: "POST",
|
||||
headers: { authorization: `Basic ${auth}`, "content-type": "application/x-www-form-urlencoded" },
|
||||
body: "grant_type=client_credentials",
|
||||
});
|
||||
if (!r.ok) throw new Error(`spotify token http ${r.status}`);
|
||||
const j = await r.json();
|
||||
spToken = j.access_token;
|
||||
spTokenExp = Date.now() + (j.expires_in - 60) * 1000;
|
||||
return spToken;
|
||||
}
|
||||
|
||||
async function viaSpotify(name) {
|
||||
const token = await spotifyToken();
|
||||
const url = `https://api.spotify.com/v1/search?type=artist&limit=5&q=${encodeURIComponent(name)}`;
|
||||
const r = await fetch(url, { headers: { authorization: `Bearer ${token}` } });
|
||||
if (!r.ok) throw new Error(`spotify search http ${r.status}`);
|
||||
const j = await r.json();
|
||||
const hit = (j.artists?.items ?? []).find((a) => norm(a.name) === norm(name));
|
||||
if (!hit) return null;
|
||||
return {
|
||||
name: hit.name,
|
||||
spotify: hit.external_urls?.spotify ?? spotifySearch(hit.name),
|
||||
bandcamp: bandcampSearch(hit.name),
|
||||
};
|
||||
}
|
||||
|
||||
// --- MusicBrainz (zero-cred fallback) ---------------------------------------
|
||||
// MusicBrainz asks for <=1 request/second, so issuance is serialized + spaced.
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
let mbGate = Promise.resolve();
|
||||
let mbLast = 0;
|
||||
function mbThrottled(name) {
|
||||
const gate = mbGate.then(async () => {
|
||||
const wait = 1100 - (Date.now() - mbLast);
|
||||
if (wait > 0) await sleep(wait);
|
||||
mbLast = Date.now();
|
||||
});
|
||||
mbGate = gate.catch(() => {}); // a failure never wedges the queue
|
||||
return gate.then(() => viaMusicBrainz(name));
|
||||
}
|
||||
|
||||
async function viaMusicBrainz(name) {
|
||||
const q = encodeURIComponent(`artist:"${name}"`);
|
||||
const url = `https://musicbrainz.org/ws/2/artist?fmt=json&limit=5&query=${q}`;
|
||||
const r = await fetch(url, { headers: { "user-agent": UA, accept: "application/json" } });
|
||||
if (!r.ok) throw new Error(`musicbrainz http ${r.status}`);
|
||||
const j = await r.json();
|
||||
const hit = (j.artists ?? []).find((a) => norm(a.name) === norm(name) && (a.score ?? 0) >= 90);
|
||||
if (!hit) return null;
|
||||
return { name: hit.name, spotify: spotifySearch(hit.name), bandcamp: bandcampSearch(hit.name) };
|
||||
}
|
||||
|
||||
// --- resolve one candidate (cached) -----------------------------------------
|
||||
async function resolveOne(name) {
|
||||
const key = norm(name);
|
||||
if (!key) return null;
|
||||
if (cache.has(key)) return cache.get(key);
|
||||
try {
|
||||
const result = USE_SPOTIFY ? await viaSpotify(name) : await mbThrottled(name);
|
||||
cache.set(key, result); // cache hits AND confirmed misses
|
||||
return result;
|
||||
} catch (e) {
|
||||
console.error(`resolve "${name}": ${e.message}`); // transient -> don't cache
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveAll(candidates) {
|
||||
const uniq = [...new Set(candidates.map((c) => String(c).trim()).filter(Boolean))].slice(0, MAX_CANDIDATES);
|
||||
const out = {};
|
||||
await Promise.all(uniq.map(async (name) => { out[name] = await resolveOne(name); }));
|
||||
return out;
|
||||
}
|
||||
|
||||
// --- HTTP -------------------------------------------------------------------
|
||||
function readBody(req) {
|
||||
return new Promise((resolve, reject) => {
|
||||
let data = "";
|
||||
req.on("data", (c) => {
|
||||
data += c;
|
||||
if (data.length > 1e6) { reject(new Error("body too large")); req.destroy(); }
|
||||
});
|
||||
req.on("end", () => resolve(data));
|
||||
req.on("error", reject);
|
||||
});
|
||||
}
|
||||
|
||||
const json = (res, code, obj) => {
|
||||
res.writeHead(code, { "content-type": "application/json" });
|
||||
res.end(JSON.stringify(obj));
|
||||
};
|
||||
|
||||
const server = createServer(async (req, res) => {
|
||||
res.setHeader("access-control-allow-origin", "*");
|
||||
res.setHeader("access-control-allow-headers", "content-type");
|
||||
res.setHeader("access-control-allow-methods", "GET, POST, OPTIONS");
|
||||
if (req.method === "OPTIONS") { res.writeHead(204); return res.end(); }
|
||||
|
||||
if (req.method === "GET" && req.url === "/health") {
|
||||
return json(res, 200, { ok: true, provider: USE_SPOTIFY ? "spotify" : "musicbrainz", cached: cache.size });
|
||||
}
|
||||
|
||||
if (req.method === "POST" && req.url === "/resolve") {
|
||||
try {
|
||||
const { candidates } = JSON.parse((await readBody(req)) || "{}");
|
||||
if (!Array.isArray(candidates)) return json(res, 400, { error: "candidates must be an array" });
|
||||
return json(res, 200, await resolveAll(candidates));
|
||||
} catch (e) {
|
||||
return json(res, 500, { error: e.message });
|
||||
}
|
||||
}
|
||||
|
||||
json(res, 404, { error: "not found" });
|
||||
});
|
||||
|
||||
server.listen(PORT, () => {
|
||||
console.log(`resolver listening on http://localhost:${PORT} (provider: ${USE_SPOTIFY ? "spotify" : "musicbrainz"})`);
|
||||
});
|
||||
Reference in New Issue
Block a user