feat: download a clip as a title-named folder bundle #7
5 changed files with 194 additions and 3 deletions
|
|
@ -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.
|
||||
|
||||
|
|
|
|||
|
|
@ -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];
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
69
tests/e2e/api/test_clip_download.py
Normal file
69
tests/e2e/api/test_clip_download.py
Normal file
|
|
@ -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
|
||||
Loading…
Reference in a new issue