Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

refactor: share the yt-dlp spawn, marker parsing and exit classification between the audio and video importers (#5718)

[._.]/ Adam Eivyc7e41ef8b3b7
diff --git a/server/services/ytdlpAudioImport.js b/server/services/ytdlpAudioImport.js
index e0d6f7aec9..7acb21f45c 100644
--- a/server/services/ytdlpAudioImport.js
+++ b/server/services/ytdlpAudioImport.js
@@ -5,7 +5,9 @@
* round reference-audio "Download from URL" convenience (#2120) — can reuse the
* hard part (yt-dlp arg construction, `--progress-template` machine-readable
* progress parsing, cancel-aware exit classification, temp-file cleanup) rather
- * than duplicating ~120 lines of subtle yt-dlp knowledge.
+ * than duplicating ~120 lines of subtle yt-dlp knowledge. The spawn, marker
+ * parsing and exit classification it shares with the video core live in
+ * ytdlpRun.js; this module owns the audio argv and the temp-file lifecycle.
*
* A single yt-dlp invocation does the whole job (`-x --audio-format mp3`,
* pointed at our discovered ffmpeg via --ffmpeg-location) — yt-dlp already
@@ -20,7 +22,6 @@
* http(s) URL (SSRF-guarded) — so the core never sees an unvetted URL.
*/
-import { spawn } from '../lib/childProcess.js';
import { existsSync } from 'fs';
import { readdir, unlink } from 'fs/promises';
import { tmpdir } from 'os';
@@ -28,17 +29,7 @@ import { join, dirname } from 'path';
import { ServerError } from '../lib/errorHandler.js';
import { findFfmpeg } from '../lib/ffmpeg.js';
import { findYtDlp } from '../lib/ytdlp.js';
-import { safeChildProcessOptions } from '../lib/processEnv.js';
-import { createLineReader } from '../lib/streamLines.js';
-
-const TITLE_PREFIX = 'PORTOS_TITLE:';
-// Custom progress markers via yt-dlp's `--progress-template`, rather than
-// scraping the human-readable `[download] NN%` / `[ExtractAudio]` console
-// lines — a stable machine interface (mirrors ffmpeg's `-progress pipe:2`
-// key=value protocol used by render.js) that a yt-dlp text-format change
-// can't silently break.
-const PROGRESS_PREFIX = 'PORTOS_PROGRESS:';
-const STAGE_PREFIX = 'PORTOS_STAGE:';
+import { runYtDlp, ytdlpMarkerArgs } from './ytdlpRun.js';
/**
* Locate yt-dlp + ffmpeg, throwing an actionable ServerError if either is
@@ -93,25 +84,12 @@ export async function downloadAudioToTempMp3({
const tempBase = join(tmpdir(), tempPrefix);
const outPath = `${tempBase}.mp3`;
- let title = '';
const args = [
'-f', 'bestaudio/best',
'-x', '--audio-format', 'mp3', '--audio-quality', '0',
'--no-playlist',
'--ffmpeg-location', dirname(ffmpeg),
- '--newline',
- '--print', `${TITLE_PREFIX}%(title)s`,
- '--progress-template', `download:${PROGRESS_PREFIX}%(progress._percent_str)s`,
- '--progress-template', `postprocess:${STAGE_PREFIX}extracting`,
- // `--print` has two side effects that would otherwise break this job
- // (confirmed against a real download): it implies `--simulate` (skips the
- // actual download/postprocess entirely, so `--no-simulate` is required to
- // force the real run), AND it suppresses ALL of yt-dlp's normal
- // progress/postprocessor reporting — so `--progress` plus the two
- // `--progress-template`s above are required to get stable, machine-readable
- // progress/stage markers back alongside the printed title in one invocation.
- '--no-simulate',
- '--progress',
+ ...ytdlpMarkerArgs('extracting'),
// Bound resource use — without these, a long video or a livestream/archive
// URL downloads and transcodes unbounded, eating disk in tmpdir() and CPU
// with no cap.
@@ -121,51 +99,16 @@ export async function downloadAudioToTempMp3({
url,
];
- const proc = spawn(ytDlp, args, safeChildProcessOptions({ stdio: ['ignore', 'pipe', 'pipe'] }));
- registerProcess(proc);
-
- const onLine = (line) => {
- if (line.startsWith(TITLE_PREFIX)) {
- title = line.slice(TITLE_PREFIX.length).trim();
- return;
- }
- if (line.startsWith(PROGRESS_PREFIX)) {
- const percent = parseFloat(line.slice(PROGRESS_PREFIX.length));
- if (Number.isFinite(percent)) onProgress({ percent });
- return;
- }
- if (line.startsWith(STAGE_PREFIX)) {
- onProgress({ percent: 100, stage: line.slice(STAGE_PREFIX.length) });
- }
- };
- // Separate readers per stream — stdout and stderr chunks arrive
- // independently, so a shared buffer can complete a partial line from one
- // stream with a chunk from the other, corrupting a marker line.
- const stdoutReader = createLineReader(onLine);
- const stderrReader = createLineReader(onLine);
- proc.stdout.on('data', stdoutReader.push);
- proc.stderr.on('data', stderrReader.push); // yt-dlp writes some progress/info lines to stderr too
-
- const exit = await new Promise((resolve) => {
- proc.on('error', (err) => resolve({ code: null, reason: `spawn failed: ${err.message}` }));
- proc.on('close', (code, signal) => resolve({ code, signal }));
- });
- registerProcess(null);
+ const exit = await runYtDlp({ ytDlp, args, onProgress, registerProcess });
- if (exit.signal === 'SIGTERM' || exit.signal === 'SIGKILL') {
- // Don't flush on cancel — a SIGKILL'd child leaves only a partial marker
- // line in the carry, and emitting it would fire a stray progress/stage
- // callback right before the caller reports the cancellation.
+ if (exit.canceled) {
await cleanupYtDlpTemp(tempPrefix);
return { outcome: 'canceled' };
}
- // Flush any final line the child wrote without a trailing newline before exit.
- stdoutReader.flush();
- stderrReader.flush();
if (exit.code !== 0 || !existsSync(outPath)) {
// A --match-filters/--max-filesize rejection exits 0 with no output file
// (yt-dlp treats a filtered-out video as "nothing to do", not an error) —
- // `--print`'s suppression of normal reporting (see above) means the
+ // `--print`'s suppression of normal reporting (see ytdlpRun) means the
// specific reason never reaches our stdout/stderr parsing, so name the two
// known bounds explicitly rather than a bare exit code.
const reason = exit.code === 0
@@ -175,5 +118,5 @@ export async function downloadAudioToTempMp3({
return { outcome: 'failed', reason };
}
- return { outcome: 'complete', outPath, title };
+ return { outcome: 'complete', outPath, title: exit.title };
}
diff --git a/server/services/ytdlpAudioImport.test.js b/server/services/ytdlpAudioImport.test.js
index b3b1f4a4dd..8295662a21 100644
--- a/server/services/ytdlpAudioImport.test.js
+++ b/server/services/ytdlpAudioImport.test.js
@@ -86,6 +86,9 @@ describe('downloadAudioToTempMp3 — outcomes', () => {
const result = await downloadAudioToTempMp3(baseArgs);
expect(result.outcome).toBe('failed');
expect(result.reason).toMatch(/no audio was produced/);
+ // The bounds are the only diagnosis the user gets — --print suppresses yt-dlp's own.
+ expect(result.reason).toMatch(/20 minutes/);
+ expect(result.reason).toMatch(/60MB/);
});
it('reports failed with the exit code when yt-dlp errors', async () => {
diff --git a/server/services/ytdlpRun.js b/server/services/ytdlpRun.js
new file mode 100644
index 0000000000..64c9386035
--- /dev/null
+++ b/server/services/ytdlpRun.js
@@ -0,0 +1,126 @@
+/**
+ * The yt-dlp invocation core shared by the audio and video importers.
+ *
+ * `ytdlpAudioImport.js` and `ytdlpVideoImport.js` are mirror images: they build
+ * different argv (audio extraction vs. video merge/remux) and discover their
+ * output differently, but the middle — spawn, per-stream line reading, the
+ * `PORTOS_*` marker protocol, the exit promise, the cancel-without-flush branch
+ * — was duplicated verbatim in both. A yt-dlp release that renames a
+ * `--progress-template` key or changes signal behaviour then had to be fixed
+ * twice. This module owns that middle so it is fixed once.
+ *
+ * It deliberately does NOT touch the filesystem: creating the destination,
+ * probing for the produced file, and deleting partials stay with the caller,
+ * which is what lets the two importers keep their different output-discovery
+ * strategies.
+ *
+ * Runs outside the Express request lifecycle (child-process event handlers), so
+ * it never throws for a yt-dlp runtime failure — it classifies the exit and
+ * RETURNS it. The caller turns that into an outcome and user-facing prose.
+ */
+
+import { spawn } from '../lib/childProcess.js';
+import { safeChildProcessOptions } from '../lib/processEnv.js';
+import { createLineReader } from '../lib/streamLines.js';
+
+/**
+ * The wire protocol between our `--progress-template`/`--print` flags and the
+ * parser below. Custom markers rather than scraping the human-readable
+ * `[download] NN%` / `[ExtractAudio]` console lines — a stable machine
+ * interface (mirrors ffmpeg's `-progress pipe:2` key=value protocol used by
+ * render.js) that a yt-dlp text-format change can't silently break.
+ */
+export const YTDLP_MARKERS = {
+ TITLE: 'PORTOS_TITLE:',
+ PROGRESS: 'PORTOS_PROGRESS:',
+ STAGE: 'PORTOS_STAGE:',
+};
+
+/**
+ * The argv fragment that emits the markers `runYtDlp` parses. Shared because it
+ * IS the protocol; the format-selection flags around it stay with each importer,
+ * since those are the actual domain difference.
+ *
+ * `--print` has two side effects that would otherwise break the job (confirmed
+ * against a real download): it implies `--simulate` (skips the actual
+ * download/postprocess entirely, so `--no-simulate` is required to force the
+ * real run), AND it suppresses ALL of yt-dlp's normal progress/postprocessor
+ * reporting — so `--progress` plus the two `--progress-template`s are required
+ * to get stable, machine-readable progress/stage markers back alongside the
+ * printed title in one invocation.
+ *
+ * @param {string} postprocessStage Stage label reported once postprocessing
+ * starts ('extracting' for audio, 'merging' for video).
+ */
+export const ytdlpMarkerArgs = (postprocessStage) => [
+ '--newline',
+ '--print', `${YTDLP_MARKERS.TITLE}%(title)s`,
+ '--progress-template', `download:${YTDLP_MARKERS.PROGRESS}%(progress._percent_str)s`,
+ '--progress-template', `postprocess:${YTDLP_MARKERS.STAGE}${postprocessStage}`,
+ '--no-simulate',
+ '--progress',
+];
+
+/**
+ * Spawn yt-dlp, stream its markers to `onProgress`, and classify the exit.
+ *
+ * @param {object} opts
+ * @param {string} opts.ytDlp yt-dlp binary path.
+ * @param {string[]} opts.args Fully-built argv (marker args included).
+ * @param {function} opts.onProgress ({ percent, stage }) => void — SSE-agnostic.
+ * @param {function} opts.registerProcess (proc|null) => void — lets the caller wire cancel.
+ * @returns {Promise<{ canceled:boolean, code:number|null, signal:string|null, reason:string|null, title:string }>}
+ * `canceled` is true when the child died on SIGTERM/SIGKILL. `reason` carries
+ * the spawn-failure message when the binary never started, else null.
+ */
+export async function runYtDlp({ ytDlp, args, onProgress, registerProcess }) {
+ const proc = spawn(ytDlp, args, safeChildProcessOptions({ stdio: ['ignore', 'pipe', 'pipe'] }));
+ registerProcess(proc);
+
+ let title = '';
+ const onLine = (line) => {
+ if (line.startsWith(YTDLP_MARKERS.TITLE)) {
+ title = line.slice(YTDLP_MARKERS.TITLE.length).trim();
+ return;
+ }
+ if (line.startsWith(YTDLP_MARKERS.PROGRESS)) {
+ const percent = parseFloat(line.slice(YTDLP_MARKERS.PROGRESS.length));
+ if (Number.isFinite(percent)) onProgress({ percent });
+ return;
+ }
+ if (line.startsWith(YTDLP_MARKERS.STAGE)) {
+ onProgress({ percent: 100, stage: line.slice(YTDLP_MARKERS.STAGE.length) });
+ }
+ };
+ // Separate readers per stream — stdout and stderr chunks arrive
+ // independently, so a shared buffer can complete a partial line from one
+ // stream with a chunk from the other, corrupting a marker line.
+ const stdoutReader = createLineReader(onLine);
+ const stderrReader = createLineReader(onLine);
+ proc.stdout.on('data', stdoutReader.push);
+ proc.stderr.on('data', stderrReader.push); // yt-dlp writes some progress/info lines to stderr too
+
+ const exit = await new Promise((resolve) => {
+ proc.on('error', (err) => resolve({ code: null, reason: `spawn failed: ${err.message}` }));
+ proc.on('close', (code, signal) => resolve({ code, signal }));
+ });
+ registerProcess(null);
+
+ if (exit.signal === 'SIGTERM' || exit.signal === 'SIGKILL') {
+ // Don't flush on cancel — a SIGKILL'd child leaves only a partial marker
+ // line in the carry, and emitting it would fire a stray progress/stage
+ // callback right before the caller reports the cancellation.
+ return { canceled: true, code: exit.code ?? null, signal: exit.signal, reason: null, title };
+ }
+ // Flush any final line the child wrote without a trailing newline before exit.
+ stdoutReader.flush();
+ stderrReader.flush();
+
+ return {
+ canceled: false,
+ code: exit.code ?? null,
+ signal: exit.signal ?? null,
+ reason: exit.reason ?? null,
+ title,
+ };
+}
diff --git a/server/services/ytdlpRun.test.js b/server/services/ytdlpRun.test.js
new file mode 100644
index 0000000000..6a4985b30e
--- /dev/null
+++ b/server/services/ytdlpRun.test.js
@@ -0,0 +1,132 @@
+/**
+ * The shared yt-dlp spawn/marker/exit core.
+ *
+ * These pin the parts both importers used to own a copy of: the per-stream line
+ * readers (a marker split across chunks, and two streams interleaving), and the
+ * cancel branch that deliberately does NOT flush the carry.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { EventEmitter } from 'events';
+
+vi.mock('../lib/childProcess.js', async (importOriginal) => ({ ...(await importOriginal()), spawn: vi.fn() }));
+
+const { spawn } = await import('../lib/childProcess.js');
+const { runYtDlp, ytdlpMarkerArgs, YTDLP_MARKERS } = await import('./ytdlpRun.js');
+
+/**
+ * A fake yt-dlp child. `script` is a list of `[stream, chunk]` pairs written in
+ * order before the close, so a test can split one line across two chunks or
+ * interleave the two streams.
+ */
+function fakeChild({ code = 0, signal = null, script = [] } = {}) {
+ const proc = new EventEmitter();
+ proc.stdout = new EventEmitter();
+ proc.stderr = new EventEmitter();
+ setImmediate(() => {
+ for (const [stream, chunk] of script) proc[stream].emit('data', Buffer.from(chunk));
+ proc.emit('close', code, signal);
+ });
+ return proc;
+}
+
+const baseArgs = { ytDlp: '/usr/local/bin/yt-dlp', args: ['--version'], onProgress: () => {}, registerProcess: () => {} };
+
+beforeEach(() => { vi.clearAllMocks(); });
+
+describe('ytdlpMarkerArgs', () => {
+ it('emits the print/progress-template pair plus the --no-simulate workaround', () => {
+ const args = ytdlpMarkerArgs('extracting');
+ expect(args).toEqual(expect.arrayContaining(['--print', `${YTDLP_MARKERS.TITLE}%(title)s`]));
+ expect(args).toEqual(expect.arrayContaining([
+ '--progress-template', `download:${YTDLP_MARKERS.PROGRESS}%(progress._percent_str)s`,
+ ]));
+ expect(args).toEqual(expect.arrayContaining([
+ '--progress-template', `postprocess:${YTDLP_MARKERS.STAGE}extracting`,
+ ]));
+ // --print implies --simulate and suppresses reporting; both undos must ride along.
+ expect(args).toEqual(expect.arrayContaining(['--no-simulate', '--progress']));
+ });
+});
+
+describe('runYtDlp — marker parsing', () => {
+ it('emits one progress frame for a marker split across two stdout chunks', async () => {
+ const seen = [];
+ spawn.mockReturnValue(fakeChild({ script: [['stdout', 'PORTOS_PROG'], ['stdout', 'RESS: 42.0%\n']] }));
+ await runYtDlp({ ...baseArgs, onProgress: (p) => seen.push(p) });
+ expect(seen).toEqual([{ percent: 42 }]);
+ });
+
+ it('does not corrupt a marker when stdout and stderr interleave mid-line', async () => {
+ const seen = [];
+ spawn.mockReturnValue(fakeChild({
+ // The reason each stream needs its OWN reader: a shared carry would
+ // splice stderr's chunk onto stdout's partial line.
+ script: [
+ ['stdout', 'PORTOS_PROGRESS: 10'],
+ ['stderr', 'PORTOS_STAGE:extracting\n'],
+ ['stdout', '.0%\n'],
+ ],
+ }));
+ await runYtDlp({ ...baseArgs, onProgress: (p) => seen.push(p) });
+ expect(seen).toEqual([{ percent: 100, stage: 'extracting' }, { percent: 10 }]);
+ });
+
+ it('captures the title marker and ignores a non-numeric percent', async () => {
+ const seen = [];
+ spawn.mockReturnValue(fakeChild({
+ script: [['stdout', 'PORTOS_TITLE:Example Clip \nPORTOS_PROGRESS:not-a-number\n']],
+ }));
+ const result = await runYtDlp({ ...baseArgs, onProgress: (p) => seen.push(p) });
+ expect(result.title).toBe('Example Clip');
+ expect(seen).toEqual([]);
+ });
+
+ it('flushes a final unterminated line on a normal exit', async () => {
+ const seen = [];
+ spawn.mockReturnValue(fakeChild({ script: [['stdout', 'PORTOS_PROGRESS: 99.0%']] })); // no trailing newline
+ await runYtDlp({ ...baseArgs, onProgress: (p) => seen.push(p) });
+ expect(seen).toEqual([{ percent: 99 }]);
+ });
+});
+
+describe('runYtDlp — exit classification', () => {
+ it('reports canceled on SIGKILL and fires no progress frame from the unflushed carry', async () => {
+ const seen = [];
+ spawn.mockReturnValue(fakeChild({
+ code: null, signal: 'SIGKILL', script: [['stdout', 'PORTOS_PROGRESS: 50.0%']], // partial line, no newline
+ }));
+ const result = await runYtDlp({ ...baseArgs, onProgress: (p) => seen.push(p) });
+ expect(result).toMatchObject({ canceled: true, signal: 'SIGKILL' });
+ expect(seen).toEqual([]);
+ });
+
+ it('reports canceled on SIGTERM', async () => {
+ spawn.mockReturnValue(fakeChild({ code: null, signal: 'SIGTERM' }));
+ await expect(runYtDlp(baseArgs)).resolves.toMatchObject({ canceled: true, signal: 'SIGTERM' });
+ });
+
+ it('passes a non-zero exit code through without a reason', async () => {
+ spawn.mockReturnValue(fakeChild({ code: 1 }));
+ await expect(runYtDlp(baseArgs)).resolves.toMatchObject({ canceled: false, code: 1, reason: null });
+ });
+
+ it('reports a spawn failure as a reason rather than throwing', async () => {
+ const proc = new EventEmitter();
+ proc.stdout = new EventEmitter();
+ proc.stderr = new EventEmitter();
+ setImmediate(() => proc.emit('error', new Error('ENOENT')));
+ spawn.mockReturnValue(proc);
+ const result = await runYtDlp(baseArgs);
+ expect(result).toMatchObject({ canceled: false, code: null, reason: 'spawn failed: ENOENT' });
+ });
+
+ it('registers the child then clears it after the exit', async () => {
+ const registered = [];
+ spawn.mockReturnValue(fakeChild({ code: 0 }));
+ await runYtDlp({ ...baseArgs, registerProcess: (p) => registered.push(p) });
+ expect(registered).toHaveLength(2);
+ expect(registered[0]).not.toBeNull();
+ expect(registered[1]).toBeNull();
+ });
+});
diff --git a/server/services/ytdlpVideoImport.js b/server/services/ytdlpVideoImport.js
index 239bf6bc66..f2a4a392f6 100644
--- a/server/services/ytdlpVideoImport.js
+++ b/server/services/ytdlpVideoImport.js
@@ -7,7 +7,8 @@
* remux flags, the `--progress-template` machine-readable markers, the
* two-`--match-filters` duration bound, and the "find the produced file, because
* the extension isn't knowable up front" logic — but as ONE step inside a larger
- * job rather than as its own SSE-owning service.
+ * job rather than as its own SSE-owning service. The spawn/marker-parsing/exit
+ * classification middle both importers share lives in ytdlpRun.js.
*
* Like the audio core, this is deliberately SSE-agnostic: it takes `onProgress`
* and `registerProcess` callbacks and RETURNS an outcome. The caller owns the
@@ -16,18 +17,10 @@
* unvetted URL.
*/
-import { spawn } from '../lib/childProcess.js';
import { readdir, unlink } from 'fs/promises';
import { join, dirname } from 'path';
import { ensureDir } from '../lib/fileUtils.js';
-import { safeChildProcessOptions } from '../lib/processEnv.js';
-import { createLineReader } from '../lib/streamLines.js';
-
-const TITLE_PREFIX = 'PORTOS_TITLE:';
-// Machine-readable progress markers via yt-dlp's --progress-template rather than
-// scraping human-readable console lines — same rationale as ytdlpAudioImport.
-const PROGRESS_PREFIX = 'PORTOS_PROGRESS:';
-const STAGE_PREFIX = 'PORTOS_STAGE:';
+import { runYtDlp, ytdlpMarkerArgs } from './ytdlpRun.js';
/**
* Locate the final produced file for a download prefix. yt-dlp writes
@@ -92,7 +85,6 @@ export async function downloadVideoToDir({
// yt-dlp points at a missing directory and fails before producing a file.
await ensureDir(outDir);
- let title = '';
const args = [
// Prefer an mp4 (h264/aac) video+audio pair that merges cleanly for broad
// browser playback; fall back to best single-file mp4, then best.
@@ -104,15 +96,7 @@ export async function downloadVideoToDir({
'--remux-video', 'mp4',
'--no-playlist',
'--ffmpeg-location', dirname(ffmpeg),
- '--newline',
- '--print', `${TITLE_PREFIX}%(title)s`,
- '--progress-template', `download:${PROGRESS_PREFIX}%(progress._percent_str)s`,
- '--progress-template', `postprocess:${STAGE_PREFIX}merging`,
- // --print implies --simulate AND suppresses normal progress reporting;
- // --no-simulate + --progress restore the real run + machine markers
- // (the yt-dlp quirk documented at length in ytdlpAudioImport).
- '--no-simulate',
- '--progress',
+ ...ytdlpMarkerArgs('merging'),
'--max-filesize', String(maxBytes),
// Two --match-filters are OR'd by yt-dlp: bound KNOWN-duration videos to the
// cap, but let a post whose duration can't be resolved pre-download (common
@@ -125,47 +109,12 @@ export async function downloadVideoToDir({
url,
];
- const proc = spawn(ytDlp, args, safeChildProcessOptions({ stdio: ['ignore', 'pipe', 'pipe'] }));
- registerProcess(proc);
-
- const onLine = (line) => {
- if (line.startsWith(TITLE_PREFIX)) {
- title = line.slice(TITLE_PREFIX.length).trim();
- return;
- }
- if (line.startsWith(PROGRESS_PREFIX)) {
- const percent = parseFloat(line.slice(PROGRESS_PREFIX.length));
- if (Number.isFinite(percent)) onProgress({ percent });
- return;
- }
- if (line.startsWith(STAGE_PREFIX)) {
- onProgress({ percent: 100, stage: line.slice(STAGE_PREFIX.length) });
- }
- };
- // Separate readers per stream — stdout and stderr chunks arrive independently,
- // so a shared buffer can complete a partial line from one stream with a chunk
- // from the other, corrupting a marker line.
- const stdoutReader = createLineReader(onLine);
- const stderrReader = createLineReader(onLine);
- proc.stdout.on('data', stdoutReader.push);
- proc.stderr.on('data', stderrReader.push); // yt-dlp writes some progress/info lines to stderr too
-
- const exit = await new Promise((resolve) => {
- proc.on('error', (err) => resolve({ code: null, reason: `spawn failed: ${err.message}` }));
- proc.on('close', (code, signal) => resolve({ code, signal }));
- });
- registerProcess(null);
+ const exit = await runYtDlp({ ytDlp, args, onProgress, registerProcess });
- if (exit.signal === 'SIGTERM' || exit.signal === 'SIGKILL') {
- // Don't flush on cancel — a SIGKILL'd child leaves only a partial marker
- // line in the carry, and emitting it would fire a stray progress/stage
- // callback right before the caller reports the cancellation.
+ if (exit.canceled) {
await cleanupProducedFiles(filePrefix, outDir);
return { outcome: 'canceled' };
}
- // Flush any final line the child wrote without a trailing newline before exit.
- stdoutReader.flush();
- stderrReader.flush();
const filename = await findProducedFile(filePrefix, outDir);
if (exit.code !== 0 || !filename) {
@@ -180,5 +129,5 @@ export async function downloadVideoToDir({
return { outcome: 'failed', reason };
}
- return { outcome: 'complete', filename, title };
+ return { outcome: 'complete', filename, title: exit.title };
}
diff --git a/server/services/ytdlpVideoImport.test.js b/server/services/ytdlpVideoImport.test.js
index 293611c7f0..c577b52203 100644
--- a/server/services/ytdlpVideoImport.test.js
+++ b/server/services/ytdlpVideoImport.test.js
@@ -7,11 +7,16 @@
* Dev Tools downloader that used to own it.
*/
-import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { mkdtemp, writeFile, rm } from 'fs/promises';
+import { EventEmitter } from 'events';
import { join } from 'path';
import { tmpdir } from 'os';
-import { findProducedFile, cleanupProducedFiles } from './ytdlpVideoImport.js';
+
+vi.mock('../lib/childProcess.js', async (importOriginal) => ({ ...(await importOriginal()), spawn: vi.fn() }));
+
+const { spawn } = await import('../lib/childProcess.js');
+const { findProducedFile, cleanupProducedFiles, downloadVideoToDir } = await import('./ytdlpVideoImport.js');
describe('findProducedFile (robust output detection)', () => {
let dir;
@@ -62,3 +67,60 @@ describe('cleanupProducedFiles', () => {
expect(await findProducedFile('downloaded-b', dir)).toBe('downloaded-b.mp4');
});
});
+
+describe('downloadVideoToDir — argv and failure prose', () => {
+ let dir;
+ beforeEach(async () => { vi.clearAllMocks(); dir = await mkdtemp(join(tmpdir(), 'viddl-run-')); });
+ afterEach(async () => { await rm(dir, { recursive: true, force: true }); });
+
+ const baseArgs = () => ({
+ url: 'https://example.com/clip',
+ ytDlp: '/usr/local/bin/yt-dlp',
+ ffmpeg: '/usr/local/bin/ffmpeg',
+ outDir: dir,
+ filePrefix: 'downloaded-run',
+ maxBytes: 2 * 1024 * 1024 * 1024,
+ maxDurationSec: 1800,
+ onProgress: () => {},
+ registerProcess: () => {},
+ });
+
+ // Built inside mockImplementation, not handed to mockReturnValue: downloadVideoToDir
+ // awaits ensureDir before spawning, so a child constructed up front would fire its
+ // close during that await, before any listener is attached.
+ const mockChild = ({ code = 0, signal = null } = {}) => spawn.mockImplementation(() => {
+ const proc = new EventEmitter();
+ proc.stdout = new EventEmitter();
+ proc.stderr = new EventEmitter();
+ setImmediate(() => proc.emit('close', code, signal));
+ return proc;
+ });
+
+ it('keeps the video format chain and both --match-filters alongside the shared marker args', async () => {
+ mockChild({ code: 1 });
+ await downloadVideoToDir(baseArgs());
+
+ const [bin, args] = spawn.mock.calls[0];
+ expect(bin).toBe('/usr/local/bin/yt-dlp');
+ expect(args).toEqual(expect.arrayContaining(['--merge-output-format', 'mp4']));
+ expect(args).toEqual(expect.arrayContaining(['--remux-video', 'mp4']));
+ expect(args).toEqual(expect.arrayContaining(['--match-filters', 'duration <= 1800']));
+ expect(args).toEqual(expect.arrayContaining(['--match-filters', '!duration']));
+ expect(args).toEqual(expect.arrayContaining(['--print', 'PORTOS_TITLE:%(title)s']));
+ expect(args[args.length - 1]).toBe('https://example.com/clip');
+ });
+
+ it('names the duration and size bounds when a clean exit produced nothing', async () => {
+ mockChild({ code: 0 });
+ const result = await downloadVideoToDir(baseArgs());
+ expect(result.outcome).toBe('failed');
+ expect(result.reason).toMatch(/no video was produced/);
+ expect(result.reason).toMatch(/30 minutes/);
+ expect(result.reason).toMatch(/2GB/);
+ });
+
+ it('reports canceled on SIGTERM', async () => {
+ mockChild({ code: null, signal: 'SIGTERM' });
+ await expect(downloadVideoToDir(baseArgs())).resolves.toEqual({ outcome: 'canceled' });
+ });
+});