dzen.nstarikov.ru/dzen-assistant/app/routes.py

857 lines
31 KiB
Python
Raw Normal View History

2026-06-27 14:07:10 +03:00
import asyncio
from datetime import datetime, timezone
from html import escape, unescape
from html.parser import HTMLParser
import os
from pathlib import Path
import random
import re
import subprocess
from uuid import uuid4
from fastapi import APIRouter, Body, Depends, File, HTTPException, Query, UploadFile, WebSocket, WebSocketDisconnect
from fastapi.responses import HTMLResponse, Response
from pydantic import BaseModel
from sqlalchemy import func, select
from sqlalchemy.orm import Session
from app.config import Settings, get_settings
from app.captions import strip_leading_duplicate_title
from app.database import SessionLocal, get_session
from app.models import Article, Frame, Source, Video
from app.quality import validate_article_content
from app.rss import article_url, build_feed_xml, render_article_html
from app.worker import process_video, scan_sources
router = APIRouter()
ZEN_VERIFICATION_FILE = "zen_y2a3098Zp7skRQXDYdkEOwOXFDdQsSzU7bkouMOhtBECx6zgC5CCqVZRxslhhjSg.html"
ZEN_VERIFICATION_FILE_LOWER = "zen_y2a3098zp7skrqxdydkeowoxfddqsszu7bkoumohtbecx6zgc5ccqvzrxslhhjsg.html"
ZEN_VERIFICATION_FILE_LEGACY = "zen_y2a3098Zp7skRQXDYdkEOwOXFDdQsSzU7bkouM0htBECx6zgC5CCqVZRxslhhjSg.html"
ZEN_VERIFICATION_META = (
'<meta name="zen-verification" '
'content="y2a3098Zp7skRQXDYdkEOwOXFDdQsSzU7bkouMOhtBECx6zgC5CCqVZRxslhhjSg" />'
)
class SourceIn(BaseModel):
name: str
url: str
source_type: str = "yt_dlp"
enabled: bool = True
class ChatIn(BaseModel):
message: str
class ArticleUpdateIn(BaseModel):
title: str
editableHtml: str
class ArticlePublishIn(BaseModel):
publishedAt: datetime | None = None
@router.get("/health")
def health() -> dict[str, str]:
return {"status": "ok"}
@router.get("/feed")
def feed(session: Session = Depends(get_session), settings: Settings = Depends(get_settings)) -> Response:
return Response(build_feed_xml(session, settings), media_type="application/rss+xml; charset=utf-8")
@router.head("/feed")
def feed_head(session: Session = Depends(get_session), settings: Settings = Depends(get_settings)) -> Response:
content = build_feed_xml(session, settings).encode("utf-8")
return Response(
headers={"Content-Length": str(len(content))},
media_type="application/rss+xml; charset=utf-8",
)
@router.get("/robots.txt")
def robots_txt(settings: Settings = Depends(get_settings)) -> Response:
content = f"""User-agent: *
Allow: /
Allow: /feed
Sitemap: {settings.public_base_url.rstrip("/")}/feed
"""
return Response(content, media_type="text/plain; charset=utf-8")
@router.head("/robots.txt")
def robots_txt_head(settings: Settings = Depends(get_settings)) -> Response:
content = f"""User-agent: *
Allow: /
Allow: /feed
Sitemap: {settings.public_base_url.rstrip("/")}/feed
""".encode("utf-8")
return Response(headers={"Content-Length": str(len(content))}, media_type="text/plain; charset=utf-8")
def plain_excerpt(html: str, limit: int = 260) -> str:
text = re.sub(r"<[^>]+>", " ", html)
text = re.sub(r"\s+", " ", unescape(text)).strip()
if len(text) <= limit:
return text
return text[:limit].rsplit(" ", 1)[0].strip() + "..."
class ArticleHtmlSanitizer(HTMLParser):
allowed_tags = {
"p",
"br",
"h2",
"h3",
"strong",
"b",
"em",
"i",
"u",
"s",
"ul",
"ol",
"li",
"blockquote",
"figure",
"figcaption",
"img",
"a",
}
void_tags = {"br", "img"}
allowed_attrs = {
"a": {"href", "title"},
"img": {"src", "alt"},
}
def __init__(self) -> None:
super().__init__(convert_charrefs=False)
self.parts: list[str] = []
self.skip_depth = 0
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
tag = tag.lower()
if tag in {"script", "style", "iframe", "object", "embed"}:
self.skip_depth += 1
return
if self.skip_depth or tag not in self.allowed_tags:
return
clean_attrs: list[str] = []
for name, value in attrs:
name = name.lower()
if value is None or name not in self.allowed_attrs.get(tag, set()):
continue
value = value.strip()
if name in {"href", "src"} and not re.match(r"^(https?://|/media/)", value, flags=re.I):
continue
clean_attrs.append(f'{name}="{escape(value, quote=True)}"')
attr_text = f" {' '.join(clean_attrs)}" if clean_attrs else ""
self.parts.append(f"<{tag}{attr_text}>")
def handle_endtag(self, tag: str) -> None:
tag = tag.lower()
if tag in {"script", "style", "iframe", "object", "embed"} and self.skip_depth:
self.skip_depth -= 1
return
if self.skip_depth or tag not in self.allowed_tags or tag in self.void_tags:
return
self.parts.append(f"</{tag}>")
def handle_data(self, data: str) -> None:
if not self.skip_depth:
self.parts.append(escape(data))
def handle_entityref(self, name: str) -> None:
if not self.skip_depth:
self.parts.append(f"&{name};")
def handle_charref(self, name: str) -> None:
if not self.skip_depth:
self.parts.append(f"&#{name};")
def sanitize_article_editor_html(html: str) -> str:
sanitizer = ArticleHtmlSanitizer()
sanitizer.feed(html)
sanitized = "".join(sanitizer.parts)
sanitized = re.sub(r"<p>\s*</p>", "", sanitized)
sanitized = re.sub(r"\n{3,}", "\n\n", sanitized).strip()
return sanitized
def editable_article_html(article: Article) -> str:
html = "\n".join(part for part in [article.lead, article.body_html] if part).strip()
return strip_leading_duplicate_title(html, article.title)
def split_lead_and_body(html: str) -> tuple[str, str]:
match = re.match(r"\s*(<p\b[^>]*>.*?</p>)(.*)\s*$", html, flags=re.I | re.S)
if not match:
return "", html.strip()
return match.group(1).strip(), match.group(2).strip()
def article_cover_url(session: Session, article: Article) -> str | None:
if article.video and article.video.thumbnail_url:
return article.video.thumbnail_url
if not article.video_id:
return None
frame = session.scalar(
select(Frame)
.where(Frame.video_id == article.video_id, Frame.selected == True) # noqa: E712
.order_by(Frame.score.desc(), Frame.id.asc())
.limit(1)
)
return frame.public_url if frame else None
def local_video_file(video: Video, settings: Settings) -> Path | None:
if video.local_video_path:
path = Path(video.local_video_path)
if path.exists():
return path
video_dir = settings.videos_path / str(video.id)
for candidate in sorted(video_dir.glob("video.*")):
if candidate.is_file():
return candidate
return None
def create_random_frame(video: Video, settings: Settings) -> tuple[Path, str, int]:
video_path = local_video_file(video, settings)
if not video_path:
raise HTTPException(status_code=422, detail="Локальный видеофайл еще не найден. Сначала обработайте ролик.")
duration = max(1, video.duration_seconds or 60)
start = 2 if duration > 6 else 0
end = max(start, duration - 2)
timestamp = random.randint(start, end)
target_dir = settings.media_path / "videos" / str(video.id) / "manual"
target_dir.mkdir(parents=True, exist_ok=True)
target = target_dir / f"frame-{timestamp}-{uuid4().hex[:8]}.webp"
command = [
"ffmpeg",
"-y",
"-ss",
str(timestamp),
"-i",
str(video_path),
"-frames:v",
"1",
"-vf",
"scale=1280:720:force_original_aspect_ratio=decrease,pad=1280:720:(ow-iw)/2:(oh-ih)/2",
"-c:v",
"libwebp",
"-quality",
"84",
str(target),
]
result = subprocess.run(command, text=True, capture_output=True)
if result.returncode or not target.exists():
detail = (result.stderr or result.stdout or "ffmpeg не смог создать кадр").strip()
raise HTTPException(status_code=500, detail=detail[-1200:])
public_url = f"{settings.public_base_url.rstrip('/')}/media/videos/{video.id}/manual/{target.name}"
return target, public_url, timestamp
@router.get(f"/{ZEN_VERIFICATION_FILE}", response_class=HTMLResponse)
@router.get(f"/{ZEN_VERIFICATION_FILE_LOWER}", response_class=HTMLResponse)
@router.get(f"/{ZEN_VERIFICATION_FILE_LEGACY}", response_class=HTMLResponse)
def zen_verification() -> str:
return ZEN_VERIFICATION_META
@router.head(f"/{ZEN_VERIFICATION_FILE}")
@router.head(f"/{ZEN_VERIFICATION_FILE_LOWER}")
@router.head(f"/{ZEN_VERIFICATION_FILE_LEGACY}")
def zen_verification_head() -> Response:
return Response(media_type="text/html; charset=utf-8")
@router.get("/", response_class=HTMLResponse)
def home(
page: int = Query(1, ge=1),
session: Session = Depends(get_session),
settings: Settings = Depends(get_settings),
) -> str:
per_page = 12
total = session.scalar(select(func.count(Article.id)).where(Article.status == "published")) or 0
pages = max(1, (total + per_page - 1) // per_page)
current_page = min(page, pages)
articles = session.scalars(
select(Article)
.where(Article.status == "published")
.order_by(Article.published_at.desc(), Article.id.desc())
.offset((current_page - 1) * per_page)
.limit(per_page)
).all()
cards = []
for article in articles:
url = article_url(settings, article)
cover = article_cover_url(session, article)
image_html = (
f'<img src="{escape(cover)}" alt="{escape(article.title)}" class="h-full w-full object-cover">'
if cover
else '<div class="flex h-full w-full items-center justify-center bg-zinc-100 text-sm text-zinc-400">Без изображения</div>'
)
excerpt = plain_excerpt(render_article_html(article, include_video_embed=False))
cards.append(
f"""
<article class="overflow-hidden rounded-lg border border-zinc-200 bg-white shadow-sm transition hover:border-zinc-300 hover:shadow-md">
<a href="{escape(url)}" class="block aspect-video bg-zinc-100">{image_html}</a>
<div class="flex min-h-[220px] flex-col gap-4 p-5">
<div class="flex flex-col gap-2">
<a href="{escape(url)}" class="text-xl font-bold leading-snug tracking-normal text-zinc-950 hover:text-zinc-700">{escape(article.title)}</a>
<p class="text-sm leading-6 text-zinc-600">{escape(excerpt)}</p>
</div>
<a href="{escape(url)}" class="mt-auto inline-flex w-fit items-center rounded-md bg-zinc-950 px-4 py-2 text-sm font-medium text-white hover:bg-zinc-800">Читать полностью</a>
</div>
</article>""".strip()
)
previous_link = (
f'<a href="/?page={current_page - 1}" class="rounded-md border border-zinc-200 bg-white px-4 py-2 text-sm font-medium text-zinc-900 hover:bg-zinc-50">Назад</a>'
if current_page > 1
else '<span class="rounded-md border border-zinc-100 bg-zinc-100 px-4 py-2 text-sm font-medium text-zinc-400">Назад</span>'
)
next_link = (
f'<a href="/?page={current_page + 1}" class="rounded-md border border-zinc-200 bg-white px-4 py-2 text-sm font-medium text-zinc-900 hover:bg-zinc-50">Вперед</a>'
if current_page < pages
else '<span class="rounded-md border border-zinc-100 bg-zinc-100 px-4 py-2 text-sm font-medium text-zinc-400">Вперед</span>'
)
empty_state = ""
if not articles:
empty_state = '<div class="rounded-lg border border-zinc-200 bg-white p-8 text-center text-zinc-600">Опубликованных материалов пока нет.</div>'
return f"""<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
{ZEN_VERIFICATION_META}
<link rel="alternate" type="application/rss+xml" title="Николай Стариков" href="{escape(settings.public_base_url.rstrip())}/feed">
<title>Николай Стариков</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-zinc-50 text-zinc-950">
<main class="mx-auto flex w-full max-w-[1180px] flex-col gap-8 px-4 py-8 sm:px-6 lg:px-8">
<header class="flex flex-col gap-3 border-b border-zinc-200 pb-6">
<p class="text-sm font-medium uppercase tracking-normal text-zinc-500">Лента материалов</p>
<div class="flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
<div class="flex max-w-3xl flex-col gap-3">
<h1 class="text-4xl font-bold leading-tight tracking-normal text-zinc-950 sm:text-5xl">Николай Стариков</h1>
<p class="text-lg leading-8 text-zinc-600">Публикации, подготовленные по выступлениям и видеоматериалам.</p>
</div>
<a href="/feed" class="inline-flex w-fit items-center rounded-md border border-zinc-200 bg-white px-4 py-2 text-sm font-medium text-zinc-900 hover:bg-zinc-50">RSS</a>
</div>
</header>
{empty_state}
<section class="grid grid-cols-1 gap-6 md:grid-cols-2 xl:grid-cols-3">
{chr(10).join(cards)}
</section>
<nav class="flex items-center justify-between border-t border-zinc-200 pt-6">
{previous_link}
<span class="text-sm text-zinc-500">Страница {current_page} из {pages}</span>
{next_link}
</nav>
</main>
</body>
</html>"""
@router.head("/")
def home_head() -> Response:
return Response(media_type="text/html; charset=utf-8")
@router.get("/posts/{slug}", response_class=HTMLResponse)
def post(slug: str, session: Session = Depends(get_session), settings: Settings = Depends(get_settings)) -> str:
article = session.scalar(select(Article).where(Article.slug == slug))
if not article or article.status != "published":
raise HTTPException(status_code=404, detail="Article not found")
title = escape(article.title)
return f"""<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="canonical" href="{article_url(settings, article)}">
<title>{title}</title>
<script src="https://cdn.tailwindcss.com"></script>
<style>
article :where(p) {{
margin-top: 1rem;
font-size: 1.125rem;
line-height: 1.8;
color: rgb(39 39 42);
}}
article :where(h2) {{
margin-top: 2.25rem;
font-size: 1.875rem;
line-height: 1.2;
font-weight: 700;
color: rgb(24 24 27);
}}
article :where(figure) {{
margin: 2rem 0;
}}
article :where(img) {{
width: 100%;
aspect-ratio: 16 / 9;
object-fit: cover;
border-radius: 0.5rem;
border: 1px solid rgb(228 228 231);
background: rgb(244 244 245);
}}
article :where(figcaption) {{
margin-top: 0.5rem;
font-size: 0.875rem;
line-height: 1.5;
color: rgb(113 113 122);
}}
article :where(.premium-cta) {{
margin-top: 2.5rem;
border-radius: 0.5rem;
border: 1px solid rgb(120 87 43);
background: rgb(9 9 11);
padding: 1.5rem;
color: rgb(250 250 250);
}}
article :where(.premium-cover) {{
margin: 0 0 1.5rem 0;
}}
article :where(.premium-cta h2) {{
margin-top: 0;
color: rgb(250 250 250);
}}
article :where(.premium-cta p) {{
color: rgb(228 228 231);
}}
article :where(.premium-cta a) {{
font-weight: 700;
color: rgb(251 191 36);
text-decoration: underline;
text-underline-offset: 3px;
}}
article :where(.cultural-initiatives) {{
margin-top: 2.5rem;
border-radius: 0.5rem;
border: 1px solid rgb(186 230 253);
background: rgb(240 249 255);
padding: 1.25rem;
}}
article :where(.cultural-initiatives p) {{
margin: 0.5rem 0;
color: rgb(12 74 110);
}}
article :where(.cultural-initiatives a) {{
font-weight: 700;
color: rgb(2 132 199);
text-decoration: underline;
text-underline-offset: 3px;
}}
article :where(.video-embed) {{
margin-top: 2.5rem;
border-top: 1px solid rgb(228 228 231);
padding-top: 2rem;
}}
article :where(.video-embed__frame) {{
margin-top: 1rem;
aspect-ratio: 16 / 9;
overflow: hidden;
border-radius: 0.5rem;
border: 1px solid rgb(228 228 231);
background: rgb(24 24 27);
}}
article :where(iframe) {{
width: 100%;
height: 100%;
display: block;
}}
</style>
</head>
<body class="bg-zinc-50 text-zinc-950">
<main class="mx-auto w-full max-w-[1024px] px-4 py-8 sm:px-6 lg:px-8">
<article class="rounded-lg border border-zinc-200 bg-white px-5 py-7 shadow-sm sm:px-8 lg:px-10">
<h1 class="text-3xl font-bold leading-tight tracking-normal text-zinc-950 sm:text-4xl">{title}</h1>
{render_article_html(article)}
</article>
</main>
</body>
</html>"""
@router.head("/posts/{slug}")
def post_head(slug: str, session: Session = Depends(get_session)) -> Response:
article = session.scalar(select(Article).where(Article.slug == slug))
if not article or article.status != "published":
raise HTTPException(status_code=404, detail="Article not found")
return Response(media_type="text/html; charset=utf-8")
@router.get("/api/dashboard")
def dashboard(session: Session = Depends(get_session)) -> dict:
now = datetime.now(timezone.utc)
return {
"sources": session.scalar(select(func.count(Source.id))),
"videos": session.scalar(select(func.count(Video.id)).where(Video.status != "ignored")),
"newVideos": session.scalar(select(func.count(Video.id)).where(Video.status == "new")),
"processingVideos": session.scalar(select(func.count(Video.id)).where(Video.status.in_(["queued", "processing"]))),
"drafts": session.scalar(select(func.count(Article.id)).where(Article.status == "draft")),
"scheduled": session.scalar(select(func.count(Article.id)).where(Article.status == "published", Article.published_at > now)),
"published": session.scalar(
select(func.count(Article.id)).where(
Article.status == "published",
Article.published_at.is_not(None),
Article.published_at <= now,
)
),
}
@router.get("/api/sources")
def list_sources(session: Session = Depends(get_session)) -> list[dict]:
sources = session.scalars(select(Source).order_by(Source.id.desc())).all()
return [
{
"id": source.id,
"name": source.name,
"url": source.url,
"sourceType": source.source_type,
"enabled": source.enabled,
"lastCheckedAt": source.last_checked_at,
}
for source in sources
]
@router.post("/api/sources")
def create_source(payload: SourceIn, session: Session = Depends(get_session)) -> dict:
source = Source(
name=payload.name,
url=payload.url,
source_type=payload.source_type,
enabled=payload.enabled,
)
session.add(source)
session.commit()
return {"id": source.id}
@router.post("/api/sources/scan")
def scan_all_sources() -> dict[str, str]:
task = scan_sources.delay()
return {"taskId": task.id}
@router.get("/api/videos")
def list_videos(session: Session = Depends(get_session)) -> list[dict]:
videos = session.scalars(
select(Video)
.where(Video.status != "ignored")
.order_by(func.coalesce(Video.published_at, Video.created_at).desc(), Video.id.desc())
.limit(200)
).all()
return [
{
"id": video.id,
"title": video.title,
"sourceUrl": video.source_url,
"status": video.status,
"progressPercent": video.progress_percent,
"progressStage": video.progress_stage,
"durationSeconds": video.duration_seconds,
"createdAt": video.created_at,
"publishedAt": video.published_at,
"errorMessage": video.error_message,
"articleIds": [article.id for article in video.articles if article.status != "rejected"],
"articles": [
{
"id": article.id,
"title": article.title,
"status": article.status,
}
for article in video.articles
if article.status != "rejected"
],
}
for video in videos
]
@router.post("/api/videos/{video_id}/process")
def process_video_route(video_id: int) -> dict[str, str]:
with SessionLocal() as session:
video = session.get(Video, video_id)
if not video:
raise HTTPException(status_code=404, detail="Video not found")
was_active = video.status in {"queued", "processing"}
video.status = "queued"
video.progress_percent = 1
video.progress_stage = "В очереди"
action = "задача перезапущена" if was_active else "задача поставлена в обработку"
video.progress_log = f"[{datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S')}] В очереди: {action}"
video.error_message = None
session.commit()
task = process_video.delay(video_id)
return {"taskId": task.id}
@router.delete("/api/videos/{video_id}")
def ignore_video(video_id: int, session: Session = Depends(get_session)) -> dict[str, int | str]:
video = session.get(Video, video_id)
if not video:
raise HTTPException(status_code=404, detail="Video not found")
video.status = "ignored"
video.progress_percent = 0
video.progress_stage = "Удалено"
video.error_message = None
video.progress_log = f"[{datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S')}] Удалено: ролик исключен из обработки и повторного импорта"
for article in video.articles:
if article.status != "published":
article.status = "rejected"
session.commit()
return {"id": video.id, "status": video.status}
def delete_source_video_file(video: Video | None) -> None:
if not video or not video.local_video_path:
return
path = Path(video.local_video_path)
if path.exists() and path.is_file():
path.unlink()
video.local_video_path = None
def video_log_payload(video: Video) -> dict[str, str | int | None]:
return {
"id": video.id,
"title": video.title,
"status": video.status,
"progressPercent": video.progress_percent,
"progressStage": video.progress_stage,
"progressLog": video.progress_log or "",
"errorMessage": video.error_message,
}
@router.get("/api/videos/{video_id}/logs")
def video_logs(video_id: int, session: Session = Depends(get_session)) -> dict[str, str | int | None]:
video = session.get(Video, video_id)
if not video:
raise HTTPException(status_code=404, detail="Video not found")
return video_log_payload(video)
@router.websocket("/api/videos/{video_id}/logs/ws")
async def video_logs_ws(websocket: WebSocket, video_id: int) -> None:
await websocket.accept()
last_payload: dict[str, str | int | None] | None = None
try:
while True:
with SessionLocal() as session:
video = session.get(Video, video_id)
if not video:
await websocket.send_json({"errorMessage": "Video not found", "status": "error"})
await websocket.close(code=1008)
return
payload = video_log_payload(video)
if payload != last_payload:
await websocket.send_json(payload)
last_payload = payload
await asyncio.sleep(1)
except WebSocketDisconnect:
return
@router.get("/api/articles")
def list_articles(
status: str | None = Query(default=None),
limit: int = Query(default=10, ge=1, le=50),
offset: int = Query(default=0, ge=0),
session: Session = Depends(get_session),
settings: Settings = Depends(get_settings),
) -> dict:
filters = [Article.status != "rejected"]
if status:
filters.append(Article.status == status)
total = session.scalar(select(func.count(Article.id)).where(*filters)) or 0
articles = session.scalars(
select(Article)
.where(*filters)
.order_by(func.coalesce(Article.published_at, Article.created_at).desc(), Article.id.desc())
.offset(offset)
.limit(limit)
).all()
items = [
{
"id": article.id,
"title": article.title,
"slug": article.slug,
"status": article.status,
"url": article_url(settings, article),
"createdAt": article.created_at,
"publishedAt": article.published_at,
}
for article in articles
]
return {"items": items, "total": total, "limit": limit, "offset": offset, "hasMore": offset + len(items) < total}
@router.get("/api/articles/{article_id}")
def get_article(article_id: int, session: Session = Depends(get_session), settings: Settings = Depends(get_settings)) -> dict:
article = session.get(Article, article_id)
if not article:
raise HTTPException(status_code=404, detail="Article not found")
return {
"id": article.id,
"title": article.title,
"slug": article.slug,
"status": article.status,
"videoId": article.video_id,
"url": article_url(settings, article),
"createdAt": article.created_at,
"publishedAt": article.published_at,
"contentHtml": render_article_html(article),
"editableHtml": editable_article_html(article),
}
@router.patch("/api/articles/{article_id}")
def update_article(article_id: int, payload: ArticleUpdateIn, session: Session = Depends(get_session), settings: Settings = Depends(get_settings)) -> dict:
article = session.get(Article, article_id)
if not article:
raise HTTPException(status_code=404, detail="Article not found")
title = payload.title.strip()
body = sanitize_article_editor_html(payload.editableHtml)
body = strip_leading_duplicate_title(body, title)
if not title:
raise HTTPException(status_code=422, detail="Title is required")
lead, body_html = split_lead_and_body(body)
try:
validate_article_content(title, lead, body_html)
except RuntimeError as exc:
raise HTTPException(status_code=422, detail=str(exc)) from exc
article.title = title
article.lead = lead
article.body_html = body_html
session.commit()
session.refresh(article)
return {
"id": article.id,
"title": article.title,
"slug": article.slug,
"status": article.status,
"videoId": article.video_id,
"url": article_url(settings, article),
"createdAt": article.created_at,
"publishedAt": article.published_at,
"contentHtml": render_article_html(article),
"editableHtml": editable_article_html(article),
}
@router.post("/api/articles/{article_id}/random-frame")
def random_article_frame(article_id: int, session: Session = Depends(get_session), settings: Settings = Depends(get_settings)) -> dict[str, str | int]:
article = session.get(Article, article_id)
if not article:
raise HTTPException(status_code=404, detail="Article not found")
if not article.video:
raise HTTPException(status_code=422, detail="У статьи нет исходного видео.")
path, public_url, timestamp = create_random_frame(article.video, settings)
frame = Frame(
video_id=article.video.id,
local_path=str(path),
public_url=public_url,
timestamp_seconds=timestamp,
score=1,
reason="Кадр выбран вручную редактором через случайную замену в админке.",
selected=False,
)
session.add(frame)
session.commit()
return {
"url": public_url,
"timestampSeconds": timestamp,
}
@router.delete("/api/articles/{article_id}")
def delete_article(article_id: int, session: Session = Depends(get_session)) -> dict[str, str | int]:
article = session.get(Article, article_id)
if not article:
raise HTTPException(status_code=404, detail="Article not found")
article.status = "rejected"
article.published_at = None
article.rss_guid = None
session.commit()
return {"id": article.id, "status": "deleted"}
@router.post("/api/uploads/images")
async def upload_image(file: UploadFile = File(...), settings: Settings = Depends(get_settings)) -> dict[str, str]:
if not file.content_type or not file.content_type.startswith("image/"):
raise HTTPException(status_code=422, detail="Only image files are supported")
suffix = Path(file.filename or "").suffix.lower()
if suffix not in {".jpg", ".jpeg", ".png", ".webp", ".gif"}:
suffix = ".jpg"
date_dir = datetime.now(timezone.utc).strftime("%Y%m%d")
upload_dir = settings.media_path / "uploads" / date_dir
upload_dir.mkdir(parents=True, exist_ok=True)
filename = f"{uuid4().hex}{suffix}"
target = upload_dir / filename
size = 0
with target.open("wb") as output:
while chunk := await file.read(1024 * 1024):
size += len(chunk)
if size > 12 * 1024 * 1024:
output.close()
target.unlink(missing_ok=True)
raise HTTPException(status_code=413, detail="Image is too large")
output.write(chunk)
os.chmod(target, 0o644)
return {"url": f"{settings.public_base_url.rstrip('/')}/media/uploads/{date_dir}/{filename}"}
@router.post("/api/articles/{article_id}/publish")
def publish_article(
article_id: int,
payload: ArticlePublishIn | None = Body(default=None),
session: Session = Depends(get_session),
settings: Settings = Depends(get_settings),
) -> dict:
article = session.get(Article, article_id)
if not article:
raise HTTPException(status_code=404, detail="Article not found")
try:
validate_article_content(article.title, article.lead, article.body_html)
except RuntimeError as exc:
raise HTTPException(status_code=422, detail=str(exc)) from exc
published_at = payload.publishedAt if payload and payload.publishedAt else datetime.now(timezone.utc)
if published_at.tzinfo is None:
published_at = published_at.replace(tzinfo=timezone.utc)
published_at = published_at.astimezone(timezone.utc)
article.status = "published"
article.published_at = published_at
article.rss_guid = f"{article_url(settings, article)}?rss_guid={int(published_at.timestamp())}-{article.id}"
delete_source_video_file(article.video)
session.commit()
return {"status": "published", "url": article_url(settings, article), "publishedAt": article.published_at}
@router.post("/api/chat")
def chat(payload: ChatIn) -> dict[str, str]:
text = payload.message.strip().lower()
if "скан" in text or "проверь" in text:
task = scan_sources.delay()
return {"message": f"Запустил проверку источников. Task: {task.id}"}
return {
"message": "Я пока MVP-ассистент: умею запускать проверку источников, показывать ролики, черновики и публиковать статьи в RSS.",
}