caelum0x d56639a594
Some checks failed
build-images / web (push) Has been cancelled
vision2026-ci / Python SDK resource tests (push) Has been cancelled
build-images / api (push) Has been cancelled
build-images / worker-gpu (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (comfy-workflow-schema) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (effects-core) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (eventbus-types) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (growth-analytics) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (provider-adapter-kit) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (publishing-connectors) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (render-core) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (shot-template-schema) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (trends-schema) (push) Has been cancelled
vision2026-ci / Desktop engine crates (test + clippy + fmt) (push) Has been cancelled
codeql / Analyze (javascript-typescript) (push) Has been cancelled
codeql / Analyze (python) (push) Has been cancelled
perf / API hot-path micro-smoke (budgeted) (push) Has been cancelled
perf / Desktop engine crates (release build check) (push) Has been cancelled
vision2026-ci / API phase modules (ruff + pytest) (push) Has been cancelled
vision2026-ci / Alembic upgrade + drift check (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (caption-engine) (push) Has been cancelled
Menivor — open source release (MIT), free to use and fork
Paid, hosted product at menivor.com, now retired as a company project.
Fresh squashed history of the cleaned working tree (secret-scanned,
no .env, no customer data, no outreach logs). Built on
MoneyPrinterTurbo (MIT, harry0703) — see NOTICE.
2026-12-04 02:10:26 +03:00

244 lines
9.0 KiB
Python

"""Orchestrates one anonymous reel preview: classify the URL, fetch its real
public content (reusing the exact same fetchers :mod:`app.domains.appaudit`
and :mod:`app.domains.applisting` already use for App Store/Play listings,
and :mod:`app.domains.ingest` already uses for websites), write ONE real
opening hook from those facts (the same writer :mod:`app.domains.styles.hooks`
uses for the paid run), and pick a real "hook frame" image -- an app-store
screenshot/icon, or the page's own ``og:image``. Never a rendered video, so
one anonymous preview costs one page/listing fetch plus one hook-writing
call, not a render.
Cached by ``url_hash`` for :data:`CACHE_TTL_S` so repeat pastes of the same
link, by anyone, cost nothing further (the router's rate limit bounds how
many *new* previews one caller can create per hour; a cache hit still counts
against that limit -- it is nearly free, but still a request). Persisted so a
specific preview can later be "claimed" into a brand-new account right after
sign-up (:func:`claim_preview`) -- see ``app/domains/reel_preview/router.py``
and the web side's ``OneFlowCreate`` for how the preview id survives the
sign-up round-trip. The claim is bookkeeping/attribution only: the actual
paid run reuses the preview's own ``url``/``preset_id`` through the existing
``/create?q=&preset=&auto=1`` entry point, so claiming never repeats the
preview's own fetch/LLM cost.
"""
from __future__ import annotations
import hashlib
import uuid
from datetime import datetime, timedelta, timezone
from typing import Any, Callable
from app.domains.capture import store
from app.domains.capture.sources import KIND_AUTO, SourceError, classify
from app.domains.capture.store import StoreError
from app.domains.ingest.errors import IngestError
from app.domains.ingest.extract import extract_content
from app.domains.ingest.safe_fetch import fetch_website
from app.domains.styles.hooks import write_hooks
from app.models.db.anon_preview import AnonPreview
KIND_APP_STORE = "app_store"
KIND_PLAY_STORE = "play_store"
KIND_WEBSITE = "website"
#: A listing/page rarely changes meaningfully faster than this, so a repeat
#: paste of the same link -- by anyone -- is served from the DB for free.
CACHE_TTL_S = 7 * 24 * 3600
MAX_FETCH_BYTES = 2_000_000
#: Matches `gameplay_split` (the default link preset -- see
#: `apps/web/.../one-flow/plan.ts:defaultPresetFor`), whose hook family's
#: first format is "pov". One format = one LLM-writable hook, the cheapest
#: real preview that still matches what the paid run itself would open on.
HOOK_FORMAT = "pov"
MAX_FRAMES = 3
Getter = Callable[..., Any]
Fetcher = Callable[[str], str]
Generate = Callable[[str], str]
class ReelPreviewError(ValueError):
def __init__(self, status_code: int, message: str) -> None:
super().__init__(message)
self.status_code = status_code
self.message = message
def url_hash_of(url: str) -> str:
"""Stable cache key for a pasted URL (case/whitespace-insensitive)."""
return hashlib.sha256(url.strip().lower().encode("utf-8")).hexdigest()
def ip_hash_of(remote_ip: str) -> str:
"""Never persist the raw caller IP; a digest is enough for abuse forensics."""
return hashlib.sha256((remote_ip or "unknown").encode("utf-8")).hexdigest()
def _preset_id_for(source_kind: str) -> str:
# Both branches default to the same preset the paid link-run flow starts
# on for any pasted link (`defaultPresetFor` in plan.ts); the visitor can
# always change the style before the real run.
del source_kind
return "gameplay_split"
def _cached_row(session: Any, url_hash: str, now: datetime) -> AnonPreview | None:
cutoff = now - timedelta(seconds=CACHE_TTL_S)
return (
session.query(AnonPreview)
.filter(AnonPreview.url_hash == url_hash, AnonPreview.created_at >= cutoff)
.order_by(AnonPreview.created_at.desc())
.first()
)
def _to_payload(row: AnonPreview, *, cached: bool) -> dict[str, Any]:
return {
"preview_id": row.id,
"url": row.url,
"source_kind": row.source_kind,
"preset_id": row.preset_id,
"title": row.title,
"hook": {"line": row.hook_line, "style": row.hook_style, "source": row.hook_source},
"frames": list(row.frames or []),
"cached": cached,
}
def _store_branch(source, *, getter: Getter) -> tuple[str, str, list[str], list[str]]:
"""Returns ``(title, description, [], frames)`` for a store listing."""
try:
listing = (
store.fetch_app_store(source.ref, getter=getter)
if source.kind == KIND_APP_STORE
else store.fetch_play_store(source.ref, getter=getter)
)
except StoreError as exc:
raise ReelPreviewError(exc.status_code, exc.message) from exc
title = listing.get("title") or ""
description = listing.get("description") or ""
frames = [shot for shot in (listing.get("screenshots") or []) if shot][:MAX_FRAMES]
if not frames and listing.get("icon_url"):
frames = [listing["icon_url"]]
return title, description, [], frames
def _website_branch(url: str, *, fetcher: Fetcher | None) -> tuple[str, str, list[str], list[str]]:
"""Returns ``(title, description, features, frames)`` for any other link."""
fetch = fetcher or (lambda u: fetch_website(u)[:MAX_FETCH_BYTES])
try:
html = fetch(url)
except IngestError as exc:
raise ReelPreviewError(exc.status_code, exc.message) from exc
content = extract_content(html, url)
if not content.get("title") and not content.get("description"):
raise ReelPreviewError(422, "could not extract usable content from that page")
frames = [content["image"]] if content.get("image") else []
return content.get("title") or "", content.get("description") or "", list(content.get("features") or []), frames
def build_preview(
url: str,
*,
session: Any,
remote_ip: str = "",
requested_kind: str = KIND_AUTO,
getter: Getter | None = None,
fetcher: Fetcher | None = None,
generate: Generate | None = None,
now: datetime | None = None,
) -> dict[str, Any]:
"""Build (or return the cached) public, no-sign-in reel preview for ``url``.
Raises :class:`ReelPreviewError` for anything user-presentable (bad URL,
store lookup failure, an unfetchable page). ``getter``/``fetcher``/
``generate`` are injection points for tests; production callers leave
them at their defaults.
"""
url = (url or "").strip()
if not url:
raise ReelPreviewError(400, "a URL is required")
now = now or datetime.now(timezone.utc)
url_hash = url_hash_of(url)
cached = _cached_row(session, url_hash, now)
if cached is not None:
return _to_payload(cached, cached=True)
from app.domains.adstudio.fetch import safe_get
getter = getter or safe_get
try:
source = classify(url, requested_kind)
except SourceError as exc:
raise ReelPreviewError(422, str(exc)) from exc
if source.kind in (KIND_APP_STORE, KIND_PLAY_STORE):
title, description, features, frames = _store_branch(source, getter=getter)
source_kind = source.kind
else:
title, description, features, frames = _website_branch(url, fetcher=fetcher)
source_kind = KIND_WEBSITE
hook_kwargs: dict[str, Any] = {}
if generate is not None:
hook_kwargs["generate"] = generate
hooks = write_hooks(
title=title,
description=description,
features=features,
formats=[HOOK_FORMAT],
language="auto",
**hook_kwargs,
)
hook = hooks[0] if hooks else {"hook_style": HOOK_FORMAT, "hook": title or "See it in action.", "source": "template"}
row = AnonPreview(
id=str(uuid.uuid4()),
url_hash=url_hash,
url=url,
ip_hash=ip_hash_of(remote_ip),
source_kind=source_kind,
preset_id=_preset_id_for(source_kind),
title=title[:300],
hook_line=hook["hook"][:300],
hook_style=hook["hook_style"][:40],
hook_source=hook["source"][:20],
frames=frames,
content={"title": title, "description": description, "features": features, "url": url},
created_at=now,
)
session.add(row)
session.flush()
return _to_payload(row, cached=False)
def claim_preview(
preview_id: str, user_id: str, *, session: Any, now: datetime | None = None
) -> dict[str, Any] | None:
"""Mark ``preview_id`` claimed by ``user_id`` (first claim wins; idempotent) and
return its payload, or ``None`` if the id doesn't exist (e.g. it expired
past any cache window a cleanup job may later add, or was mistyped).
"""
row = session.query(AnonPreview).filter(AnonPreview.id == preview_id).first()
if row is None:
return None
if row.claimed_user_id is None:
row.claimed_user_id = user_id
row.claimed_at = now or datetime.now(timezone.utc)
session.add(row)
session.flush()
return _to_payload(row, cached=True)
__all__ = [
"KIND_APP_STORE",
"KIND_PLAY_STORE",
"KIND_WEBSITE",
"ReelPreviewError",
"build_preview",
"claim_preview",
"url_hash_of",
]