dzen.nstarikov.ru/app/routes.py
nstarikov e877de1d54
All checks were successful
Deploy Dzen assistant / deploy (push) Successful in 30s
Add VK iframe embed block to article editor
2026-09-16 12:00:26 +03:00

1517 lines
60 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import asyncio
from datetime import datetime, timezone
from html import escape, unescape
from html.parser import HTMLParser
import hashlib
import json
import os
from pathlib import Path
import random
import re
import shutil
import subprocess
import secrets
from typing import Any
from uuid import uuid4
from urllib.parse import urlparse
from fastapi import APIRouter, Body, Depends, File, HTTPException, Query, Request, UploadFile, WebSocket, WebSocketDisconnect
from fastapi.responses import HTMLResponse, RedirectResponse, Response
from pydantic import BaseModel
from sqlalchemy import func, select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from app.config import Settings, get_settings
from app.auth import (
authentication_options,
clear_session,
has_valid_session,
registration_options,
require_session,
session_cookie,
verify_vk_access_token,
verify_authentication,
verify_registration,
SESSION_COOKIE,
)
from app.captions import strip_leading_duplicate_title
from app.chapters import chapter_to_payload, parse_video_chapters
from app.database import SessionLocal, get_session
from app.models import AppSetting, Article, Frame, ImageGenerationBatch, ImageGenerationJob, PasskeyCredential, Source, Video
from app.image_generation import DEFAULT_API_URL, DEFAULT_MODEL, build_prompt, normalize_api_url
from app.quality import validate_article_content
from app.rss import VIDEO_PLACEHOLDER, article_url, build_feed_xml, render_article_html, split_audience_question_html
from app.worker import best_thumbnail_url, create_chapter_plan, generate_article_image, parse_upload_date, process_video, scan_sources, ytdlp_base_args
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" />'
)
PUBLIC_REDIRECT_URL = "https://nstarikov.ru"
ALLOWED_VIDEO_EXTENSIONS = {".mp4", ".webm", ".mov", ".mkv"}
MAX_VIDEO_UPLOAD_BYTES = 10 * 1024 * 1024 * 1024
VIDEO_UPLOAD_CHUNK_BYTES = 1024 * 1024
VIDEO_UPLOAD_LOG_INTERVAL_BYTES = 5 * 1024 * 1024
ARTICLE_SLUG_PATTERN = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$")
ARTICLE_SLUG_MAX_LENGTH = 240
def normalize_article_slug(value: str) -> str:
slug = value.strip().lower()
if not slug:
raise HTTPException(status_code=422, detail="Slug не может быть пустым.")
if len(slug) > ARTICLE_SLUG_MAX_LENGTH:
raise HTTPException(status_code=422, detail=f"Slug не может быть длиннее {ARTICLE_SLUG_MAX_LENGTH} символов.")
if not ARTICLE_SLUG_PATTERN.fullmatch(slug):
raise HTTPException(
status_code=422,
detail="Slug должен содержать только строчные латинские буквы, цифры и дефисы.",
)
return slug
def unique_article_slug(session: Session, value: str, article_id: int | None = None) -> str:
base = normalize_article_slug(value)
if not session.scalar(select(Article.id).where(Article.slug == base, Article.id != article_id)):
return base
for _ in range(10):
suffix = secrets.token_hex(3)
candidate = f"{base[: ARTICLE_SLUG_MAX_LENGTH - len(suffix) - 1].rstrip('-')}-{suffix}"
if not session.scalar(select(Article.id).where(Article.slug == candidate, Article.id != article_id)):
return candidate
raise HTTPException(status_code=409, detail="Не удалось подобрать уникальный slug.")
class SourceIn(BaseModel):
name: str
url: str
source_type: str = "yt_dlp"
enabled: bool = True
class ManualVideoIn(BaseModel):
url: str
class AuthCredentialIn(BaseModel):
challengeId: str
credential: dict[str, Any]
class VkAuthIn(BaseModel):
accessToken: str
class AppSettingsIn(BaseModel):
signatureHtml: str = ""
llmInstructions: str = ""
imageApiUrl: str | None = None
imageModel: str | None = None
imageApiToken: str | None = None
deleteImageApiToken: bool = False
class DraftCreateIn(BaseModel):
title: str
slug: str
lead: str = ""
bodyHtml: str = ""
featureImageUrl: str = ""
ctaHtml: str | None = None
class ChatIn(BaseModel):
message: str
class ArticleUpdateIn(BaseModel):
title: str
editableHtml: str
featureImageUrl: str | None = None
slug: str | None = None
class ArticlePublishIn(BaseModel):
publishedAt: datetime | None = None
class ImageGenerationIn(BaseModel):
mode: str
title: str
featureImageUrl: str | None = None
editorData: dict[str, Any]
snapshotId: str
targetBlockId: str | None = None
class VideoChapterIn(BaseModel):
id: str | None = None
title: str
startSeconds: int
endSeconds: int | None = None
class VideoProcessIn(BaseModel):
chapters: list[VideoChapterIn] | None = None
recreateDrafts: bool = False
@router.get("/health")
def health() -> dict[str, str]:
return {"status": "ok"}
SETTING_SIGNATURE = "article_signature_html"
SETTING_LLM_INSTRUCTIONS = "llm_instructions"
SETTING_IMAGE_API_URL = "image_api_url"
SETTING_IMAGE_MODEL = "image_model"
SETTING_IMAGE_API_TOKEN = "image_api_token"
SETTING_DRAFT_API_KEY_HASH = "draft_api_key_hash"
SETTING_DRAFT_API_KEY_PREFIX = "draft_api_key_prefix"
def app_settings_payload(session: Session) -> dict[str, Any]:
values = {
setting.key: setting.value
for setting in session.scalars(
select(AppSetting).where(AppSetting.key.in_([SETTING_SIGNATURE, SETTING_LLM_INSTRUCTIONS, SETTING_IMAGE_API_URL, SETTING_IMAGE_MODEL, SETTING_IMAGE_API_TOKEN, SETTING_DRAFT_API_KEY_PREFIX]))
).all()
}
return {
"signatureHtml": values.get(SETTING_SIGNATURE, ""),
"llmInstructions": values.get(SETTING_LLM_INSTRUCTIONS, ""),
"imageApiUrl": values.get(SETTING_IMAGE_API_URL, DEFAULT_API_URL),
"imageModel": values.get(SETTING_IMAGE_MODEL, DEFAULT_MODEL),
"imageApiTokenConfigured": bool(values.get(SETTING_IMAGE_API_TOKEN, "")),
"draftApiKeyConfigured": bool(values.get(SETTING_DRAFT_API_KEY_PREFIX, "")),
"draftApiKeyPrefix": values.get(SETTING_DRAFT_API_KEY_PREFIX, ""),
}
@router.get("/api/settings")
def get_app_settings(request: Request, session: Session = Depends(get_session)) -> dict[str, Any]:
require_session(request)
return app_settings_payload(session)
@router.get("/api/auth/status")
def auth_status(request: Request, session: Session = Depends(get_session)) -> dict[str, bool]:
return {
"authenticated": has_valid_session(request.cookies.get(SESSION_COOKIE)),
"hasPasskeys": session.scalar(select(func.count(PasskeyCredential.id))) > 0,
}
@router.post("/api/auth/register/options")
def passkey_registration_options(request: Request, session: Session = Depends(get_session), settings: Settings = Depends(get_settings)) -> dict:
# Passkeys can only be enrolled after the account has been authenticated via VK ID.
# The request object is intentionally checked in the verify endpoint as well.
require_session(request)
return registration_options(session, settings)
@router.post("/api/auth/register/verify")
def passkey_registration_verify(payload: AuthCredentialIn, request: Request, response: Response, session: Session = Depends(get_session), settings: Settings = Depends(get_settings)) -> dict[str, bool]:
require_session(request)
verify_registration(session, settings, payload.challengeId, payload.credential)
session_cookie(response, settings)
return {"authenticated": True}
@router.post("/api/auth/login/options")
def passkey_login_options(session: Session = Depends(get_session), settings: Settings = Depends(get_settings)) -> dict:
if session.scalar(select(func.count(PasskeyCredential.id))) == 0:
raise HTTPException(status_code=404, detail="Пока не зарегистрировано ни одного устройства.")
return authentication_options(session, settings)
@router.post("/api/auth/login/verify")
def passkey_login_verify(payload: AuthCredentialIn, response: Response, session: Session = Depends(get_session), settings: Settings = Depends(get_settings)) -> dict[str, bool]:
verify_authentication(session, settings, payload.challengeId, payload.credential)
session_cookie(response, settings)
return {"authenticated": True}
@router.post("/api/auth/vk")
async def vk_login(payload: VkAuthIn, response: Response, settings: Settings = Depends(get_settings)) -> dict[str, bool]:
await verify_vk_access_token(payload.accessToken, settings)
session_cookie(response, settings)
return {"authenticated": True}
@router.post("/api/auth/logout")
def passkey_logout(request: Request, response: Response) -> dict[str, bool]:
clear_session(response, request)
return {"authenticated": False}
@router.put("/api/settings")
def update_app_settings(payload: AppSettingsIn, request: Request, session: Session = Depends(get_session)) -> dict[str, Any]:
require_session(request)
token = (payload.imageApiToken or "").strip()
if payload.deleteImageApiToken and token:
raise HTTPException(status_code=422, detail="Нельзя одновременно заменить и удалить токен.")
try:
image_url = normalize_api_url(payload.imageApiUrl) if payload.imageApiUrl is not None else None
except ValueError as exc:
raise HTTPException(status_code=422, detail=str(exc)) from exc
image_model = payload.imageModel.strip() if payload.imageModel is not None else None
if image_model is not None and not image_model:
raise HTTPException(status_code=422, detail="Модель не может быть пустой.")
values = {
SETTING_SIGNATURE: payload.signatureHtml.strip(),
SETTING_LLM_INSTRUCTIONS: payload.llmInstructions.strip(),
}
if image_url is not None:
values[SETTING_IMAGE_API_URL] = image_url
if image_model is not None:
values[SETTING_IMAGE_MODEL] = image_model
if payload.deleteImageApiToken:
values[SETTING_IMAGE_API_TOKEN] = ""
elif token:
values[SETTING_IMAGE_API_TOKEN] = token
existing = {
setting.key: setting
for setting in session.scalars(select(AppSetting).where(AppSetting.key.in_(values))).all()
}
for key, value in values.items():
setting = existing.get(key)
if setting:
setting.value = value
else:
session.add(AppSetting(key=key, value=value))
session.commit()
return app_settings_payload(session)
def draft_api_key_hash(value: str) -> str:
return hashlib.sha256(value.encode("utf-8")).hexdigest()
def require_draft_api_key(request: Request, session: Session) -> None:
authorization = request.headers.get("authorization", "")
token = authorization[7:].strip() if authorization.lower().startswith("bearer ") else request.headers.get("x-dzen-api-key", "").strip()
configured_hash = session.scalar(select(AppSetting.value).where(AppSetting.key == SETTING_DRAFT_API_KEY_HASH)) or ""
if not token or not configured_hash or not secrets.compare_digest(draft_api_key_hash(token), configured_hash):
raise HTTPException(status_code=401, detail="Неверный API-ключ для создания черновиков.")
def draft_api_payload(session: Session, article: Article, settings: Settings) -> dict[str, Any]:
video = article.video
return {
"id": article.id,
"title": article.title,
"slug": article.slug,
"status": article.status,
"url": article_url(settings, article),
"featureImageUrl": article_cover_url(session, article),
"lead": article.lead,
"bodyHtml": article.body_html,
"ctaHtml": article.cta_html,
"contentHtml": render_article_html(article),
"editableHtml": editable_article_html(article),
"createdAt": article.created_at,
"publishedAt": article.published_at,
"video": {
"id": video.id,
"title": video.title,
"sourceUrl": video.source_url,
"durationSeconds": video.duration_seconds,
"publishedAt": video.published_at,
} if video else None,
}
@router.post("/api/settings/draft-api-key")
def generate_draft_api_key(request: Request, session: Session = Depends(get_session)) -> dict[str, str | bool]:
require_session(request)
api_key = f"dzen_draft_{secrets.token_urlsafe(32)}"
prefix = api_key[:20]
existing = {
setting.key: setting
for setting in session.scalars(
select(AppSetting).where(AppSetting.key.in_([SETTING_DRAFT_API_KEY_HASH, SETTING_DRAFT_API_KEY_PREFIX]))
).all()
}
for key, value in ((SETTING_DRAFT_API_KEY_HASH, draft_api_key_hash(api_key)), (SETTING_DRAFT_API_KEY_PREFIX, prefix)):
setting = existing.get(key)
if setting:
setting.value = value
else:
session.add(AppSetting(key=key, value=value))
session.commit()
return {"apiKey": api_key, "prefix": prefix, "configured": True}
@router.post("/api/v1/drafts", status_code=201)
def create_api_draft(
payload: DraftCreateIn,
request: Request,
session: Session = Depends(get_session),
settings: Settings = Depends(get_settings),
) -> dict[str, Any]:
require_draft_api_key(request, session)
title = payload.title.strip()
if not title:
raise HTTPException(status_code=422, detail="Поле title обязательно.")
slug = normalize_article_slug(payload.slug)
if session.scalar(select(Article.id).where(Article.slug == slug)):
raise HTTPException(status_code=409, detail="Slug уже используется.")
feature_image_url = payload.featureImageUrl.strip()
if feature_image_url and not re.match(r"^(https?://|/media/)", feature_image_url, flags=re.I):
raise HTTPException(status_code=422, detail="featureImageUrl должен быть HTTPS-адресом или локальным /media/ URL.")
body_html = strip_leading_duplicate_title(sanitize_article_editor_html(payload.bodyHtml), title)
lead_html = sanitize_article_editor_html(payload.lead)
signature_html = payload.ctaHtml if payload.ctaHtml is not None else session.scalar(
select(AppSetting.value).where(AppSetting.key == SETTING_SIGNATURE)
) or ""
article = Article(
slug=slug,
title=title,
lead=lead_html,
body_html=body_html,
cta_html=sanitize_article_editor_html(signature_html),
feature_image_url=feature_image_url,
status="draft",
)
session.add(article)
try:
session.commit()
except IntegrityError:
session.rollback()
if session.scalar(select(Article.id).where(Article.slug == slug)):
raise HTTPException(status_code=409, detail="Slug уже используется.")
raise
session.refresh(article)
return draft_api_payload(session, article, settings)
@router.get("/api/v1/drafts")
def list_api_drafts(
request: Request,
status: str = Query(default="draft"),
video_id: int | None = Query(default=None, alias="videoId"),
limit: int = Query(default=20, ge=1, le=100),
offset: int = Query(default=0, ge=0),
session: Session = Depends(get_session),
settings: Settings = Depends(get_settings),
) -> dict[str, Any]:
require_draft_api_key(request, session)
filters = [Article.status != "rejected"]
if status != "all":
filters.append(Article.status == status)
if video_id is not None:
filters.append(Article.video_id == video_id)
total = session.scalar(select(func.count(Article.id)).where(*filters)) or 0
articles = session.scalars(
select(Article)
.where(*filters)
.order_by(func.coalesce(Article.created_at, Article.published_at).desc(), Article.id.desc())
.offset(offset)
.limit(limit)
).all()
return {
"items": [draft_api_payload(session, article, settings) for article in articles],
"total": total,
"limit": limit,
"offset": offset,
"hasMore": offset + len(articles) < total,
}
@router.get("/api/v1/drafts/{article_id}")
def get_api_draft(
article_id: int,
request: Request,
session: Session = Depends(get_session),
settings: Settings = Depends(get_settings),
) -> dict[str, Any]:
require_draft_api_key(request, session)
article = session.get(Article, article_id)
if not article or article.status == "rejected":
raise HTTPException(status_code=404, detail="Черновик не найден.")
return draft_api_payload(session, article, settings)
@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",
"iframe",
}
void_tags = {"br", "img"}
allowed_attrs = {
"a": {"href", "title"},
"img": {"src", "alt"},
"p": {"class"},
"iframe": {"src", "title", "width", "height", "allow", "frameborder", "allowfullscreen"},
}
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", "object", "embed"}:
self.skip_depth += 1
return
if tag == "iframe":
src = next((value or "" for name, value in attrs if name.lower() == "src"), "").strip()
if not is_safe_vk_embed_url(src):
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 == "class":
if tag == "p" and "audience-question" in value.split():
clean_attrs.append('class="audience-question"')
continue
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 = strip_article_cover_html(sanitized)
sanitized = re.sub(r"<p>\s*</p>", "", sanitized)
sanitized = re.sub(r"\n{3,}", "\n\n", sanitized).strip()
return sanitized
def is_safe_vk_embed_url(value: str) -> bool:
try:
parsed = urlparse(value)
except ValueError:
return False
return (
parsed.scheme == "https"
and parsed.hostname in {"vkvideo.ru", "www.vkvideo.ru", "vk.com", "www.vk.com", "m.vk.com"}
and parsed.path == "/video_ext.php"
)
def strip_article_cover_html(html: str) -> str:
return re.sub(
r"<figure\b[^>]*class=[\"'][^\"']*\barticle-cover\b[^\"']*[\"'][^>]*>.*?</figure>",
"",
html or "",
flags=re.I | re.S,
).strip()
def editable_article_html(article: Article) -> str:
lead_html, lead_question_html = split_audience_question_html(article.lead)
body_html, audience_question_html = split_audience_question_html(article.body_html)
audience_question_html = audience_question_html or lead_question_html
if article.video_id and VIDEO_PLACEHOLDER not in body_html:
body_html = "\n".join(part for part in [body_html, f"<p>{VIDEO_PLACEHOLDER}</p>"] if part)
html = "\n".join(part for part in [lead_html, body_html, audience_question_html, article.cta_html] if part).strip()
html = strip_article_cover_html(html)
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.feature_image_url:
return article.feature_image_url
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 video_storage_payload(settings: Settings) -> dict[str, int]:
settings.videos_path.mkdir(parents=True, exist_ok=True)
usage = shutil.disk_usage(settings.videos_path)
used_percent = round(usage.used / usage.total * 100) if usage.total else 0
free_percent = round(usage.free / usage.total * 100) if usage.total else 0
return {
"totalBytes": usage.total,
"usedBytes": usage.used,
"freeBytes": usage.free,
"usedPercent": used_percent,
"freePercent": free_percent,
}
def uploaded_video_duration(path: Path) -> int:
command = [
"ffprobe",
"-v",
"error",
"-show_entries",
"format=duration",
"-of",
"default=noprint_wrappers=1:nokey=1",
str(path),
]
try:
result = subprocess.run(command, capture_output=True, text=True, timeout=30, check=False)
duration = float(result.stdout.strip()) if result.returncode == 0 else 0
except (OSError, subprocess.TimeoutExpired, ValueError):
duration = 0
if duration <= 0:
raise HTTPException(status_code=422, detail="Не удалось определить длительность видео через ffprobe.")
return round(duration)
def upload_log_line(stage: str, message: str) -> str:
now = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
return f"[{now}] {stage}: {message}"
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("/")
def home() -> RedirectResponse:
return RedirectResponse(url=PUBLIC_REDIRECT_URL, status_code=302)
@router.head("/")
def home_head() -> RedirectResponse:
return RedirectResponse(url=PUBLIC_REDIRECT_URL, status_code=302)
@router.get("/posts/{slug}")
def post(slug: str) -> RedirectResponse:
return RedirectResponse(url=PUBLIC_REDIRECT_URL, status_code=302)
@router.head("/posts/{slug}")
def post_head(slug: str) -> RedirectResponse:
return RedirectResponse(url=PUBLIC_REDIRECT_URL, status_code=302)
@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.post("/api/videos/import")
def import_video(payload: ManualVideoIn, session: Session = Depends(get_session)) -> dict[str, int | str | None]:
source_url = payload.url.strip()
if not source_url:
raise HTTPException(status_code=400, detail="Вставьте ссылку на видео.")
command = ytdlp_base_args() + [
"--no-playlist",
"--dump-single-json",
"--skip-download",
"--no-warnings",
source_url,
]
try:
result = subprocess.run(command, text=True, capture_output=True, timeout=90, check=False)
except subprocess.TimeoutExpired as exc:
raise HTTPException(status_code=422, detail="yt-dlp не успел проверить ссылку за 90 секунд.") from exc
if result.returncode != 0:
details = (result.stderr or result.stdout or "Не удалось разобрать ссылку через yt-dlp").strip()
raise HTTPException(status_code=422, detail=f"yt-dlp не смог проверить ссылку: {details[-1200:]}")
try:
metadata = json.loads(result.stdout)
except json.JSONDecodeError as exc:
raise HTTPException(status_code=422, detail="yt-dlp вернул некорректные метаданные для этой ссылки.") from exc
if not isinstance(metadata, dict) or metadata.get("_type") == "playlist":
raise HTTPException(status_code=422, detail="Нужна ссылка на отдельный ролик, а не на плейлист.")
external_id = str(metadata.get("id") or metadata.get("webpage_url") or source_url)
external_id = f"manual:{hashlib.sha256(external_id.encode('utf-8')).hexdigest()}"
existing = session.scalar(select(Video).where(Video.source_id.is_(None), Video.external_id == external_id))
if existing:
raise HTTPException(status_code=409, detail=f"Этот ролик уже добавлен: #{existing.id}")
# A manually imported video enters our queue now, regardless of its original age.
published_at = datetime.now(timezone.utc)
duration = metadata.get("duration")
try:
duration = round(float(duration)) if duration is not None else None
except (TypeError, ValueError):
duration = None
video = Video(
source_id=None,
external_id=external_id,
source_url=source_url,
thumbnail_url=best_thumbnail_url(metadata),
title=str(metadata.get("title") or metadata.get("fulltitle") or "Произвольный ролик"),
description=str(metadata.get("description") or ""),
duration_seconds=duration,
published_at=published_at,
status="new",
)
session.add(video)
session.commit()
session.refresh(video)
return {
"id": video.id,
"title": video.title,
"sourceUrl": video.source_url,
"durationSeconds": video.duration_seconds,
"status": video.status,
}
@router.get("/api/storage/videos")
def video_storage(settings: Settings = Depends(get_settings)) -> dict[str, int]:
return video_storage_payload(settings)
@router.post("/api/videos/upload")
async def upload_video(
file: UploadFile = File(...),
session: Session = Depends(get_session),
settings: Settings = Depends(get_settings),
) -> dict[str, int | str | None]:
filename = Path(file.filename or "").name
suffix = Path(filename).suffix.lower()
if suffix not in ALLOWED_VIDEO_EXTENSIONS:
raise HTTPException(status_code=422, detail="Поддерживаются только MP4, WebM, MOV и MKV.")
settings.videos_path.mkdir(parents=True, exist_ok=True)
if shutil.disk_usage(settings.videos_path).free <= 0:
raise HTTPException(status_code=507, detail="На диске для видео нет свободного места.")
external_id = f"upload:{uuid4().hex}"
title = Path(filename).stem.strip() or "Загруженный ролик"
video = Video(
source_id=None,
external_id=external_id,
source_url=f"upload://{external_id}",
title=title,
description="",
published_at=datetime.now(timezone.utc),
status="new",
progress_percent=0,
progress_stage="Загрузка файла",
progress_log=upload_log_line("Загрузка", f"Начинаю прием файла: {filename}"),
)
session.add(video)
session.commit()
session.refresh(video)
root = settings.videos_path.resolve()
video_dir = (settings.videos_path / str(video.id)).resolve()
target = video_dir / f"video{suffix}"
bytes_written = 0
bytes_at_last_log = 0
declared_size = getattr(file, "size", None)
total_bytes = declared_size if isinstance(declared_size, int) and declared_size > 0 else None
try:
if not video_dir.is_relative_to(root):
raise RuntimeError("Небезопасный путь для загруженного видео.")
video_dir.mkdir(parents=True, exist_ok=False)
with target.open("xb") as output:
while chunk := await file.read(VIDEO_UPLOAD_CHUNK_BYTES):
next_size = bytes_written + len(chunk)
if next_size > MAX_VIDEO_UPLOAD_BYTES:
raise HTTPException(status_code=413, detail="Размер видео не должен превышать 10 ГБ.")
if len(chunk) > shutil.disk_usage(settings.videos_path).free:
raise HTTPException(status_code=507, detail="На диске для видео закончилось свободное место.")
output.write(chunk)
bytes_written = next_size
if bytes_written - bytes_at_last_log >= VIDEO_UPLOAD_LOG_INTERVAL_BYTES:
uploaded_mb = bytes_written / 1024 / 1024
size_note = f" из {total_bytes / 1024 / 1024:.1f} МБ" if total_bytes else ""
video.progress_percent = min(99, round(bytes_written / total_bytes * 100)) if total_bytes else 0
video.progress_log = "\n".join(
[video.progress_log, upload_log_line("Загрузка", f"Получено {uploaded_mb:.1f} МБ{size_note}")]
)
session.commit()
bytes_at_last_log = bytes_written
if not bytes_written:
raise HTTPException(status_code=422, detail="Загруженный файл пуст.")
duration = uploaded_video_duration(target)
os.chmod(target, 0o644)
size_mb = bytes_written / 1024 / 1024
video.local_video_path = str(target)
video.duration_seconds = duration
video.progress_percent = 0
video.progress_stage = "Готов к обработке"
video.progress_log = "\n".join(
[
video.progress_log,
upload_log_line("Загрузка", f"Файл сохранен: {size_mb:.1f} МБ"),
upload_log_line("Подготовка", f"Длительность определена: {duration} сек. Ролик готов к обработке."),
]
)
session.commit()
return {
"id": video.id,
"title": video.title,
"sourceUrl": video.source_url,
"durationSeconds": video.duration_seconds,
"status": video.status,
}
except Exception:
if video_dir.is_relative_to(root):
shutil.rmtree(video_dir, ignore_errors=True)
session.delete(video)
session.commit()
raise
finally:
await file.close()
@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,
"manual": video.source_id is None,
"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, payload: VideoProcessIn | None = Body(default=None)) -> 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")
selected_chapters = [chapter.model_dump() for chapter in (payload.chapters if payload else []) or []]
recreate_drafts = bool(payload and payload.recreateDrafts)
if recreate_drafts:
for article in video.articles:
if article.status != "published":
article.status = "rejected"
article.published_at = None
article.rss_guid = None
was_active = video.status in {"queued", "processing"}
video.status = "queued"
video.progress_percent = 1
video.progress_stage = "В очереди"
action = "задача перезапущена" if was_active else "задача поставлена в обработку"
if recreate_drafts:
action = "старые черновики отправлены на переделку"
if selected_chapters:
action += f", выбрано глав: {len(selected_chapters)}"
queue_log = f"[{datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S')}] В очереди: {action}"
video.progress_log = "\n".join(part for part in [video.progress_log, queue_log] if part)
video.error_message = None
session.commit()
task = process_video.delay(video_id, selected_chapters or None)
return {"taskId": task.id}
@router.get("/api/videos/{video_id}/chapters")
def video_chapters(video_id: int, session: Session = Depends(get_session)) -> dict:
video = session.get(Video, video_id)
if not video:
raise HTTPException(status_code=404, detail="Video not found")
chapters = parse_video_chapters(video.description, video.duration_seconds)
return {
"videoId": video.id,
"title": video.title,
"durationSeconds": video.duration_seconds,
"chapters": [chapter_to_payload(chapter) for chapter in chapters],
"canSplit": len(chapters) >= 2,
}
@router.post("/api/videos/{video_id}/chapter-plan")
def create_video_chapter_plan(video_id: int, session: Session = Depends(get_session)) -> dict[str, str]:
video = session.get(Video, video_id)
if not video:
raise HTTPException(status_code=404, detail="Video not found")
if not video.duration_seconds or video.duration_seconds < 20 * 60:
raise HTTPException(status_code=422, detail="Хронометраж нужен только для роликов длиннее 20 минут.")
if video.status in {"queued", "processing", "planning"}:
raise HTTPException(status_code=409, detail="Ролик уже находится в обработке.")
video.status = "planning"
video.progress_percent = 1
video.progress_stage = "В очереди на хронометраж"
video.error_message = None
plan_log = upload_log_line("Хронометраж", "Задача поставлена в очередь: транскрибация и анализ тем")
video.progress_log = "\n".join(part for part in [video.progress_log, plan_log] if part)
session.commit()
task = create_chapter_plan.delay(video_id)
return {"taskId": task.id}
def delete_video_storage_dir(video: Video, settings: Settings) -> None:
root = settings.videos_path.resolve()
video_dir = (root / str(video.id)).resolve()
if video_dir != root and video_dir.is_relative_to(root):
shutil.rmtree(video_dir, ignore_errors=True)
video.local_video_path = None
@router.delete("/api/videos/{video_id}")
def ignore_video(
video_id: int,
session: Session = Depends(get_session),
settings: Settings = Depends(get_settings),
) -> 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"
delete_video_storage_dir(video, settings)
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),
manual: bool = Query(default=False),
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)
if manual:
filters.append(Article.video_id.is_(None))
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),
"featureImageUrl": article_cover_url(session, 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.post("/api/articles", status_code=201)
def create_manual_article(session: Session = Depends(get_session), settings: Settings = Depends(get_settings)) -> dict:
signature_html = session.scalar(select(AppSetting.value).where(AppSetting.key == SETTING_SIGNATURE)) or ""
article = Article(
slug=f"manual-{uuid4().hex}",
title="Новый материал",
cta_html=sanitize_article_editor_html(signature_html),
status="draft",
)
session.add(article)
session.commit()
session.refresh(article)
return {
"id": article.id,
"title": article.title,
"slug": article.slug,
"status": article.status,
"videoId": None,
"videoSourceUrl": "",
"url": article_url(settings, article),
"featureImageUrl": article_cover_url(session, article),
"createdAt": article.created_at,
"publishedAt": article.published_at,
"contentHtml": render_article_html(article),
"editableHtml": editable_article_html(article),
}
@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,
"videoSourceUrl": article.video.source_url if article.video else "",
"url": article_url(settings, article),
"featureImageUrl": article_cover_url(session, article),
"createdAt": article.created_at,
"publishedAt": article.published_at,
"contentHtml": render_article_html(article),
"editableHtml": editable_article_html(article),
}
def image_job_payload(job: ImageGenerationJob) -> dict[str, Any]:
return {
"id": job.id,
"target": job.target,
"status": job.status,
"progress": job.progress,
"stage": job.stage,
"localUrl": job.local_url if job.status == "ready" else None,
"errorCode": job.error_code,
"errorMessage": job.error_message,
"targetBlockId": job.target_block_id,
"snapshotId": job.snapshot_id,
}
def image_batch_payload(batch: ImageGenerationBatch) -> dict[str, Any]:
return {"batchId": batch.id, "status": batch.status, "snapshotId": batch.snapshot_id, "jobs": [image_job_payload(job) for job in batch.jobs]}
def active_image_batch(session: Session, article_id: int) -> ImageGenerationBatch | None:
return session.scalar(
select(ImageGenerationBatch)
.where(ImageGenerationBatch.article_id == article_id, ImageGenerationBatch.status.in_(["queued", "running"]))
.order_by(ImageGenerationBatch.created_at.desc())
)
@router.get("/api/articles/{article_id}/image-generations/active")
def active_article_image_generation(article_id: int, request: Request, session: Session = Depends(get_session)) -> Any:
require_session(request)
if not session.get(Article, article_id):
raise HTTPException(status_code=404, detail="Article not found")
batch = active_image_batch(session, article_id)
if not batch:
batch = session.scalar(
select(ImageGenerationBatch)
.where(ImageGenerationBatch.article_id == article_id)
.order_by(ImageGenerationBatch.created_at.desc())
)
return Response(status_code=204) if not batch else image_batch_payload(batch)
@router.get("/api/articles/{article_id}/image-generations/{batch_id}")
def article_image_generation(article_id: int, batch_id: str, request: Request, session: Session = Depends(get_session)) -> dict[str, Any]:
require_session(request)
batch = session.get(ImageGenerationBatch, batch_id)
if not batch or batch.article_id != article_id:
raise HTTPException(status_code=404, detail="Image generation not found")
return image_batch_payload(batch)
@router.post("/api/articles/{article_id}/image-generations", status_code=202)
def create_article_image_generation(article_id: int, payload: ImageGenerationIn, request: Request, session: Session = Depends(get_session)) -> dict[str, Any]:
require_session(request)
article = session.get(Article, article_id)
if not article:
raise HTTPException(status_code=404, detail="Article not found")
if payload.mode not in {"all", "cover", "middle", "final"}:
raise HTTPException(status_code=422, detail="Неизвестный режим генерации.")
if not payload.title.strip() or not payload.snapshotId.strip():
raise HTTPException(status_code=422, detail="Нужны заголовок и идентификатор снимка.")
if payload.mode in {"middle", "final"} and payload.mode != "all" and not payload.targetBlockId:
raise HTTPException(status_code=422, detail="Для перегенерации изображения нужен targetBlockId.")
try:
# Validate the untrusted snapshot before persisting a job.
build_prompt("cover", payload.title, payload.editorData)
except ValueError as exc:
raise HTTPException(status_code=422, detail=str(exc)) from exc
active = active_image_batch(session, article_id)
if active and payload.mode == "all":
return image_batch_payload(active)
targets = ["cover", "middle", "final"] if payload.mode == "all" else [payload.mode]
if active and payload.mode != "all":
active_targets = {job.target for job in active.jobs if job.status in {"queued", "requesting", "generating", "downloading"}}
if payload.mode in active_targets:
return image_batch_payload(active)
values = {item.key: item.value for item in session.scalars(select(AppSetting).where(AppSetting.key.in_([SETTING_IMAGE_API_URL, SETTING_IMAGE_MODEL]))).all()}
api_url, model = values.get(SETTING_IMAGE_API_URL, DEFAULT_API_URL), values.get(SETTING_IMAGE_MODEL, DEFAULT_MODEL)
try:
api_url = normalize_api_url(api_url)
except ValueError as exc:
raise HTTPException(status_code=422, detail="Некорректный API URL в настройках.") from exc
if not model.strip():
raise HTTPException(status_code=422, detail="Не задана модель генерации.")
batch = ImageGenerationBatch(id=str(uuid4()), article_id=article_id, snapshot_id=payload.snapshotId.strip(), status="queued")
session.add(batch)
jobs: list[ImageGenerationJob] = []
for target in targets:
job = ImageGenerationJob(
id=str(uuid4()), batch_id=batch.id, article_id=article_id, target=target,
target_block_id=payload.targetBlockId if target in {"middle", "final"} else None,
snapshot_id=batch.snapshot_id, prompt=build_prompt(target, payload.title, payload.editorData, payload.targetBlockId),
api_url=api_url, model=model.strip(), status="queued", progress=0, stage="В очереди",
)
session.add(job)
jobs.append(job)
session.commit()
for job in jobs:
task = generate_article_image.delay(job.id)
job.celery_task_id = task.id
session.commit()
session.refresh(batch)
return image_batch_payload(batch)
@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()
if not title:
raise HTTPException(status_code=422, detail="Title is required")
next_slug = unique_article_slug(session, payload.slug, article.id) if payload.slug is not None else article.slug
body = sanitize_article_editor_html(payload.editableHtml)
body = strip_leading_duplicate_title(body, title)
signature_html = sanitize_article_editor_html(article.cta_html)
if signature_html and signature_html in body:
body = body.replace(signature_html, "").rstrip()
else:
signature_html = ""
_, prior_lead_question = split_audience_question_html(article.lead)
_, prior_body_question = split_audience_question_html(article.body_html)
prior_question = prior_body_question or prior_lead_question
body, updated_question = split_audience_question_html(body)
audience_question_html = updated_question or prior_question
if article.video_id:
if VIDEO_PLACEHOLDER not in body:
body = "\n".join(part for part in [body.strip(), f"<p>{VIDEO_PLACEHOLDER}</p>"] if part)
elif body.count(VIDEO_PLACEHOLDER) > 1:
before, after = body.split(VIDEO_PLACEHOLDER, 1)
body = before + VIDEO_PLACEHOLDER + after.replace(VIDEO_PLACEHOLDER, "")
body = "\n".join(part for part in [body, audience_question_html] if part)
lead, body_html = split_lead_and_body(body)
article.title = title
article.slug = next_slug
article.lead = lead
article.body_html = body_html
article.cta_html = signature_html.strip()
if payload.featureImageUrl is not None:
article.feature_image_url = payload.featureImageUrl.strip()
session.commit()
session.refresh(article)
return {
"id": article.id,
"title": article.title,
"slug": article.slug,
"status": article.status,
"videoId": article.video_id,
"videoSourceUrl": article.video.source_url if article.video else "",
"url": article_url(settings, article),
"featureImageUrl": article_cover_url(session, 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"}
async def store_uploaded_image(file: UploadFile, settings: 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/uploads/images")
async def upload_image(file: UploadFile = File(...), settings: Settings = Depends(get_settings)) -> dict[str, str]:
return await store_uploaded_image(file, settings)
@router.post("/api/v1/media/images")
async def upload_api_image(
request: Request,
file: UploadFile = File(...),
session: Session = Depends(get_session),
settings: Settings = Depends(get_settings),
) -> dict[str, str]:
require_draft_api_key(request, session)
return await store_uploaded_image(file, settings)
@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")
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.",
}