From 747117c6f891361f357f5732ae3acd02c1e1205a Mon Sep 17 00:00:00 2001 From: pedro-bento Date: Mon, 5 Oct 2026 14:22:01 +0100 Subject: [PATCH] feat: download a clip as a title-named folder bundle The per-clip download button now fetches a new GET /api/jobs/{job_id}/clip/{clip_index}/download endpoint that packages the saved clip as a ZIP shaped like a folder named after the clip title: /clip.mp4 <title>/description.txt Titles are sanitized into a single filesystem-safe path segment, and the archive is named <title>.zip. File resolution mirrors download-all (live record, then metadata URL, then canonical derived name). The frontend keeps its streaming progress UI and derives the filename from Content-Disposition. --- clipwright/api/app.py | 78 +++++++++++++++++++++ dashboard/e2e/fixtures/api-mocks.js | 9 +++ dashboard/e2e/specs/results-actions.spec.js | 15 ++++ dashboard/src/components/ResultCard.jsx | 26 ++++++- tests/e2e/api/test_clip_download.py | 69 ++++++++++++++++++ 5 files changed, 194 insertions(+), 3 deletions(-) create mode 100644 tests/e2e/api/test_clip_download.py diff --git a/clipwright/api/app.py b/clipwright/api/app.py index 4acbfc4..8fb8116 100644 --- a/clipwright/api/app.py +++ b/clipwright/api/app.py @@ -343,6 +343,22 @@ def _canonical_clip_file(output_dir, base_name, index): return os.path.basename(max(derived, key=os.path.getmtime)) +def _safe_clip_bundle_name(title): + """A filesystem-safe folder name for a single-clip ZIP bundle. + + Titles come from Gemini and routinely carry ``/``, ``:`` and quotes; any of + those would either break the archive or let a crafted title climb out of the + top-level folder on extraction. Collapse the unsafe bytes to spaces, drop + the leading/trailing dots and spaces that ZIP extractors choke on, and cap + the length so ``<folder>.zip`` stays a sane filename. Never returns a path + separator or ``..``. + """ + name = re.sub(r'[\\/:*?"<>|\x00-\x1f]', ' ', str(title or '')) + name = re.sub(r'\s+', ' ', name).strip(' .') + name = name[:100].strip(' .') + return name or "clip" + + def _clips_actually_rendered(job_id, output_dir, base_name, clips): """Keep only the clips whose file is really on disk. Returns (kept, missing). @@ -2516,6 +2532,68 @@ async def download_all_clips(job_id: str, request: Request): ) +@app.get("/api/jobs/{job_id}/clip/{clip_index}/download") +async def download_clip_bundle(job_id: str, clip_index: int, request: Request): + """Bundle ONE clip into a ZIP shaped like a folder named after its title. + + Extracting the archive yields ``<title>/clip.mp4`` with the copy text + beside it, which is what the per-clip download button promises. File + resolution mirrors ``download_all_clips``: prefer the live record (it tracks + recuts and captions), fall back to the metadata's URL, then to the canonical + name the restore path rebuilds. + """ + if job_id in jobs: + await _assert_job_owner(request, jobs[job_id]) + + output_dir = os.path.join(OUTPUT_DIR, job_id) + json_files = glob.glob(os.path.join(output_dir, "*_metadata.json")) + if not json_files: + raise HTTPException(status_code=404, detail="Job not found") + + with open(json_files[0], 'r', encoding='utf-8') as f: + data = json.load(f) + + clips = data.get('shorts', []) + if clip_index < 0 or clip_index >= len(clips): + raise HTTPException(status_code=404, detail="Clip not found") + clip = clips[clip_index] + + base_name = os.path.basename(json_files[0]).replace('_metadata.json', '') + mem_clips = ((jobs.get(job_id) or {}).get('result') or {}).get('clips') or [] + url = (mem_clips[clip_index] or {}).get('video_url') if clip_index < len(mem_clips) else None + url = url or clip.get('video_url') + filename = (os.path.basename(url.split('/')[-1]) if url + else _canonical_clip_file(output_dir, base_name, clip_index)) + clip_path = os.path.join(output_dir, filename) + if not filename or not os.path.exists(clip_path) or os.path.getsize(clip_path) == 0: + raise HTTPException(status_code=404, detail="Clip file not found") + + title = clip.get('video_title_for_youtube_short') or clip.get('title') or 'clip' + folder = _safe_clip_bundle_name(title) + description = (clip.get('video_description_for_instagram') + or clip.get('video_description_for_tiktok') + or clip.get('video_description_for_youtube') + or '') + + zip_path = os.path.join(output_dir, f"clip_{uuid.uuid4().hex[:8]}.zip") + + def build_zip(): + # Videos are already compressed; store instead of deflate for speed. + with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_STORED) as zf: + zf.write(clip_path, arcname=f"{folder}/clip.mp4") + zf.writestr(f"{folder}/description.txt", description) + + loop = asyncio.get_event_loop() + await loop.run_in_executor(None, build_zip) + + return FileResponse( + zip_path, + media_type="application/zip", + filename=f"{folder}.zip", + background=BackgroundTask(os.remove, zip_path), + ) + + # --- Project restore (paid mode) -------------------------------------------- # Files live on local disk in this self-host fork, so there is nothing to restore. diff --git a/dashboard/e2e/fixtures/api-mocks.js b/dashboard/e2e/fixtures/api-mocks.js index 929beeb..a9944aa 100644 --- a/dashboard/e2e/fixtures/api-mocks.js +++ b/dashboard/e2e/fixtures/api-mocks.js @@ -260,6 +260,15 @@ export async function installApiMocks(page, options = {}) { return route.fulfill({ status: 200, contentType: 'application/zip', body: 'PK-e2e-zip' }); } + if (method === 'GET' && /^\/api\/jobs\/[^/]+\/clip\/\d+\/download$/.test(path)) { + return route.fulfill({ + status: 200, + contentType: 'application/zip', + headers: { 'content-disposition': 'attachment; filename="Test Clip.zip"' }, + body: 'PK-e2e-zip', + }); + } + const clipMatch = path.match(/^\/api\/clip\/([^/]+)\/(\d+)\/(transcript|edl|scenes)$/); if (method === 'GET' && clipMatch) { const kind = clipMatch[3]; diff --git a/dashboard/e2e/specs/results-actions.spec.js b/dashboard/e2e/specs/results-actions.spec.js index e7643a5..567b31a 100644 --- a/dashboard/e2e/specs/results-actions.spec.js +++ b/dashboard/e2e/specs/results-actions.spec.js @@ -17,6 +17,21 @@ test.describe('results actions', () => { expect(download.suggestedFilename()).toContain('clipwright_clips_'); }); + test('downloads a single clip as a titled zip', async ({ page }) => { + await openApp(page, { seed: { session: completedSession() } }); + await expect(page.getByRole('heading', { name: 'First viral clip' })).toBeVisible(); + + const requestPromise = page.waitForRequest( + (r) => r.method() === 'GET' && r.url().includes(`/api/jobs/${JOB_ID}/clip/0/download`), + ); + const downloadPromise = page.waitForEvent('download'); + await page.getByRole('button', { name: 'download', exact: true }).first().click(); + + await requestPromise; + const download = await downloadPromise; + expect(download.suggestedFilename()).toBe('Test Clip.zip'); + }); + test('opens the generated descriptions', async ({ page }) => { await openApp(page, { seed: { session: completedSession() } }); await expect(page.getByRole('heading', { name: 'First viral clip' })).toBeVisible(); diff --git a/dashboard/src/components/ResultCard.jsx b/dashboard/src/components/ResultCard.jsx index c4583ec..bfcb038 100644 --- a/dashboard/src/components/ResultCard.jsx +++ b/dashboard/src/components/ResultCard.jsx @@ -106,7 +106,9 @@ export default function ResultCard({ clip, index, jobId, postizKey, postizUrl, g const downloadClip = async () => { try { setDownloadPct(0); - const response = await fetch(currentVideoUrl); + // The server packages the saved clip (not the transient blob: + // preview this card may be showing) as a `<title>/` folder zip. + const response = await fetch(getApiUrl(`/api/jobs/${jobId}/clip/${index}/download`)); if (!response.ok) throw new Error('Download failed'); const total = Number(response.headers.get('content-length')) || 0; let blob; @@ -125,13 +127,31 @@ export default function ResultCard({ clip, index, jobId, postizKey, postizUrl, g received += value.length; setDownloadPct(Math.min(99, Math.round((received / total) * 100))); } - blob = new Blob(chunks, { type: 'video/mp4' }); + blob = new Blob(chunks, { type: 'application/zip' }); } + + // The server names the bundle `<title>.zip`. Prefer the RFC 5987 + // form when present so non-ASCII titles survive; fall back to the + // plain quoted filename, then to a generic numbered name. + let filename = `clip-${index + 1}.zip`; + const disposition = response.headers.get('content-disposition') || ''; + const rfc5987 = disposition.match(/filename\*=UTF-8''([^;]+)/i); + const plain = disposition.match(/filename="?([^";]+)"?/i); + if (rfc5987) { + try { + filename = decodeURIComponent(rfc5987[1]); + } catch { + // malformed percent-encoding — keep the fallback name + } + } else if (plain) { + filename = plain[1]; + } + const url = window.URL.createObjectURL(blob); const a = document.createElement('a'); a.style.display = 'none'; a.href = url; - a.download = `clip-${index + 1}.mp4`; + a.download = filename; document.body.appendChild(a); a.click(); window.URL.revokeObjectURL(url); diff --git a/tests/e2e/api/test_clip_download.py b/tests/e2e/api/test_clip_download.py new file mode 100644 index 0000000..428ab6e --- /dev/null +++ b/tests/e2e/api/test_clip_download.py @@ -0,0 +1,69 @@ +"""L1 API core: the single-clip ZIP download bundle.""" + +import io +import json +import zipfile + +import pytest + +import clipwright.api.app as app + +pytestmark = pytest.mark.e2e + + +async def test_clip_download_returns_folder_shaped_zip(client, seeded_job): + job_id = seeded_job(job_id="job-clip", base="bundle", clips=1) + + resp = await client.get(f"/api/jobs/{job_id}/clip/0/download") + assert resp.status_code == 200 + assert resp.headers["content-type"] == "application/zip" + + with zipfile.ZipFile(io.BytesIO(resp.content)) as zf: + assert sorted(zf.namelist()) == [ + "Seeded clip 1/clip.mp4", + "Seeded clip 1/description.txt", + ] + assert zf.read("Seeded clip 1/clip.mp4") + assert zf.read("Seeded clip 1/description.txt").decode("utf-8") == "Seeded #test" + + +async def test_clip_download_out_of_range_is_404(client, seeded_job): + job_id = seeded_job(job_id="job-clip-range", base="bundle", clips=1) + + resp = await client.get(f"/api/jobs/{job_id}/clip/5/download") + assert resp.status_code == 404 + assert resp.json()["detail"] == "Clip not found" + + +async def test_clip_download_without_metadata_is_404(client): + resp = await client.get("/api/jobs/nobody-home/clip/0/download") + assert resp.status_code == 404 + assert resp.json()["detail"] == "Job not found" + + +async def test_clip_download_without_clip_file_is_404(client, app_state): + job_id = "job-clip-missing" + job_dir = app_state.out / job_id + job_dir.mkdir() + # Metadata promises a clip; the file itself was never rendered. + (job_dir / "missing_metadata.json").write_text(json.dumps({ + "shorts": [{ + "start": 0.0, + "end": 5.0, + "video_title_for_youtube_short": "Gone", + }], + })) + + resp = await client.get(f"/api/jobs/{job_id}/clip/0/download") + assert resp.status_code == 404 + assert resp.json()["detail"] == "Clip file not found" + + +def test_safe_clip_bundle_name_sanitises(): + name = app._safe_clip_bundle_name('A/B: c?') + assert not (set(name) & set('/\\:*?"<>|')) + assert name == name.strip(' .') + + assert app._safe_clip_bundle_name(' .. ') == 'clip' + + assert len(app._safe_clip_bundle_name('x' * 200)) <= 100 -- 2.45.2