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
|
2026-08-08 14:02:14 +03:00
|
|
|
|
import hashlib
|
|
|
|
|
|
import json
|
2026-06-27 14:07:10 +03:00
|
|
|
|
import os
|
|
|
|
|
|
from pathlib import Path
|
|
|
|
|
|
import random
|
|
|
|
|
|
import re
|
2026-08-15 11:23:45 +03:00
|
|
|
|
import shutil
|
2026-06-27 14:07:10 +03:00
|
|
|
|
import subprocess
|
2026-08-11 12:47:48 +03:00
|
|
|
|
from typing import Any
|
2026-06-27 14:07:10 +03:00
|
|
|
|
from uuid import uuid4
|
|
|
|
|
|
|
2026-08-11 12:47:48 +03:00
|
|
|
|
from fastapi import APIRouter, Body, Depends, File, HTTPException, Query, Request, UploadFile, WebSocket, WebSocketDisconnect
|
2026-08-08 14:02:14 +03:00
|
|
|
|
from fastapi.responses import HTMLResponse, RedirectResponse, Response
|
2026-06-27 14:07:10 +03:00
|
|
|
|
from pydantic import BaseModel
|
|
|
|
|
|
from sqlalchemy import func, select
|
|
|
|
|
|
from sqlalchemy.orm import Session
|
|
|
|
|
|
|
|
|
|
|
|
from app.config import Settings, get_settings
|
2026-08-11 12:47:48 +03:00
|
|
|
|
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,
|
|
|
|
|
|
)
|
2026-06-27 14:07:10 +03:00
|
|
|
|
from app.captions import strip_leading_duplicate_title
|
2026-08-08 14:02:14 +03:00
|
|
|
|
from app.chapters import chapter_to_payload, parse_video_chapters
|
2026-06-27 14:07:10 +03:00
|
|
|
|
from app.database import SessionLocal, get_session
|
2026-08-11 17:53:54 +03:00
|
|
|
|
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
|
2026-06-27 14:07:10 +03:00
|
|
|
|
from app.quality import validate_article_content
|
2026-08-13 11:43:53 +03:00
|
|
|
|
from app.rss import VIDEO_PLACEHOLDER, article_url, build_feed_xml, render_article_html, split_audience_question_html
|
2026-08-11 17:53:54 +03:00
|
|
|
|
from app.worker import best_thumbnail_url, generate_article_image, parse_upload_date, process_video, scan_sources, ytdlp_base_args
|
2026-06-27 14:07:10 +03:00
|
|
|
|
|
|
|
|
|
|
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" />'
|
|
|
|
|
|
)
|
2026-08-08 14:02:14 +03:00
|
|
|
|
PUBLIC_REDIRECT_URL = "https://nstarikov.ru"
|
2026-08-15 11:23:45 +03:00
|
|
|
|
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
|
2026-06-27 14:07:10 +03:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class SourceIn(BaseModel):
|
|
|
|
|
|
name: str
|
|
|
|
|
|
url: str
|
|
|
|
|
|
source_type: str = "yt_dlp"
|
|
|
|
|
|
enabled: bool = True
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-08-08 14:02:14 +03:00
|
|
|
|
class ManualVideoIn(BaseModel):
|
|
|
|
|
|
url: str
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-08-11 12:47:48 +03:00
|
|
|
|
class AuthCredentialIn(BaseModel):
|
|
|
|
|
|
challengeId: str
|
|
|
|
|
|
credential: dict[str, Any]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class VkAuthIn(BaseModel):
|
|
|
|
|
|
accessToken: str
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-08-08 14:02:14 +03:00
|
|
|
|
class AppSettingsIn(BaseModel):
|
|
|
|
|
|
signatureHtml: str = ""
|
|
|
|
|
|
llmInstructions: str = ""
|
2026-08-11 17:53:54 +03:00
|
|
|
|
imageApiUrl: str | None = None
|
|
|
|
|
|
imageModel: str | None = None
|
|
|
|
|
|
imageApiToken: str | None = None
|
|
|
|
|
|
deleteImageApiToken: bool = False
|
2026-08-08 14:02:14 +03:00
|
|
|
|
|
|
|
|
|
|
|
2026-06-27 14:07:10 +03:00
|
|
|
|
class ChatIn(BaseModel):
|
|
|
|
|
|
message: str
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class ArticleUpdateIn(BaseModel):
|
|
|
|
|
|
title: str
|
|
|
|
|
|
editableHtml: str
|
2026-08-08 14:02:14 +03:00
|
|
|
|
featureImageUrl: str | None = None
|
2026-06-27 14:07:10 +03:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class ArticlePublishIn(BaseModel):
|
|
|
|
|
|
publishedAt: datetime | None = None
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-08-11 17:53:54 +03:00
|
|
|
|
class ImageGenerationIn(BaseModel):
|
|
|
|
|
|
mode: str
|
|
|
|
|
|
title: str
|
|
|
|
|
|
featureImageUrl: str | None = None
|
|
|
|
|
|
editorData: dict[str, Any]
|
|
|
|
|
|
snapshotId: str
|
|
|
|
|
|
targetBlockId: str | None = None
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-08-08 14:02:14 +03:00
|
|
|
|
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
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-06-27 14:07:10 +03:00
|
|
|
|
@router.get("/health")
|
|
|
|
|
|
def health() -> dict[str, str]:
|
|
|
|
|
|
return {"status": "ok"}
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-08-08 14:02:14 +03:00
|
|
|
|
SETTING_SIGNATURE = "article_signature_html"
|
|
|
|
|
|
SETTING_LLM_INSTRUCTIONS = "llm_instructions"
|
2026-08-11 17:53:54 +03:00
|
|
|
|
SETTING_IMAGE_API_URL = "image_api_url"
|
|
|
|
|
|
SETTING_IMAGE_MODEL = "image_model"
|
|
|
|
|
|
SETTING_IMAGE_API_TOKEN = "image_api_token"
|
2026-08-08 14:02:14 +03:00
|
|
|
|
|
|
|
|
|
|
|
2026-08-11 17:53:54 +03:00
|
|
|
|
def app_settings_payload(session: Session) -> dict[str, Any]:
|
2026-08-08 14:02:14 +03:00
|
|
|
|
values = {
|
|
|
|
|
|
setting.key: setting.value
|
|
|
|
|
|
for setting in session.scalars(
|
2026-08-11 17:53:54 +03:00
|
|
|
|
select(AppSetting).where(AppSetting.key.in_([SETTING_SIGNATURE, SETTING_LLM_INSTRUCTIONS, SETTING_IMAGE_API_URL, SETTING_IMAGE_MODEL, SETTING_IMAGE_API_TOKEN]))
|
2026-08-08 14:02:14 +03:00
|
|
|
|
).all()
|
|
|
|
|
|
}
|
|
|
|
|
|
return {
|
|
|
|
|
|
"signatureHtml": values.get(SETTING_SIGNATURE, ""),
|
|
|
|
|
|
"llmInstructions": values.get(SETTING_LLM_INSTRUCTIONS, ""),
|
2026-08-11 17:53:54 +03:00
|
|
|
|
"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, "")),
|
2026-08-08 14:02:14 +03:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@router.get("/api/settings")
|
2026-08-11 17:53:54 +03:00
|
|
|
|
def get_app_settings(request: Request, session: Session = Depends(get_session)) -> dict[str, Any]:
|
|
|
|
|
|
require_session(request)
|
2026-08-08 14:02:14 +03:00
|
|
|
|
return app_settings_payload(session)
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-08-11 12:47:48 +03:00
|
|
|
|
@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}
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-08-08 14:02:14 +03:00
|
|
|
|
@router.put("/api/settings")
|
2026-08-11 17:53:54 +03:00
|
|
|
|
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="Модель не может быть пустой.")
|
2026-08-08 14:02:14 +03:00
|
|
|
|
values = {
|
|
|
|
|
|
SETTING_SIGNATURE: payload.signatureHtml.strip(),
|
|
|
|
|
|
SETTING_LLM_INSTRUCTIONS: payload.llmInstructions.strip(),
|
|
|
|
|
|
}
|
2026-08-11 17:53:54 +03:00
|
|
|
|
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
|
2026-08-08 14:02:14 +03:00
|
|
|
|
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)
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-06-27 14:07:10 +03:00
|
|
|
|
@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"},
|
2026-08-13 11:43:53 +03:00
|
|
|
|
"p": {"class"},
|
2026-06-27 14:07:10 +03:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
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()
|
2026-08-13 11:43:53 +03:00
|
|
|
|
if name == "class":
|
|
|
|
|
|
if tag == "p" and "audience-question" in value.split():
|
|
|
|
|
|
clean_attrs.append('class="audience-question"')
|
|
|
|
|
|
continue
|
2026-06-27 14:07:10 +03:00
|
|
|
|
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)
|
2026-08-08 14:02:14 +03:00
|
|
|
|
sanitized = strip_article_cover_html(sanitized)
|
2026-06-27 14:07:10 +03:00
|
|
|
|
sanitized = re.sub(r"<p>\s*</p>", "", sanitized)
|
|
|
|
|
|
sanitized = re.sub(r"\n{3,}", "\n\n", sanitized).strip()
|
|
|
|
|
|
return sanitized
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-08-08 14:02:14 +03:00
|
|
|
|
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()
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-06-27 14:07:10 +03:00
|
|
|
|
def editable_article_html(article: Article) -> str:
|
2026-08-15 08:39:30 +03:00
|
|
|
|
lead_html, lead_question_html = split_audience_question_html(article.lead)
|
2026-08-13 11:43:53 +03:00
|
|
|
|
body_html, audience_question_html = split_audience_question_html(article.body_html)
|
2026-08-15 08:39:30 +03:00
|
|
|
|
audience_question_html = audience_question_html or lead_question_html
|
2026-08-13 11:43:53 +03:00
|
|
|
|
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)
|
2026-08-15 08:39:30 +03:00
|
|
|
|
html = "\n".join(part for part in [lead_html, body_html, audience_question_html, article.cta_html] if part).strip()
|
2026-08-08 14:02:14 +03:00
|
|
|
|
html = strip_article_cover_html(html)
|
2026-06-27 14:07:10 +03:00
|
|
|
|
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:
|
2026-08-08 14:02:14 +03:00
|
|
|
|
if article.feature_image_url:
|
|
|
|
|
|
return article.feature_image_url
|
2026-06-27 14:07:10 +03:00
|
|
|
|
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
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-08-15 11:23:45 +03:00
|
|
|
|
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}"
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-06-27 14:07:10 +03:00
|
|
|
|
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")
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-08-08 14:02:14 +03:00
|
|
|
|
@router.get("/")
|
|
|
|
|
|
def home() -> RedirectResponse:
|
|
|
|
|
|
return RedirectResponse(url=PUBLIC_REDIRECT_URL, status_code=302)
|
2026-06-27 14:07:10 +03:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@router.head("/")
|
2026-08-08 14:02:14 +03:00
|
|
|
|
def home_head() -> RedirectResponse:
|
|
|
|
|
|
return RedirectResponse(url=PUBLIC_REDIRECT_URL, status_code=302)
|
2026-06-27 14:07:10 +03:00
|
|
|
|
|
|
|
|
|
|
|
2026-08-08 14:02:14 +03:00
|
|
|
|
@router.get("/posts/{slug}")
|
|
|
|
|
|
def post(slug: str) -> RedirectResponse:
|
|
|
|
|
|
return RedirectResponse(url=PUBLIC_REDIRECT_URL, status_code=302)
|
2026-06-27 14:07:10 +03:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@router.head("/posts/{slug}")
|
2026-08-08 14:02:14 +03:00
|
|
|
|
def post_head(slug: str) -> RedirectResponse:
|
|
|
|
|
|
return RedirectResponse(url=PUBLIC_REDIRECT_URL, status_code=302)
|
2026-06-27 14:07:10 +03:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@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}
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-08-08 14:02:14 +03:00
|
|
|
|
@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}")
|
|
|
|
|
|
|
2026-08-11 11:56:47 +03:00
|
|
|
|
# A manually imported video enters our queue now, regardless of its original age.
|
|
|
|
|
|
published_at = datetime.now(timezone.utc)
|
2026-08-08 14:02:14 +03:00
|
|
|
|
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,
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-08-15 11:23:45 +03:00
|
|
|
|
@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()
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-06-27 14:07:10 +03:00
|
|
|
|
@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,
|
2026-08-11 11:56:47 +03:00
|
|
|
|
"manual": video.source_id is None,
|
2026-06-27 14:07:10 +03:00
|
|
|
|
"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")
|
2026-08-08 14:02:14 +03:00
|
|
|
|
def process_video_route(video_id: int, payload: VideoProcessIn | None = Body(default=None)) -> dict[str, str]:
|
2026-06-27 14:07:10 +03:00
|
|
|
|
with SessionLocal() as session:
|
|
|
|
|
|
video = session.get(Video, video_id)
|
|
|
|
|
|
if not video:
|
|
|
|
|
|
raise HTTPException(status_code=404, detail="Video not found")
|
2026-08-08 14:02:14 +03:00
|
|
|
|
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
|
2026-06-27 14:07:10 +03:00
|
|
|
|
was_active = video.status in {"queued", "processing"}
|
|
|
|
|
|
video.status = "queued"
|
|
|
|
|
|
video.progress_percent = 1
|
|
|
|
|
|
video.progress_stage = "В очереди"
|
|
|
|
|
|
action = "задача перезапущена" if was_active else "задача поставлена в обработку"
|
2026-08-08 14:02:14 +03:00
|
|
|
|
if recreate_drafts:
|
|
|
|
|
|
action = "старые черновики отправлены на переделку"
|
|
|
|
|
|
if selected_chapters:
|
|
|
|
|
|
action += f", выбрано глав: {len(selected_chapters)}"
|
2026-06-27 14:07:10 +03:00
|
|
|
|
video.progress_log = f"[{datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S')}] В очереди: {action}"
|
|
|
|
|
|
video.error_message = None
|
|
|
|
|
|
session.commit()
|
2026-08-08 14:02:14 +03:00
|
|
|
|
task = process_video.delay(video_id, selected_chapters or None)
|
2026-06-27 14:07:10 +03:00
|
|
|
|
return {"taskId": task.id}
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-08-08 14:02:14 +03:00
|
|
|
|
@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,
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-06-27 14:07:10 +03:00
|
|
|
|
@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),
|
2026-08-08 14:02:14 +03:00
|
|
|
|
"featureImageUrl": article_cover_url(session, article),
|
2026-06-27 14:07:10 +03:00
|
|
|
|
"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,
|
2026-08-13 11:43:53 +03:00
|
|
|
|
"videoSourceUrl": article.video.source_url if article.video else "",
|
2026-06-27 14:07:10 +03:00
|
|
|
|
"url": article_url(settings, article),
|
2026-08-08 14:02:14 +03:00
|
|
|
|
"featureImageUrl": article_cover_url(session, article),
|
2026-06-27 14:07:10 +03:00
|
|
|
|
"createdAt": article.created_at,
|
|
|
|
|
|
"publishedAt": article.published_at,
|
|
|
|
|
|
"contentHtml": render_article_html(article),
|
|
|
|
|
|
"editableHtml": editable_article_html(article),
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-08-11 17:53:54 +03:00
|
|
|
|
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)
|
2026-08-11 19:46:19 +03:00
|
|
|
|
if not batch:
|
|
|
|
|
|
batch = session.scalar(
|
|
|
|
|
|
select(ImageGenerationBatch)
|
|
|
|
|
|
.where(ImageGenerationBatch.article_id == article_id)
|
|
|
|
|
|
.order_by(ImageGenerationBatch.created_at.desc())
|
|
|
|
|
|
)
|
2026-08-11 17:53:54 +03:00
|
|
|
|
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)
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-06-27 14:07:10 +03:00
|
|
|
|
@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")
|
2026-08-13 11:43:53 +03:00
|
|
|
|
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 = ""
|
2026-08-15 08:39:30 +03:00
|
|
|
|
_, 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
|
2026-08-13 11:43:53 +03:00
|
|
|
|
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)
|
2026-06-27 14:07:10 +03:00
|
|
|
|
lead, body_html = split_lead_and_body(body)
|
|
|
|
|
|
article.title = title
|
|
|
|
|
|
article.lead = lead
|
|
|
|
|
|
article.body_html = body_html
|
2026-08-08 14:02:14 +03:00
|
|
|
|
article.cta_html = signature_html.strip()
|
|
|
|
|
|
if payload.featureImageUrl is not None:
|
|
|
|
|
|
article.feature_image_url = payload.featureImageUrl.strip()
|
2026-06-27 14:07:10 +03:00
|
|
|
|
session.commit()
|
|
|
|
|
|
session.refresh(article)
|
|
|
|
|
|
return {
|
|
|
|
|
|
"id": article.id,
|
|
|
|
|
|
"title": article.title,
|
|
|
|
|
|
"slug": article.slug,
|
|
|
|
|
|
"status": article.status,
|
|
|
|
|
|
"videoId": article.video_id,
|
2026-08-13 11:43:53 +03:00
|
|
|
|
"videoSourceUrl": article.video.source_url if article.video else "",
|
2026-06-27 14:07:10 +03:00
|
|
|
|
"url": article_url(settings, article),
|
2026-08-08 14:02:14 +03:00
|
|
|
|
"featureImageUrl": article_cover_url(session, article),
|
2026-06-27 14:07:10 +03:00
|
|
|
|
"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")
|
|
|
|
|
|
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.",
|
|
|
|
|
|
}
|