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

831 lines
30 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 subprocess
from uuid import uuid4
from fastapi import APIRouter, Body, Depends, File, HTTPException, Query, UploadFile, WebSocket, WebSocketDisconnect
from fastapi.responses import HTMLResponse, RedirectResponse, 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.chapters import chapter_to_payload, parse_video_chapters
from app.database import SessionLocal, get_session
from app.models import AppSetting, 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 best_thumbnail_url, 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"
class SourceIn(BaseModel):
name: str
url: str
source_type: str = "yt_dlp"
enabled: bool = True
class ManualVideoIn(BaseModel):
url: str
class AppSettingsIn(BaseModel):
signatureHtml: str = ""
llmInstructions: str = ""
class ChatIn(BaseModel):
message: str
class ArticleUpdateIn(BaseModel):
title: str
editableHtml: str
featureImageUrl: str | None = None
class ArticlePublishIn(BaseModel):
publishedAt: datetime | 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"
def app_settings_payload(session: Session) -> dict[str, str]:
values = {
setting.key: setting.value
for setting in session.scalars(
select(AppSetting).where(AppSetting.key.in_([SETTING_SIGNATURE, SETTING_LLM_INSTRUCTIONS]))
).all()
}
return {
"signatureHtml": values.get(SETTING_SIGNATURE, ""),
"llmInstructions": values.get(SETTING_LLM_INSTRUCTIONS, ""),
}
@router.get("/api/settings")
def get_app_settings(session: Session = Depends(get_session)) -> dict[str, str]:
return app_settings_payload(session)
@router.put("/api/settings")
def update_app_settings(payload: AppSettingsIn, session: Session = Depends(get_session)) -> dict[str, str]:
values = {
SETTING_SIGNATURE: payload.signatureHtml.strip(),
SETTING_LLM_INSTRUCTIONS: payload.llmInstructions.strip(),
}
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)
@router.get("/feed")
def feed(session: Session = Depends(get_session), settings: Settings = Depends(get_settings)) -> Response:
return Response(build_feed_xml(session, settings), media_type="application/rss+xml; charset=utf-8")
@router.head("/feed")
def feed_head(session: Session = Depends(get_session), settings: Settings = Depends(get_settings)) -> Response:
content = build_feed_xml(session, settings).encode("utf-8")
return Response(
headers={"Content-Length": str(len(content))},
media_type="application/rss+xml; charset=utf-8",
)
@router.get("/robots.txt")
def robots_txt(settings: Settings = Depends(get_settings)) -> Response:
content = f"""User-agent: *
Allow: /
Allow: /feed
Sitemap: {settings.public_base_url.rstrip("/")}/feed
"""
return Response(content, media_type="text/plain; charset=utf-8")
@router.head("/robots.txt")
def robots_txt_head(settings: Settings = Depends(get_settings)) -> Response:
content = f"""User-agent: *
Allow: /
Allow: /feed
Sitemap: {settings.public_base_url.rstrip("/")}/feed
""".encode("utf-8")
return Response(headers={"Content-Length": str(len(content))}, media_type="text/plain; charset=utf-8")
def plain_excerpt(html: str, limit: int = 260) -> str:
text = re.sub(r"<[^>]+>", " ", html)
text = re.sub(r"\s+", " ", unescape(text)).strip()
if len(text) <= limit:
return text
return text[:limit].rsplit(" ", 1)[0].strip() + "..."
class ArticleHtmlSanitizer(HTMLParser):
allowed_tags = {
"p",
"br",
"h2",
"h3",
"strong",
"b",
"em",
"i",
"u",
"s",
"ul",
"ol",
"li",
"blockquote",
"figure",
"figcaption",
"img",
"a",
}
void_tags = {"br", "img"}
allowed_attrs = {
"a": {"href", "title"},
"img": {"src", "alt"},
}
def __init__(self) -> None:
super().__init__(convert_charrefs=False)
self.parts: list[str] = []
self.skip_depth = 0
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
tag = tag.lower()
if tag in {"script", "style", "iframe", "object", "embed"}:
self.skip_depth += 1
return
if self.skip_depth or tag not in self.allowed_tags:
return
clean_attrs: list[str] = []
for name, value in attrs:
name = name.lower()
if value is None or name not in self.allowed_attrs.get(tag, set()):
continue
value = value.strip()
if name in {"href", "src"} and not re.match(r"^(https?://|/media/)", value, flags=re.I):
continue
clean_attrs.append(f'{name}="{escape(value, quote=True)}"')
attr_text = f" {' '.join(clean_attrs)}" if clean_attrs else ""
self.parts.append(f"<{tag}{attr_text}>")
def handle_endtag(self, tag: str) -> None:
tag = tag.lower()
if tag in {"script", "style", "iframe", "object", "embed"} and self.skip_depth:
self.skip_depth -= 1
return
if self.skip_depth or tag not in self.allowed_tags or tag in self.void_tags:
return
self.parts.append(f"</{tag}>")
def handle_data(self, data: str) -> None:
if not self.skip_depth:
self.parts.append(escape(data))
def handle_entityref(self, name: str) -> None:
if not self.skip_depth:
self.parts.append(f"&{name};")
def handle_charref(self, name: str) -> None:
if not self.skip_depth:
self.parts.append(f"&#{name};")
def sanitize_article_editor_html(html: str) -> str:
sanitizer = ArticleHtmlSanitizer()
sanitizer.feed(html)
sanitized = "".join(sanitizer.parts)
sanitized = 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 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:
html = "\n".join(part for part in [article.lead, article.body_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 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/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)}"
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, 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.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),
"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.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),
"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.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")
configured_signature = session.scalar(
select(AppSetting.value).where(AppSetting.key == SETTING_SIGNATURE)
) or ""
signature_html = article.cta_html or configured_signature
if signature_html.strip() and body.rstrip().endswith(signature_html.strip()):
body = body[: -len(signature_html.strip())].rstrip()
lead, body_html = split_lead_and_body(body)
article.title = title
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,
"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"}
@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.",
}