feat(queue): publish queue with slots, /plan page and dry-run runner
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
# Публикация поста: publisher-сервис + бандл + запись в published.
|
||||
# Модуль НЕ импортирует FastAPI — его использует и веб-приложение, и фоновый
|
||||
# публикатор очереди (scripts/publish_runner.py), которому незачем поднимать app.
|
||||
import json
|
||||
|
||||
from config import BASE_DIR
|
||||
from publisher.card import make_card
|
||||
from web.db import db
|
||||
|
||||
|
||||
def impl_approve(post_id: int, comment: str = "", dirs_selected: list[str] | None = None) -> str | None:
|
||||
"""Публикация поста: publisher + бандл + статус published. Возвращает None при успехе,
|
||||
строку ошибки при неудаче (для bulk — собираем ошибки, для POST — редирект с error)."""
|
||||
from web.publisher_client import publish as http_publish
|
||||
from web.store import create_bundle
|
||||
|
||||
conn = db()
|
||||
post = conn.execute("SELECT p.*, s.name source_name, s.lang FROM posts p LEFT JOIN sources s ON s.id=p.source_id WHERE p.id=?", (post_id,)).fetchone()
|
||||
if not post:
|
||||
conn.close()
|
||||
return "notfound"
|
||||
post = dict(post)
|
||||
is_own = int(post.get("is_own") or 0) == 1
|
||||
dirn = post.get("direction") or "linux"
|
||||
lang = post.get("lang") or "ru"
|
||||
|
||||
if dirs_selected is None:
|
||||
# по умолчанию: направления классификации (classifications) или направление поста
|
||||
cls = conn.execute("SELECT direction FROM classifications WHERE post_id=? ORDER BY id", (post_id,)).fetchall()
|
||||
dirs_selected = [r["direction"] for r in cls] if cls else [dirn]
|
||||
dirs_selected = list(dict.fromkeys([d for d in dirs_selected if d]))
|
||||
|
||||
card = make_card(post, comment)
|
||||
card["direction"] = dirn
|
||||
card["lang"] = lang
|
||||
|
||||
try:
|
||||
res = http_publish(card)
|
||||
except RuntimeError as e:
|
||||
conn.close()
|
||||
return f"publisher:{e}"
|
||||
|
||||
_res = res.get("results", {})
|
||||
# свой контент: ключи — направления; внешний: ключи — каналы
|
||||
if is_own:
|
||||
tg_message_id = next(iter((r or {}).get("message_id") or 0 for r in _res.values()), 0) if res else 0
|
||||
views_by_dir = {d: (r.get("views") or 0) for d, r in _res.items()}
|
||||
else:
|
||||
tg_message_id = next((r.get("message_id") or 0 for r in _res.values() if r.get("message_id")), 0) if _res else 0
|
||||
views_by_dir = {d: (r.get("views") or 0) for d, r in _res.items()}
|
||||
|
||||
# банк статей (markdown-бандл + медиа) — по каждому направлению fan-out
|
||||
try:
|
||||
bundle = create_bundle(post, bundles_dir=BASE_DIR / "bundles", directions=dirs_selected)
|
||||
except Exception as e:
|
||||
bundle = {"error": str(e)}
|
||||
|
||||
conn.execute("UPDATE posts SET status='published', comment=?, scheduled_at=NULL WHERE id=?", (comment.strip(), post_id))
|
||||
distributed = json.dumps(dirs_selected, ensure_ascii=False) if is_own else json.dumps([dirn])
|
||||
conn.execute(
|
||||
"INSERT INTO published (post_id, bundle_path, tg_message_id, distributed_dirs, views) VALUES (?,?,?,?,?)",
|
||||
(post_id, bundle.get("path", ""), tg_message_id, distributed, sum(views_by_dir.values())),
|
||||
)
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return None
|
||||
Reference in New Issue
Block a user