feat(queue): publish queue with slots, /plan page and dry-run runner
This commit is contained in:
+93
-67
@@ -22,6 +22,10 @@ try: # bleach — санитайзер HTML из RSS (allowlist); см. require
|
||||
except ImportError:
|
||||
bleach = None
|
||||
|
||||
from web.publish import impl_approve
|
||||
from web import queue
|
||||
from config import PUBLISH_QUEUE_LIVE, PUBLISH_SLOTS, PUBLISH_TZ
|
||||
|
||||
# CRUD источников: работа с sources.yaml (источник истины) + БД синк
|
||||
from sources.sources import (
|
||||
db_source_to_yaml,
|
||||
@@ -137,18 +141,9 @@ def _db() -> sqlite3.Connection:
|
||||
|
||||
|
||||
def _migrate():
|
||||
"""Идемпотентные миграции при старте веб-сервиса."""
|
||||
conn = sqlite3.connect(DB_PATH, timeout=10)
|
||||
try:
|
||||
cols = [r[1] for r in conn.execute("PRAGMA table_info(posts)").fetchall()]
|
||||
if "is_read" not in cols:
|
||||
conn.execute("ALTER TABLE posts ADD COLUMN is_read INTEGER DEFAULT 0")
|
||||
conn.commit()
|
||||
if "translated_text" not in cols:
|
||||
conn.execute("ALTER TABLE posts ADD COLUMN translated_text TEXT")
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
"""Идемпотентные миграции при старте веб-сервиса (реализация — web/db.py)."""
|
||||
from web.db import migrate
|
||||
migrate()
|
||||
|
||||
|
||||
_migrate()
|
||||
@@ -206,10 +201,11 @@ def _is_htmx(request: Request) -> bool:
|
||||
def _htmx_refresh(back: str) -> Response:
|
||||
"""204 + HX-Trigger → клиент перезапрашивает список и деталь без перезагрузки.
|
||||
|
||||
Два события: refresh-list (левая панель) и refresh-detail (правая деталь).
|
||||
Три события: refresh-list (левая панель), refresh-detail (правая деталь),
|
||||
refresh-plan (очередь на /plan; если слушателя нет — событие игнорируется).
|
||||
"""
|
||||
return Response(status_code=204, headers={
|
||||
"HX-Trigger": "refresh-list, refresh-detail",
|
||||
"HX-Trigger": "refresh-list, refresh-detail, refresh-plan",
|
||||
"HX-Push-Url": back,
|
||||
})
|
||||
|
||||
@@ -343,11 +339,12 @@ def _translate_text(text: str) -> str:
|
||||
STATUS_LABELS = {
|
||||
"new": "💎 Новые",
|
||||
"selected": "⭐ Отобранные",
|
||||
"queued": "🗓 В плане",
|
||||
"rejected": "🗑 Отклонённые",
|
||||
"published": "✅ Опубликованные",
|
||||
"": "Все",
|
||||
}
|
||||
STATUS_COLORS = {"new": "success", "selected": "warning", "rejected": "danger", "published": "primary"}
|
||||
STATUS_COLORS = {"new": "success", "selected": "warning", "queued": "info", "rejected": "danger", "published": "primary"}
|
||||
|
||||
|
||||
def _group_label(group_by: str, key: str) -> str:
|
||||
@@ -643,6 +640,19 @@ def candidates_bulk(request: Request, action: str = Form(...), ids: list[int] =
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return _htmx_or_redirect(request, back)
|
||||
if action == "enqueue":
|
||||
# поставить отмеченные посты в план публикации (каждый получает следующий слот)
|
||||
ok, errs = 0, []
|
||||
for r in rows:
|
||||
try:
|
||||
queue.enqueue(conn, int(r["id"]))
|
||||
ok += 1
|
||||
except Exception as e:
|
||||
errs.append(f"{r['id']}({e})")
|
||||
conn.close()
|
||||
if errs:
|
||||
return RedirectResponse(url=f"/plan?error=enqueue_partial:{quote(','.join(map(str, errs))[:120])}&did={ok}", status_code=302)
|
||||
return RedirectResponse(url=f"/plan?did=queued:{ok}", status_code=302)
|
||||
conn.close()
|
||||
if action == "process":
|
||||
# обработка локальной моделью (переклассификация) по выбранным
|
||||
@@ -878,64 +888,80 @@ def published(request: Request, year: str = "", month: str = "", nodate: str = "
|
||||
return HTMLResponse(html)
|
||||
|
||||
|
||||
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 publisher.card import make_card
|
||||
from web.store import create_bundle
|
||||
# ---------- План публикаций: очередь и слоты (change publish-queue) ----------
|
||||
|
||||
@app.post("/posts/{post_id}/enqueue")
|
||||
def post_enqueue(post_id: int, request: Request,
|
||||
group_by: str = Form(""), direction: str = Form(""), own: str = Form(""),
|
||||
q: str = Form(""), src: str = Form("selected")):
|
||||
"""Поставить отобранный пост в план публикации: status='queued' + ближайший свободный слот."""
|
||||
_require_auth(request)
|
||||
back = _cand_back(group_by, direction, own, q, src=src, selected=post_id)
|
||||
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:
|
||||
p = conn.execute("SELECT id FROM posts WHERE id=?", (post_id,)).fetchone()
|
||||
if not p:
|
||||
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
|
||||
|
||||
return RedirectResponse(url=back + "&error=notfound", status_code=302)
|
||||
try:
|
||||
res = http_publish(card)
|
||||
except RuntimeError as e:
|
||||
queue.enqueue(conn, post_id)
|
||||
except ValueError:
|
||||
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)}
|
||||
|
||||
import json as _json
|
||||
conn.execute("UPDATE posts SET status='published', comment=? 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()
|
||||
return RedirectResponse(url=back + "&error=no_slot", status_code=302)
|
||||
conn.close()
|
||||
return None
|
||||
return _htmx_or_redirect(request, back)
|
||||
|
||||
|
||||
@app.get("/plan", response_class=HTMLResponse)
|
||||
def plan_page(request: Request, error: str = "", did: str = ""):
|
||||
"""Контент-план: очередь публикаций по слотам."""
|
||||
_require_auth(request)
|
||||
conn = _db()
|
||||
rows = [dict(r) for r in queue.queue_rows(conn)]
|
||||
ahead = queue.days_ahead(conn)
|
||||
conn.close()
|
||||
return HTMLResponse(tpl.get_template("plan.html").render(
|
||||
rows=rows, ahead=ahead, slots=PUBLISH_SLOTS, live=PUBLISH_QUEUE_LIVE,
|
||||
next_slot=rows[0]["scheduled_at"] if rows else "", now=queue.fmt(queue.now_local()),
|
||||
tz_name=PUBLISH_TZ, error=error, did=did,
|
||||
))
|
||||
|
||||
|
||||
def _plan_move(request: Request, post_id: int, direction: str) -> Response:
|
||||
_require_auth(request)
|
||||
conn = _db()
|
||||
ok = queue.move(conn, post_id, direction)
|
||||
conn.close()
|
||||
return RedirectResponse(url="/plan" if ok else "/plan?error=move", status_code=302)
|
||||
|
||||
|
||||
@app.post("/plan/{post_id}/up")
|
||||
def plan_up(post_id: int, request: Request):
|
||||
return _plan_move(request, post_id, "up")
|
||||
|
||||
|
||||
@app.post("/plan/{post_id}/down")
|
||||
def plan_down(post_id: int, request: Request):
|
||||
return _plan_move(request, post_id, "down")
|
||||
|
||||
|
||||
@app.post("/plan/{post_id}/dequeue")
|
||||
def plan_dequeue(post_id: int, request: Request):
|
||||
"""Снять с плана: пост возвращается в «Отобранные», время очищается."""
|
||||
_require_auth(request)
|
||||
conn = _db()
|
||||
queue.dequeue(conn, post_id)
|
||||
conn.close()
|
||||
return RedirectResponse(url="/plan", status_code=302)
|
||||
|
||||
|
||||
@app.post("/plan/{post_id}/publish-now")
|
||||
def plan_publish_now(post_id: int, request: Request):
|
||||
"""Опубликовать мимо расписания (кнопка 🚀 на /plan, подтверждение в форме)."""
|
||||
_require_auth(request)
|
||||
err = impl_approve(post_id)
|
||||
if err:
|
||||
return RedirectResponse(url=f"/plan?error=publish:{quote(err)}", status_code=302)
|
||||
return RedirectResponse(url="/published", status_code=302)
|
||||
|
||||
|
||||
@app.post("/posts/{post_id}/approve")
|
||||
|
||||
Reference in New Issue
Block a user