feat(cloud): bake bgutil 720p into image, profile menu, video-URL info, trial→pricing
- Dockerfile: bake bgutil PO-token provider in script mode (no sidecar); 720p verified - main.py / cloud/metering.py: support BGUTIL_SCRIPT_PATH (script mode) alongside HTTP - docker-compose.cloud.yml: drop bgutil sidecar; .env.cloud.example documents script mode - docker-compose.e2e.local.yml: local FRONTEND_URL/ALLOWED_ORIGINS/VITE_API_URL for testing - AuthContext: new/non-entitled sign-ins land on pricing to start the trial - ProfileMenu: header account dropdown (email, account & billing, sign out) - MediaInput: "YouTube URL" → "Video URL" + supported-platforms info popover
This commit is contained in:
parent
1901b06f3a
commit
d298f69f12
18 changed files with 413 additions and 62 deletions
|
|
@ -38,6 +38,15 @@ videos/
|
||||||
# Model files (downloaded at build time)
|
# Model files (downloaded at build time)
|
||||||
*.pt
|
*.pt
|
||||||
|
|
||||||
|
# Secrets — never bake real credentials into the image (repo is public,
|
||||||
|
# image may be pushed to a registry). Runtime env comes via compose env_file.
|
||||||
|
.env
|
||||||
|
.env.*
|
||||||
|
!.env.example
|
||||||
|
!.env.cloud.example
|
||||||
|
*.pem
|
||||||
|
*.key
|
||||||
|
|
||||||
# Docker
|
# Docker
|
||||||
Dockerfile
|
Dockerfile
|
||||||
docker-compose.yml
|
docker-compose.yml
|
||||||
|
|
|
||||||
|
|
@ -50,6 +50,8 @@ R2_BUCKET=openshorts-videos
|
||||||
R2_ACCESS_KEY_ID=
|
R2_ACCESS_KEY_ID=
|
||||||
R2_SECRET_ACCESS_KEY=
|
R2_SECRET_ACCESS_KEY=
|
||||||
|
|
||||||
# PO-token provider for 720p/1080p YouTube (bgutil sidecar in docker-compose.cloud.yml).
|
# PO-token provider for 720p/1080p YouTube downloads.
|
||||||
# Defaults to the sidecar; only override if you run bgutil elsewhere.
|
# The bgutil provider is baked into the backend image in *script mode*
|
||||||
BGUTIL_BASE_URL=http://bgutil:4416
|
# (BGUTIL_SCRIPT_PATH is set inside the Dockerfile) — no sidecar, nothing to set here.
|
||||||
|
# Only if you run bgutil as an external HTTP service, point at it instead:
|
||||||
|
# BGUTIL_BASE_URL=http://bgutil:4416
|
||||||
|
|
|
||||||
18
Dockerfile
18
Dockerfile
|
|
@ -24,7 +24,7 @@ FROM python:3.11-slim
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
# Install FFmpeg, OpenCV dependencies, and Node.js (for yt-dlp JS challenges)
|
# Install FFmpeg, OpenCV deps, Node.js + npm + git (for yt-dlp JS + bgutil build)
|
||||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||||
ffmpeg \
|
ffmpeg \
|
||||||
libgl1 \
|
libgl1 \
|
||||||
|
|
@ -33,19 +33,29 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||||
libxext6 \
|
libxext6 \
|
||||||
libxrender1 \
|
libxrender1 \
|
||||||
nodejs \
|
nodejs \
|
||||||
|
npm \
|
||||||
|
git \
|
||||||
&& rm -rf /var/lib/apt/lists/*
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
# Deno JS runtime — yt-dlp needs it to solve YouTube's nsig challenge for 720p+
|
# Deno JS runtime — yt-dlp needs it to solve YouTube's nsig challenge for 720p+.
|
||||||
# (used together with the bgutil PO-token sidecar in cloud mode).
|
|
||||||
COPY --from=denoland/deno:bin /deno /usr/local/bin/deno
|
COPY --from=denoland/deno:bin /deno /usr/local/bin/deno
|
||||||
|
|
||||||
|
# bgutil PO-token provider, baked in as a local Node script (script mode) — no
|
||||||
|
# separate service/sidecar needed. Unlocks 720p/1080p together with Deno.
|
||||||
|
RUN git clone --depth 1 https://github.com/Brainicism/bgutil-ytdlp-pot-provider /opt/bgutil-provider \
|
||||||
|
&& cd /opt/bgutil-provider/server \
|
||||||
|
&& npm install --no-audit --no-fund \
|
||||||
|
&& npx tsc \
|
||||||
|
&& npm cache clean --force
|
||||||
|
ENV BGUTIL_SCRIPT_PATH=/opt/bgutil-provider/server/build/generate_once.js
|
||||||
|
|
||||||
# Copy virtual env from builder
|
# Copy virtual env from builder
|
||||||
COPY --from=builder /opt/venv /opt/venv
|
COPY --from=builder /opt/venv /opt/venv
|
||||||
ENV PATH="/opt/venv/bin:$PATH"
|
ENV PATH="/opt/venv/bin:$PATH"
|
||||||
ENV PYTHONUNBUFFERED=1
|
ENV PYTHONUNBUFFERED=1
|
||||||
|
|
||||||
# Latest yt-dlp (nightly, YouTube changes constantly) + the bgutil PO-token
|
# Latest yt-dlp (nightly, YouTube changes constantly) + the bgutil PO-token
|
||||||
# provider plugin. Together with Deno + the bgutil sidecar this unlocks 720p/1080p.
|
# provider plugin. Together with Deno + the baked-in bgutil script this unlocks 720p.
|
||||||
RUN pip install --upgrade --pre --no-cache-dir "yt-dlp[default]" bgutil-ytdlp-pot-provider
|
RUN pip install --upgrade --pre --no-cache-dir "yt-dlp[default]" bgutil-ytdlp-pot-provider
|
||||||
|
|
||||||
# Copy application code
|
# Copy application code
|
||||||
|
|
|
||||||
105
app.py
105
app.py
|
|
@ -120,8 +120,13 @@ async def reserve_process_minutes(request, url, input_path, job_id):
|
||||||
For a managed (entitled, no BYOK header) request this probes the input
|
For a managed (entitled, no BYOK header) request this probes the input
|
||||||
duration, enforces the per-user concurrent-job limit, and reserves minutes —
|
duration, enforces the per-user concurrent-job limit, and reserves minutes —
|
||||||
raising 402 (quota) or 429 (too many jobs) as needed.
|
raising 402 (quota) or 429 (too many jobs) as needed.
|
||||||
|
|
||||||
|
NOTE: in cloud mode ``resolve_gemini`` ignores ``X-Gemini-Key`` (paid-only,
|
||||||
|
no BYOK), so we must NOT skip metering just because that header is present —
|
||||||
|
otherwise a client could send a dummy header and run unlimited managed jobs
|
||||||
|
on the operator's key for free. Only skip metering when billing is off.
|
||||||
"""
|
"""
|
||||||
if not BILLING_ENABLED or request.headers.get("X-Gemini-Key"):
|
if not BILLING_ENABLED:
|
||||||
return None, 2, None
|
return None, 2, None
|
||||||
user = await _user_from_request(request)
|
user = await _user_from_request(request)
|
||||||
if not managed_keys.has_active_entitlement(user):
|
if not managed_keys.has_active_entitlement(user):
|
||||||
|
|
@ -180,6 +185,23 @@ async def reserve_managed_action(request, minutes, job_id, job_type):
|
||||||
"minutes_remaining": e.remaining,
|
"minutes_remaining": e.remaining,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
|
async def require_managed_entitlement(request):
|
||||||
|
"""Gate a managed compute endpoint that doesn't resolve a Gemini key itself.
|
||||||
|
|
||||||
|
Some endpoints (subtitle/hook FFmpeg re-encodes, render proxy, the thumbnail
|
||||||
|
upload that kicks off a YouTube download + Whisper) do expensive server work
|
||||||
|
without ever calling ``resolve_gemini``, so nothing was stopping an anonymous
|
||||||
|
or non-entitled caller from driving unbounded compute in cloud mode. In cloud
|
||||||
|
mode this rejects them with 402; it's a no-op for self-host (BILLING off).
|
||||||
|
"""
|
||||||
|
if not BILLING_ENABLED:
|
||||||
|
return None
|
||||||
|
user = await _user_from_request(request)
|
||||||
|
if not managed_keys.has_active_entitlement(user):
|
||||||
|
raise gemini_missing_error()
|
||||||
|
return user
|
||||||
|
|
||||||
# Application State
|
# Application State
|
||||||
# PriorityQueue holds (priority, seq, job_id). Lower priority dispatches first:
|
# PriorityQueue holds (priority, seq, job_id). Lower priority dispatches first:
|
||||||
# pro=0, starter/creator=1, BYOK/anonymous/self-host=2. The seq counter keeps
|
# pro=0, starter/creator=1, BYOK/anonymous/self-host=2. The seq counter keeps
|
||||||
|
|
@ -402,6 +424,20 @@ THUMBNAILS_DIR = os.path.join(OUTPUT_DIR, "thumbnails")
|
||||||
os.makedirs(THUMBNAILS_DIR, exist_ok=True)
|
os.makedirs(THUMBNAILS_DIR, exist_ok=True)
|
||||||
app.mount("/thumbnails", StaticFiles(directory=THUMBNAILS_DIR), name="thumbnails")
|
app.mount("/thumbnails", StaticFiles(directory=THUMBNAILS_DIR), name="thumbnails")
|
||||||
|
|
||||||
|
|
||||||
|
def _safe_under(base_dir: str, user_rel_path: str) -> Optional[str]:
|
||||||
|
"""Resolve ``user_rel_path`` under ``base_dir`` and reject path traversal.
|
||||||
|
|
||||||
|
Returns the absolute path only if it stays inside ``base_dir`` (after
|
||||||
|
following ``..``); otherwise None. Used to sanitize client-supplied file
|
||||||
|
references so ``../../.env`` can't escape the output directories.
|
||||||
|
"""
|
||||||
|
base = os.path.realpath(base_dir)
|
||||||
|
target = os.path.realpath(os.path.join(base, user_rel_path))
|
||||||
|
if target == base or target.startswith(base + os.sep):
|
||||||
|
return target
|
||||||
|
return None
|
||||||
|
|
||||||
class ProcessRequest(BaseModel):
|
class ProcessRequest(BaseModel):
|
||||||
url: str
|
url: str
|
||||||
|
|
||||||
|
|
@ -679,6 +715,12 @@ async def edit_clip(
|
||||||
if 'result' not in job or 'clips' not in job['result']:
|
if 'result' not in job or 'clips' not in job['result']:
|
||||||
raise HTTPException(status_code=400, detail="Job result not available")
|
raise HTTPException(status_code=400, detail="Job result not available")
|
||||||
|
|
||||||
|
# Meter the managed Gemini call so it can't be looped for free. Skip when the
|
||||||
|
# caller supplied their own key (BYOK body) or self-host (reserve is a no-op).
|
||||||
|
edit_minutes = _cloud_config.MANAGED_ANALYSIS_MINUTES if BILLING_ENABLED else 0
|
||||||
|
reservation_id = None if req.api_key else await reserve_managed_action(
|
||||||
|
request, edit_minutes, req.job_id, "edit")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Resolve Input Path: Prefer explict input_filename from frontend (chaining edits)
|
# Resolve Input Path: Prefer explict input_filename from frontend (chaining edits)
|
||||||
if req.input_filename:
|
if req.input_filename:
|
||||||
|
|
@ -774,6 +816,8 @@ async def edit_clip(
|
||||||
# Let's update the current one's video_url but keep backup?
|
# Let's update the current one's video_url but keep backup?
|
||||||
# Or return the new URL to the frontend to display.
|
# Or return the new URL to the frontend to display.
|
||||||
|
|
||||||
|
if reservation_id:
|
||||||
|
await _metering.commit_reservation(reservation_id)
|
||||||
return {
|
return {
|
||||||
"success": True,
|
"success": True,
|
||||||
"new_video_url": new_video_url,
|
"new_video_url": new_video_url,
|
||||||
|
|
@ -781,6 +825,8 @@ async def edit_clip(
|
||||||
}
|
}
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
if reservation_id:
|
||||||
|
await _metering.release_reservation(reservation_id)
|
||||||
print(f"❌ Edit Error: {e}")
|
print(f"❌ Edit Error: {e}")
|
||||||
raise HTTPException(status_code=500, detail=str(e))
|
raise HTTPException(status_code=500, detail=str(e))
|
||||||
|
|
||||||
|
|
@ -851,6 +897,7 @@ RENDER_SERVICE_URL = os.getenv("RENDER_SERVICE_URL", "http://renderer:3100")
|
||||||
@app.post("/api/render")
|
@app.post("/api/render")
|
||||||
async def proxy_render(request: Request):
|
async def proxy_render(request: Request):
|
||||||
"""Proxy render requests to the Node.js Remotion render service."""
|
"""Proxy render requests to the Node.js Remotion render service."""
|
||||||
|
await require_managed_entitlement(request)
|
||||||
import httpx
|
import httpx
|
||||||
body = await request.json()
|
body = await request.json()
|
||||||
try:
|
try:
|
||||||
|
|
@ -895,6 +942,10 @@ async def generate_effects_config(
|
||||||
if 'result' not in job or 'clips' not in job['result']:
|
if 'result' not in job or 'clips' not in job['result']:
|
||||||
raise HTTPException(status_code=400, detail="Job result not available")
|
raise HTTPException(status_code=400, detail="Job result not available")
|
||||||
|
|
||||||
|
# Meter the managed Gemini call (no-op for self-host).
|
||||||
|
fx_minutes = _cloud_config.MANAGED_ANALYSIS_MINUTES if BILLING_ENABLED else 0
|
||||||
|
reservation_id = await reserve_managed_action(request, fx_minutes, req.job_id, "effects")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Resolve input path
|
# Resolve input path
|
||||||
if req.input_filename:
|
if req.input_filename:
|
||||||
|
|
@ -973,17 +1024,24 @@ async def generate_effects_config(
|
||||||
if effects_config is None:
|
if effects_config is None:
|
||||||
raise HTTPException(status_code=500, detail="Failed to generate effects config from Gemini")
|
raise HTTPException(status_code=500, detail="Failed to generate effects config from Gemini")
|
||||||
|
|
||||||
|
if reservation_id:
|
||||||
|
await _metering.commit_reservation(reservation_id)
|
||||||
return {"effects": effects_config}
|
return {"effects": effects_config}
|
||||||
|
|
||||||
except HTTPException:
|
except HTTPException:
|
||||||
|
if reservation_id:
|
||||||
|
await _metering.release_reservation(reservation_id)
|
||||||
raise
|
raise
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
if reservation_id:
|
||||||
|
await _metering.release_reservation(reservation_id)
|
||||||
print(f"❌ Effects Generation Error: {e}")
|
print(f"❌ Effects Generation Error: {e}")
|
||||||
raise HTTPException(status_code=500, detail=str(e))
|
raise HTTPException(status_code=500, detail=str(e))
|
||||||
|
|
||||||
|
|
||||||
@app.post("/api/subtitle")
|
@app.post("/api/subtitle")
|
||||||
async def add_subtitles(req: SubtitleRequest):
|
async def add_subtitles(req: SubtitleRequest, request: Request):
|
||||||
|
await require_managed_entitlement(request)
|
||||||
if req.job_id not in jobs:
|
if req.job_id not in jobs:
|
||||||
raise HTTPException(status_code=404, detail="Job not found")
|
raise HTTPException(status_code=404, detail="Job not found")
|
||||||
|
|
||||||
|
|
@ -1104,7 +1162,8 @@ class HookRequest(BaseModel):
|
||||||
size: Optional[str] = "M" # S, M, L
|
size: Optional[str] = "M" # S, M, L
|
||||||
|
|
||||||
@app.post("/api/hook")
|
@app.post("/api/hook")
|
||||||
async def add_hook(req: HookRequest):
|
async def add_hook(req: HookRequest, request: Request):
|
||||||
|
await require_managed_entitlement(request)
|
||||||
if req.job_id not in jobs:
|
if req.job_id not in jobs:
|
||||||
raise HTTPException(status_code=404, detail="Job not found")
|
raise HTTPException(status_code=404, detail="Job not found")
|
||||||
|
|
||||||
|
|
@ -1450,10 +1509,12 @@ async def get_social_user(request: Request):
|
||||||
|
|
||||||
@app.post("/api/thumbnail/upload")
|
@app.post("/api/thumbnail/upload")
|
||||||
async def thumbnail_upload(
|
async def thumbnail_upload(
|
||||||
|
request: Request,
|
||||||
file: Optional[UploadFile] = File(None),
|
file: Optional[UploadFile] = File(None),
|
||||||
url: Optional[str] = Form(None),
|
url: Optional[str] = Form(None),
|
||||||
):
|
):
|
||||||
"""Upload video and start background Whisper transcription immediately."""
|
"""Upload video and start background Whisper transcription immediately."""
|
||||||
|
await require_managed_entitlement(request)
|
||||||
if not url and not file:
|
if not url and not file:
|
||||||
raise HTTPException(status_code=400, detail="Must provide URL or File")
|
raise HTTPException(status_code=400, detail="Must provide URL or File")
|
||||||
|
|
||||||
|
|
@ -1568,6 +1629,10 @@ async def thumbnail_analyze(
|
||||||
content = await file.read()
|
content = await file.read()
|
||||||
buffer.write(content)
|
buffer.write(content)
|
||||||
|
|
||||||
|
# Meter the managed Gemini analysis (no-op for self-host).
|
||||||
|
analyze_minutes = _cloud_config.MANAGED_ANALYSIS_MINUTES if BILLING_ENABLED else 0
|
||||||
|
reservation_id = await reserve_managed_action(request, analyze_minutes, session_id, "thumbnail_analyze")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Run analysis in thread pool (skips Whisper if pre_transcript is available)
|
# Run analysis in thread pool (skips Whisper if pre_transcript is available)
|
||||||
loop = asyncio.get_event_loop()
|
loop = asyncio.get_event_loop()
|
||||||
|
|
@ -1587,6 +1652,8 @@ async def thumbnail_analyze(
|
||||||
"video_duration": result.get("video_duration", 0)
|
"video_duration": result.get("video_duration", 0)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
if reservation_id:
|
||||||
|
await _metering.commit_reservation(reservation_id)
|
||||||
return {
|
return {
|
||||||
"session_id": session_id,
|
"session_id": session_id,
|
||||||
"titles": result.get("titles", []),
|
"titles": result.get("titles", []),
|
||||||
|
|
@ -1596,6 +1663,8 @@ async def thumbnail_analyze(
|
||||||
}
|
}
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
if reservation_id:
|
||||||
|
await _metering.release_reservation(reservation_id)
|
||||||
print(f"❌ Thumbnail Analyze Error: {e}")
|
print(f"❌ Thumbnail Analyze Error: {e}")
|
||||||
raise HTTPException(status_code=500, detail=str(e))
|
raise HTTPException(status_code=500, detail=str(e))
|
||||||
|
|
||||||
|
|
@ -1808,15 +1877,19 @@ async def thumbnail_publish(
|
||||||
if not video_path or not os.path.exists(video_path):
|
if not video_path or not os.path.exists(video_path):
|
||||||
raise HTTPException(status_code=404, detail="Original video file not found")
|
raise HTTPException(status_code=404, detail="Original video file not found")
|
||||||
|
|
||||||
# Resolve thumbnail path from URL
|
# Resolve thumbnail path from URL — sanitize against path traversal so a
|
||||||
|
# crafted thumbnail_url (e.g. "thumbnails/../../.env") can't read server
|
||||||
|
# files and exfiltrate them via the Upload-Post multipart body.
|
||||||
thumb_relative = thumbnail_url.lstrip("/")
|
thumb_relative = thumbnail_url.lstrip("/")
|
||||||
if thumb_relative.startswith("thumbnails/"):
|
if thumb_relative.startswith("thumbnails/"):
|
||||||
thumb_path = os.path.join(OUTPUT_DIR, thumb_relative)
|
thumb_path = _safe_under(OUTPUT_DIR, thumb_relative)
|
||||||
else:
|
else:
|
||||||
thumb_path = os.path.join(THUMBNAILS_DIR, thumb_relative)
|
thumb_path = _safe_under(THUMBNAILS_DIR, thumb_relative)
|
||||||
|
|
||||||
|
if not thumb_path:
|
||||||
|
raise HTTPException(status_code=400, detail="Invalid thumbnail path")
|
||||||
if not os.path.exists(thumb_path):
|
if not os.path.exists(thumb_path):
|
||||||
raise HTTPException(status_code=404, detail=f"Thumbnail file not found: {thumb_path}")
|
raise HTTPException(status_code=404, detail="Thumbnail file not found")
|
||||||
|
|
||||||
# Generate a unique ID for this publish job so the frontend can poll
|
# Generate a unique ID for this publish job so the frontend can poll
|
||||||
publish_id = str(uuid.uuid4())
|
publish_id = str(uuid.uuid4())
|
||||||
|
|
@ -1951,6 +2024,10 @@ async def saasshorts_analyze(
|
||||||
if not req.url and not req.description:
|
if not req.url and not req.description:
|
||||||
raise HTTPException(status_code=400, detail="Provide a URL or a product description")
|
raise HTTPException(status_code=400, detail="Provide a URL or a product description")
|
||||||
|
|
||||||
|
# Meter the managed Gemini research/analysis (no-op for self-host).
|
||||||
|
saas_minutes = _cloud_config.MANAGED_ANALYSIS_MINUTES if BILLING_ENABLED else 0
|
||||||
|
reservation_id = await reserve_managed_action(request, saas_minutes, "saasshorts", "saasshorts_analyze")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
loop = asyncio.get_event_loop()
|
loop = asyncio.get_event_loop()
|
||||||
|
|
||||||
|
|
@ -1982,9 +2059,13 @@ async def saasshorts_analyze(
|
||||||
}
|
}
|
||||||
|
|
||||||
result = await loop.run_in_executor(None, run_analysis)
|
result = await loop.run_in_executor(None, run_analysis)
|
||||||
|
if reservation_id:
|
||||||
|
await _metering.commit_reservation(reservation_id)
|
||||||
return result
|
return result
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
if reservation_id:
|
||||||
|
await _metering.release_reservation(reservation_id)
|
||||||
raise HTTPException(status_code=500, detail=str(e))
|
raise HTTPException(status_code=500, detail=str(e))
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -2400,10 +2481,13 @@ async def saasshorts_generate(
|
||||||
if req.selected_actor_url.startswith("http"):
|
if req.selected_actor_url.startswith("http"):
|
||||||
# Download from S3 public URL to job output dir
|
# Download from S3 public URL to job output dir
|
||||||
import httpx
|
import httpx
|
||||||
|
from security_utils import assert_public_url
|
||||||
try:
|
try:
|
||||||
|
# SSRF guard: block private / metadata hosts before fetching.
|
||||||
|
safe_actor_url = assert_public_url(req.selected_actor_url)
|
||||||
actor_local = os.path.join(job_output_dir, "selected_actor.png")
|
actor_local = os.path.join(job_output_dir, "selected_actor.png")
|
||||||
with httpx.Client(timeout=30.0) as client:
|
with httpx.Client(timeout=30.0) as client:
|
||||||
resp = client.get(req.selected_actor_url)
|
resp = client.get(safe_actor_url)
|
||||||
if resp.status_code == 200:
|
if resp.status_code == 200:
|
||||||
with open(actor_local, "wb") as f:
|
with open(actor_local, "wb") as f:
|
||||||
f.write(resp.content)
|
f.write(resp.content)
|
||||||
|
|
@ -2411,8 +2495,9 @@ async def saasshorts_generate(
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
else:
|
else:
|
||||||
src = os.path.join(OUTPUT_DIR, req.selected_actor_url.replace("/videos/", ""))
|
# Sanitize against traversal — the client controls selected_actor_url.
|
||||||
if os.path.exists(src):
|
src = _safe_under(OUTPUT_DIR, req.selected_actor_url.replace("/videos/", "").lstrip("/"))
|
||||||
|
if src and os.path.exists(src):
|
||||||
selected_actor_path = src
|
selected_actor_path = src
|
||||||
|
|
||||||
config = {
|
config = {
|
||||||
|
|
|
||||||
|
|
@ -37,6 +37,12 @@ TRIAL_DAYS = 3
|
||||||
# roughly matching its cost to the per-minute economics. Text (titles/desc) is free.
|
# roughly matching its cost to the per-minute economics. Text (titles/desc) is free.
|
||||||
THUMBNAIL_MINUTES = 3
|
THUMBNAIL_MINUTES = 3
|
||||||
|
|
||||||
|
# Other managed Gemini calls that upload a video for context (AI effect/filter
|
||||||
|
# generation, thumbnail analysis, SaaS-shorts analysis). Cheaper than image gen
|
||||||
|
# but not free — meter a small fixed cost so an entitled user can't loop them to
|
||||||
|
# burn the operator's managed Gemini budget. Pure-text calls (titles/desc) stay free.
|
||||||
|
MANAGED_ANALYSIS_MINUTES = 1
|
||||||
|
|
||||||
# Stripe prices are resolved at runtime by these stable lookup_keys, so no price
|
# Stripe prices are resolved at runtime by these stable lookup_keys, so no price
|
||||||
# IDs need to be copied into env vars (they differ between test and live anyway).
|
# IDs need to be copied into env vars (they differ between test and live anyway).
|
||||||
SUBSCRIPTION_LOOKUP_KEYS = [
|
SUBSCRIPTION_LOOKUP_KEYS = [
|
||||||
|
|
|
||||||
|
|
@ -72,13 +72,24 @@ def probe_url_minutes(url: str) -> float:
|
||||||
bandwidth. Raises ValueError if the duration is unknown (e.g. live streams).
|
bandwidth. Raises ValueError if the duration is unknown (e.g. live streams).
|
||||||
"""
|
"""
|
||||||
import yt_dlp
|
import yt_dlp
|
||||||
bgutil = os.environ.get("BGUTIL_BASE_URL", "").strip()
|
# SSRF guard: reject non-http(s) / private / metadata hosts before probing.
|
||||||
|
from security_utils import assert_public_url
|
||||||
|
assert_public_url(url)
|
||||||
|
|
||||||
|
bgutil_http = os.environ.get("BGUTIL_BASE_URL", "").strip()
|
||||||
|
bgutil_script = os.environ.get("BGUTIL_SCRIPT_PATH", "").strip()
|
||||||
proxy = os.environ.get("PROXY_URL", "").strip()
|
proxy = os.environ.get("PROXY_URL", "").strip()
|
||||||
conservative = {"youtube": {"player_client": ["tv_embed", "android", "mweb", "web"],
|
conservative = {"youtube": {"player_client": ["tv_embed", "android", "mweb", "web"],
|
||||||
"player_skip": ["webpage", "configs"]}}
|
"player_skip": ["webpage", "configs"]}}
|
||||||
# Try the bgutil/HD extractor first, then the conservative one — mirrors the
|
# Try the bgutil/HD extractor first (http or baked-in script), then the
|
||||||
# download's HD→fallback logic so the probe never fails alone.
|
# conservative one — mirrors the download's HD→fallback logic.
|
||||||
strategies = ([{"youtubepot-bgutilhttp": {"base_url": [bgutil]}}] if bgutil else []) + [conservative]
|
if bgutil_http:
|
||||||
|
hd = [{"youtubepot-bgutilhttp": {"base_url": [bgutil_http]}}]
|
||||||
|
elif bgutil_script:
|
||||||
|
hd = [{"youtubepot-bgutilscript": {"script_path": [bgutil_script]}}]
|
||||||
|
else:
|
||||||
|
hd = []
|
||||||
|
strategies = hd + [conservative]
|
||||||
|
|
||||||
last_err = None
|
last_err = None
|
||||||
for extractor_args in strategies:
|
for extractor_args in strategies:
|
||||||
|
|
|
||||||
|
|
@ -15,6 +15,7 @@ import LoginModal from './components/LoginModal';
|
||||||
import TrialGate from './components/TrialGate';
|
import TrialGate from './components/TrialGate';
|
||||||
import AdvancedBanner from './components/AdvancedBanner';
|
import AdvancedBanner from './components/AdvancedBanner';
|
||||||
import HistoryTab from './components/HistoryTab';
|
import HistoryTab from './components/HistoryTab';
|
||||||
|
import ProfileMenu from './components/ProfileMenu';
|
||||||
import { useAuth } from './contexts/AuthContext';
|
import { useAuth } from './contexts/AuthContext';
|
||||||
import { apiFetch, apiJson, QuotaError } from './lib/api';
|
import { apiFetch, apiJson, QuotaError } from './lib/api';
|
||||||
import { getApiUrl } from './config';
|
import { getApiUrl } from './config';
|
||||||
|
|
@ -573,6 +574,7 @@ function App() {
|
||||||
Sign in
|
Sign in
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
|
{billingEnabled && isSignedIn && <ProfileMenu />}
|
||||||
|
|
||||||
{keysMissing && (
|
{keysMissing && (
|
||||||
<button
|
<button
|
||||||
|
|
|
||||||
|
|
@ -1,13 +1,30 @@
|
||||||
import React, { useState, useEffect } from 'react';
|
import React, { useState, useEffect, useRef } from 'react';
|
||||||
import { Youtube, Upload, FileVideo, X } from 'lucide-react';
|
import { Link2, Upload, FileVideo, X, Info } from 'lucide-react';
|
||||||
import { getApiUrl } from '../config';
|
import { getApiUrl } from '../config';
|
||||||
|
|
||||||
|
const SUPPORTED_PLATFORMS = [
|
||||||
|
'YouTube', 'Vimeo', 'TikTok', 'X / Twitter', 'Twitch',
|
||||||
|
'Facebook', 'Instagram', 'Dailymotion', 'Reddit', 'Streamable',
|
||||||
|
];
|
||||||
|
|
||||||
export default function MediaInput({ onProcess, isProcessing }) {
|
export default function MediaInput({ onProcess, isProcessing }) {
|
||||||
const [youtubeUrlEnabled, setYoutubeUrlEnabled] = useState(true);
|
const [youtubeUrlEnabled, setYoutubeUrlEnabled] = useState(true);
|
||||||
const [mode, setMode] = useState('url'); // 'url' | 'file'
|
const [mode, setMode] = useState('url'); // 'url' | 'file'
|
||||||
const [url, setUrl] = useState('');
|
const [url, setUrl] = useState('');
|
||||||
const [file, setFile] = useState(null);
|
const [file, setFile] = useState(null);
|
||||||
const [acknowledged, setAcknowledged] = useState(false);
|
const [acknowledged, setAcknowledged] = useState(false);
|
||||||
|
const [showInfo, setShowInfo] = useState(false);
|
||||||
|
const infoRef = useRef(null);
|
||||||
|
|
||||||
|
// Close the compatibility popover on any outside click.
|
||||||
|
useEffect(() => {
|
||||||
|
if (!showInfo) return;
|
||||||
|
const onClick = (e) => {
|
||||||
|
if (infoRef.current && !infoRef.current.contains(e.target)) setShowInfo(false);
|
||||||
|
};
|
||||||
|
document.addEventListener('mousedown', onClick);
|
||||||
|
return () => document.removeEventListener('mousedown', onClick);
|
||||||
|
}, [showInfo]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
fetch(getApiUrl('/api/config'))
|
fetch(getApiUrl('/api/config'))
|
||||||
|
|
@ -50,8 +67,8 @@ export default function MediaInput({ onProcess, isProcessing }) {
|
||||||
: 'text-zinc-400 hover:text-white'
|
: 'text-zinc-400 hover:text-white'
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
<Youtube size={18} />
|
<Link2 size={18} />
|
||||||
YouTube URL
|
Video URL
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
<button
|
<button
|
||||||
|
|
@ -69,14 +86,41 @@ export default function MediaInput({ onProcess, isProcessing }) {
|
||||||
<form onSubmit={handleSubmit}>
|
<form onSubmit={handleSubmit}>
|
||||||
{mode === 'url' ? (
|
{mode === 'url' ? (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<input
|
<div className="relative">
|
||||||
type="url"
|
<input
|
||||||
value={url}
|
type="url"
|
||||||
onChange={(e) => setUrl(e.target.value)}
|
value={url}
|
||||||
placeholder="https://www.youtube.com/watch?v=..."
|
onChange={(e) => setUrl(e.target.value)}
|
||||||
className="input-field"
|
placeholder="https://... paste a video link"
|
||||||
required
|
className="input-field pr-11"
|
||||||
/>
|
required
|
||||||
|
/>
|
||||||
|
<div className="absolute inset-y-0 right-2 flex items-center" ref={infoRef}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setShowInfo((v) => !v)}
|
||||||
|
aria-label="Supported platforms"
|
||||||
|
className="p-1.5 text-zinc-500 hover:text-primary transition-colors"
|
||||||
|
>
|
||||||
|
<Info size={18} />
|
||||||
|
</button>
|
||||||
|
{showInfo && (
|
||||||
|
<div className="absolute right-0 top-full mt-2 w-64 z-20 bg-surface border border-white/10 rounded-xl shadow-xl p-4 text-left animate-[fadeIn_0.15s_ease-out]">
|
||||||
|
<p className="text-xs font-semibold text-white mb-2">Paste a link from</p>
|
||||||
|
<div className="flex flex-wrap gap-1.5">
|
||||||
|
{SUPPORTED_PLATFORMS.map((p) => (
|
||||||
|
<span key={p} className="text-[11px] px-2 py-0.5 rounded-full bg-white/5 text-zinc-300 border border-white/5">
|
||||||
|
{p}
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<p className="text-[11px] text-zinc-500 mt-2.5 leading-relaxed">
|
||||||
|
…and 1,000+ more sites. If a link has a public video, we can usually fetch it.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div
|
<div
|
||||||
|
|
|
||||||
62
dashboard/src/components/ProfileMenu.jsx
Normal file
62
dashboard/src/components/ProfileMenu.jsx
Normal file
|
|
@ -0,0 +1,62 @@
|
||||||
|
import React, { useState, useRef, useEffect } from 'react';
|
||||||
|
import { User, CreditCard, LogOut, Sparkles } from 'lucide-react';
|
||||||
|
import { useAuth } from '../contexts/AuthContext';
|
||||||
|
|
||||||
|
// Header avatar + dropdown for signed-in cloud users: shows the email and gives
|
||||||
|
// access to Account & billing (manage subscription, top-ups) and Sign out.
|
||||||
|
export default function ProfileMenu() {
|
||||||
|
const { user, isManaged, logout } = useAuth();
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
const ref = useRef(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return;
|
||||||
|
const onClick = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
|
||||||
|
document.addEventListener('mousedown', onClick);
|
||||||
|
return () => document.removeEventListener('mousedown', onClick);
|
||||||
|
}, [open]);
|
||||||
|
|
||||||
|
if (!user) return null;
|
||||||
|
const initial = (user.email || '?').trim().charAt(0).toUpperCase();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="relative" ref={ref}>
|
||||||
|
<button
|
||||||
|
onClick={() => setOpen((v) => !v)}
|
||||||
|
aria-label="Account menu"
|
||||||
|
className="w-8 h-8 rounded-full bg-primary/20 border border-primary/30 text-primary flex items-center justify-center text-sm font-semibold hover:bg-primary/30 transition-colors"
|
||||||
|
>
|
||||||
|
{initial}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{open && (
|
||||||
|
<div className="absolute right-0 top-full mt-2 w-60 z-30 bg-surface border border-white/10 rounded-xl shadow-xl overflow-hidden animate-[fadeIn_0.15s_ease-out]">
|
||||||
|
<div className="px-4 py-3 border-b border-white/5">
|
||||||
|
<p className="text-xs text-zinc-500">Signed in as</p>
|
||||||
|
<p className="text-sm text-white truncate" title={user.email}>{user.email}</p>
|
||||||
|
</div>
|
||||||
|
{!isManaged && (
|
||||||
|
<button
|
||||||
|
onClick={() => { setOpen(false); window.location.hash = '#/pricing'; }}
|
||||||
|
className="w-full flex items-center gap-3 px-4 py-2.5 text-sm text-primary hover:bg-white/5 transition-colors"
|
||||||
|
>
|
||||||
|
<Sparkles size={16} /> Start free trial
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
<button
|
||||||
|
onClick={() => { setOpen(false); window.location.hash = '#/account'; }}
|
||||||
|
className="w-full flex items-center gap-3 px-4 py-2.5 text-sm text-zinc-200 hover:bg-white/5 transition-colors"
|
||||||
|
>
|
||||||
|
<CreditCard size={16} /> Account & billing
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => { setOpen(false); logout(); }}
|
||||||
|
className="w-full flex items-center gap-3 px-4 py-2.5 text-sm text-zinc-200 hover:bg-white/5 transition-colors border-t border-white/5"
|
||||||
|
>
|
||||||
|
<LogOut size={16} /> Sign out
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
import React, { useState, useEffect } from 'react';
|
import React, { useState, useEffect } from 'react';
|
||||||
import { Download, Share2, Instagram, Youtube, Video, CheckCircle, AlertCircle, X, Loader2, Copy, Wand2, Type, Calendar, Clock, Languages } from 'lucide-react';
|
import { Download, Share2, Instagram, Youtube, Video, CheckCircle, AlertCircle, X, Loader2, Copy, Wand2, Type, Calendar, Clock, Languages } from 'lucide-react';
|
||||||
import { getApiUrl } from '../config';
|
import { getApiUrl } from '../config';
|
||||||
|
import { apiFetch } from '../lib/api';
|
||||||
import SubtitleModal from './SubtitleModal';
|
import SubtitleModal from './SubtitleModal';
|
||||||
import HookModal from './HookModal';
|
import HookModal from './HookModal';
|
||||||
import TranslateModal from './TranslateModal';
|
import TranslateModal from './TranslateModal';
|
||||||
|
|
@ -165,7 +166,7 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fallback: legacy FFmpeg
|
// Fallback: legacy FFmpeg
|
||||||
const res = await fetch(getApiUrl('/api/subtitle'), {
|
const res = await apiFetch('/api/subtitle', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
|
|
@ -224,7 +225,7 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs
|
||||||
? { text: hookData, position: 'top', size: 'M' }
|
? { text: hookData, position: 'top', size: 'M' }
|
||||||
: hookData;
|
: hookData;
|
||||||
|
|
||||||
const res = await fetch(getApiUrl('/api/hook'), {
|
const res = await apiFetch('/api/hook', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
|
|
|
||||||
|
|
@ -151,7 +151,7 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse
|
||||||
const formData = new FormData();
|
const formData = new FormData();
|
||||||
formData.append('file', file);
|
formData.append('file', file);
|
||||||
|
|
||||||
const res = await fetch(getApiUrl('/api/thumbnail/upload'), {
|
const res = await apiFetch('/api/thumbnail/upload', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: formData
|
body: formData
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -40,10 +40,19 @@ export function AuthProvider({ children }) {
|
||||||
const params = new URLSearchParams(query);
|
const params = new URLSearchParams(query);
|
||||||
|
|
||||||
setSigningIn(true);
|
setSigningIn(true);
|
||||||
|
let destination = '#app';
|
||||||
try {
|
try {
|
||||||
if (kind === 'callback') {
|
if (kind === 'callback') {
|
||||||
const token = params.get('token');
|
const token = params.get('token');
|
||||||
if (token) setToken(token);
|
if (token) {
|
||||||
|
setToken(token);
|
||||||
|
// Scrub the token from the URL immediately (replaceState, no new
|
||||||
|
// history entry) so the bearer token isn't left reachable via Back.
|
||||||
|
try {
|
||||||
|
window.history.replaceState(null, document.title,
|
||||||
|
window.location.pathname + window.location.search);
|
||||||
|
} catch (_) { /* ignore */ }
|
||||||
|
}
|
||||||
} else if (kind === 'verify') {
|
} else if (kind === 'verify') {
|
||||||
const ml = params.get('ml');
|
const ml = params.get('ml');
|
||||||
if (ml) {
|
if (ml) {
|
||||||
|
|
@ -55,13 +64,16 @@ export function AuthProvider({ children }) {
|
||||||
if (data.token) setToken(data.token);
|
if (data.token) setToken(data.token);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
await refreshMe();
|
const signedInMe = await refreshMe();
|
||||||
|
// New sign-ups (and anyone without an active plan/trial) go straight to
|
||||||
|
// pricing so they can start their free trial; entitled users land in the app.
|
||||||
|
if (signedInMe?.user && !signedInMe?.entitled) destination = '#/pricing';
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
// fall through — user lands signed-out
|
// fall through — user lands signed-out
|
||||||
} finally {
|
} finally {
|
||||||
setSigningIn(false);
|
setSigningIn(false);
|
||||||
// Clear the sensitive hash, land in the app.
|
// Clear the sensitive hash, land wherever we resolved above.
|
||||||
window.location.hash = '#app';
|
window.location.hash = destination;
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}, [refreshMe]);
|
}, [refreshMe]);
|
||||||
|
|
|
||||||
|
|
@ -10,7 +10,8 @@ services:
|
||||||
container_name: openshorts-db
|
container_name: openshorts-db
|
||||||
environment:
|
environment:
|
||||||
- POSTGRES_USER=openshorts
|
- POSTGRES_USER=openshorts
|
||||||
- POSTGRES_PASSWORD=${POSTGRES_PASSWORD:-openshorts}
|
# Fail the deploy loudly if unset, rather than silently using a weak default.
|
||||||
|
- POSTGRES_PASSWORD=${POSTGRES_PASSWORD:?POSTGRES_PASSWORD must be set for cloud mode}
|
||||||
- POSTGRES_DB=openshorts
|
- POSTGRES_DB=openshorts
|
||||||
volumes:
|
volumes:
|
||||||
- pgdata:/var/lib/postgresql/data
|
- pgdata:/var/lib/postgresql/data
|
||||||
|
|
@ -21,22 +22,13 @@ services:
|
||||||
retries: 10
|
retries: 10
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
|
||||||
# PO-token provider — lets yt-dlp fetch YouTube's GVS PO tokens so 720p/1080p
|
|
||||||
# formats are available (with Deno + a recent yt-dlp in the backend image).
|
|
||||||
bgutil:
|
|
||||||
image: brainicism/bgutil-ytdlp-pot-provider
|
|
||||||
container_name: openshorts-bgutil
|
|
||||||
restart: unless-stopped
|
|
||||||
|
|
||||||
backend:
|
backend:
|
||||||
depends_on:
|
depends_on:
|
||||||
db:
|
db:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
bgutil:
|
|
||||||
condition: service_started
|
|
||||||
environment:
|
environment:
|
||||||
- BILLING_ENABLED=true
|
- BILLING_ENABLED=true
|
||||||
- DATABASE_URL=postgresql+asyncpg://openshorts:${POSTGRES_PASSWORD:-openshorts}@db:5432/openshorts
|
- DATABASE_URL=postgresql+asyncpg://openshorts:${POSTGRES_PASSWORD:?POSTGRES_PASSWORD must be set for cloud mode}@db:5432/openshorts
|
||||||
- JWT_SECRET=${JWT_SECRET}
|
- JWT_SECRET=${JWT_SECRET}
|
||||||
- FRONTEND_URL=${FRONTEND_URL:-https://openshorts.app}
|
- FRONTEND_URL=${FRONTEND_URL:-https://openshorts.app}
|
||||||
- ALLOWED_ORIGINS=${ALLOWED_ORIGINS:-https://openshorts.app}
|
- ALLOWED_ORIGINS=${ALLOWED_ORIGINS:-https://openshorts.app}
|
||||||
|
|
@ -57,8 +49,8 @@ services:
|
||||||
# Residential proxy for YouTube downloads (avoids datacenter-IP bans).
|
# Residential proxy for YouTube downloads (avoids datacenter-IP bans).
|
||||||
# e.g. http://user:pass@gate.dataimpulse.com:823 — leave empty to go direct.
|
# e.g. http://user:pass@gate.dataimpulse.com:823 — leave empty to go direct.
|
||||||
- PROXY_URL=${PROXY_URL:-}
|
- PROXY_URL=${PROXY_URL:-}
|
||||||
# PO-token provider (bgutil sidecar) → unlocks 720p/1080p downloads.
|
# 720p/1080p: the bgutil PO-token provider is baked into the backend image
|
||||||
- BGUTIL_BASE_URL=${BGUTIL_BASE_URL:-http://bgutil:4416}
|
# (script mode, BGUTIL_SCRIPT_PATH). No sidecar or BGUTIL_BASE_URL needed.
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
pgdata:
|
pgdata:
|
||||||
|
|
|
||||||
|
|
@ -5,6 +5,15 @@ services:
|
||||||
backend:
|
backend:
|
||||||
ports: !override
|
ports: !override
|
||||||
- "8001:8000"
|
- "8001:8000"
|
||||||
|
environment:
|
||||||
|
# Point auth/magic-link/CORS at the local frontend instead of openshorts.app.
|
||||||
|
- FRONTEND_URL=http://localhost:5176
|
||||||
|
- ALLOWED_ORIGINS=http://localhost:5176,http://localhost:5175,http://localhost:8001
|
||||||
frontend:
|
frontend:
|
||||||
ports: !override
|
ports: !override
|
||||||
- "5176:5173"
|
- "5176:5173"
|
||||||
|
environment:
|
||||||
|
# Call the backend directly (not via the Vite proxy) so Google OAuth builds
|
||||||
|
# a redirect_uri of http://localhost:8001/... which matches the registered
|
||||||
|
# client. Cross-origin API calls are allowed by ALLOWED_ORIGINS above.
|
||||||
|
- VITE_API_URL=http://localhost:8001
|
||||||
|
|
|
||||||
17
main.py
17
main.py
|
|
@ -451,6 +451,11 @@ def download_youtube_video(url, output_dir="."):
|
||||||
Downloads a YouTube video using yt-dlp.
|
Downloads a YouTube video using yt-dlp.
|
||||||
Returns the path to the downloaded video and the video title.
|
Returns the path to the downloaded video and the video title.
|
||||||
"""
|
"""
|
||||||
|
# SSRF guard: block non-http(s) schemes and private/loopback/metadata hosts
|
||||||
|
# before handing the URL to yt-dlp.
|
||||||
|
from security_utils import assert_public_url
|
||||||
|
assert_public_url(url)
|
||||||
|
|
||||||
print(f"🔍 Debug: yt-dlp version: {yt_dlp.version.__version__}")
|
print(f"🔍 Debug: yt-dlp version: {yt_dlp.version.__version__}")
|
||||||
print("📥 Downloading video from YouTube...")
|
print("📥 Downloading video from YouTube...")
|
||||||
step_start_time = time.time()
|
step_start_time = time.time()
|
||||||
|
|
@ -487,8 +492,16 @@ def download_youtube_video(url, output_dir="."):
|
||||||
# (BGUTIL_BASE_URL, needs the sidecar + Deno + recent yt-dlp) → 720p/1080p.
|
# (BGUTIL_BASE_URL, needs the sidecar + Deno + recent yt-dlp) → 720p/1080p.
|
||||||
# 2) Fallback — conservative tv_embed/android clients, no PO provider (~360p),
|
# 2) Fallback — conservative tv_embed/android clients, no PO provider (~360p),
|
||||||
# which is also the ONLY strategy for self-host (no bgutil configured).
|
# which is also the ONLY strategy for self-host (no bgutil configured).
|
||||||
_bgutil = os.environ.get("BGUTIL_BASE_URL", "").strip()
|
# PO-token provider: HTTP mode (external BGUTIL_BASE_URL) or the baked-in
|
||||||
hd_args = {'youtubepot-bgutilhttp': {'base_url': [_bgutil]}} if _bgutil else None
|
# local Node script (BGUTIL_SCRIPT_PATH, set in the image). Either enables HD.
|
||||||
|
_bgutil_http = os.environ.get("BGUTIL_BASE_URL", "").strip()
|
||||||
|
_bgutil_script = os.environ.get("BGUTIL_SCRIPT_PATH", "").strip()
|
||||||
|
if _bgutil_http:
|
||||||
|
hd_args = {'youtubepot-bgutilhttp': {'base_url': [_bgutil_http]}}
|
||||||
|
elif _bgutil_script:
|
||||||
|
hd_args = {'youtubepot-bgutilscript': {'script_path': [_bgutil_script]}}
|
||||||
|
else:
|
||||||
|
hd_args = None
|
||||||
fallback_args = {
|
fallback_args = {
|
||||||
'youtube': {
|
'youtube': {
|
||||||
'player_client': ['tv_embed', 'android', 'mweb', 'web'],
|
'player_client': ['tv_embed', 'android', 'mweb', 'web'],
|
||||||
|
|
|
||||||
|
|
@ -150,15 +150,25 @@ Be thorough. Use REAL data from your search results, not made-up information."""
|
||||||
def scrape_website(url: str) -> dict:
|
def scrape_website(url: str) -> dict:
|
||||||
"""Scrape a SaaS website to extract key content for analysis."""
|
"""Scrape a SaaS website to extract key content for analysis."""
|
||||||
from bs4 import BeautifulSoup
|
from bs4 import BeautifulSoup
|
||||||
|
from security_utils import assert_public_url
|
||||||
|
|
||||||
|
# SSRF guard: reject non-http(s) / private / metadata hosts, and re-validate
|
||||||
|
# every redirect hop so a public URL can't 30x-bounce us to an internal host.
|
||||||
|
current = assert_public_url(url)
|
||||||
print(f"[SaaSShorts] 🌐 Scraping {url}...")
|
print(f"[SaaSShorts] 🌐 Scraping {url}...")
|
||||||
|
|
||||||
headers = {
|
headers = {
|
||||||
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
|
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
|
||||||
}
|
}
|
||||||
|
|
||||||
with httpx.Client(timeout=30.0, follow_redirects=True) as client:
|
with httpx.Client(timeout=30.0, follow_redirects=False) as client:
|
||||||
response = client.get(url, headers=headers)
|
response = None
|
||||||
|
for _ in range(5):
|
||||||
|
response = client.get(current, headers=headers)
|
||||||
|
if response.has_redirect_location:
|
||||||
|
current = assert_public_url(str(response.next_request.url))
|
||||||
|
continue
|
||||||
|
break
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
|
|
||||||
soup = BeautifulSoup(response.text, "html.parser")
|
soup = BeautifulSoup(response.text, "html.parser")
|
||||||
|
|
|
||||||
76
security_utils.py
Normal file
76
security_utils.py
Normal file
|
|
@ -0,0 +1,76 @@
|
||||||
|
"""Small, dependency-free SSRF guards shared by the download / scrape paths.
|
||||||
|
|
||||||
|
The app fetches user-supplied URLs server-side (yt-dlp downloads, SaaS landing
|
||||||
|
page scraping, actor-image download). Without a guard, a caller can point those
|
||||||
|
at internal services or the cloud metadata endpoint (169.254.169.254) to read
|
||||||
|
instance credentials. ``assert_public_url`` rejects non-HTTP(S) schemes and any
|
||||||
|
host that resolves to a private / loopback / link-local / reserved address.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import ipaddress
|
||||||
|
import socket
|
||||||
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
|
|
||||||
|
class UnsafeURLError(ValueError):
|
||||||
|
"""Raised when a URL is not safe to fetch server-side."""
|
||||||
|
|
||||||
|
|
||||||
|
def _ip_is_public(ip: str) -> bool:
|
||||||
|
try:
|
||||||
|
addr = ipaddress.ip_address(ip)
|
||||||
|
except ValueError:
|
||||||
|
return False
|
||||||
|
return not (
|
||||||
|
addr.is_private
|
||||||
|
or addr.is_loopback
|
||||||
|
or addr.is_link_local
|
||||||
|
or addr.is_reserved
|
||||||
|
or addr.is_multicast
|
||||||
|
or addr.is_unspecified
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def assert_public_url(url: str) -> str:
|
||||||
|
"""Return ``url`` if it is safe to fetch, else raise ``UnsafeURLError``.
|
||||||
|
|
||||||
|
Blocks non-http(s) schemes and hosts that resolve to any non-public IP.
|
||||||
|
Resolves every A/AAAA record so a hostname that maps to a private range
|
||||||
|
(or to 169.254.169.254) is rejected rather than silently fetched.
|
||||||
|
"""
|
||||||
|
if not url or not isinstance(url, str):
|
||||||
|
raise UnsafeURLError("Empty URL")
|
||||||
|
|
||||||
|
parsed = urlparse(url.strip())
|
||||||
|
if parsed.scheme.lower() not in ("http", "https"):
|
||||||
|
raise UnsafeURLError(f"Unsupported URL scheme: {parsed.scheme!r}")
|
||||||
|
|
||||||
|
host = parsed.hostname
|
||||||
|
if not host:
|
||||||
|
raise UnsafeURLError("URL has no host")
|
||||||
|
|
||||||
|
# If the host is a literal IP, validate it directly (no DNS).
|
||||||
|
try:
|
||||||
|
ipaddress.ip_address(host)
|
||||||
|
is_ip_literal = True
|
||||||
|
except ValueError:
|
||||||
|
is_ip_literal = False
|
||||||
|
|
||||||
|
if is_ip_literal:
|
||||||
|
if not _ip_is_public(host):
|
||||||
|
raise UnsafeURLError(f"URL host is not a public address: {host}")
|
||||||
|
return url
|
||||||
|
|
||||||
|
try:
|
||||||
|
infos = socket.getaddrinfo(host, parsed.port or None, proto=socket.IPPROTO_TCP)
|
||||||
|
except socket.gaierror as e:
|
||||||
|
raise UnsafeURLError(f"Could not resolve host {host!r}: {e}")
|
||||||
|
|
||||||
|
resolved = {info[4][0] for info in infos}
|
||||||
|
if not resolved:
|
||||||
|
raise UnsafeURLError(f"Host {host!r} did not resolve")
|
||||||
|
for ip in resolved:
|
||||||
|
if not _ip_is_public(ip):
|
||||||
|
raise UnsafeURLError(f"Host {host!r} resolves to a non-public address: {ip}")
|
||||||
|
return url
|
||||||
|
|
@ -155,6 +155,13 @@ def burn_subtitles(video_path, srt_path, output_path, alignment=2, fontsize=16,
|
||||||
- Outline mode (bg_opacity=0): Text with colored outline/border
|
- Outline mode (bg_opacity=0): Text with colored outline/border
|
||||||
- Box mode (bg_opacity>0): Text with semi-transparent background box
|
- Box mode (bg_opacity>0): Text with semi-transparent background box
|
||||||
"""
|
"""
|
||||||
|
# Sanitize the client-supplied font name before it goes into the FFmpeg
|
||||||
|
# force_style string. A quote/comma/colon/backslash would break out of the
|
||||||
|
# quoted style and inject extra libavfilter directives (filtergraph
|
||||||
|
# injection / DoS). Keep only safe font-name characters.
|
||||||
|
import re as _re
|
||||||
|
font_name = _re.sub(r"[^A-Za-z0-9 _\-]", "", str(font_name))[:64].strip() or "Verdana"
|
||||||
|
|
||||||
# Position mapping
|
# Position mapping
|
||||||
ass_alignment = 2
|
ass_alignment = 2
|
||||||
align_lower = str(alignment).lower()
|
align_lower = str(alignment).lower()
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue