import asyncio from datetime import datetime, timezone from html import escape, unescape from html.parser import HTMLParser import os from pathlib import Path import random import re import subprocess from uuid import uuid4 from fastapi import APIRouter, Body, Depends, File, HTTPException, Query, UploadFile, WebSocket, WebSocketDisconnect from fastapi.responses import HTMLResponse, Response from pydantic import BaseModel from sqlalchemy import func, select from sqlalchemy.orm import Session from app.config import Settings, get_settings from app.captions import strip_leading_duplicate_title from app.database import SessionLocal, get_session from app.models import Article, Frame, Source, Video from app.quality import validate_article_content from app.rss import article_url, build_feed_xml, render_article_html from app.worker import process_video, scan_sources router = APIRouter() ZEN_VERIFICATION_FILE = "zen_y2a3098Zp7skRQXDYdkEOwOXFDdQsSzU7bkouMOhtBECx6zgC5CCqVZRxslhhjSg.html" ZEN_VERIFICATION_FILE_LOWER = "zen_y2a3098zp7skrqxdydkeowoxfddqsszu7bkoumohtbecx6zgc5ccqvzrxslhhjsg.html" ZEN_VERIFICATION_FILE_LEGACY = "zen_y2a3098Zp7skRQXDYdkEOwOXFDdQsSzU7bkouM0htBECx6zgC5CCqVZRxslhhjSg.html" ZEN_VERIFICATION_META = ( '' ) class SourceIn(BaseModel): name: str url: str source_type: str = "yt_dlp" enabled: bool = True class ChatIn(BaseModel): message: str class ArticleUpdateIn(BaseModel): title: str editableHtml: str class ArticlePublishIn(BaseModel): publishedAt: datetime | None = None @router.get("/health") def health() -> dict[str, str]: return {"status": "ok"} @router.get("/feed") def feed(session: Session = Depends(get_session), settings: Settings = Depends(get_settings)) -> Response: return Response(build_feed_xml(session, settings), media_type="application/rss+xml; charset=utf-8") @router.head("/feed") def feed_head(session: Session = Depends(get_session), settings: Settings = Depends(get_settings)) -> Response: content = build_feed_xml(session, settings).encode("utf-8") return Response( headers={"Content-Length": str(len(content))}, media_type="application/rss+xml; charset=utf-8", ) @router.get("/robots.txt") def robots_txt(settings: Settings = Depends(get_settings)) -> Response: content = f"""User-agent: * Allow: / Allow: /feed Sitemap: {settings.public_base_url.rstrip("/")}/feed """ return Response(content, media_type="text/plain; charset=utf-8") @router.head("/robots.txt") def robots_txt_head(settings: Settings = Depends(get_settings)) -> Response: content = f"""User-agent: * Allow: / Allow: /feed Sitemap: {settings.public_base_url.rstrip("/")}/feed """.encode("utf-8") return Response(headers={"Content-Length": str(len(content))}, media_type="text/plain; charset=utf-8") def plain_excerpt(html: str, limit: int = 260) -> str: text = re.sub(r"<[^>]+>", " ", html) text = re.sub(r"\s+", " ", unescape(text)).strip() if len(text) <= limit: return text return text[:limit].rsplit(" ", 1)[0].strip() + "..." class ArticleHtmlSanitizer(HTMLParser): allowed_tags = { "p", "br", "h2", "h3", "strong", "b", "em", "i", "u", "s", "ul", "ol", "li", "blockquote", "figure", "figcaption", "img", "a", } void_tags = {"br", "img"} allowed_attrs = { "a": {"href", "title"}, "img": {"src", "alt"}, } def __init__(self) -> None: super().__init__(convert_charrefs=False) self.parts: list[str] = [] self.skip_depth = 0 def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: tag = tag.lower() if tag in {"script", "style", "iframe", "object", "embed"}: self.skip_depth += 1 return if self.skip_depth or tag not in self.allowed_tags: return clean_attrs: list[str] = [] for name, value in attrs: name = name.lower() if value is None or name not in self.allowed_attrs.get(tag, set()): continue value = value.strip() if name in {"href", "src"} and not re.match(r"^(https?://|/media/)", value, flags=re.I): continue clean_attrs.append(f'{name}="{escape(value, quote=True)}"') attr_text = f" {' '.join(clean_attrs)}" if clean_attrs else "" self.parts.append(f"<{tag}{attr_text}>") def handle_endtag(self, tag: str) -> None: tag = tag.lower() if tag in {"script", "style", "iframe", "object", "embed"} and self.skip_depth: self.skip_depth -= 1 return if self.skip_depth or tag not in self.allowed_tags or tag in self.void_tags: return self.parts.append(f"") def handle_data(self, data: str) -> None: if not self.skip_depth: self.parts.append(escape(data)) def handle_entityref(self, name: str) -> None: if not self.skip_depth: self.parts.append(f"&{name};") def handle_charref(self, name: str) -> None: if not self.skip_depth: self.parts.append(f"&#{name};") def sanitize_article_editor_html(html: str) -> str: sanitizer = ArticleHtmlSanitizer() sanitizer.feed(html) sanitized = "".join(sanitizer.parts) sanitized = re.sub(r"

\s*

", "", sanitized) sanitized = re.sub(r"\n{3,}", "\n\n", sanitized).strip() return sanitized def editable_article_html(article: Article) -> str: html = "\n".join(part for part in [article.lead, article.body_html] if part).strip() return strip_leading_duplicate_title(html, article.title) def split_lead_and_body(html: str) -> tuple[str, str]: match = re.match(r"\s*(]*>.*?

)(.*)\s*$", html, flags=re.I | re.S) if not match: return "", html.strip() return match.group(1).strip(), match.group(2).strip() def article_cover_url(session: Session, article: Article) -> str | None: if article.video and article.video.thumbnail_url: return article.video.thumbnail_url if not article.video_id: return None frame = session.scalar( select(Frame) .where(Frame.video_id == article.video_id, Frame.selected == True) # noqa: E712 .order_by(Frame.score.desc(), Frame.id.asc()) .limit(1) ) return frame.public_url if frame else None def local_video_file(video: Video, settings: Settings) -> Path | None: if video.local_video_path: path = Path(video.local_video_path) if path.exists(): return path video_dir = settings.videos_path / str(video.id) for candidate in sorted(video_dir.glob("video.*")): if candidate.is_file(): return candidate return None def create_random_frame(video: Video, settings: Settings) -> tuple[Path, str, int]: video_path = local_video_file(video, settings) if not video_path: raise HTTPException(status_code=422, detail="Локальный видеофайл еще не найден. Сначала обработайте ролик.") duration = max(1, video.duration_seconds or 60) start = 2 if duration > 6 else 0 end = max(start, duration - 2) timestamp = random.randint(start, end) target_dir = settings.media_path / "videos" / str(video.id) / "manual" target_dir.mkdir(parents=True, exist_ok=True) target = target_dir / f"frame-{timestamp}-{uuid4().hex[:8]}.webp" command = [ "ffmpeg", "-y", "-ss", str(timestamp), "-i", str(video_path), "-frames:v", "1", "-vf", "scale=1280:720:force_original_aspect_ratio=decrease,pad=1280:720:(ow-iw)/2:(oh-ih)/2", "-c:v", "libwebp", "-quality", "84", str(target), ] result = subprocess.run(command, text=True, capture_output=True) if result.returncode or not target.exists(): detail = (result.stderr or result.stdout or "ffmpeg не смог создать кадр").strip() raise HTTPException(status_code=500, detail=detail[-1200:]) public_url = f"{settings.public_base_url.rstrip('/')}/media/videos/{video.id}/manual/{target.name}" return target, public_url, timestamp @router.get(f"/{ZEN_VERIFICATION_FILE}", response_class=HTMLResponse) @router.get(f"/{ZEN_VERIFICATION_FILE_LOWER}", response_class=HTMLResponse) @router.get(f"/{ZEN_VERIFICATION_FILE_LEGACY}", response_class=HTMLResponse) def zen_verification() -> str: return ZEN_VERIFICATION_META @router.head(f"/{ZEN_VERIFICATION_FILE}") @router.head(f"/{ZEN_VERIFICATION_FILE_LOWER}") @router.head(f"/{ZEN_VERIFICATION_FILE_LEGACY}") def zen_verification_head() -> Response: return Response(media_type="text/html; charset=utf-8") @router.get("/", response_class=HTMLResponse) def home( page: int = Query(1, ge=1), session: Session = Depends(get_session), settings: Settings = Depends(get_settings), ) -> str: per_page = 12 total = session.scalar(select(func.count(Article.id)).where(Article.status == "published")) or 0 pages = max(1, (total + per_page - 1) // per_page) current_page = min(page, pages) articles = session.scalars( select(Article) .where(Article.status == "published") .order_by(Article.published_at.desc(), Article.id.desc()) .offset((current_page - 1) * per_page) .limit(per_page) ).all() cards = [] for article in articles: url = article_url(settings, article) cover = article_cover_url(session, article) image_html = ( f'{escape(article.title)}' if cover else '
Без изображения
' ) excerpt = plain_excerpt(render_article_html(article, include_video_embed=False)) cards.append( f"""
{image_html}
""".strip() ) previous_link = ( f'Назад' if current_page > 1 else 'Назад' ) next_link = ( f'Вперед' if current_page < pages else 'Вперед' ) empty_state = "" if not articles: empty_state = '
Опубликованных материалов пока нет.
' return f""" {ZEN_VERIFICATION_META} Николай Стариков

Лента материалов

Николай Стариков

Публикации, подготовленные по выступлениям и видеоматериалам.

RSS
{empty_state}
{chr(10).join(cards)}
""" @router.head("/") def home_head() -> Response: return Response(media_type="text/html; charset=utf-8") @router.get("/posts/{slug}", response_class=HTMLResponse) def post(slug: str, session: Session = Depends(get_session), settings: Settings = Depends(get_settings)) -> str: article = session.scalar(select(Article).where(Article.slug == slug)) if not article or article.status != "published": raise HTTPException(status_code=404, detail="Article not found") title = escape(article.title) return f""" {title}

{title}

{render_article_html(article)}
""" @router.head("/posts/{slug}") def post_head(slug: str, session: Session = Depends(get_session)) -> Response: article = session.scalar(select(Article).where(Article.slug == slug)) if not article or article.status != "published": raise HTTPException(status_code=404, detail="Article not found") return Response(media_type="text/html; charset=utf-8") @router.get("/api/dashboard") def dashboard(session: Session = Depends(get_session)) -> dict: now = datetime.now(timezone.utc) return { "sources": session.scalar(select(func.count(Source.id))), "videos": session.scalar(select(func.count(Video.id)).where(Video.status != "ignored")), "newVideos": session.scalar(select(func.count(Video.id)).where(Video.status == "new")), "processingVideos": session.scalar(select(func.count(Video.id)).where(Video.status.in_(["queued", "processing"]))), "drafts": session.scalar(select(func.count(Article.id)).where(Article.status == "draft")), "scheduled": session.scalar(select(func.count(Article.id)).where(Article.status == "published", Article.published_at > now)), "published": session.scalar( select(func.count(Article.id)).where( Article.status == "published", Article.published_at.is_not(None), Article.published_at <= now, ) ), } @router.get("/api/sources") def list_sources(session: Session = Depends(get_session)) -> list[dict]: sources = session.scalars(select(Source).order_by(Source.id.desc())).all() return [ { "id": source.id, "name": source.name, "url": source.url, "sourceType": source.source_type, "enabled": source.enabled, "lastCheckedAt": source.last_checked_at, } for source in sources ] @router.post("/api/sources") def create_source(payload: SourceIn, session: Session = Depends(get_session)) -> dict: source = Source( name=payload.name, url=payload.url, source_type=payload.source_type, enabled=payload.enabled, ) session.add(source) session.commit() return {"id": source.id} @router.post("/api/sources/scan") def scan_all_sources() -> dict[str, str]: task = scan_sources.delay() return {"taskId": task.id} @router.get("/api/videos") def list_videos(session: Session = Depends(get_session)) -> list[dict]: videos = session.scalars( select(Video) .where(Video.status != "ignored") .order_by(func.coalesce(Video.published_at, Video.created_at).desc(), Video.id.desc()) .limit(200) ).all() return [ { "id": video.id, "title": video.title, "sourceUrl": video.source_url, "status": video.status, "progressPercent": video.progress_percent, "progressStage": video.progress_stage, "durationSeconds": video.duration_seconds, "createdAt": video.created_at, "publishedAt": video.published_at, "errorMessage": video.error_message, "articleIds": [article.id for article in video.articles if article.status != "rejected"], "articles": [ { "id": article.id, "title": article.title, "status": article.status, } for article in video.articles if article.status != "rejected" ], } for video in videos ] @router.post("/api/videos/{video_id}/process") def process_video_route(video_id: int) -> dict[str, str]: with SessionLocal() as session: video = session.get(Video, video_id) if not video: raise HTTPException(status_code=404, detail="Video not found") was_active = video.status in {"queued", "processing"} video.status = "queued" video.progress_percent = 1 video.progress_stage = "В очереди" action = "задача перезапущена" if was_active else "задача поставлена в обработку" video.progress_log = f"[{datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S')}] В очереди: {action}" video.error_message = None session.commit() task = process_video.delay(video_id) return {"taskId": task.id} @router.delete("/api/videos/{video_id}") def ignore_video(video_id: int, session: Session = Depends(get_session)) -> dict[str, int | str]: video = session.get(Video, video_id) if not video: raise HTTPException(status_code=404, detail="Video not found") video.status = "ignored" video.progress_percent = 0 video.progress_stage = "Удалено" video.error_message = None video.progress_log = f"[{datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S')}] Удалено: ролик исключен из обработки и повторного импорта" for article in video.articles: if article.status != "published": article.status = "rejected" session.commit() return {"id": video.id, "status": video.status} def delete_source_video_file(video: Video | None) -> None: if not video or not video.local_video_path: return path = Path(video.local_video_path) if path.exists() and path.is_file(): path.unlink() video.local_video_path = None def video_log_payload(video: Video) -> dict[str, str | int | None]: return { "id": video.id, "title": video.title, "status": video.status, "progressPercent": video.progress_percent, "progressStage": video.progress_stage, "progressLog": video.progress_log or "", "errorMessage": video.error_message, } @router.get("/api/videos/{video_id}/logs") def video_logs(video_id: int, session: Session = Depends(get_session)) -> dict[str, str | int | None]: video = session.get(Video, video_id) if not video: raise HTTPException(status_code=404, detail="Video not found") return video_log_payload(video) @router.websocket("/api/videos/{video_id}/logs/ws") async def video_logs_ws(websocket: WebSocket, video_id: int) -> None: await websocket.accept() last_payload: dict[str, str | int | None] | None = None try: while True: with SessionLocal() as session: video = session.get(Video, video_id) if not video: await websocket.send_json({"errorMessage": "Video not found", "status": "error"}) await websocket.close(code=1008) return payload = video_log_payload(video) if payload != last_payload: await websocket.send_json(payload) last_payload = payload await asyncio.sleep(1) except WebSocketDisconnect: return @router.get("/api/articles") def list_articles( status: str | None = Query(default=None), limit: int = Query(default=10, ge=1, le=50), offset: int = Query(default=0, ge=0), session: Session = Depends(get_session), settings: Settings = Depends(get_settings), ) -> dict: filters = [Article.status != "rejected"] if status: filters.append(Article.status == status) total = session.scalar(select(func.count(Article.id)).where(*filters)) or 0 articles = session.scalars( select(Article) .where(*filters) .order_by(func.coalesce(Article.published_at, Article.created_at).desc(), Article.id.desc()) .offset(offset) .limit(limit) ).all() items = [ { "id": article.id, "title": article.title, "slug": article.slug, "status": article.status, "url": article_url(settings, article), "createdAt": article.created_at, "publishedAt": article.published_at, } for article in articles ] return {"items": items, "total": total, "limit": limit, "offset": offset, "hasMore": offset + len(items) < total} @router.get("/api/articles/{article_id}") def get_article(article_id: int, session: Session = Depends(get_session), settings: Settings = Depends(get_settings)) -> dict: article = session.get(Article, article_id) if not article: raise HTTPException(status_code=404, detail="Article not found") return { "id": article.id, "title": article.title, "slug": article.slug, "status": article.status, "videoId": article.video_id, "url": article_url(settings, article), "createdAt": article.created_at, "publishedAt": article.published_at, "contentHtml": render_article_html(article), "editableHtml": editable_article_html(article), } @router.patch("/api/articles/{article_id}") def update_article(article_id: int, payload: ArticleUpdateIn, session: Session = Depends(get_session), settings: Settings = Depends(get_settings)) -> dict: article = session.get(Article, article_id) if not article: raise HTTPException(status_code=404, detail="Article not found") title = payload.title.strip() body = sanitize_article_editor_html(payload.editableHtml) body = strip_leading_duplicate_title(body, title) if not title: raise HTTPException(status_code=422, detail="Title is required") lead, body_html = split_lead_and_body(body) try: validate_article_content(title, lead, body_html) except RuntimeError as exc: raise HTTPException(status_code=422, detail=str(exc)) from exc article.title = title article.lead = lead article.body_html = body_html session.commit() session.refresh(article) return { "id": article.id, "title": article.title, "slug": article.slug, "status": article.status, "videoId": article.video_id, "url": article_url(settings, article), "createdAt": article.created_at, "publishedAt": article.published_at, "contentHtml": render_article_html(article), "editableHtml": editable_article_html(article), } @router.post("/api/articles/{article_id}/random-frame") def random_article_frame(article_id: int, session: Session = Depends(get_session), settings: Settings = Depends(get_settings)) -> dict[str, str | int]: article = session.get(Article, article_id) if not article: raise HTTPException(status_code=404, detail="Article not found") if not article.video: raise HTTPException(status_code=422, detail="У статьи нет исходного видео.") path, public_url, timestamp = create_random_frame(article.video, settings) frame = Frame( video_id=article.video.id, local_path=str(path), public_url=public_url, timestamp_seconds=timestamp, score=1, reason="Кадр выбран вручную редактором через случайную замену в админке.", selected=False, ) session.add(frame) session.commit() return { "url": public_url, "timestampSeconds": timestamp, } @router.delete("/api/articles/{article_id}") def delete_article(article_id: int, session: Session = Depends(get_session)) -> dict[str, str | int]: article = session.get(Article, article_id) if not article: raise HTTPException(status_code=404, detail="Article not found") article.status = "rejected" article.published_at = None article.rss_guid = None session.commit() return {"id": article.id, "status": "deleted"} @router.post("/api/uploads/images") async def upload_image(file: UploadFile = File(...), settings: Settings = Depends(get_settings)) -> dict[str, str]: if not file.content_type or not file.content_type.startswith("image/"): raise HTTPException(status_code=422, detail="Only image files are supported") suffix = Path(file.filename or "").suffix.lower() if suffix not in {".jpg", ".jpeg", ".png", ".webp", ".gif"}: suffix = ".jpg" date_dir = datetime.now(timezone.utc).strftime("%Y%m%d") upload_dir = settings.media_path / "uploads" / date_dir upload_dir.mkdir(parents=True, exist_ok=True) filename = f"{uuid4().hex}{suffix}" target = upload_dir / filename size = 0 with target.open("wb") as output: while chunk := await file.read(1024 * 1024): size += len(chunk) if size > 12 * 1024 * 1024: output.close() target.unlink(missing_ok=True) raise HTTPException(status_code=413, detail="Image is too large") output.write(chunk) os.chmod(target, 0o644) return {"url": f"{settings.public_base_url.rstrip('/')}/media/uploads/{date_dir}/{filename}"} @router.post("/api/articles/{article_id}/publish") def publish_article( article_id: int, payload: ArticlePublishIn | None = Body(default=None), session: Session = Depends(get_session), settings: Settings = Depends(get_settings), ) -> dict: article = session.get(Article, article_id) if not article: raise HTTPException(status_code=404, detail="Article not found") try: validate_article_content(article.title, article.lead, article.body_html) except RuntimeError as exc: raise HTTPException(status_code=422, detail=str(exc)) from exc published_at = payload.publishedAt if payload and payload.publishedAt else datetime.now(timezone.utc) if published_at.tzinfo is None: published_at = published_at.replace(tzinfo=timezone.utc) published_at = published_at.astimezone(timezone.utc) article.status = "published" article.published_at = published_at article.rss_guid = f"{article_url(settings, article)}?rss_guid={int(published_at.timestamp())}-{article.id}" delete_source_video_file(article.video) session.commit() return {"status": "published", "url": article_url(settings, article), "publishedAt": article.published_at} @router.post("/api/chat") def chat(payload: ChatIn) -> dict[str, str]: text = payload.message.strip().lower() if "скан" in text or "проверь" in text: task = scan_sources.delay() return {"message": f"Запустил проверку источников. Task: {task.id}"} return { "message": "Я пока MVP-ассистент: умею запускать проверку источников, показывать ролики, черновики и публиковать статьи в RSS.", }