feat(bridge): shorts-to-long-form bridge + dashboard UI
This commit is contained in:
parent
702495b27c
commit
0cdd0b91b8
9 changed files with 1129 additions and 0 deletions
154
clipwright/integrations/youtube_data.py
Normal file
154
clipwright/integrations/youtube_data.py
Normal file
|
|
@ -0,0 +1,154 @@
|
|||
"""Minimal YouTube Data API v3 client -- first comment only (PLAN #6).
|
||||
|
||||
The Shorts "Related video" link and comment pinning are Studio-UI only and are
|
||||
**not** exposed by any API, so this module deliberately does one thing: post a
|
||||
top-level comment on a video via ``commentThreads.insert``. Pinning that comment
|
||||
stays manual.
|
||||
|
||||
Auth is a real-channel OAuth refresh token (service accounts do not work for
|
||||
this scope). Credentials come from the environment and the integration is
|
||||
**opt-in**: with any of them missing, :func:`is_configured` is false and no
|
||||
network call is ever made. Callers must check :func:`is_configured` (or handle
|
||||
:class:`YoutubeDataError`) before asking for a comment.
|
||||
|
||||
Quota: ``commentThreads.insert`` costs 50 units of the default 10,000/day
|
||||
project quota (~200 comments/day). That is the whole reason posting is a
|
||||
deliberate, caller-triggered action and never automatic.
|
||||
|
||||
Blocking, like ``postiz.py``: call through ``asyncio.to_thread`` from async
|
||||
handlers. Every function accepts an optional pre-built ``httpx.Client`` so tests
|
||||
can inject a ``httpx.MockTransport`` and no live OAuth is ever needed.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
import httpx
|
||||
|
||||
TOKEN_URI = "https://oauth2.googleapis.com/token"
|
||||
COMMENT_THREADS_URL = "https://www.googleapis.com/youtube/v3/commentThreads"
|
||||
# Required by insert (the comment posting endpoint). Read-only analytics use a
|
||||
# different scope; this module never reads.
|
||||
SCOPE = "https://www.googleapis.com/auth/youtube.force-ssl"
|
||||
|
||||
# Environment variable names, kept as constants so the API layer can name them
|
||||
# in its "not configured" message without duplicating strings.
|
||||
CLIENT_ID_ENV = "YOUTUBE_OAUTH_CLIENT_ID"
|
||||
CLIENT_SECRET_ENV = "YOUTUBE_OAUTH_CLIENT_SECRET"
|
||||
REFRESH_TOKEN_ENV = "YOUTUBE_OAUTH_REFRESH_TOKEN"
|
||||
TOKEN_URI_ENV = "YOUTUBE_OAUTH_TOKEN_URI"
|
||||
|
||||
|
||||
class YoutubeDataError(Exception):
|
||||
"""A missing config or non-2xx response from the YouTube Data API.
|
||||
|
||||
Carries the status and body so the FastAPI layer can translate it into the
|
||||
same status/detail it would have surfaced otherwise.
|
||||
"""
|
||||
|
||||
def __init__(self, status_code: int, detail: str):
|
||||
super().__init__(detail)
|
||||
self.status_code = status_code
|
||||
self.detail = detail
|
||||
|
||||
|
||||
def _env(name: str, default: Optional[str] = None) -> Optional[str]:
|
||||
value = os.environ.get(name)
|
||||
if value is None:
|
||||
return default
|
||||
value = value.strip()
|
||||
return value or default
|
||||
|
||||
|
||||
def credentials() -> Dict[str, Optional[str]]:
|
||||
"""The OAuth credentials read from the environment (values may be None)."""
|
||||
return {
|
||||
"client_id": _env(CLIENT_ID_ENV),
|
||||
"client_secret": _env(CLIENT_SECRET_ENV),
|
||||
"refresh_token": _env(REFRESH_TOKEN_ENV),
|
||||
"token_uri": _env(TOKEN_URI_ENV, TOKEN_URI),
|
||||
}
|
||||
|
||||
|
||||
def is_configured() -> bool:
|
||||
"""True when a refresh-token flow can run. False = no-op, never called."""
|
||||
creds = credentials()
|
||||
return all(creds[key] for key in ("client_id", "client_secret", "refresh_token"))
|
||||
|
||||
|
||||
def _access_token(client: httpx.Client, creds: Dict[str, Optional[str]]) -> str:
|
||||
resp = client.post(str(creds["token_uri"]), data={
|
||||
"client_id": creds["client_id"],
|
||||
"client_secret": creds["client_secret"],
|
||||
"refresh_token": creds["refresh_token"],
|
||||
"grant_type": "refresh_token",
|
||||
})
|
||||
if resp.status_code != 200:
|
||||
raise YoutubeDataError(
|
||||
502,
|
||||
f"YouTube OAuth token refresh failed: {(resp.text or '')[:300]}",
|
||||
)
|
||||
try:
|
||||
token = (resp.json() or {}).get("access_token")
|
||||
except ValueError:
|
||||
token = None
|
||||
if not token:
|
||||
raise YoutubeDataError(502, "YouTube OAuth token refresh returned no access_token")
|
||||
return token
|
||||
|
||||
|
||||
def post_first_comment(video_id: str, text: str, timeout: float = 60.0,
|
||||
client: Optional[httpx.Client] = None) -> Dict[str, Any]:
|
||||
"""Post ``text`` as a top-level comment on ``video_id``.
|
||||
|
||||
Returns the API's ``commentThreads.insert`` response (id + snippet).
|
||||
|
||||
Raises :class:`YoutubeDataError` when unconfigured, given bad input, or when
|
||||
YouTube rejects the insert. ``client`` is the test seam; pass an
|
||||
``httpx.Client`` built with a ``MockTransport`` to exercise this offline.
|
||||
"""
|
||||
if not video_id or not str(video_id).strip():
|
||||
raise YoutubeDataError(400, "video_id is required")
|
||||
if not text or not str(text).strip():
|
||||
raise YoutubeDataError(400, "comment text is required")
|
||||
if not is_configured():
|
||||
raise YoutubeDataError(
|
||||
400,
|
||||
"YouTube Data API is not configured; set "
|
||||
f"{CLIENT_ID_ENV}, {CLIENT_SECRET_ENV} and {REFRESH_TOKEN_ENV}",
|
||||
)
|
||||
|
||||
owns_client = client is None
|
||||
client = client or httpx.Client(timeout=timeout)
|
||||
try:
|
||||
token = _access_token(client, credentials())
|
||||
resp = client.post(
|
||||
COMMENT_THREADS_URL,
|
||||
params={"part": "snippet"},
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
json={"snippet": {
|
||||
"videoId": str(video_id).strip(),
|
||||
"topLevelComment": {
|
||||
"snippet": {"textOriginal": str(text)},
|
||||
},
|
||||
}},
|
||||
)
|
||||
finally:
|
||||
if owns_client:
|
||||
client.close()
|
||||
|
||||
if resp.status_code not in (200, 201):
|
||||
# 4xx are the caller's (invalid video / scope); 5xx become 502 so the
|
||||
# API layer does not claim the upstream is down with a gateway code
|
||||
# that came from YouTube, not this server.
|
||||
status = resp.status_code if resp.status_code < 500 else 502
|
||||
raise YoutubeDataError(
|
||||
status,
|
||||
f"YouTube commentThreads.insert failed: {(resp.text or '')[:300]}",
|
||||
)
|
||||
try:
|
||||
return resp.json() or {}
|
||||
except ValueError:
|
||||
return {}
|
||||
207
clipwright/pipeline/bridge.py
Normal file
207
clipwright/pipeline/bridge.py
Normal file
|
|
@ -0,0 +1,207 @@
|
|||
"""Shorts -> long-form bridge copy (PLAN #6).
|
||||
|
||||
Pure, network-free helpers that turn the active channel profile (+ its
|
||||
``published_video_history``) into the copy a Short needs to funnel viewers to a
|
||||
long-form video:
|
||||
|
||||
* ``description_bridge`` -- a block appended to the Short's YouTube description;
|
||||
* ``first_comment`` -- the top-level comment to post (and pin).
|
||||
|
||||
Two "related video" features are Studio-UI only and are **not** exposed by any
|
||||
API: the Shorts "Related video" link and comment pinning. Those therefore stay
|
||||
manual, and ``checklist`` spells out the exact Studio steps including the
|
||||
target long-form URL.
|
||||
|
||||
The explicit target wins over the profile history. Callers pass it from the CLI
|
||||
(``--longform-url``) or the API (``related_video_url``); nothing here performs
|
||||
I/O.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Mapping, Optional
|
||||
|
||||
from clipwright.pipeline import profile_prompts
|
||||
from clipwright.pipeline.profiles import Profile
|
||||
|
||||
# Fallback label when the target URL is provided but the profile says nothing.
|
||||
DEFAULT_TARGET_LABEL = "Full video"
|
||||
|
||||
# Keys a published_video_history entry may carry to identify the video. The
|
||||
# first match wins; ``id``/``video_id`` build a watch URL.
|
||||
_URL_KEYS = ("url", "video_url", "watch_url", "link")
|
||||
_ID_KEYS = ("id", "video_id", "youtube_id")
|
||||
_DATE_KEYS = ("published_at", "published", "date", "uploaded_at")
|
||||
|
||||
|
||||
def _entry_url(entry: Mapping) -> Optional[str]:
|
||||
"""The watch URL for one ``published_video_history`` entry, or None."""
|
||||
if not isinstance(entry, Mapping):
|
||||
return None
|
||||
for key in _URL_KEYS:
|
||||
value = entry.get(key)
|
||||
if isinstance(value, str) and value.strip():
|
||||
return value.strip()
|
||||
for key in _ID_KEYS:
|
||||
value = entry.get(key)
|
||||
if isinstance(value, str) and value.strip():
|
||||
return f"https://www.youtube.com/watch?v={value.strip()}"
|
||||
return None
|
||||
|
||||
|
||||
def _entry_sort_key(entry: Mapping) -> str:
|
||||
for key in _DATE_KEYS:
|
||||
value = entry.get(key)
|
||||
if isinstance(value, str) and value.strip():
|
||||
return value.strip()
|
||||
return ""
|
||||
|
||||
|
||||
def target_video(profile: Optional[Profile],
|
||||
related_video_url: Optional[str] = None) -> Optional[str]:
|
||||
"""The long-form target: the explicit URL, else the newest history entry.
|
||||
|
||||
An explicit ``related_video_url`` always wins. Otherwise the profile's
|
||||
``published_video_history`` is searched for an entry that names a video
|
||||
(``url``/``video_url``/... or an ``id``); the newest by a best-effort date
|
||||
field is chosen, falling back to the last entry listed.
|
||||
"""
|
||||
if isinstance(related_video_url, str) and related_video_url.strip():
|
||||
return related_video_url.strip()
|
||||
history = list(getattr(profile, "published_video_history", None) or [])
|
||||
candidates = [(k, e) for e in history if (k := _entry_url(e))]
|
||||
if not candidates:
|
||||
return None
|
||||
candidates.sort(key=lambda pair: _entry_sort_key(pair[1]))
|
||||
return candidates[-1][0]
|
||||
|
||||
|
||||
def _target_label(profile: Optional[Profile]) -> str:
|
||||
"""A human label for the target, derived from the profile's description."""
|
||||
template = getattr(profile, "description_template", "") if profile else ""
|
||||
# Templates look like "{hook}\n\nFull video: {link}\n\n#tags" -- lift the
|
||||
# words before "{link}" when they name the long-form video.
|
||||
if "{link}" in template:
|
||||
prefix = template.split("{link}")[0].strip().splitlines()[-1].strip()
|
||||
prefix = prefix.rstrip(":").strip()
|
||||
if prefix and "{hook}" not in prefix:
|
||||
return prefix
|
||||
return DEFAULT_TARGET_LABEL
|
||||
|
||||
|
||||
def _clip_hook(clip: Optional[Mapping]) -> str:
|
||||
"""The clip's hook text if the pipeline produced one, else its title."""
|
||||
if not isinstance(clip, Mapping):
|
||||
return ""
|
||||
for key in ("viral_hook_text", "hook_text", "video_title_for_youtube_short"):
|
||||
value = clip.get(key)
|
||||
if isinstance(value, str) and value.strip():
|
||||
return value.strip()
|
||||
return ""
|
||||
|
||||
|
||||
def _render_description_template(template: str, target: Optional[str],
|
||||
clip: Optional[Mapping]) -> str:
|
||||
"""Fill the profile's ``{hook}``/``{link}`` slots without str.format.
|
||||
|
||||
``str.format`` would explode on any other brace in the template (or
|
||||
hashtags that are fine today); a literal replace can only touch the two
|
||||
documented placeholders.
|
||||
"""
|
||||
rendered = template.replace("{hook}", _clip_hook(clip))
|
||||
rendered = rendered.replace("{link}", target or "")
|
||||
return "\n".join(line.rstrip() for line in rendered.splitlines()).strip()
|
||||
|
||||
|
||||
def description_bridge(profile: Optional[Profile],
|
||||
related_video_url: Optional[str] = None,
|
||||
clip: Optional[Mapping] = None) -> str:
|
||||
"""The description block: a target CTA plus the profile's description copy.
|
||||
|
||||
The target URL appears first (and in the rendered template when the profile
|
||||
has one). Without a target the channel links/description still render, so a
|
||||
bridge is produced even before a long-form URL is chosen.
|
||||
"""
|
||||
target = target_video(profile, related_video_url)
|
||||
parts: list[str] = []
|
||||
if target:
|
||||
parts.append(f"▶ {_target_label(profile)}: {target}")
|
||||
|
||||
template = (getattr(profile, "description_template", "") if profile else "") or ""
|
||||
rendered = _render_description_template(template, target, clip) if template else ""
|
||||
if rendered:
|
||||
parts.append(rendered)
|
||||
else:
|
||||
# No template: fall back to the profile's plain description block.
|
||||
block = profile_prompts.description_block(profile) if profile else ""
|
||||
if block:
|
||||
parts.append(block.rstrip())
|
||||
|
||||
# The profile's links belong in the bridge even when the template's {link}
|
||||
# slot was empty (no target yet) or the template does not mention them.
|
||||
links = [link for link in (getattr(profile, "links", None) or [])
|
||||
if isinstance(link, str) and link.strip()]
|
||||
if links and not any(link in "\n".join(parts) for link in links):
|
||||
parts.append("More from this channel: " + " | ".join(links))
|
||||
|
||||
return "\n\n".join(p for p in parts if p).strip()
|
||||
|
||||
|
||||
def first_comment(profile: Optional[Profile],
|
||||
related_video_url: Optional[str] = None,
|
||||
clip: Optional[Mapping] = None) -> str:
|
||||
"""The top-level comment text. Always carries the long-form reference.
|
||||
|
||||
With no target it points at the channel's links (or the description) rather
|
||||
than inventing a URL; it is never empty.
|
||||
"""
|
||||
target = target_video(profile, related_video_url)
|
||||
hook = _clip_hook(clip)
|
||||
if target:
|
||||
text = f"▶ {_target_label(profile)}: {target}"
|
||||
if hook:
|
||||
text += f"\n\n{_target_label(profile)} covers this: {hook}"
|
||||
return text
|
||||
links = list(getattr(profile, "links", None) or [])
|
||||
if links:
|
||||
return f"Watch the long-form videos here: {links[0]}"
|
||||
return "The full long-form video is linked in the description."
|
||||
|
||||
|
||||
def checklist(profile: Optional[Profile],
|
||||
related_video_url: Optional[str] = None) -> list[str]:
|
||||
"""The manual Studio steps for this Short (both are Studio-UI only).
|
||||
|
||||
The Shorts "Related video" link and comment pinning have no public API, so
|
||||
they are copy-paste steps, not something the server can do.
|
||||
"""
|
||||
target = target_video(profile, related_video_url)
|
||||
target_text = target or "<paste the long-form video URL>"
|
||||
return [
|
||||
"Open YouTube Studio -> Content -> this Short -> Edit.",
|
||||
f"Details -> Related video: set it to {target_text} "
|
||||
"(the Shorts related-video link is Studio-UI only; no API can set it).",
|
||||
"Post the generated first comment "
|
||||
"(or call this clip's bridge/comment endpoint if the YouTube Data API "
|
||||
"is configured).",
|
||||
"Pin the first comment: hover it -> the three-dot menu -> Pin. "
|
||||
"Pinning stays manual (no API).",
|
||||
]
|
||||
|
||||
|
||||
def build_bridge(profile: Optional[Profile],
|
||||
clip: Optional[Mapping] = None,
|
||||
related_video_url: Optional[str] = None) -> dict[str, Any]:
|
||||
"""All bridge fields for one clip, ready to merge into clip metadata.
|
||||
|
||||
``related_video_url`` is the explicit target (CLI ``--longform-url`` / API
|
||||
``related_video_url``); when omitted the profile history is used.
|
||||
"""
|
||||
target = target_video(profile, related_video_url)
|
||||
return {
|
||||
"related_video_url": target,
|
||||
"description_bridge": description_bridge(profile, target, clip),
|
||||
"first_comment": first_comment(profile, target, clip),
|
||||
"checklist": checklist(profile, target),
|
||||
"manual_pin_required": True,
|
||||
}
|
||||
|
|
@ -673,6 +673,9 @@ function App() {
|
|||
auto_hook_style: data.autoHook ? (data.autoHookStyle || 'pill') : null,
|
||||
// 'auto' is the server default, so only a deliberate choice travels.
|
||||
layouts: data.layout && data.layout !== 'auto' ? data.layout : null,
|
||||
// Channel profile slug (channels/<slug>.json). Absent = no profile, so
|
||||
// the default request stays byte-identical to the pre-feature one.
|
||||
channel: data.channel || null,
|
||||
};
|
||||
|
||||
if (data.type === 'url') {
|
||||
|
|
|
|||
331
dashboard/src/components/BridgeModal.jsx
Normal file
331
dashboard/src/components/BridgeModal.jsx
Normal file
|
|
@ -0,0 +1,331 @@
|
|||
import React, { useState, useEffect } from 'react';
|
||||
import { Copy, Check, CheckCircle2, AlertCircle, Loader2, Link2, Youtube, MessageSquare } from 'lucide-react';
|
||||
import Modal from './ui/Modal';
|
||||
import { apiFetch } from '../lib/api';
|
||||
|
||||
// Shorts -> long-form bridge (PLAN #6). The related-video link and comment
|
||||
// pinning are Studio-UI only, so this panel always carries the manual steps:
|
||||
// it never pretends the server can set them.
|
||||
//
|
||||
// Copy it? Use the copy buttons. Post the first comment automatically? Only
|
||||
// when you click it, and only on a server with the YouTube Data API wired up.
|
||||
|
||||
// Accept a full YouTube URL or a bare id and return just the id. The published
|
||||
// Short's id is what the comment endpoint needs; people usually have the URL.
|
||||
function videoIdFrom(raw) {
|
||||
const value = String(raw || '').trim();
|
||||
if (!value) return '';
|
||||
const urlMatch = value.match(/(?:v=|\/shorts\/|youtu\.be\/|\/embed\/)([A-Za-z0-9_-]{6,})/);
|
||||
if (urlMatch) return urlMatch[1];
|
||||
const bare = value.match(/^([A-Za-z0-9_-]{6,})$/);
|
||||
return bare ? bare[1] : value;
|
||||
}
|
||||
|
||||
export default function BridgeModal({ isOpen, onClose, jobId, clipIndex }) {
|
||||
const [data, setData] = useState(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState(null);
|
||||
const [copied, setCopied] = useState(null);
|
||||
|
||||
// Checked-off Studio steps, remembered per clip so closing the sheet while
|
||||
// working through the manual steps doesn't lose your place.
|
||||
const storageKey = `cw_bridge_check_${jobId}_${clipIndex}`;
|
||||
const [checkedSteps, setCheckedSteps] = useState({});
|
||||
|
||||
const [videoId, setVideoId] = useState('');
|
||||
const [posting, setPosting] = useState(false);
|
||||
const [postStatus, setPostStatus] = useState(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen) return undefined;
|
||||
let cancelled = false;
|
||||
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
setData(null);
|
||||
setPostStatus(null);
|
||||
setVideoId('');
|
||||
try {
|
||||
setCheckedSteps(JSON.parse(localStorage.getItem(storageKey)) || {});
|
||||
} catch {
|
||||
setCheckedSteps({});
|
||||
}
|
||||
|
||||
apiFetch(`/api/clip/${jobId}/${clipIndex}/bridge`)
|
||||
.then(async (res) => {
|
||||
if (!res.ok) {
|
||||
let detail = '';
|
||||
const text = await res.text().catch(() => '');
|
||||
try {
|
||||
const j = JSON.parse(text);
|
||||
if (typeof j.detail === 'string') detail = j.detail;
|
||||
} catch { /* keep the raw body */ }
|
||||
throw new Error(detail || `Could not load the bridge (${res.status}).`);
|
||||
}
|
||||
return res.json();
|
||||
})
|
||||
.then((payload) => { if (!cancelled) setData(payload); })
|
||||
.catch((e) => { if (!cancelled) setError(e.message || 'Could not load the bridge.'); })
|
||||
.finally(() => { if (!cancelled) setLoading(false); });
|
||||
|
||||
return () => { cancelled = true; };
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [isOpen, jobId, clipIndex]);
|
||||
|
||||
const handleCopy = async (field, text) => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text || '');
|
||||
setCopied(field);
|
||||
setTimeout(() => setCopied(null), 2000);
|
||||
} catch {
|
||||
// clipboard unavailable — silent
|
||||
}
|
||||
};
|
||||
|
||||
const toggleStep = (i) => {
|
||||
setCheckedSteps((prev) => {
|
||||
const next = { ...prev, [i]: !prev[i] };
|
||||
try { localStorage.setItem(storageKey, JSON.stringify(next)); } catch { /* storage unavailable */ }
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const handlePostComment = async () => {
|
||||
const vid = videoIdFrom(videoId);
|
||||
if (!vid) return;
|
||||
setPosting(true);
|
||||
setPostStatus(null);
|
||||
try {
|
||||
const res = await apiFetch(`/api/clip/${jobId}/${clipIndex}/bridge/comment`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ video_id: vid, text: data?.first_comment || undefined }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
let detail = '';
|
||||
const text = await res.text().catch(() => '');
|
||||
try {
|
||||
const j = JSON.parse(text);
|
||||
if (typeof j.detail === 'string') detail = j.detail;
|
||||
} catch { /* keep the raw body */ }
|
||||
// A 400 here almost always means the YouTube integration is not
|
||||
// configured; say that plainly and point at the manual route.
|
||||
const fallback = res.status === 400
|
||||
? "This server can't post comments yet — the YouTube Data API isn't set up. Copy the comment above and post it in Studio instead."
|
||||
: `Could not post the comment (${res.status}).`;
|
||||
setPostStatus({ ok: false, msg: detail || fallback });
|
||||
return;
|
||||
}
|
||||
await res.json().catch(() => ({}));
|
||||
setPostStatus({ ok: true, msg: 'Comment posted. Open YouTube Studio and pin it — pinning stays manual.' });
|
||||
} catch (e) {
|
||||
setPostStatus({ ok: false, msg: e.message || 'Could not post the comment.' });
|
||||
} finally {
|
||||
setPosting(false);
|
||||
}
|
||||
};
|
||||
|
||||
// The endpoint reports whether comment posting is available on this server.
|
||||
// An older/absent field is treated as "try it" — a 400 is handled above.
|
||||
const configured = data ? data.comment_api_configured !== false : true;
|
||||
const canPostComment = configured && !!videoId.trim() && !!data?.first_comment;
|
||||
|
||||
return (
|
||||
<Modal
|
||||
isOpen={isOpen}
|
||||
onClose={onClose}
|
||||
eyebrow="YOUTUBE · BRIDGE"
|
||||
title="shorts → long-form"
|
||||
size="lg"
|
||||
>
|
||||
{loading && (
|
||||
<div className="flex items-center justify-center gap-2 py-10 text-sm text-muted lowercase">
|
||||
<Loader2 size={16} className="animate-spin text-brass" /> loading bridge…
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!loading && error && (
|
||||
<div className="px-3 py-2 rounded-input text-xs text-danger bg-[color-mix(in_oklab,var(--color-danger)_10%,transparent)] flex items-start gap-2">
|
||||
<AlertCircle size={14} className="mt-0.5 shrink-0" />
|
||||
<span className="break-words">{error}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!loading && !error && data && (
|
||||
<div>
|
||||
<p className="text-xs text-muted leading-snug mb-5">
|
||||
Funnel viewers of this Short to a long-form video. The related-video link and the comment pin live only in YouTube Studio, so those steps stay manual.
|
||||
</p>
|
||||
|
||||
{/* Related-video target */}
|
||||
<section className="mb-5">
|
||||
<label className="eyebrow block mb-1.5">RELATED VIDEO TARGET</label>
|
||||
{data.related_video_url ? (
|
||||
<div className="flex items-center gap-2 bg-paper rounded-input border border-rule px-3 py-2 min-w-0">
|
||||
<Youtube size={14} className="text-muted shrink-0" />
|
||||
<a
|
||||
href={data.related_video_url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-xs text-ink2 truncate flex-1 min-w-0 hover:text-brass transition-colors"
|
||||
>
|
||||
{data.related_video_url}
|
||||
</a>
|
||||
<button
|
||||
onClick={() => handleCopy('target', data.related_video_url)}
|
||||
aria-label="copy related video url"
|
||||
className="p-1 rounded-full text-muted hover:text-brass transition-colors shrink-0"
|
||||
>
|
||||
{copied === 'target' ? <Check size={14} className="text-ok" /> : <Copy size={14} />}
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="px-3 py-2 rounded-input text-xs text-warn bg-[color-mix(in_oklab,var(--color-warn)_10%,transparent)] flex items-start gap-2">
|
||||
<AlertCircle size={14} className="mt-0.5 shrink-0" />
|
||||
<span>
|
||||
No related video set for this clip yet. Paste the long-form URL into YouTube Studio's
|
||||
{' '}<b className="font-medium">Related video</b> field when you set it up — the checklist below has the steps.
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
{/* Manual Studio checklist */}
|
||||
<section className="mb-5">
|
||||
<div className="flex items-center justify-between gap-2 mb-2">
|
||||
<label className="eyebrow">STUDIO CHECKLIST</label>
|
||||
<span className="readout">manual · no api</span>
|
||||
</div>
|
||||
{Array.isArray(data.checklist) && data.checklist.length > 0 ? (
|
||||
<ol className="space-y-1.5">
|
||||
{data.checklist.map((step, i) => {
|
||||
const done = !!checkedSteps[i];
|
||||
return (
|
||||
<li key={i}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => toggleStep(i)}
|
||||
aria-pressed={done}
|
||||
className={`w-full text-left flex items-start gap-2.5 px-3 py-2 rounded-input border transition-colors ${done ? 'border-rule bg-paper opacity-70' : 'border-rule hover:bg-paper3'}`}
|
||||
>
|
||||
{done
|
||||
? <CheckCircle2 size={15} className="text-ok mt-0.5 shrink-0" />
|
||||
: <span className="mt-0.5 w-[15px] h-[15px] rounded-full border border-rule2 shrink-0" aria-hidden="true" />}
|
||||
<span className={`text-xs leading-snug ${done ? 'text-muted' : 'text-ink2'}`}>{step}</span>
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ol>
|
||||
) : (
|
||||
<p className="text-xs text-muted lowercase">no checklist saved for this clip.</p>
|
||||
)}
|
||||
</section>
|
||||
|
||||
{/* Copy-paste copy */}
|
||||
<section className="mb-5">
|
||||
<div className="flex items-center justify-between gap-2 mb-1.5">
|
||||
<label className="eyebrow">DESCRIPTION BRIDGE</label>
|
||||
<button
|
||||
onClick={() => handleCopy('desc', data.description_bridge)}
|
||||
aria-label="copy description bridge"
|
||||
className="p-1 rounded-full text-muted hover:text-brass transition-colors shrink-0"
|
||||
>
|
||||
{copied === 'desc' ? <Check size={14} className="text-ok" /> : <Copy size={14} />}
|
||||
</button>
|
||||
</div>
|
||||
{data.description_bridge ? (
|
||||
<p className="text-xs text-ink2 select-all break-words whitespace-pre-wrap bg-paper rounded-input p-3 border border-rule max-h-40 overflow-y-auto custom-scrollbar">
|
||||
{data.description_bridge}
|
||||
</p>
|
||||
) : (
|
||||
<p className="text-xs text-muted lowercase bg-paper rounded-input p-3 border border-dashed border-rule">
|
||||
no description copy generated for this clip.
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section className="mb-5">
|
||||
<div className="flex items-center justify-between gap-2 mb-1.5">
|
||||
<label className="eyebrow">FIRST COMMENT</label>
|
||||
<button
|
||||
onClick={() => handleCopy('comment', data.first_comment)}
|
||||
aria-label="copy first comment"
|
||||
className="p-1 rounded-full text-muted hover:text-brass transition-colors shrink-0"
|
||||
>
|
||||
{copied === 'comment' ? <Check size={14} className="text-ok" /> : <Copy size={14} />}
|
||||
</button>
|
||||
</div>
|
||||
{data.first_comment ? (
|
||||
<p className="text-xs text-ink2 select-all break-words whitespace-pre-wrap bg-paper rounded-input p-3 border border-rule">
|
||||
{data.first_comment}
|
||||
</p>
|
||||
) : (
|
||||
<p className="text-xs text-muted lowercase bg-paper rounded-input p-3 border border-dashed border-rule">
|
||||
no first comment generated for this clip.
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
|
||||
{/* Optional opt-in comment posting */}
|
||||
<section className="border-t border-rule pt-4">
|
||||
<div className="flex items-center gap-2 mb-1.5">
|
||||
<label className="eyebrow">POST FIRST COMMENT</label>
|
||||
<span className="badge-ok">opt-in</span>
|
||||
</div>
|
||||
<p className="text-xs text-muted leading-snug mb-3">
|
||||
Optional. clipwright never posts on its own — this runs only when you click the button. Pinning the comment still has to be done by hand in Studio.
|
||||
</p>
|
||||
|
||||
{!configured ? (
|
||||
<div className="px-3 py-2 rounded-input text-xs text-warn bg-[color-mix(in_oklab,var(--color-warn)_10%,transparent)] flex items-start gap-2">
|
||||
<AlertCircle size={14} className="mt-0.5 shrink-0" />
|
||||
<span>
|
||||
This server has no YouTube Data API credentials, so it can't post for you. Copy the comment above and post it in Studio instead.
|
||||
</span>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
<div className="flex flex-col sm:flex-row gap-2">
|
||||
<input
|
||||
type="text"
|
||||
value={videoId}
|
||||
onChange={(e) => setVideoId(e.target.value)}
|
||||
className="input-field sm:flex-1"
|
||||
placeholder="published Short video id or URL"
|
||||
aria-label="published Short video id or URL"
|
||||
/>
|
||||
<button
|
||||
onClick={handlePostComment}
|
||||
disabled={posting || !canPostComment}
|
||||
className="btn-primary shrink-0"
|
||||
title={!data.first_comment ? 'No comment text to post' : (videoId.trim() ? undefined : 'Enter the published Short id first')}
|
||||
>
|
||||
{posting
|
||||
? <><Loader2 size={15} className="animate-spin" /> posting…</>
|
||||
: <><MessageSquare size={15} /> post comment</>}
|
||||
</button>
|
||||
</div>
|
||||
{postStatus && (
|
||||
<div className={`px-3 py-2 rounded-input text-xs flex items-start gap-2 ${postStatus.ok
|
||||
? 'text-ok bg-[color-mix(in_oklab,var(--color-ok)_10%,transparent)]'
|
||||
: 'text-danger bg-[color-mix(in_oklab,var(--color-danger)_10%,transparent)]'}`}
|
||||
>
|
||||
{postStatus.ok
|
||||
? <Check size={14} className="mt-0.5 shrink-0" />
|
||||
: <AlertCircle size={14} className="mt-0.5 shrink-0" />}
|
||||
<span className="break-words">{postStatus.msg}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<p className="readout mt-3 flex items-center gap-1.5">
|
||||
<Link2 size={12} className="shrink-0" /> related-video link + pin: Studio only
|
||||
</p>
|
||||
</section>
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
|
@ -61,6 +61,13 @@ export default function MediaInput({ onProcess, isProcessing }) {
|
|||
const [layout, setLayout] = useState(() => {
|
||||
try { return localStorage.getItem('cw_layout') || 'auto'; } catch { return 'auto'; }
|
||||
});
|
||||
// Channel profile (channels/<slug>.json on the server): tunes how the AI
|
||||
// writes titles, hooks and the description, and how it art-directs the
|
||||
// thumbnail. Per job and off by default, so nothing changes for anyone who
|
||||
// does not use profiles. Fetched from GET /api/channels; when that list is
|
||||
// empty or unreachable the selector simply does not render.
|
||||
const [channels, setChannels] = useState([]);
|
||||
const [channel, setChannel] = useState('none');
|
||||
const infoRef = useRef(null);
|
||||
|
||||
// Close the compatibility popover on any outside click.
|
||||
|
|
@ -99,6 +106,22 @@ export default function MediaInput({ onProcess, isProcessing }) {
|
|||
.catch(() => {});
|
||||
}, []);
|
||||
|
||||
// Channel profiles available on this install. A missing route, an empty
|
||||
// directory or a network error all leave the list empty, which keeps the
|
||||
// selector hidden — profiles are opt-in and never block a job.
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
fetch(getApiUrl('/api/channels'))
|
||||
.then((r) => (r.ok ? r.json() : null))
|
||||
.then((data) => {
|
||||
if (cancelled || !data) return;
|
||||
const list = Array.isArray(data.channels) ? data.channels : [];
|
||||
setChannels(list.filter((c) => c && c.slug));
|
||||
})
|
||||
.catch(() => {});
|
||||
return () => { cancelled = true; };
|
||||
}, []);
|
||||
|
||||
// A link pasted in the landing hero: preload it here so the user picks up
|
||||
// where they left off. Not auto-submitted — the rights attestation below
|
||||
// has to be ticked by the user.
|
||||
|
|
@ -124,6 +147,9 @@ export default function MediaInput({ onProcess, isProcessing }) {
|
|||
autoHook,
|
||||
autoHookStyle,
|
||||
layout,
|
||||
// 'none' = no profile; only a real slug travels, so the default
|
||||
// request stays byte-identical to the pre-feature one.
|
||||
channel: channel === 'none' ? null : channel,
|
||||
};
|
||||
try {
|
||||
localStorage.setItem('cw_auto_hook', autoHook ? '1' : '0');
|
||||
|
|
@ -291,6 +317,32 @@ export default function MediaInput({ onProcess, isProcessing }) {
|
|||
</div>
|
||||
</div>
|
||||
|
||||
{/* Channel profile — only rendered when the install has profiles,
|
||||
so an empty list or a failed fetch leaves no trace. Tunes the
|
||||
packaging the AI writes for a job: title, hook, description
|
||||
and thumbnail. Defaults to no profile. */}
|
||||
{channels.length > 0 && (
|
||||
<div className="mt-5" data-tutorial="channel-profile">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<p className="eyebrow">channel profile</p>
|
||||
<select
|
||||
value={channel}
|
||||
onChange={(e) => setChannel(e.target.value)}
|
||||
className="input-field !w-auto text-xs py-1.5"
|
||||
aria-label="channel profile"
|
||||
>
|
||||
<option value="none">None (generic)</option>
|
||||
{channels.map((ch) => (
|
||||
<option key={ch.slug} value={ch.slug}>{ch.name || ch.slug}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<p className="text-[11px] leading-relaxed text-muted mt-1.5">
|
||||
Tailors titles, hooks, description and thumbnail for that channel.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Advanced generation controls — collapsed by default; blank = AI decides */}
|
||||
<div className="mt-4">
|
||||
<button
|
||||
|
|
@ -353,6 +405,7 @@ export default function MediaInput({ onProcess, isProcessing }) {
|
|||
<option value="auto">Auto (AI picks per video)</option>
|
||||
<option value="split">Two speakers stacked</option>
|
||||
<option value="screencast">Screen over presenter</option>
|
||||
<option value="code">Code / terminal (zoom to text)</option>
|
||||
<option value="none">Single crop only</option>
|
||||
</select>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import { getApiUrl } from '../config';
|
|||
import { apiFetch } from '../lib/api';
|
||||
import SubtitleModal from './SubtitleModal';
|
||||
import HookModal from './HookModal';
|
||||
import BridgeModal from './BridgeModal';
|
||||
import Modal from './ui/Modal';
|
||||
import { renderInBrowser } from '../lib/renderInBrowser';
|
||||
|
||||
|
|
@ -214,6 +215,7 @@ export default function ResultCard({ clip, index, jobId, postizKey, postizUrl, g
|
|||
const [isSubtitling, setIsSubtitling] = useState(false);
|
||||
const [isHooking, setIsHooking] = useState(false);
|
||||
const [showHookModal, setShowHookModal] = useState(false);
|
||||
const [showBridgeModal, setShowBridgeModal] = useState(false);
|
||||
const [editError, setEditError] = useState(null);
|
||||
|
||||
const [clipDuration, setClipDuration] = useState(() => {
|
||||
|
|
@ -924,6 +926,15 @@ export default function ResultCard({ clip, index, jobId, postizKey, postizUrl, g
|
|||
{isHooking ? 'saving…' : 'edit hook'}
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => setShowBridgeModal(true)}
|
||||
className={QUIET_BTN}
|
||||
title="Shorts → long-form bridge: related video, first comment, Studio checklist"
|
||||
>
|
||||
<Link2 size={16} className="text-muted group-hover:text-brass transition-colors shrink-0" />
|
||||
bridge
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => setShowModal(true)}
|
||||
className="btn-primary flex-col gap-1 py-2.5 sm:py-2 px-1 text-[11px] leading-none rounded-input whitespace-nowrap"
|
||||
|
|
@ -1176,6 +1187,13 @@ export default function ResultCard({ clip, index, jobId, postizKey, postizUrl, g
|
|||
onRemove={burnedHook ? handleRemoveHook : null}
|
||||
/>
|
||||
|
||||
<BridgeModal
|
||||
isOpen={showBridgeModal}
|
||||
onClose={() => setShowBridgeModal(false)}
|
||||
jobId={jobId}
|
||||
clipIndex={index}
|
||||
/>
|
||||
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
101
tests/test_bridge.py
Normal file
101
tests/test_bridge.py
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
"""Shorts -> long-form bridge copy (PLAN #6): pure, deterministic generation.
|
||||
|
||||
The bridge is derived from the active profile (+ its ``published_video_history``)
|
||||
and the clip, with an optional explicit target. No LLM, no network: the same
|
||||
inputs must always yield the same copy.
|
||||
"""
|
||||
import pytest
|
||||
|
||||
from clipwright.pipeline import bridge, profiles
|
||||
|
||||
TARGET = "https://www.youtube.com/watch?v=LONGFORM123"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def cseea():
|
||||
return profiles.load_profile("cseea")
|
||||
|
||||
|
||||
def _clip():
|
||||
return {"video_title_for_youtube_short": "I broke the world",
|
||||
"viral_hook_text": "I broke the world in one block"}
|
||||
|
||||
|
||||
def test_explicit_target_reaches_every_field(cseea):
|
||||
result = bridge.build_bridge(cseea, clip=_clip(), related_video_url=TARGET)
|
||||
assert result["related_video_url"] == TARGET
|
||||
assert TARGET in result["description_bridge"]
|
||||
assert TARGET in result["first_comment"]
|
||||
assert any(TARGET in step for step in result["checklist"])
|
||||
assert result["manual_pin_required"] is True
|
||||
|
||||
|
||||
def test_checklist_names_the_manual_studio_steps(cseea):
|
||||
result = bridge.build_bridge(cseea, clip=_clip(), related_video_url=TARGET)
|
||||
joined = "\n".join(result["checklist"])
|
||||
assert "Studio" in joined
|
||||
assert "Related video" in joined
|
||||
assert "Pin" in joined
|
||||
assert "no api" in joined.lower()
|
||||
|
||||
|
||||
def test_no_target_uses_profile_links_and_invents_no_url(cseea):
|
||||
result = bridge.build_bridge(cseea, clip=_clip(), related_video_url=None)
|
||||
assert result["related_video_url"] is None
|
||||
# The channel's own links still appear; no watch URL is fabricated.
|
||||
assert "youtube.com/@cseea" in result["description_bridge"]
|
||||
assert "youtube.com/@cseea" in result["first_comment"]
|
||||
assert "watch?v=" not in result["description_bridge"]
|
||||
# The checklist tells the operator to paste the target themselves.
|
||||
assert any("paste" in step.lower() for step in result["checklist"])
|
||||
|
||||
|
||||
def test_published_history_supplies_the_target_when_none_given():
|
||||
profile = profiles.Profile(
|
||||
slug="t",
|
||||
description_template="{hook}\n\nFull video: {link}",
|
||||
links=["https://example.com/channel"],
|
||||
published_video_history=[
|
||||
{"id": "OLD", "published_at": "2026-01-01"},
|
||||
{"id": "NEW", "published_at": "2026-06-01"},
|
||||
],
|
||||
)
|
||||
result = bridge.build_bridge(profile, clip=_clip())
|
||||
assert result["related_video_url"] == "https://www.youtube.com/watch?v=NEW"
|
||||
assert "watch?v=NEW" in result["first_comment"]
|
||||
|
||||
|
||||
def test_explicit_target_wins_over_history_and_url_field_preferred():
|
||||
profile = profiles.Profile(
|
||||
slug="t",
|
||||
published_video_history=[{"url": "https://youtu.be/HISTORY"}],
|
||||
)
|
||||
assert bridge.target_video(profile, TARGET) == TARGET
|
||||
assert bridge.target_video(profile) == "https://youtu.be/HISTORY"
|
||||
|
||||
|
||||
def test_profiles_produce_different_bridge_copy(cseea):
|
||||
pedro = profiles.load_profile("pedro")
|
||||
cseea_bridge = bridge.build_bridge(cseea, clip=_clip(), related_video_url=TARGET)
|
||||
pedro_bridge = bridge.build_bridge(pedro, clip=_clip(), related_video_url=TARGET)
|
||||
assert cseea_bridge["description_bridge"] != pedro_bridge["description_bridge"]
|
||||
assert "#minecraft" in cseea_bridge["description_bridge"]
|
||||
assert "Chapters and source" in pedro_bridge["description_bridge"]
|
||||
|
||||
|
||||
def test_no_profile_still_produces_usable_copy():
|
||||
result = bridge.build_bridge(None, clip=_clip(), related_video_url=TARGET)
|
||||
assert TARGET in result["first_comment"]
|
||||
assert TARGET in result["description_bridge"]
|
||||
assert result["checklist"] # never empty
|
||||
|
||||
|
||||
def test_bridge_fields_merge_into_clip_metadata(cseea):
|
||||
"""The exact merge ``main.py`` performs must land every bridge field."""
|
||||
clip = _clip()
|
||||
clip.update(bridge.build_bridge(cseea, clip=clip, related_video_url=TARGET))
|
||||
assert set(bridge.build_bridge(cseea, clip=clip).keys()) <= set(clip.keys())
|
||||
assert clip["related_video_url"] == TARGET
|
||||
assert isinstance(clip["checklist"], list)
|
||||
assert isinstance(clip["description_bridge"], str) and clip["description_bridge"]
|
||||
assert isinstance(clip["first_comment"], str) and clip["first_comment"]
|
||||
132
tests/test_bridge_endpoint.py
Normal file
132
tests/test_bridge_endpoint.py
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
"""Bridge copy + opt-in first-comment endpoints (PLAN #6).
|
||||
|
||||
Confirms the generated copy/checklist is exposed from clip metadata, that the
|
||||
comment endpoint is guarded when the YouTube Data API is unconfigured (clear
|
||||
error, no post), and that posting only happens when the caller opts in.
|
||||
"""
|
||||
import asyncio
|
||||
import json
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
app_module = pytest.importorskip("clipwright.api.app")
|
||||
from clipwright.integrations import youtube_data # noqa: E402
|
||||
|
||||
JOB_ID = "bridge-endpoint-test-job"
|
||||
TARGET = "https://www.youtube.com/watch?v=LONGFORM123"
|
||||
|
||||
CHECKLIST = [
|
||||
"Open YouTube Studio -> Content -> this Short -> Edit.",
|
||||
f"Details -> Related video: set it to {TARGET} (no API).",
|
||||
"Post the generated first comment.",
|
||||
"Pin the first comment (no API).",
|
||||
]
|
||||
|
||||
|
||||
def _request(method, path, json_body=None):
|
||||
async def _do():
|
||||
transport = httpx.ASGITransport(app=app_module.app)
|
||||
async with httpx.AsyncClient(transport=transport,
|
||||
base_url="http://testserver") as client:
|
||||
return await client.request(method, path, json=json_body)
|
||||
return asyncio.run(_do())
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def job(tmp_path, monkeypatch):
|
||||
out_root = tmp_path / "output"
|
||||
job_dir = out_root / JOB_ID
|
||||
job_dir.mkdir(parents=True)
|
||||
monkeypatch.setattr(app_module, "OUTPUT_DIR", str(out_root))
|
||||
|
||||
clip = {
|
||||
"start": 0.0, "end": 30.0,
|
||||
"video_title_for_youtube_short": "I broke the world",
|
||||
"video_url": f"/videos/{JOB_ID}/mytitle_clip_1.mp4",
|
||||
# The fields main.py merges into clip metadata before writing.
|
||||
"related_video_url": TARGET,
|
||||
"description_bridge": f"▶ Full video: {TARGET}",
|
||||
"first_comment": f"▶ Full video: {TARGET}",
|
||||
"checklist": CHECKLIST,
|
||||
"manual_pin_required": True,
|
||||
}
|
||||
meta = {"shorts": [clip], "transcript": {"language": "none", "segments": []},
|
||||
"source_video": "src.mp4", "output_format": "auto"}
|
||||
(job_dir / "mytitle_metadata.json").write_text(json.dumps(meta))
|
||||
|
||||
app_module.jobs[JOB_ID] = {
|
||||
"status": "completed", "logs": [],
|
||||
"result": {"clips": [dict(clip)]}, "user_id": None,
|
||||
}
|
||||
try:
|
||||
yield {"dir": job_dir, "meta_path": job_dir / "mytitle_metadata.json"}
|
||||
finally:
|
||||
app_module.jobs.pop(JOB_ID, None)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def unconfigured(monkeypatch):
|
||||
for name in (youtube_data.CLIENT_ID_ENV, youtube_data.CLIENT_SECRET_ENV,
|
||||
youtube_data.REFRESH_TOKEN_ENV):
|
||||
monkeypatch.delenv(name, raising=False)
|
||||
|
||||
|
||||
class TestBridgeCopyEndpoint:
|
||||
def test_returns_generated_copy_and_checklist(self, job, unconfigured):
|
||||
resp = _request("GET", f"/api/clip/{JOB_ID}/0/bridge")
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["related_video_url"] == TARGET
|
||||
assert TARGET in data["description_bridge"]
|
||||
assert TARGET in data["first_comment"]
|
||||
assert data["checklist"] == CHECKLIST
|
||||
assert data["manual_pin_required"] is True
|
||||
assert data["comment_api_configured"] is False
|
||||
|
||||
def test_unknown_clip_is_404(self, job, unconfigured):
|
||||
resp = _request("GET", f"/api/clip/{JOB_ID}/99/bridge")
|
||||
assert resp.status_code == 404
|
||||
|
||||
|
||||
class TestBridgeCommentEndpoint:
|
||||
def test_unconfigured_is_a_clear_400_and_posts_nothing(self, job, unconfigured,
|
||||
monkeypatch):
|
||||
calls = []
|
||||
monkeypatch.setattr(app_module.youtube_data, "post_first_comment",
|
||||
lambda *a, **k: calls.append((a, k)))
|
||||
resp = _request("POST", f"/api/clip/{JOB_ID}/0/bridge/comment",
|
||||
{"video_id": "short-1"})
|
||||
assert resp.status_code == 400
|
||||
assert "not configured" in resp.json()["detail"]
|
||||
assert calls == []
|
||||
|
||||
def test_configured_posts_the_first_comment(self, job, monkeypatch):
|
||||
monkeypatch.setenv(youtube_data.CLIENT_ID_ENV, "cid")
|
||||
monkeypatch.setenv(youtube_data.CLIENT_SECRET_ENV, "secret")
|
||||
monkeypatch.setenv(youtube_data.REFRESH_TOKEN_ENV, "refresh")
|
||||
calls = []
|
||||
|
||||
def fake_post(video_id, text):
|
||||
calls.append((video_id, text))
|
||||
return {"id": "comment-1"}
|
||||
|
||||
monkeypatch.setattr(app_module.youtube_data, "post_first_comment", fake_post)
|
||||
resp = _request("POST", f"/api/clip/{JOB_ID}/0/bridge/comment",
|
||||
{"video_id": "short-1"})
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["posted"] is True
|
||||
assert resp.json()["comment_id"] == "comment-1"
|
||||
assert resp.json()["manual_pin_required"] is True
|
||||
# The generated first_comment was used; posting is explicit, not auto.
|
||||
assert calls == [("short-1", f"▶ Full video: {TARGET}")]
|
||||
|
||||
def test_caller_can_override_the_comment_text(self, job, monkeypatch):
|
||||
monkeypatch.setenv(youtube_data.CLIENT_ID_ENV, "cid")
|
||||
monkeypatch.setenv(youtube_data.CLIENT_SECRET_ENV, "secret")
|
||||
monkeypatch.setenv(youtube_data.REFRESH_TOKEN_ENV, "refresh")
|
||||
monkeypatch.setattr(app_module.youtube_data, "post_first_comment",
|
||||
lambda video_id, text: {"id": "c"})
|
||||
resp = _request("POST", f"/api/clip/{JOB_ID}/0/bridge/comment",
|
||||
{"video_id": "short-1", "text": "custom"})
|
||||
assert resp.status_code == 200
|
||||
130
tests/test_youtube_data.py
Normal file
130
tests/test_youtube_data.py
Normal file
|
|
@ -0,0 +1,130 @@
|
|||
"""``integrations.youtube_data`` (PLAN #6): mocked HTTP, never live OAuth.
|
||||
|
||||
Every call goes through an ``httpx.Client`` built on a ``MockTransport``, so no
|
||||
network is touched. The unconfigured path must be a hard no-op: not one request.
|
||||
"""
|
||||
import json
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from clipwright.integrations import youtube_data
|
||||
|
||||
|
||||
def _configure(monkeypatch):
|
||||
monkeypatch.setenv(youtube_data.CLIENT_ID_ENV, "cid")
|
||||
monkeypatch.setenv(youtube_data.CLIENT_SECRET_ENV, "secret")
|
||||
monkeypatch.setenv(youtube_data.REFRESH_TOKEN_ENV, "refresh")
|
||||
monkeypatch.setenv(youtube_data.TOKEN_URI_ENV, "https://oauth.test/token")
|
||||
|
||||
|
||||
def _unconfigure(monkeypatch):
|
||||
for name in (youtube_data.CLIENT_ID_ENV, youtube_data.CLIENT_SECRET_ENV,
|
||||
youtube_data.REFRESH_TOKEN_ENV):
|
||||
monkeypatch.delenv(name, raising=False)
|
||||
|
||||
|
||||
class _Recorder:
|
||||
"""Records requests and answers the token + comment calls."""
|
||||
|
||||
def __init__(self, token_status=200, comment_status=200,
|
||||
comment_json=None):
|
||||
self.requests = []
|
||||
self.token_status = token_status
|
||||
self.comment_status = comment_status
|
||||
self.comment_json = comment_json or {
|
||||
"id": "comment-1",
|
||||
"snippet": {"videoId": "short-1"},
|
||||
}
|
||||
|
||||
def handler(self, request):
|
||||
self.requests.append(request)
|
||||
if request.url.path.endswith("/token"):
|
||||
return httpx.Response(self.token_status, json={"access_token": "tok"})
|
||||
return httpx.Response(self.comment_status, json=self.comment_json)
|
||||
|
||||
def client(self):
|
||||
return httpx.Client(transport=httpx.MockTransport(self.handler))
|
||||
|
||||
|
||||
def test_is_configured_tracks_env(monkeypatch):
|
||||
_unconfigure(monkeypatch)
|
||||
assert youtube_data.is_configured() is False
|
||||
_configure(monkeypatch)
|
||||
assert youtube_data.is_configured() is True
|
||||
|
||||
|
||||
def test_unconfigured_is_a_noop_and_makes_no_request(monkeypatch):
|
||||
_unconfigure(monkeypatch)
|
||||
recorder = _Recorder()
|
||||
with pytest.raises(youtube_data.YoutubeDataError) as exc:
|
||||
youtube_data.post_first_comment("short-1", "hello", client=recorder.client())
|
||||
assert exc.value.status_code == 400
|
||||
assert "not configured" in exc.value.detail
|
||||
assert recorder.requests == []
|
||||
|
||||
|
||||
def test_posts_first_comment_with_refresh_token(monkeypatch):
|
||||
_configure(monkeypatch)
|
||||
recorder = _Recorder()
|
||||
result = youtube_data.post_first_comment(
|
||||
"short-1", "watch the full video", client=recorder.client())
|
||||
|
||||
assert result["id"] == "comment-1"
|
||||
assert [r.method for r in recorder.requests] == ["POST", "POST"]
|
||||
token_req, comment_req = recorder.requests
|
||||
assert token_req.url == "https://oauth.test/token"
|
||||
assert b"grant_type=refresh_token" in token_req.content
|
||||
assert b"refresh_token=refresh" in token_req.content
|
||||
|
||||
assert comment_req.url.path.endswith("/commentThreads")
|
||||
assert comment_req.url.params["part"] == "snippet"
|
||||
assert comment_req.headers["authorization"] == "Bearer tok"
|
||||
body = json.loads(comment_req.content)
|
||||
assert body["snippet"]["videoId"] == "short-1"
|
||||
assert (body["snippet"]["topLevelComment"]["snippet"]["textOriginal"]
|
||||
== "watch the full video")
|
||||
|
||||
|
||||
def test_token_failure_is_reported_without_posting(monkeypatch):
|
||||
_configure(monkeypatch)
|
||||
recorder = _Recorder(token_status=401)
|
||||
with pytest.raises(youtube_data.YoutubeDataError) as exc:
|
||||
youtube_data.post_first_comment("short-1", "hi", client=recorder.client())
|
||||
assert exc.value.status_code == 502
|
||||
assert "token refresh failed" in exc.value.detail
|
||||
assert len(recorder.requests) == 1 # never reached commentThreads
|
||||
|
||||
|
||||
def test_comment_error_carries_status_and_truncated_body(monkeypatch):
|
||||
_configure(monkeypatch)
|
||||
recorder = _Recorder(comment_status=403)
|
||||
with pytest.raises(youtube_data.YoutubeDataError) as exc:
|
||||
youtube_data.post_first_comment("short-1", "hi", client=recorder.client())
|
||||
assert exc.value.status_code == 403
|
||||
assert "commentThreads.insert failed" in exc.value.detail
|
||||
|
||||
|
||||
def test_server_error_maps_to_502(monkeypatch):
|
||||
_configure(monkeypatch)
|
||||
recorder = _Recorder(comment_status=500)
|
||||
with pytest.raises(youtube_data.YoutubeDataError) as exc:
|
||||
youtube_data.post_first_comment("short-1", "hi", client=recorder.client())
|
||||
assert exc.value.status_code == 502
|
||||
|
||||
|
||||
def test_missing_inputs_are_refused(monkeypatch):
|
||||
_configure(monkeypatch)
|
||||
recorder = _Recorder()
|
||||
client = recorder.client()
|
||||
with pytest.raises(youtube_data.YoutubeDataError):
|
||||
youtube_data.post_first_comment("", "hi", client=client)
|
||||
with pytest.raises(youtube_data.YoutubeDataError):
|
||||
youtube_data.post_first_comment("short-1", " ", client=client)
|
||||
assert recorder.requests == []
|
||||
|
||||
|
||||
def test_scope_is_force_ssl():
|
||||
# commentThreads.insert requires force-ssl; documented so a refactor cannot
|
||||
# silently drop it.
|
||||
assert youtube_data.SCOPE == "https://www.googleapis.com/auth/youtube.force-ssl"
|
||||
Loading…
Reference in a new issue