feat(projects): reopen archived projects from history for further editing
- New projects table (job_id, metadata_r2_key, state JSONB) — created via create_all
- archive_job also uploads the metadata JSON (transcript) and upserts the
Project row + user_videos (no more duplicate rows on re-archive)
- archive_clip_edit re-archives a clip after each server-side edit, keeping
only the pristine original + current version per clip in R2
- fix /api/edit: persist new video_url in job result + metadata.json (the
other edit endpoints already did)
- POST /api/projects/{job_id}/restore re-hydrates R2 files into output/{job_id}
(per-job lock, temp-dir download, .owner sidecar, idempotent fast path)
- GET /api/projects + PUT /api/projects/{job_id}/state (debounced Remotion
layer sync from the frontend)
- History tab groups clips by project with a reopen button; App restores
jobId/results/project state; ResultCard seeds serverVideoFile/activeLayers
from the restored state and reports changes upward
This commit is contained in:
parent
abf43c60b7
commit
927ee09ffc
7 changed files with 567 additions and 53 deletions
158
app.py
158
app.py
|
|
@ -449,6 +449,27 @@ async def _archive_managed_job(job_id):
|
|||
print(f"⚠️ R2 archive error for {job_id}: {e}")
|
||||
|
||||
|
||||
def _archive_clip_edit_bg(job_id: str, clip_index: int, filename: str):
|
||||
"""Fire-and-forget R2 re-archive of an edited clip (managed jobs only).
|
||||
|
||||
Keeps the user's durable library (history/projects) pointing at the current
|
||||
version of each clip without blocking the edit response."""
|
||||
if not BILLING_ENABLED:
|
||||
return
|
||||
user_id = (jobs.get(job_id) or {}).get('user_id')
|
||||
if not user_id:
|
||||
return
|
||||
output_dir = os.path.join(OUTPUT_DIR, job_id)
|
||||
|
||||
async def _run():
|
||||
try:
|
||||
await cloud.videos.archive_clip_edit(user_id, job_id, clip_index, output_dir, filename)
|
||||
except Exception as e:
|
||||
print(f"⚠️ R2 edit archive error for {job_id}: {e}")
|
||||
|
||||
asyncio.create_task(_run())
|
||||
|
||||
|
||||
async def _record_job_alert(job_id):
|
||||
if not BILLING_ENABLED:
|
||||
return
|
||||
|
|
@ -940,6 +961,111 @@ async def download_all_clips(job_id: str, request: Request):
|
|||
)
|
||||
|
||||
|
||||
# --- Project restore (paid mode) --------------------------------------------
|
||||
# Re-hydrates an archived project from R2 back into output/{job_id}/ so every
|
||||
# edit endpoint works on it again. Restored files land with a fresh mtime, so
|
||||
# the retention clock restarts; re-restoring after a purge is cheap.
|
||||
_restore_locks: Dict[str, asyncio.Lock] = {}
|
||||
|
||||
|
||||
@app.post("/api/projects/{job_id}/restore")
|
||||
async def restore_project(job_id: str, request: Request):
|
||||
if not BILLING_ENABLED:
|
||||
raise HTTPException(status_code=404, detail="Not found")
|
||||
from sqlalchemy import select
|
||||
from cloud.auth import get_current_user_required
|
||||
from cloud.models import Project
|
||||
from cloud import database as cloud_db, storage as cloud_storage
|
||||
|
||||
user = await get_current_user_required(request)
|
||||
async with cloud_db.session() as s:
|
||||
proj = (await s.execute(
|
||||
select(Project).where(Project.job_id == job_id)
|
||||
)).scalar_one_or_none()
|
||||
if proj is None or str(proj.user_id) != str(user.id):
|
||||
raise HTTPException(status_code=404, detail="Project not found")
|
||||
|
||||
# Per-job lock: a double click must not download the project twice.
|
||||
lock = _restore_locks.setdefault(job_id, asyncio.Lock())
|
||||
async with lock:
|
||||
job_dir = os.path.join(OUTPUT_DIR, job_id)
|
||||
|
||||
# Idempotent fast path: everything the project needs is already on disk.
|
||||
needed = {os.path.basename(proj.metadata_r2_key)}
|
||||
for c in (proj.state or {}).get("clips", []):
|
||||
for k in ("original_file", "server_file"):
|
||||
if c.get(k):
|
||||
needed.add(c[k])
|
||||
if os.path.isdir(job_dir) and all(
|
||||
os.path.exists(os.path.join(job_dir, f)) for f in needed
|
||||
):
|
||||
os.utime(job_dir, None) # restart the retention clock
|
||||
else:
|
||||
prefix = cloud_storage.job_key(user.id, job_id, "")
|
||||
keys = await asyncio.to_thread(cloud_storage.list_keys, prefix)
|
||||
if not keys:
|
||||
raise HTTPException(status_code=502,
|
||||
detail="Project files are no longer available")
|
||||
# Download into a temp dir first so a partial failure never leaves a
|
||||
# half-restored job dir that the fast path would mistake for complete.
|
||||
tmp_dir = job_dir + ".restoring"
|
||||
shutil.rmtree(tmp_dir, ignore_errors=True)
|
||||
os.makedirs(tmp_dir, exist_ok=True)
|
||||
sem = asyncio.Semaphore(3)
|
||||
|
||||
async def _download(key):
|
||||
fname = os.path.basename(key)
|
||||
if not fname:
|
||||
return
|
||||
async with sem:
|
||||
await asyncio.to_thread(
|
||||
cloud_storage.download_file, key, os.path.join(tmp_dir, fname))
|
||||
|
||||
try:
|
||||
await asyncio.gather(*(_download(k) for k in keys))
|
||||
except Exception as e:
|
||||
shutil.rmtree(tmp_dir, ignore_errors=True)
|
||||
raise HTTPException(status_code=502, detail=f"Restore download failed: {e}")
|
||||
# Owner sidecar keeps the multi-tenant guard after a server restart.
|
||||
with open(os.path.join(tmp_dir, ".owner"), "w") as f:
|
||||
f.write(str(user.id))
|
||||
if os.path.isdir(job_dir):
|
||||
for fname in os.listdir(tmp_dir):
|
||||
shutil.move(os.path.join(tmp_dir, fname), os.path.join(job_dir, fname))
|
||||
shutil.rmtree(tmp_dir, ignore_errors=True)
|
||||
os.utime(job_dir, None)
|
||||
else:
|
||||
os.rename(tmp_dir, job_dir)
|
||||
|
||||
# Register (or refresh) the in-memory job — same shape as
|
||||
# _recover_jobs_from_disk, so every edit endpoint works unchanged.
|
||||
json_files = glob.glob(os.path.join(job_dir, "*_metadata.json"))
|
||||
if not json_files:
|
||||
raise HTTPException(status_code=502, detail="Project metadata missing")
|
||||
with open(json_files[0], 'r') as f:
|
||||
data = json.load(f)
|
||||
base_name = os.path.basename(json_files[0]).replace('_metadata.json', '')
|
||||
clips = data.get('shorts', [])
|
||||
for i, clip in enumerate(clips):
|
||||
if not clip.get('video_url'):
|
||||
clip['video_url'] = f"/videos/{job_id}/{base_name}_clip_{i+1}.mp4"
|
||||
jobs[job_id] = {
|
||||
'status': 'completed',
|
||||
'logs': ["♻️ Project restored from your library."],
|
||||
'output_dir': job_dir,
|
||||
'user_id': str(user.id),
|
||||
'result': {'clips': clips, 'cost_analysis': data.get('cost_analysis')},
|
||||
}
|
||||
|
||||
return {
|
||||
"job_id": job_id,
|
||||
"status": "completed",
|
||||
"result": jobs[job_id]['result'],
|
||||
"project_state": proj.state,
|
||||
"title": proj.title,
|
||||
}
|
||||
|
||||
|
||||
from editor import VideoEditor
|
||||
from subtitles import generate_srt, generate_ass, burn_subtitles, generate_srt_from_video
|
||||
from hooks import add_hook_to_video
|
||||
|
|
@ -1069,15 +1195,27 @@ async def edit_clip(
|
|||
loop = asyncio.get_event_loop()
|
||||
plan = await loop.run_in_executor(None, run_edit)
|
||||
|
||||
# Update clip URL in the job result?
|
||||
# Or return new URL and let frontend handle it?
|
||||
# Updating job result allows persistence if page refreshes.
|
||||
|
||||
new_video_url = f"/videos/{req.job_id}/{edited_filename}"
|
||||
|
||||
# Start a new "edited" clip entry or just update the current one?
|
||||
# Let's update the current one's video_url but keep backup?
|
||||
# Or return the new URL to the frontend to display.
|
||||
# Persist the new current file like /api/subtitle does: in-memory job
|
||||
# result + metadata.json, so reload/recovery/re-archive see this version.
|
||||
if req.clip_index < len(job['result']['clips']):
|
||||
job['result']['clips'][req.clip_index]['video_url'] = new_video_url
|
||||
try:
|
||||
meta_files = glob.glob(os.path.join(OUTPUT_DIR, req.job_id, "*_metadata.json"))
|
||||
if meta_files:
|
||||
with open(meta_files[0], 'r') as f:
|
||||
meta = json.load(f)
|
||||
shorts = meta.get('shorts', [])
|
||||
if req.clip_index < len(shorts):
|
||||
shorts[req.clip_index]['video_url'] = new_video_url
|
||||
meta['shorts'] = shorts
|
||||
with open(meta_files[0], 'w') as f:
|
||||
json.dump(meta, f, indent=4)
|
||||
except Exception as e:
|
||||
print(f"⚠️ Failed to update metadata.json: {e}")
|
||||
|
||||
_archive_clip_edit_bg(req.job_id, req.clip_index, edited_filename)
|
||||
|
||||
if reservation_id:
|
||||
await _metering.commit_reservation(reservation_id)
|
||||
|
|
@ -1461,6 +1599,8 @@ async def add_subtitles(req: SubtitleRequest, request: Request):
|
|||
print(f"⚠️ Failed to update metadata.json: {e}")
|
||||
# Non-critical, but good for persistence
|
||||
|
||||
_archive_clip_edit_bg(req.job_id, req.clip_index, output_filename)
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
"new_video_url": f"/videos/{req.job_id}/{output_filename}"
|
||||
|
|
@ -1558,6 +1698,8 @@ async def add_hook(req: HookRequest, request: Request):
|
|||
except Exception as e:
|
||||
print(f"⚠️ Failed to update metadata.json: {e}")
|
||||
|
||||
_archive_clip_edit_bg(req.job_id, req.clip_index, output_filename)
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
"new_video_url": f"/videos/{req.job_id}/{output_filename}"
|
||||
|
|
@ -1656,6 +1798,8 @@ async def translate_clip(
|
|||
except Exception as e:
|
||||
print(f"⚠️ Failed to update metadata.json: {e}")
|
||||
|
||||
_archive_clip_edit_bg(req.job_id, req.clip_index, output_filename)
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
"new_video_url": f"/videos/{req.job_id}/{output_filename}"
|
||||
|
|
|
|||
|
|
@ -110,6 +110,28 @@ class UserVideo(Base):
|
|||
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
||||
|
||||
|
||||
class Project(Base):
|
||||
"""One re-openable project per completed job.
|
||||
|
||||
The metadata JSON in R2 (``metadata_r2_key``) is the source of truth for the
|
||||
clips + transcript; ``state`` holds only what lives outside that file: the
|
||||
browser-side Remotion layers and the current server file per clip.
|
||||
``state`` schema: {"v": 1, "clips": [{"index", "original_file",
|
||||
"server_file", "active_layers"}]}.
|
||||
"""
|
||||
__tablename__ = "projects"
|
||||
id = Column(UUID(as_uuid=True), primary_key=True, default=_uuid)
|
||||
user_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"),
|
||||
nullable=False, index=True)
|
||||
job_id = Column(Text, unique=True, nullable=False)
|
||||
title = Column(Text, nullable=True)
|
||||
metadata_r2_key = Column(Text, nullable=False)
|
||||
state = Column(JSONB, nullable=True)
|
||||
size_bytes = Column(Integer, nullable=True)
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
||||
updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
|
||||
|
||||
|
||||
class StripeEvent(Base):
|
||||
__tablename__ = "stripe_events"
|
||||
id = Column(Text, primary_key=True) # Stripe event.id — dedupe key
|
||||
|
|
|
|||
|
|
@ -39,6 +39,31 @@ def upload_file(local_path, key, content_type="video/mp4"):
|
|||
ExtraArgs={"ContentType": content_type})
|
||||
|
||||
|
||||
def download_file(key, local_path):
|
||||
client().download_file(settings.r2_bucket, key, local_path)
|
||||
|
||||
|
||||
def delete_key(key):
|
||||
client().delete_object(Bucket=settings.r2_bucket, Key=key)
|
||||
|
||||
|
||||
def list_keys(prefix) -> list:
|
||||
"""List every object key under a prefix."""
|
||||
c = client()
|
||||
keys = []
|
||||
token = None
|
||||
while True:
|
||||
kw = {"Bucket": settings.r2_bucket, "Prefix": prefix, "MaxKeys": 1000}
|
||||
if token:
|
||||
kw["ContinuationToken"] = token
|
||||
resp = c.list_objects_v2(**kw)
|
||||
keys.extend(o["Key"] for o in resp.get("Contents", []))
|
||||
if not resp.get("IsTruncated"):
|
||||
break
|
||||
token = resp.get("NextContinuationToken")
|
||||
return keys
|
||||
|
||||
|
||||
def presigned_get(key, expires=3600, download_name=None) -> str:
|
||||
params = {"Bucket": settings.r2_bucket, "Key": key}
|
||||
if download_name:
|
||||
|
|
|
|||
206
cloud/videos.py
206
cloud/videos.py
|
|
@ -2,25 +2,42 @@
|
|||
purge after the subscription grace period.
|
||||
"""
|
||||
import asyncio
|
||||
import glob
|
||||
import os
|
||||
from datetime import timedelta
|
||||
|
||||
from fastapi import APIRouter, Request
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from sqlalchemy import select, delete
|
||||
|
||||
from .config import settings, VIDEO_RETENTION_GRACE_DAYS
|
||||
from . import database, storage
|
||||
from .models import UserVideo, Subscription
|
||||
from .models import UserVideo, Subscription, Project
|
||||
from .auth import get_current_user_required
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _clip_title(clip) -> str:
|
||||
return clip.get("title") or clip.get("video_title_for_youtube_short") or "Short"
|
||||
|
||||
|
||||
async def archive_job(user_id, job_id, clips, output_dir):
|
||||
"""Upload a completed managed job's clips to R2 and record them for history."""
|
||||
"""Upload a completed managed job's clips + metadata JSON to R2 and record
|
||||
them for history. The metadata (transcript included) plus the Project row
|
||||
make the whole job re-openable and editable later, not just viewable."""
|
||||
if not settings.r2_configured or not clips:
|
||||
return
|
||||
rows = []
|
||||
metadata_r2_key = None
|
||||
meta_files = glob.glob(os.path.join(output_dir, "*_metadata.json"))
|
||||
if meta_files:
|
||||
key = storage.job_key(user_id, job_id, os.path.basename(meta_files[0]))
|
||||
try:
|
||||
await asyncio.to_thread(storage.upload_file, meta_files[0], key, "application/json")
|
||||
metadata_r2_key = key
|
||||
except Exception as e:
|
||||
print(f"⚠️ R2 upload failed for {key}: {e}")
|
||||
|
||||
uploaded = [] # (clip_index, filename, key, title, size_bytes)
|
||||
for i, clip in enumerate(clips):
|
||||
video_url = clip.get("video_url") or ""
|
||||
filename = video_url.split("/")[-1]
|
||||
|
|
@ -35,16 +52,172 @@ async def archive_job(user_id, job_id, clips, output_dir):
|
|||
except Exception as e:
|
||||
print(f"⚠️ R2 upload failed for {key}: {e}")
|
||||
continue
|
||||
rows.append(UserVideo(
|
||||
user_id=user_id, job_id=job_id, clip_index=i, r2_key=key,
|
||||
title=clip.get("title") or "Short",
|
||||
size_bytes=os.path.getsize(local_path),
|
||||
))
|
||||
if rows:
|
||||
async with database.session() as s:
|
||||
async with s.begin():
|
||||
s.add_all(rows)
|
||||
print(f"☁️ Archived {len(rows)} clip(s) to R2 for user {user_id}.")
|
||||
uploaded.append((i, filename, key, _clip_title(clip), os.path.getsize(local_path)))
|
||||
|
||||
if not uploaded:
|
||||
return
|
||||
async with database.session() as s:
|
||||
async with s.begin():
|
||||
# Upsert per-clip history rows: re-archiving a job must repoint the
|
||||
# existing rows, never duplicate them.
|
||||
existing = {
|
||||
v.clip_index: v for v in (await s.execute(
|
||||
select(UserVideo).where(UserVideo.user_id == user_id,
|
||||
UserVideo.job_id == job_id)
|
||||
)).scalars()
|
||||
}
|
||||
for i, _filename, key, title, size in uploaded:
|
||||
row = existing.get(i)
|
||||
if row is not None:
|
||||
row.r2_key, row.title, row.size_bytes = key, title, size
|
||||
else:
|
||||
s.add(UserVideo(user_id=user_id, job_id=job_id, clip_index=i,
|
||||
r2_key=key, title=title, size_bytes=size))
|
||||
# Upsert the Project row (only re-openable with the metadata in R2).
|
||||
if metadata_r2_key:
|
||||
proj = (await s.execute(
|
||||
select(Project).where(Project.job_id == job_id)
|
||||
)).scalar_one_or_none()
|
||||
state = {"v": 1, "clips": [
|
||||
{"index": i, "original_file": filename, "server_file": filename,
|
||||
"active_layers": None}
|
||||
for i, filename, _key, _title, _size in uploaded
|
||||
]}
|
||||
total = sum(u[4] for u in uploaded)
|
||||
if proj is None:
|
||||
s.add(Project(user_id=user_id, job_id=job_id, title=uploaded[0][3],
|
||||
metadata_r2_key=metadata_r2_key, state=state,
|
||||
size_bytes=total))
|
||||
else:
|
||||
proj.metadata_r2_key = metadata_r2_key
|
||||
proj.state = state
|
||||
proj.size_bytes = total
|
||||
print(f"☁️ Archived {len(uploaded)} clip(s) to R2 for user {user_id}.")
|
||||
|
||||
|
||||
async def archive_clip_edit(user_id, job_id, clip_index, output_dir, new_filename):
|
||||
"""Re-archive one clip after a server-side edit (subtitles/hook/effects/dub).
|
||||
|
||||
Uploads the new current file plus the refreshed metadata JSON, repoints the
|
||||
history row and the project state, and deletes the superseded R2 object —
|
||||
per clip only the pristine original and the current version are kept.
|
||||
"""
|
||||
if not settings.r2_configured or not user_id:
|
||||
return
|
||||
local_path = os.path.join(output_dir, new_filename)
|
||||
if not os.path.exists(local_path):
|
||||
return
|
||||
new_key = storage.job_key(user_id, job_id, new_filename)
|
||||
await asyncio.to_thread(storage.upload_file, local_path, new_key)
|
||||
|
||||
metadata_r2_key = None
|
||||
meta_files = glob.glob(os.path.join(output_dir, "*_metadata.json"))
|
||||
if meta_files:
|
||||
metadata_r2_key = storage.job_key(user_id, job_id, os.path.basename(meta_files[0]))
|
||||
try:
|
||||
await asyncio.to_thread(storage.upload_file, meta_files[0], metadata_r2_key,
|
||||
"application/json")
|
||||
except Exception as e:
|
||||
print(f"⚠️ R2 metadata refresh failed for {job_id}: {e}")
|
||||
metadata_r2_key = None
|
||||
|
||||
size = os.path.getsize(local_path)
|
||||
superseded_key = None
|
||||
async with database.session() as s:
|
||||
async with s.begin():
|
||||
proj = (await s.execute(
|
||||
select(Project).where(Project.job_id == job_id)
|
||||
)).scalar_one_or_none()
|
||||
if proj is not None:
|
||||
state = dict(proj.state or {"v": 1, "clips": []})
|
||||
clips_state = [dict(c) for c in state.get("clips", [])]
|
||||
entry = next((c for c in clips_state if c.get("index") == clip_index), None)
|
||||
if entry is None:
|
||||
entry = {"index": clip_index, "original_file": new_filename,
|
||||
"active_layers": None}
|
||||
clips_state.append(entry)
|
||||
prev = entry.get("server_file")
|
||||
if prev and prev not in (entry.get("original_file"), new_filename):
|
||||
superseded_key = storage.job_key(user_id, job_id, prev)
|
||||
entry["server_file"] = new_filename
|
||||
state["clips"] = clips_state
|
||||
proj.state = state
|
||||
if metadata_r2_key:
|
||||
proj.metadata_r2_key = metadata_r2_key
|
||||
vid = (await s.execute(
|
||||
select(UserVideo).where(UserVideo.user_id == user_id,
|
||||
UserVideo.job_id == job_id,
|
||||
UserVideo.clip_index == clip_index)
|
||||
)).scalars().first()
|
||||
if vid is not None:
|
||||
vid.r2_key, vid.size_bytes = new_key, size
|
||||
else:
|
||||
s.add(UserVideo(user_id=user_id, job_id=job_id, clip_index=clip_index,
|
||||
r2_key=new_key, size_bytes=size))
|
||||
if superseded_key and superseded_key != new_key:
|
||||
try:
|
||||
await asyncio.to_thread(storage.delete_key, superseded_key)
|
||||
except Exception as e:
|
||||
print(f"⚠️ Could not delete superseded R2 object {superseded_key}: {e}")
|
||||
|
||||
|
||||
@router.get("/api/projects")
|
||||
async def list_projects(request: Request):
|
||||
"""List the signed-in user's re-openable projects."""
|
||||
user = await get_current_user_required(request)
|
||||
async with database.session() as s:
|
||||
projs = list((await s.execute(
|
||||
select(Project).where(Project.user_id == user.id)
|
||||
.order_by(Project.created_at.desc()).limit(200)
|
||||
)).scalars())
|
||||
return {"projects": [{
|
||||
"job_id": p.job_id,
|
||||
"title": p.title,
|
||||
"clip_count": len((p.state or {}).get("clips", [])),
|
||||
"size_bytes": p.size_bytes,
|
||||
"created_at": p.created_at.isoformat() if p.created_at else None,
|
||||
"updated_at": p.updated_at.isoformat() if p.updated_at else None,
|
||||
} for p in projs]}
|
||||
|
||||
|
||||
@router.put("/api/projects/{job_id}/state")
|
||||
async def save_project_state(job_id: str, request: Request):
|
||||
"""Persist the browser-only edit state of a project's clips.
|
||||
|
||||
Body: {"clips": [{"index", "active_layers", "server_file"?}]}. The Remotion
|
||||
layers exist nowhere but the browser, so the frontend syncs them here
|
||||
(debounced) to survive reload / reopen."""
|
||||
user = await get_current_user_required(request)
|
||||
if int(request.headers.get("content-length") or 0) > 262144:
|
||||
raise HTTPException(status_code=413, detail="State too large")
|
||||
body = await request.json()
|
||||
clips_in = body.get("clips") or []
|
||||
async with database.session() as s:
|
||||
async with s.begin():
|
||||
proj = (await s.execute(
|
||||
select(Project).where(Project.job_id == job_id)
|
||||
)).scalar_one_or_none()
|
||||
if proj is None or str(proj.user_id) != str(user.id):
|
||||
raise HTTPException(status_code=404, detail="Project not found")
|
||||
state = dict(proj.state or {"v": 1, "clips": []})
|
||||
clips_state = [dict(c) for c in state.get("clips", [])]
|
||||
by_index = {c.get("index"): c for c in clips_state}
|
||||
for c in clips_in:
|
||||
idx = c.get("index")
|
||||
if not isinstance(idx, int):
|
||||
continue
|
||||
entry = by_index.get(idx)
|
||||
if entry is None:
|
||||
entry = {"index": idx, "original_file": None,
|
||||
"server_file": None, "active_layers": None}
|
||||
clips_state.append(entry)
|
||||
by_index[idx] = entry
|
||||
entry["active_layers"] = c.get("active_layers")
|
||||
if c.get("server_file"):
|
||||
entry["server_file"] = os.path.basename(str(c["server_file"]))
|
||||
state["clips"] = clips_state
|
||||
proj.state = state
|
||||
return {"success": True}
|
||||
|
||||
|
||||
@router.get("/api/history")
|
||||
|
|
@ -87,10 +260,12 @@ async def purge_expired():
|
|||
continue
|
||||
if last_event_at + timedelta(days=VIDEO_RETENTION_GRACE_DAYS) > now:
|
||||
continue
|
||||
# Any videos left?
|
||||
# Any videos or projects left?
|
||||
async with database.session() as s:
|
||||
has = (await s.execute(
|
||||
select(UserVideo.id).where(UserVideo.user_id == user_id).limit(1)
|
||||
)).first() or (await s.execute(
|
||||
select(Project.id).where(Project.user_id == user_id).limit(1)
|
||||
)).first()
|
||||
if not has:
|
||||
continue
|
||||
|
|
@ -99,6 +274,7 @@ async def purge_expired():
|
|||
async with database.session() as s:
|
||||
async with s.begin():
|
||||
await s.execute(delete(UserVideo).where(UserVideo.user_id == user_id))
|
||||
await s.execute(delete(Project).where(Project.user_id == user_id))
|
||||
print(f"🗑️ Purged {n} R2 object(s) for lapsed user {user_id}.")
|
||||
except Exception as e:
|
||||
print(f"⚠️ Video purge failed for {user_id}: {e}")
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import React, { useState, useEffect } from 'react';
|
||||
import React, { useState, useEffect, useRef } from 'react';
|
||||
import { Upload, Sparkles, Youtube, Instagram, Share2, ChevronDown, Check, Activity, LayoutDashboard, Settings, Plus, History, X, Terminal, Shield, LayoutGrid, Image, Globe, RotateCcw, Calendar, AlertTriangle, KeyRound, Bot, Users, Smartphone, ExternalLink, Copy, CheckCircle2, Mail, Loader2, Download } from 'lucide-react';
|
||||
import KeyInput from './components/KeyInput';
|
||||
import MediaInput from './components/MediaInput';
|
||||
|
|
@ -216,6 +216,12 @@ function App() {
|
|||
const [logsVisible, setLogsVisible] = useState(true);
|
||||
const [processingMedia, setProcessingMedia] = useState(null);
|
||||
const [activeTab, setActiveTab] = useState('dashboard'); // dashboard, settings
|
||||
// Reopened-project state (paid mode): per-clip {index, server_file, active_layers}
|
||||
// restored from the backend so ResultCards resume editing where they left off.
|
||||
const [projectState, setProjectState] = useState(null);
|
||||
// True when the current job was reopened from the library: its source video
|
||||
// was never persisted, so the session must not fall back to /api/source.
|
||||
const [noSource, setNoSource] = useState(false);
|
||||
|
||||
const [sessionRecovered, setSessionRecovered] = useState(false);
|
||||
const [showScheduleWeek, setShowScheduleWeek] = useState(false);
|
||||
|
|
@ -239,6 +245,54 @@ function App() {
|
|||
setIsSyncedPlaying(false);
|
||||
};
|
||||
|
||||
// --- Project persistence (paid mode) ---
|
||||
// Debounced sync of each clip's browser-only edit state (Remotion layers +
|
||||
// current server file) to the backend, so a reopened project resumes intact.
|
||||
const clipStateSync = useRef({ jobId: null, pending: {}, timer: null });
|
||||
|
||||
const flushClipState = () => {
|
||||
const s = clipStateSync.current;
|
||||
if (s.timer) { clearTimeout(s.timer); s.timer = null; }
|
||||
const entries = Object.entries(s.pending);
|
||||
if (!s.jobId || entries.length === 0) return;
|
||||
const clips = entries.map(([i, v]) => ({
|
||||
index: Number(i),
|
||||
active_layers: v.activeLayers,
|
||||
server_file: v.serverVideoFile,
|
||||
}));
|
||||
s.pending = {};
|
||||
apiFetch(`/api/projects/${s.jobId}/state`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ clips }),
|
||||
}).catch(() => {});
|
||||
};
|
||||
|
||||
const handleClipStateChange = (index, state) => {
|
||||
if (!isManaged || !jobId) return;
|
||||
const s = clipStateSync.current;
|
||||
if (s.jobId !== jobId) { s.pending = {}; s.jobId = jobId; }
|
||||
s.pending[index] = state;
|
||||
if (s.timer) clearTimeout(s.timer);
|
||||
s.timer = setTimeout(flushClipState, 2000);
|
||||
};
|
||||
|
||||
// Reopen an archived project from the History tab: the backend re-downloads
|
||||
// its files from R2 into the server's working dir and returns the full state.
|
||||
const restoreProject = async (projectJobId) => {
|
||||
const data = await apiJson(`/api/projects/${projectJobId}/restore`, { method: 'POST' });
|
||||
flushClipState();
|
||||
setProjectState(data.project_state || null);
|
||||
setNoSource(true);
|
||||
setJobId(data.job_id);
|
||||
setResults(data.result || null);
|
||||
setLogs(['♻️ Project restored from your library.']);
|
||||
setProcessingMedia(null);
|
||||
setQualityGate(null);
|
||||
setStatus('complete');
|
||||
setActiveTab('dashboard');
|
||||
};
|
||||
|
||||
// Apply one subtitle style to every clip of the job, sequentially.
|
||||
const handleBulkSubtitles = async (options) => {
|
||||
const clips = results?.clips || [];
|
||||
|
|
@ -321,9 +375,12 @@ function App() {
|
|||
setJobId(session.jobId);
|
||||
setResults(session.results || null);
|
||||
// Restore the source preview. Older sessions (or uploads) saved no
|
||||
// media, so fall back to the backend-served source for this job.
|
||||
// media, so fall back to the backend-served source for this job —
|
||||
// except for reopened projects, whose source was never persisted.
|
||||
if (session.processingMedia) setProcessingMedia(session.processingMedia);
|
||||
else setProcessingMedia({ type: 'server', payload: `/api/source/${session.jobId}` });
|
||||
else if (!session.noSource) setProcessingMedia({ type: 'server', payload: `/api/source/${session.jobId}` });
|
||||
if (session.noSource) setNoSource(true);
|
||||
if (session.projectState) setProjectState(session.projectState);
|
||||
if (session.activeTab) setActiveTab(session.activeTab);
|
||||
// If was processing, resume polling; if complete/error, just show results
|
||||
setStatus(session.status === 'processing' ? 'processing' : session.status);
|
||||
|
|
@ -354,6 +411,8 @@ function App() {
|
|||
results,
|
||||
processingMedia: persistMedia,
|
||||
activeTab,
|
||||
noSource,
|
||||
projectState,
|
||||
timestamp: Date.now()
|
||||
};
|
||||
localStorage.setItem(SESSION_KEY, JSON.stringify(sessionData));
|
||||
|
|
@ -361,7 +420,7 @@ function App() {
|
|||
// localStorage full or serialization error - ignore
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [jobId, status, results, activeTab]);
|
||||
}, [jobId, status, results, activeTab, noSource, projectState]);
|
||||
|
||||
useEffect(() => {
|
||||
// Encrypt Gemini Key too for consistency if desired, but user asked specifically about Social integration not saving well.
|
||||
|
|
@ -522,6 +581,8 @@ function App() {
|
|||
setResults(null);
|
||||
setProcessingMedia(data);
|
||||
setQualityGate(null);
|
||||
setProjectState(null);
|
||||
setNoSource(false);
|
||||
|
||||
try {
|
||||
let body;
|
||||
|
|
@ -579,11 +640,16 @@ function App() {
|
|||
};
|
||||
|
||||
const handleReset = () => {
|
||||
// Flush any pending edit-state sync before dropping the project: the clips
|
||||
// themselves are already archived to R2 as they were edited.
|
||||
flushClipState();
|
||||
setStatus('idle');
|
||||
setJobId(null);
|
||||
setResults(null);
|
||||
setLogs([]);
|
||||
setProcessingMedia(null);
|
||||
setProjectState(null);
|
||||
setNoSource(false);
|
||||
localStorage.removeItem(SESSION_KEY);
|
||||
};
|
||||
|
||||
|
|
@ -1148,7 +1214,7 @@ function App() {
|
|||
{activeTab === 'history' && (
|
||||
<div className="h-full overflow-y-auto custom-scrollbar animate-fade">
|
||||
<div className="max-w-6xl mx-auto p-6 md:p-8">
|
||||
<HistoryTab />
|
||||
<HistoryTab onReopenProject={restoreProject} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
|
@ -1289,10 +1355,12 @@ function App() {
|
|||
<div className={`grid gap-4 pb-10 ${status === 'complete' ? 'grid-cols-1 xl:grid-cols-2' : 'grid-cols-1'}`}>
|
||||
{results.clips.map((clip, i) => (
|
||||
<ResultCard
|
||||
key={i}
|
||||
key={`${jobId}-${i}`}
|
||||
clip={clip}
|
||||
index={i}
|
||||
jobId={jobId}
|
||||
initialState={projectState?.clips?.find((c) => c.index === i) || null}
|
||||
onStateChange={handleClipStateChange}
|
||||
durableUrl={durableClips[i]}
|
||||
uploadPostKey={uploadPostKey}
|
||||
uploadUserId={uploadUserId}
|
||||
|
|
|
|||
|
|
@ -1,18 +1,53 @@
|
|||
import React, { useState, useEffect } from 'react';
|
||||
import { Loader2, Download, Film } from 'lucide-react';
|
||||
import React, { useState, useEffect, useMemo } from 'react';
|
||||
import { Loader2, Download, Film, FolderOpen } from 'lucide-react';
|
||||
import { apiJson } from '../lib/api';
|
||||
|
||||
// The signed-in user's saved video library (stored in R2). Private, signed links.
|
||||
export default function HistoryTab() {
|
||||
// Videos are grouped by project (job); re-openable projects get a "reopen"
|
||||
// action that restores the whole job for further editing in the Clip Generator.
|
||||
export default function HistoryTab({ onReopenProject }) {
|
||||
const [videos, setVideos] = useState(null);
|
||||
const [projects, setProjects] = useState({});
|
||||
const [reopening, setReopening] = useState(null);
|
||||
const [reopenError, setReopenError] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
apiJson('/api/history')
|
||||
.then((d) => setVideos(d.videos || []))
|
||||
.catch(() => setError('Could not load your library.'));
|
||||
apiJson('/api/projects')
|
||||
.then((d) => {
|
||||
const map = {};
|
||||
for (const p of d.projects || []) map[p.job_id] = p;
|
||||
setProjects(map);
|
||||
})
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
|
||||
// Group videos by job, preserving the newest-first order of /api/history.
|
||||
const groups = useMemo(() => {
|
||||
const byJob = new Map();
|
||||
for (const v of videos || []) {
|
||||
const key = v.job_id || v.id;
|
||||
if (!byJob.has(key)) byJob.set(key, []);
|
||||
byJob.get(key).push(v);
|
||||
}
|
||||
return [...byJob.entries()];
|
||||
}, [videos]);
|
||||
|
||||
const handleReopen = async (jobId) => {
|
||||
if (!onReopenProject || reopening) return;
|
||||
setReopening(jobId);
|
||||
setReopenError('');
|
||||
try {
|
||||
await onReopenProject(jobId);
|
||||
} catch (e) {
|
||||
setReopenError('Could not reopen this project. Please try again.');
|
||||
setReopening(null);
|
||||
}
|
||||
};
|
||||
|
||||
const fmtDate = (iso) => (iso ? new Date(iso).toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' }) : '');
|
||||
|
||||
if (videos === null && !error) {
|
||||
|
|
@ -24,10 +59,11 @@ export default function HistoryTab() {
|
|||
<p className="eyebrow mb-1.5">06 · HISTORY</p>
|
||||
<h1 className="font-display lowercase text-2xl text-ink mb-2">Your library</h1>
|
||||
<p className="text-muted text-sm mb-8 lowercase">
|
||||
All the shorts you've generated, saved while your plan is active. Kept for 7 days after your plan ends.
|
||||
All the shorts you've generated, saved while your plan is active. Kept for 7 days after your plan ends. Reopen a project to keep editing its clips.
|
||||
</p>
|
||||
|
||||
{error && <p className="text-danger text-sm">{error}</p>}
|
||||
{reopenError && <p className="text-danger text-sm mb-4">{reopenError}</p>}
|
||||
|
||||
{videos && videos.length === 0 && (
|
||||
<div className="text-center py-20 text-muted">
|
||||
|
|
@ -36,23 +72,54 @@ export default function HistoryTab() {
|
|||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-5">
|
||||
{(videos || []).map((v) => (
|
||||
<div key={v.id} className="card card-hover overflow-hidden group">
|
||||
<div className="aspect-[9/16] bg-black">
|
||||
<video src={v.view_url} controls preload="metadata" className="w-full h-full object-contain" />
|
||||
</div>
|
||||
<div className="p-3">
|
||||
<p className="text-sm text-ink font-medium line-clamp-2 mb-1" title={v.title}>{v.title || 'Short'}</p>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="readout">{fmtDate(v.created_at)}</span>
|
||||
<a href={v.download_url} className="text-micro font-mono uppercase text-brass hover:text-ink flex items-center gap-1 transition-colors" title="Download">
|
||||
<Download size={14} /> Download
|
||||
</a>
|
||||
<div className="space-y-10">
|
||||
{groups.map(([jobId, vids]) => {
|
||||
const project = projects[jobId];
|
||||
return (
|
||||
<section key={jobId}>
|
||||
<div className="flex flex-wrap items-center justify-between gap-3 mb-4 pb-2 border-b border-rule">
|
||||
<div className="min-w-0">
|
||||
<p className="text-sm text-ink font-medium truncate" title={project?.title || vids[0]?.title}>
|
||||
{project?.title || vids[0]?.title || 'Project'}
|
||||
</p>
|
||||
<p className="readout mt-0.5">
|
||||
{fmtDate(vids[0]?.created_at)} · {vids.length} clip{vids.length === 1 ? '' : 's'}
|
||||
</p>
|
||||
</div>
|
||||
{project && onReopenProject && (
|
||||
<button
|
||||
onClick={() => handleReopen(jobId)}
|
||||
disabled={!!reopening}
|
||||
className="btn-ghost px-3 py-2 text-xs shrink-0"
|
||||
title="Restore this project in the Clip Generator to keep editing subtitles, hooks, effects and dubbing"
|
||||
>
|
||||
{reopening === jobId
|
||||
? <><Loader2 size={14} className="animate-spin" /> reopening…</>
|
||||
: <><FolderOpen size={14} /> reopen project</>}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-5">
|
||||
{vids.map((v) => (
|
||||
<div key={v.id} className="card card-hover overflow-hidden group">
|
||||
<div className="aspect-[9/16] bg-black">
|
||||
<video src={v.view_url} controls preload="metadata" className="w-full h-full object-contain" />
|
||||
</div>
|
||||
<div className="p-3">
|
||||
<p className="text-sm text-ink font-medium line-clamp-2 mb-1" title={v.title}>{v.title || 'Short'}</p>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="readout">{fmtDate(v.created_at)}</span>
|
||||
<a href={v.download_url} className="text-micro font-mono uppercase text-brass hover:text-ink flex items-center gap-1 transition-colors" title="Download">
|
||||
<Download size={14} /> Download
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -23,7 +23,7 @@ function formatDuration(clip) {
|
|||
return `${String(Math.floor(secs / 60)).padStart(2, '0')}:${String(secs % 60).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
export default function ResultCard({ clip, index, jobId, durableUrl, uploadPostKey, uploadUserId, geminiApiKey, elevenLabsKey, isManaged, onPlay, onPause, onBulkSubtitle, clipCount = 1, bulkProgress }) {
|
||||
export default function ResultCard({ clip, index, jobId, durableUrl, uploadPostKey, uploadUserId, geminiApiKey, elevenLabsKey, isManaged, onPlay, onPause, onBulkSubtitle, clipCount = 1, bulkProgress, initialState = null, onStateChange }) {
|
||||
const [showModal, setShowModal] = useState(false);
|
||||
const [showSubtitleModal, setShowSubtitleModal] = useState(false);
|
||||
const videoRef = React.useRef(null);
|
||||
|
|
@ -41,7 +41,8 @@ export default function ResultCard({ clip, index, jobId, durableUrl, uploadPostK
|
|||
// Latest file that exists ON THE SERVER (blob: previews don't count).
|
||||
// All server-side operations must chain from this, so burned-in edits
|
||||
// (subtitles, hooks, effects) never get silently dropped.
|
||||
const [serverVideoFile, setServerVideoFile] = useState((clip.video_url || '').split('/').pop());
|
||||
// A reopened project seeds it from the persisted project state.
|
||||
const [serverVideoFile, setServerVideoFile] = useState(initialState?.server_file || (clip.video_url || '').split('/').pop());
|
||||
const [videoErrored, setVideoErrored] = useState(false);
|
||||
|
||||
// If the local video failed and a durable R2 URL is (now) available, use it.
|
||||
|
|
@ -101,8 +102,19 @@ export default function ResultCard({ clip, index, jobId, durableUrl, uploadPostK
|
|||
|
||||
const [clipDuration, setClipDuration] = useState(clip.end && clip.start ? clip.end - clip.start : 30);
|
||||
|
||||
// Accumulate Remotion layers across operations
|
||||
const [activeLayers, setActiveLayers] = useState({ subtitles: null, hook: null, effects: null });
|
||||
// Accumulate Remotion layers across operations. A reopened project restores
|
||||
// the layers persisted in its project state, so the next edit composes over
|
||||
// them instead of silently dropping previous browser-side work.
|
||||
const [activeLayers, setActiveLayers] = useState(initialState?.active_layers || { subtitles: null, hook: null, effects: null });
|
||||
|
||||
// Report edit state upward (debounced sync to the project record). Skip the
|
||||
// mount run: only user-driven changes are worth persisting.
|
||||
const stateReported = React.useRef(false);
|
||||
useEffect(() => {
|
||||
if (!stateReported.current) { stateReported.current = true; return; }
|
||||
onStateChange?.(index, { activeLayers, serverVideoFile });
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [activeLayers, serverVideoFile]);
|
||||
|
||||
// True when the current server file already carries burned-in content.
|
||||
// Browser (Remotion) renders compose over the ORIGINAL clip, so using them
|
||||
|
|
|
|||
Loading…
Reference in a new issue