Dough Git

commit

feat: Add yt-dlp support

commit
1d3681e40cb37c8a301e5cc6cded177a5bff5d89
author
Clove Twilight <[email protected]>
date
2026-08-30 23:45

diff --git a/.env.example b/.env.example
index 79b1a37..3f0d3cb 100644
--- a/.env.example
+++ b/.env.example
@@ -19,6 +19,12 @@ MUSIC_MEDIA_DIR=/app/data/media
 MUSIC_MAX_UPLOAD_MB=500
 MUSIC_XACCEL_PREFIX=
 
+# YouTube import (upload screen -> "YouTube link"). Needs yt-dlp + ffmpeg on
+# PATH (both are in the Docker image). Set _ENABLED=false to hide the feature.
+MUSIC_YTDLP_ENABLED=true
+MUSIC_YTDLP_BIN=yt-dlp
+MUSIC_YTDLP_TIMEOUT_MS=120000
+
 # LastFM
 MUSIC_LASTFM_API_KEY=
 MUSIC_LASTFM_SHARED_SECRET=
\ No newline at end of file
diff --git a/Dockerfile b/Dockerfile
index fa16923..eb42a64 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -1,10 +1,21 @@
 FROM oven/bun:1 AS base
 WORKDIR /app
 
-# ffmpeg powers the background Opus transcode (lib/media.ts). Without it the
-# app still runs — transcoding just no-ops and /stream serves the master.
+# ffmpeg powers the background Opus transcode (lib/media.ts) and yt-dlp's
+# audio extraction. yt-dlp backs "Import from YouTube" on the upload screen
+# (config.youtube / routes/songs.ts POST /import). Both are optional at
+# runtime: without ffmpeg the transcode no-ops; without yt-dlp the import
+# endpoint returns 503 and file upload is unaffected.
+#
+# yt-dlp_linux is the self-contained PyInstaller build (no system Python).
+# It's fetched from the `latest` release on purpose — yt-dlp needs frequent
+# updates to keep working against YouTube, so a rebuild picks up the newest.
 RUN apt-get update \
-  && apt-get install -y --no-install-recommends ffmpeg \
+  && apt-get install -y --no-install-recommends ffmpeg curl ca-certificates \
+  && curl -fsSL -o /usr/local/bin/yt-dlp \
+       https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_linux \
+  && chmod a+rx /usr/local/bin/yt-dlp \
+  && /usr/local/bin/yt-dlp --version \
   && rm -rf /var/lib/apt/lists/*
 
 COPY . .
diff --git a/ReadMe.md b/ReadMe.md
index f2987c4..6ad5743 100644
--- a/ReadMe.md
+++ b/ReadMe.md
@@ -14,6 +14,7 @@ account system.
 - Stream your own music library with seek/scrub (HTTP range) and gapless-ish playback
 - Playlists, artists, and shared (public) playlists
 - Upload tracks straight from the web UI, with automatic Opus transcoding for smaller mobile streams
+- Import a track from a YouTube link (server-side `yt-dlp`) — same review flow as an upload
 - Duplicate detection to keep the library tidy
 - Lyrics lookup
 - Last.fm scrobbling
@@ -31,7 +32,7 @@ account system.
 | Desktop     | [Electron](https://www.electronjs.org/) (TypeScript) · Discord Rich Presence over IPC |
 | Android     | Native Kotlin · WebView UI + Media3/ExoPlayer for background playback    |
 | Auth        | Pocket ID (OIDC) — session cookie for web, bearer token for native apps  |
-| Media       | FFmpeg (Opus transcode) · optional nginx `X-Accel-Redirect` offload      |
+| Media       | FFmpeg (Opus transcode) · `yt-dlp` (YouTube import) · optional nginx `X-Accel-Redirect` offload |
 | Tooling     | Bun workspaces monorepo · Docker / Compose                              |
 
 ## Project structure
@@ -49,9 +50,11 @@ apps/
 
 ## Getting started
 
-**Prerequisites:** [Bun](https://bun.sh), PostgreSQL, and Redis. The desktop app
-needs only Bun (Electron installs as a dev dependency); the Android app needs
-JDK 17 and the Android SDK.
+**Prerequisites:** [Bun](https://bun.sh), PostgreSQL, and Redis. `ffmpeg` (Opus
+transcode) and `yt-dlp` (YouTube import) are optional — both features degrade
+gracefully when the binary is missing, and the Docker image bundles both. The
+desktop app needs only Bun (Electron installs as a dev dependency); the Android
+app needs JDK 17 and the Android SDK.
 
 ```bash
 # 1. Install dependencies
@@ -84,6 +87,7 @@ list. The essentials:
 | `MUSIC_ADMINS`          | Comma-separated user IDs granted admin         |
 | `MUSIC_MEDIA_DIR`       | Where uploaded audio is stored                 |
 | `MUSIC_LASTFM_API_KEY` / `MUSIC_LASTFM_SHARED_SECRET` | Optional Last.fm scrobbling |
+| `MUSIC_YTDLP_ENABLED` / `MUSIC_YTDLP_BIN` / `MUSIC_YTDLP_TIMEOUT_MS` | YouTube import: on/off, binary name, per-download wall-clock cap |
 
 ## Building the apps
 
diff --git a/web/client/src/app.ts b/web/client/src/app.ts
index c30c308..df40bce 100644
--- a/web/client/src/app.ts
+++ b/web/client/src/app.ts
@@ -812,13 +812,20 @@ function openUploadModal(): void {
         <h2>Upload</h2>
         <button class="icon-btn" id="modal-close" title="Close"><i class="bi bi-x-lg"></i></button>
       </div>
-      <div class="dropzone" id="dropzone" tabindex="0" role="button" aria-label="Add audio files">
-        <i class="bi bi-cloud-arrow-up dz-icon"></i>
-        <span class="dz-text">Drag audio files here, or <span class="dz-link">browse</span></span>
-        <span class="dz-hint">One song lets you edit details; multiple upload in bulk.</span>
-        <input type="file" accept="audio/*" multiple hidden />
+      <div class="seg" role="tablist">
+        <button class="seg-btn active" id="tab-files" role="tab" aria-selected="true" type="button">Files</button>
+        <button class="seg-btn" id="tab-yt" role="tab" aria-selected="false" type="button">YouTube link</button>
       </div>
-      <div id="upload-body"></div>
+      <div id="files-mode">
+        <div class="dropzone" id="dropzone" tabindex="0" role="button" aria-label="Add audio files">
+          <i class="bi bi-cloud-arrow-up dz-icon"></i>
+          <span class="dz-text">Drag audio files here, or <span class="dz-link">browse</span></span>
+          <span class="dz-hint">One song lets you edit details; multiple upload in bulk.</span>
+          <input type="file" accept="audio/*" multiple hidden />
+        </div>
+        <div id="upload-body"></div>
+      </div>
+      <div id="yt-mode" hidden></div>
     </div>
   `;
   document.body.appendChild(overlay);
@@ -870,6 +877,79 @@ function openUploadModal(): void {
     onFiles((e as DragEvent).dataTransfer?.files);
   });
 
+  // --- Files / YouTube link mode switch ---
+  const filesMode = overlay.querySelector("#files-mode") as HTMLElement;
+  const ytMode = overlay.querySelector("#yt-mode") as HTMLElement;
+  const tabFiles = overlay.querySelector("#tab-files") as HTMLButtonElement;
+  const tabYt = overlay.querySelector("#tab-yt") as HTMLButtonElement;
+  let ytRendered = false;
+  const showMode = (yt: boolean) => {
+    filesMode.hidden = yt;
+    ytMode.hidden = !yt;
+    tabFiles.classList.toggle("active", !yt);
+    tabYt.classList.toggle("active", yt);
+    tabFiles.setAttribute("aria-selected", String(!yt));
+    tabYt.setAttribute("aria-selected", String(yt));
+    if (yt && !ytRendered) {
+      renderYouTube();
+      ytRendered = true;
+    }
+  };
+  tabFiles.addEventListener("click", () => showMode(false));
+  tabYt.addEventListener("click", () => showMode(true));
+
+  // --- YouTube link: server-side yt-dlp import ---
+  function renderYouTube(): void {
+    ytMode.innerHTML = `
+      <form id="yt-form" class="upload-card">
+        <label class="field"><span>YouTube link <em>(required)</em></span>
+          <input name="url" type="url" inputmode="url"
+            placeholder="https://www.youtube.com/watch?v=…" required /></label>
+        <p class="dz-hint">Audio is downloaded on the server with yt-dlp. A playlist
+          link imports only the video it points at, and it can take a minute.</p>
+        <label class="field"><span>Song name <em>(optional — overrides YouTube)</em></span>
+          <input name="title" /></label>
+        <label class="field"><span>Artist <em>(optional — overrides YouTube)</em></span>
+          <input name="artist" /></label>
+        <label class="field"><span>Album <em>(optional)</em></span>
+          <input name="album" /></label>
+        <label class="check-row"><input type="checkbox" name="explicit" value="true" /> <span>Explicit content</span></label>
+        <button class="btn btn-primary" type="submit">Import</button>
+        <span id="yt-status" class="upload-status"></span>
+      </form>
+    `;
+    const form = ytMode.querySelector("#yt-form") as HTMLFormElement;
+    const status = ytMode.querySelector("#yt-status") as HTMLElement;
+
+    form.addEventListener("submit", async (e) => {
+      e.preventDefault();
+      const fd = new FormData(form);
+      const link = String(fd.get("url") ?? "").trim();
+      if (!link) return;
+      const btn = form.querySelector("button")!;
+      btn.textContent = "Importing…";
+      btn.setAttribute("disabled", "true");
+      status.textContent = "Downloading from YouTube — this can take a minute…";
+      try {
+        const song = await api.importSong({
+          url: link,
+          title: String(fd.get("title") ?? "").trim() || undefined,
+          artist: String(fd.get("artist") ?? "").trim() || undefined,
+          album: String(fd.get("album") ?? "").trim() || undefined,
+          explicit: fd.get("explicit") === "true",
+        });
+        await loadSongs();
+        if (state.view.kind === "library") renderMain();
+        close();
+        flash(`Added "${song.title}" by ${song.artist}.`);
+      } catch (err) {
+        status.textContent = `Import failed: ${(err as Error).message}`;
+        btn.textContent = "Import";
+        btn.removeAttribute("disabled");
+      }
+    });
+  }
+
   // --- single file: prefilled, editable form ---
   function renderSingle(file: File): void {
     body.innerHTML = `
diff --git a/web/client/src/styles.css b/web/client/src/styles.css
index 6352ea3..916cc30 100644
--- a/web/client/src/styles.css
+++ b/web/client/src/styles.css
@@ -1033,6 +1033,33 @@ button {
   max-width: none;
 }
 
+/* segmented Files / YouTube switch in the upload modal */
+.seg {
+  display: flex;
+  gap: 0.25rem;
+  padding: 0.25rem;
+  margin-bottom: 1rem;
+  background: var(--panel-2);
+  border: 1px solid var(--border);
+  border-radius: 10px;
+}
+
+.seg-btn {
+  flex: 1;
+  padding: 0.4rem 0.5rem;
+  border: none;
+  border-radius: 7px;
+  background: transparent;
+  color: var(--muted);
+  font: inherit;
+  cursor: pointer;
+}
+
+.seg-btn.active {
+  background: var(--panel);
+  color: var(--text);
+}
+
 /* --- toast --- */
 
 .toast {
diff --git a/web/server/src/config.ts b/web/server/src/config.ts
index 06e7a28..7b017aa 100644
--- a/web/server/src/config.ts
+++ b/web/server/src/config.ts
@@ -100,6 +100,20 @@ export const config = {
     bitrate: optional("MUSIC_OPUS_BITRATE", "128k"),
   },
 
+  // "Import from YouTube" on the upload screen: the server shells out to
+  // yt-dlp to fetch the audio, then runs it through the same pipeline as a
+  // file upload (tags, cover, dedupe, pending-review for non-admins). Needs
+  // the `yt-dlp` binary AND ffmpeg on PATH — both are in the Docker image.
+  // Set MUSIC_YTDLP_ENABLED=false to hide the feature. Only youtube.com /
+  // youtu.be URLs are accepted (SSRF guard); playlists are collapsed to the
+  // single video they point at.
+  youtube: {
+    enabled: optional("MUSIC_YTDLP_ENABLED", "true") !== "false",
+    binary: optional("MUSIC_YTDLP_BIN", "yt-dlp"),
+    // Wall-clock cap on one download before the child process is killed.
+    timeoutMs: Number(optional("MUSIC_YTDLP_TIMEOUT_MS", "120000")),
+  },
+
   // Offload audio/cover byte-serving to nginx via X-Accel-Redirect. When set
   // (e.g. "/_media"), /stream and /cover just authenticate then hand the file
   // to nginx by internal-redirect, so the app never streams the bytes and
diff --git a/web/server/src/lib/media.ts b/web/server/src/lib/media.ts
index 683dc1c..c6071c9 100644
--- a/web/server/src/lib/media.ts
+++ b/web/server/src/lib/media.ts
@@ -2,10 +2,14 @@
 
 import {
   mkdir,
+  mkdtemp,
+  readdir,
+  readFile,
   writeFile,
   rm,
   stat,
 } from "node:fs/promises";
+import { tmpdir } from "node:os";
 import {
   join,
   resolve,
@@ -199,6 +203,174 @@ export async function transcodeToOpus(
   }
 }
 
+// --- YouTube import ------------------------------------------------------
+
+// Only these hosts are handed to yt-dlp. yt-dlp will happily fetch from any
+// site it has an extractor for (including plain http(s) URLs), so without
+// this allowlist the endpoint is an SSRF primitive.
+const YT_HOSTS = new Set([
+  "youtube.com",
+  "www.youtube.com",
+  "m.youtube.com",
+  "music.youtube.com",
+  "youtu.be",
+  "www.youtu.be",
+]);
+
+export function isSupportedYouTubeUrl(raw: string): boolean {
+  let u: URL;
+  try {
+    u = new URL(raw);
+  } catch {
+    return false;
+  }
+  if (u.protocol !== "https:" && u.protocol !== "http:") return false;
+  return YT_HOSTS.has(u.hostname.toLowerCase());
+}
+
+// Thrown by downloadFromYouTube so the route can map a stable `code` to an
+// HTTP status and a user-facing message.
+export class YouTubeImportError extends Error {
+  code: string;
+  detail: string | undefined;
+  constructor(code: string, detail?: string) {
+    super(detail ? `${code}: ${detail}` : code);
+    this.name = "YouTubeImportError";
+    this.code = code;
+    this.detail = detail;
+  }
+}
+
+export type YouTubeImport = {
+  bytes: Uint8Array;
+  ext: string; // includes the leading dot, e.g. ".m4a"
+  durationS: number | null;
+  suggested: { title: string | null; artist: string | null; album: string | null };
+  cover: { data: Uint8Array; ext: string } | null;
+};
+
+// Fetch the audio track of a single YouTube video via yt-dlp and return the
+// bytes + metadata hints, for the caller to run through the normal upload
+// pipeline. Everything happens in a throwaway temp dir that's always removed.
+//
+// Safety: host is allowlisted by the caller AND here; --no-playlist collapses
+// a playlist URL to one video; --max-filesize caps the download; a wall-clock
+// timer kills yt-dlp if it hangs. yt-dlp is spawned argv-style (no shell) with
+// `--` before the URL.
+export async function downloadFromYouTube(rawUrl: string): Promise<YouTubeImport> {
+  if (!config.youtube.enabled) throw new YouTubeImportError("youtube_import_disabled");
+  if (!isSupportedYouTubeUrl(rawUrl)) throw new YouTubeImportError("unsupported_url");
+
+  const workDir = await mkdtemp(join(tmpdir(), "dmnd-yt-"));
+  try {
+    const proc = Bun.spawn(
+      [
+        config.youtube.binary,
+        "--no-playlist",
+        "--no-progress",
+        "--no-cache-dir",
+        "--no-part",
+        "--socket-timeout", "30",
+        "--retries", "3",
+        // Prefer an already-AAC stream so --audio-format m4a only remuxes
+        // (no re-encode); fall back to re-encoding whatever bestaudio is.
+        "-f", "bestaudio[acodec^=mp4a]/bestaudio[ext=m4a]/bestaudio/best",
+        "--extract-audio",
+        "--audio-format", "m4a",
+        "--audio-quality", "0",
+        "--embed-metadata",
+        "--write-info-json",
+        "--write-thumbnail",
+        "--convert-thumbnails", "jpg",
+        "--max-filesize", String(config.maxUploadBytes),
+        "-o", join(workDir, "audio.%(ext)s"),
+        "--",
+        rawUrl,
+      ],
+      { stdout: "ignore", stderr: "pipe", stdin: "ignore" },
+    );
+
+    let timedOut = false;
+    const timer = setTimeout(() => {
+      timedOut = true;
+      proc.kill(9);
+    }, config.youtube.timeoutMs);
+    let exit: number;
+    try {
+      exit = await proc.exited;
+    } finally {
+      clearTimeout(timer);
+    }
+
+    if (timedOut) throw new YouTubeImportError("timed_out");
+
+    if (exit !== 0) {
+      const err = (await new Response(proc.stderr).text()).trim();
+      if (exit === 127 || /not found|no such file|ENOENT/i.test(err)) {
+        throw new YouTubeImportError("ytdlp_unavailable");
+      }
+      if (/max-filesize|larger than max/i.test(err)) {
+        throw new YouTubeImportError("file_too_large");
+      }
+      console.error(`yt-dlp failed (exit ${exit}): ${err}`);
+      throw new YouTubeImportError("download_failed", err.split("\n").pop() || undefined);
+    }
+
+    const entries = await readdir(workDir);
+    const isImg = (n: string) => /\.(jpe?g|png|webp)$/i.test(n);
+    const audioName = entries.find(
+      (n) => n.startsWith("audio.") && !n.endsWith(".info.json") && !isImg(n),
+    );
+    if (!audioName) throw new YouTubeImportError("download_failed", "no audio produced");
+
+    const bytes = new Uint8Array(await readFile(join(workDir, audioName)));
+    if (bytes.byteLength > config.maxUploadBytes) {
+      throw new YouTubeImportError("file_too_large");
+    }
+    const ext = extname(audioName) || ".m4a";
+
+    const suggested: YouTubeImport["suggested"] = {
+      title: null,
+      artist: null,
+      album: null,
+    };
+    let durationS: number | null = null;
+    try {
+      const info = JSON.parse(
+        await readFile(join(workDir, "audio.info.json"), "utf8"),
+      ) as Record<string, unknown>;
+      const s = (v: unknown) =>
+        typeof v === "string" && v.trim() ? v.trim() : null;
+      suggested.title = s(info.track) ?? s(info.title);
+      suggested.artist =
+        s(info.artist) ?? s(info.creator) ?? s(info.uploader) ?? s(info.channel);
+      suggested.album = s(info.album);
+      if (typeof info.duration === "number" && info.duration > 0) {
+        durationS = Math.round(info.duration);
+      }
+    } catch {
+      // no / unreadable info json — leave the hints null
+    }
+
+    let cover: YouTubeImport["cover"] = null;
+    const thumbName = entries.find((n) => n.startsWith("audio.") && isImg(n));
+    if (thumbName) {
+      try {
+        const tb = new Uint8Array(await readFile(join(workDir, thumbName)));
+        if (tb.byteLength > 0) {
+          cover = { data: tb, ext: extname(thumbName).slice(1).toLowerCase() || "jpg" };
+        }
+      } catch {
+        // thumbnail is best-effort
+      }
+    }
+
+    return { bytes, ext, durationS, suggested, cover };
+  } finally {
+    await rm(workDir, { recursive: true, force: true }).catch(() => {});
+  }
+}
+
 // Serve a stored audio file as an HTTP response: HTTP Range (seek/scrub),
 // nginx X-Accel offload when configured, hard caching, and — when
 // `attachmentName` is set — a Content-Disposition that makes the browser save
diff --git a/web/server/src/routes/songs.ts b/web/server/src/routes/songs.ts
index a0be81d..02aac8f 100644
--- a/web/server/src/routes/songs.ts
+++ b/web/server/src/routes/songs.ts
@@ -35,6 +35,9 @@ import {
   isLosslessMaster,
   transcodeToOpus,
   serveAudioFile,
+  downloadFromYouTube,
+  isSupportedYouTubeUrl,
+  YouTubeImportError,
 } from "../lib/media.ts";
 
 export const songRoutes = new Hono<AppEnv>();
@@ -308,6 +311,111 @@ songRoutes.post(
   return c.json(toPublicSong(song), 201);
 });
 
+// Import from a YouTube link: yt-dlp fetches the audio, then it flows through
+// the same path as a file upload (title/artist required, cover + dedupe,
+// pending review for non-admins). A download is much heavier than a normal
+// upload, so non-admins get a tighter, longer-window rate limit.
+const importLimit = rateLimit({ name: "yt-import", limit: 10, windowSec: 600 });
+songRoutes.post(
+  "/import",
+  (c, next) => (isAdmin(c.get("user")) ? next() : importLimit(c, next)),
+  requireAuth,
+  async (c) => {
+    if (!config.youtube.enabled) {
+      return c.json({ error: "youtube_import_disabled" }, 503);
+    }
+    await ensureMediaDirs();
+    const user = c.get("user")!;
+
+    const body = await c.req
+      .json<{
+        url?: string;
+        title?: string;
+        artist?: string;
+        album?: string;
+        explicit?: boolean;
+      }>()
+      .catch(() => ({}) as Record<string, never>);
+
+    const link = typeof body.url === "string" ? body.url.trim() : "";
+    if (!link) return c.json({ error: "url_required" }, 400);
+    if (!isSupportedYouTubeUrl(link)) {
+      return c.json({ error: "unsupported_url" }, 400);
+    }
+
+    let dl: Awaited<ReturnType<typeof downloadFromYouTube>>;
+    try {
+      dl = await downloadFromYouTube(link);
+    } catch (err) {
+      if (err instanceof YouTubeImportError) {
+        const status =
+          err.code === "ytdlp_unavailable" || err.code === "youtube_import_disabled"
+            ? 503
+            : err.code === "file_too_large"
+              ? 413
+              : err.code === "unsupported_url"
+                ? 400
+                : err.code === "timed_out"
+                  ? 504
+                  : 502;
+        return c.json({ error: err.code, detail: err.detail }, status);
+      }
+      console.error("youtube import error:", err);
+      return c.json({ error: "download_failed" }, 502);
+    }
+
+    const tags = await extractTags(dl.bytes, undefined);
+    const pick = (v: unknown, ...fallbacks: (string | null)[]): string | null => {
+      const primary = typeof v === "string" ? v.trim() : "";
+      if (primary) return primary;
+      for (const f of fallbacks) {
+        if (f && f.trim()) return f.trim();
+      }
+      return null;
+    };
+
+    const title = pick(body.title, dl.suggested.title, tags.title);
+    const artist = pick(body.artist, dl.suggested.artist, tags.artist);
+    if (!title || !artist) {
+      return c.json({ error: "title_and_artist_required" }, 400);
+    }
+    const album =
+      typeof body.album === "string"
+        ? body.album.trim() || null
+        : (dl.suggested.album ?? tags.album);
+    const explicit = body.explicit === true;
+
+    const filePath = await saveAudio(dl.bytes, `youtube${dl.ext}`);
+
+    let coverPath: string | null = null;
+    if (dl.cover) {
+      coverPath = await saveCover(dl.cover.data, dl.cover.ext);
+    } else if (tags.cover) {
+      coverPath = await saveCover(tags.cover.data, tags.cover.ext);
+    }
+
+    const status = isAdmin(user) ? "approved" : "pending";
+    const rows = await sql<Song[]>`
+      INSERT INTO songs
+        (title, artist, album, cover_path, file_path, mime, duration_s,
+         size_bytes, explicit, normalized_title, uploaded_by, status)
+      VALUES
+        (${title}, ${artist}, ${album ?? null}, ${coverPath}, ${filePath},
+         ${mimeForAudioPath(filePath)}, ${tags.durationS ?? dl.durationS},
+         ${dl.bytes.byteLength}, ${explicit}, ${normalizeTitle(title)},
+         ${user.id}, ${status})
+      RETURNING *
+    `;
+    const song = rows[0]!;
+
+    findAndFlagDuplicates(song).catch((err) =>
+      console.error("duplicate detection failed:", err),
+    );
+
+    return c.json(toPublicSong(song), 201);
+  },
+);
+
 // Audio streaming with HTTP Range support (seek/scrub). Open to everyone —
 // streaming needs no account.
 songRoutes.get("/:id/stream", async (c) => {
diff --git a/web/shared/src/api-client.ts b/web/shared/src/api-client.ts
index e6f9837..8bced07 100644
--- a/web/shared/src/api-client.ts
+++ b/web/shared/src/api-client.ts
@@ -167,6 +167,45 @@ export const api = {
     return fetch(url("/api/songs"), { method: "POST", body: form }).then(json<Song>);
   },
 
+  // Import a single YouTube video's audio via server-side yt-dlp. Optional
+  // title/artist/album/explicit override what yt-dlp reads from the video.
+  async importSong(body: {
+    url: string;
+    title?: string;
+    artist?: string;
+    album?: string;
+    explicit?: boolean;
+  }): Promise<Song> {
+    const res = await fetch(url("/api/songs/import"), {
+      method: "POST",
+      headers: { "content-type": "application/json" },
+      body: JSON.stringify(body),
+    });
+    if (res.ok) return (await res.json()) as Song;
+
+    const data = (await res.json().catch(() => ({}))) as {
+      error?: string;
+      detail?: string;
+    };
+    const friendly: Record<string, string> = {
+      youtube_import_disabled: "YouTube import is turned off on this server.",
+      ytdlp_unavailable: "yt-dlp isn't installed on the server.",
+      unsupported_url: "Only youtube.com and youtu.be links are supported.",
+      url_required: "Paste a YouTube link first.",
+      file_too_large: "That video's audio is over the upload size limit.",
+      timed_out: "The download took too long and was stopped.",
+      title_and_artist_required:
+        "Couldn't read a title/artist — fill them in and retry.",
+      download_failed: "yt-dlp couldn't download that video.",
+    };
+    throw new Error(
+      (data.error && friendly[data.error]) ||
+        data.detail ||
+        data.error ||
+        `${res.status} ${res.statusText}`,
+    );
+  },
+
   updateSong(id: string, form: FormData): Promise<Song> {
     return fetch(url(`/api/songs/${id}`), { method: "PATCH", body: form }).then(
       json<Song>,