e5ac8bdfba
- web/crosspost_client.py: POST /api/v1/items (source vesti, external_ref vesti:<post_id>, медиа путём) - web/publish.py: при флаге и is_own=0 публикация уходит в crosspost, пост получает статус crossposted - web/app.py: метка/цвет статуса crossposted - scripts/crosspost_sync.py: GET /api/v1/queue -> published(tg_message_id), status=published, views - change openspec crosspost-publish (proposal, design, tasks, spec delta)
117 lines
4.3 KiB
Python
117 lines
4.3 KiB
Python
#!/usr/bin/env python3
|
||
"""Синхронизация crosspost → вести: доставленные новости становятся published.
|
||
|
||
Зачем: очередь и слоты теперь в crosspost, поэтому `tg_message_id` и просмотры приходят не от
|
||
publisher-service, а из `GET /api/v1/queue`. Скрипт запускается кроном каждые 5 минут.
|
||
|
||
Тихий: при отсутствии работы ничего не печатает. Ошибки доставок пишутся в logs/crosspost-sync.log.
|
||
"""
|
||
import fcntl
|
||
import json
|
||
import sys
|
||
from datetime import datetime
|
||
from pathlib import Path
|
||
|
||
import httpx
|
||
|
||
BASE = Path(__file__).resolve().parent.parent
|
||
sys.path.insert(0, str(BASE))
|
||
|
||
from config import CROSSPOST_KEY, CROSSPOST_SOURCE, CROSSPOST_URL, PUBLISH_TZ # noqa: E402
|
||
from web.db import db, migrate # noqa: E402
|
||
|
||
LOG_PATH = BASE / "logs" / "crosspost-sync.log"
|
||
LOCK_PATH = BASE / "logs" / "crosspost-sync.lock"
|
||
TIMEOUT = 20.0
|
||
|
||
|
||
def log(message: str) -> None:
|
||
LOG_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||
with LOG_PATH.open("a", encoding="utf-8") as fh:
|
||
fh.write(f"{datetime.now():%Y-%m-%d %H:%M:%S}\t{message}\n")
|
||
|
||
|
||
def fetch(status: str, limit: int = 500) -> list[dict]:
|
||
r = httpx.get(f"{CROSSPOST_URL}/api/v1/queue",
|
||
params={"status": status, "limit": limit},
|
||
headers={"Authorization": f"Bearer {CROSSPOST_KEY}"}, timeout=TIMEOUT)
|
||
r.raise_for_status()
|
||
return r.json().get("items", [])
|
||
|
||
|
||
def post_id_of(external_ref: str) -> int | None:
|
||
prefix = f"{CROSSPOST_SOURCE}:"
|
||
if not external_ref.startswith(prefix):
|
||
return None
|
||
tail = external_ref[len(prefix):].strip()
|
||
return int(tail) if tail.isdigit() else None
|
||
|
||
|
||
def views_for(message_id: str) -> int:
|
||
if not message_id or not message_id.isdigit():
|
||
return 0
|
||
from web.publisher_client import get_views
|
||
return int(get_views("dedinit_vesti", int(message_id)) or 0)
|
||
|
||
|
||
def main() -> int:
|
||
if not CROSSPOST_KEY:
|
||
log("CROSSPOST_KEY не задан — синхронизация пропущена")
|
||
return 0
|
||
|
||
LOCK_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||
with LOCK_PATH.open("w") as lock:
|
||
try:
|
||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||
except BlockingIOError:
|
||
return 0 # предыдущий прогон ещё идёт
|
||
|
||
try:
|
||
sent = fetch("sent")
|
||
failed = fetch("failed")
|
||
except Exception as e:
|
||
log(f"crosspost недоступен: {e}")
|
||
return 0
|
||
|
||
migrate()
|
||
conn = db()
|
||
done = 0
|
||
try:
|
||
for row in sent:
|
||
pid = post_id_of(row.get("external_ref") or "")
|
||
if pid is None:
|
||
continue
|
||
exists = conn.execute("SELECT 1 FROM published WHERE post_id=? LIMIT 1", (pid,)).fetchone()
|
||
if exists:
|
||
continue
|
||
post = conn.execute("SELECT id, status FROM posts WHERE id=?", (pid,)).fetchone()
|
||
if post is None:
|
||
log(f"доставка #{row['id']}: пост {pid} не найден в вести")
|
||
continue
|
||
conn.execute(
|
||
"INSERT INTO published (post_id, bundle_path, tg_message_id, views, distributed_dirs)"
|
||
" VALUES (?,?,?,?,?)",
|
||
(pid, "", str(row.get("external_id") or ""), views_for(str(row.get("external_id") or "")),
|
||
json.dumps([row.get("target")], ensure_ascii=False)),
|
||
)
|
||
conn.execute("UPDATE posts SET status='published', scheduled_at=NULL WHERE id=?", (pid,))
|
||
conn.commit()
|
||
done += 1
|
||
log(f"published: пост {pid} → message_id={row.get('external_id')} ({row.get('target')})")
|
||
|
||
for row in failed:
|
||
pid = post_id_of(row.get("external_ref") or "")
|
||
if pid is None:
|
||
continue
|
||
log(f"failed: пост {pid} ({row.get('target')}), попыток {row.get('attempts')}: {row.get('error')}")
|
||
finally:
|
||
conn.close()
|
||
|
||
if done:
|
||
print(json.dumps({"published": done}, ensure_ascii=False))
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
raise SystemExit(main())
|