douyinWEB/backend/app/pb_sync.py
eric 47d17aee3c Document YouTube groups and Shorts side-path; sync dual-platform pipeline.
Add isolated Shorts OAuth/clip/upload worker (default off), youtube-svc + group poller, Beijing time UX, and SHORTS.md.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-10 00:04:06 -05:00

493 lines
18 KiB
Python

"""
PocketBase sync — canonical admin datastore for rooms/sessions.
Monitor still uses SQLite as the hot-path worker DB; every mutation dual-writes here.
Media binaries live on SeaweedFS S3; only URLs are stored in PB/SQLite.
"""
from __future__ import annotations
import hashlib
import time
from typing import Any, Optional
import httpx
from .config import settings
_token: str = ""
_token_expire: float = 0
def _pb_id(sqlite_id: str) -> str:
"""PocketBase record id: 15-char [a-z0-9]."""
return hashlib.md5(str(sqlite_id).encode("utf-8")).hexdigest()[:15]
async def _client() -> httpx.AsyncClient:
return httpx.AsyncClient(
base_url=settings.pb_url.rstrip("/"),
timeout=20.0,
trust_env=False,
)
async def ensure_admin() -> None:
global _token, _token_expire
async with await _client() as client:
try:
resp = await client.post(
"/api/collections/_superusers/auth-with-password",
json={"identity": settings.pb_admin_email, "password": settings.pb_admin_password},
)
if resp.status_code == 200:
data = resp.json()
_token = data.get("token") or ""
_token_expire = time.time() + 3600
return
except Exception:
pass
try:
resp = await client.post(
"/api/collections/_superusers/records",
json={
"email": settings.pb_admin_email,
"password": settings.pb_admin_password,
"passwordConfirm": settings.pb_admin_password,
},
)
if resp.status_code in (200, 201):
login = await client.post(
"/api/collections/_superusers/auth-with-password",
json={"identity": settings.pb_admin_email, "password": settings.pb_admin_password},
)
if login.status_code == 200:
_token = login.json().get("token") or ""
_token_expire = time.time() + 3600
return
except Exception:
pass
# keep previous token only if still valid; otherwise clear
if time.time() > _token_expire:
_token = ""
async def _auth_headers(*, force: bool = False) -> dict[str, str]:
global _token, _token_expire
if force or not _token or time.time() > _token_expire - 60:
await ensure_admin()
return {"Authorization": _token} if _token else {}
COLLECTION_DEFS: list[dict[str, Any]] = [
{
"name": "dy_rooms",
"type": "base",
"fields": [
{"name": "url", "type": "url", "required": True},
{"name": "room_id", "type": "text", "required": True},
{"name": "note", "type": "text"},
{"name": "tags", "type": "text"},
{"name": "enabled", "type": "bool"},
{"name": "last_status", "type": "text"},
{"name": "last_anchor", "type": "text"},
{"name": "last_title", "type": "text"},
{"name": "sqlite_id", "type": "text"},
],
},
{
"name": "dy_blacklist",
"type": "base",
"fields": [
{"name": "value", "type": "text", "required": True},
{"name": "room_id", "type": "text"},
{"name": "reason", "type": "text"},
{"name": "sqlite_id", "type": "text"},
],
},
{
"name": "dy_sessions",
"type": "base",
"fields": [
{"name": "room_id", "type": "text"},
{"name": "room_pk", "type": "text"},
{"name": "source_url", "type": "url"},
{"name": "anchor_name", "type": "text"},
{"name": "title", "type": "text"},
{"name": "started_at", "type": "number"},
{"name": "ended_at", "type": "number"},
{"name": "duration_seconds", "type": "number"},
{"name": "push_date", "type": "text"},
{"name": "status", "type": "text"},
{"name": "end_reason", "type": "text"},
{"name": "cover_url", "type": "url"},
{"name": "cover_path", "type": "text"},
{"name": "platform", "type": "text"},
{"name": "group_id", "type": "text"},
{"name": "video_id", "type": "text"},
{"name": "sqlite_id", "type": "text"},
],
},
{
"name": "dy_events",
"type": "base",
"fields": [
{"name": "ts", "type": "number"},
{"name": "kind", "type": "text"},
{"name": "level", "type": "text"},
{"name": "message", "type": "text"},
{"name": "room_id", "type": "text"},
{"name": "session_id", "type": "text"},
{"name": "anchor_name", "type": "text"},
{"name": "platform", "type": "text"},
{"name": "group_id", "type": "text"},
{"name": "sqlite_id", "type": "text"},
],
},
{
"name": "yt_groups",
"type": "base",
"fields": [
{"name": "name", "type": "text", "required": True},
{"name": "platform", "type": "text"},
{"name": "channel_url", "type": "url"},
{"name": "channel_key", "type": "text"},
{"name": "channel_id", "type": "text"},
{"name": "handle", "type": "text"},
{"name": "urls", "type": "text"},
{"name": "url_count", "type": "number"},
{"name": "note", "type": "text"},
{"name": "enabled", "type": "bool"},
{"name": "last_status", "type": "text"},
{"name": "last_title", "type": "text"},
{"name": "last_live_url", "type": "url"},
{"name": "last_live_video_id", "type": "text"},
{"name": "last_checked_at", "type": "number"},
{"name": "next_check_at", "type": "number"},
{"name": "error_count", "type": "number"},
{"name": "last_error", "type": "text"},
{"name": "active_session_id", "type": "text"},
{"name": "sqlite_id", "type": "text"},
],
},
]
def _field_names(col_json: dict[str, Any]) -> set[str]:
names: set[str] = set()
for f in col_json.get("fields") or col_json.get("schema") or []:
n = f.get("name")
if n:
names.add(n)
return names
async def _ensure_fields(client: httpx.AsyncClient, headers: dict[str, str], col_def: dict[str, Any]) -> list[str]:
"""Add missing fields onto an existing PocketBase collection."""
name = col_def["name"]
resp = await client.get(f"/api/collections/{name}", headers=headers)
if resp.status_code != 200:
return [f"{name}: fetch {resp.status_code}"]
col = resp.json()
existing = _field_names(col)
missing = [f for f in col_def["fields"] if f["name"] not in existing]
if not missing:
return []
# PocketBase 0.22+ uses "fields"
fields = list(col.get("fields") or [])
if not fields and col.get("schema"):
fields = list(col.get("schema") or [])
for f in missing:
fields.append(dict(f))
payload = {"fields": fields}
patch = await client.patch(f"/api/collections/{name}", headers=headers, json=payload)
if patch.status_code not in (200, 204):
return [f"{name}: patch fields {patch.status_code} {patch.text[:180]}"]
return []
async def ensure_collections() -> dict[str, Any]:
await ensure_admin()
headers = await _auth_headers()
created: list[str] = []
updated: list[str] = []
skipped: list[str] = []
errors: list[str] = []
async with await _client() as client:
existing = await client.get("/api/collections", headers=headers)
by_name: dict[str, Any] = {}
if existing.status_code == 200:
for item in existing.json().get("items") or []:
by_name[item.get("name")] = item
for col in COLLECTION_DEFS:
if col["name"] in by_name:
field_errs = await _ensure_fields(client, headers, col)
if field_errs:
errors.extend(field_errs)
else:
updated.append(col["name"])
continue
payload = {
"name": col["name"],
"type": col["type"],
"fields": [
{"name": "id", "type": "text", "primaryKey": True, "system": True},
*col["fields"],
{"name": "created", "type": "autodate", "onCreate": True, "onUpdate": False},
{"name": "updated", "type": "autodate", "onCreate": True, "onUpdate": True},
],
}
resp = await client.post("/api/collections", headers=headers, json=payload)
if resp.status_code in (200, 201):
created.append(col["name"])
else:
errors.append(f"{col['name']}: {resp.status_code} {resp.text[:200]}")
return {
"created": created,
"updated": updated,
"skipped": skipped,
"errors": errors,
"ok": not errors,
}
async def upsert_record(collection: str, sqlite_id: str, data: dict[str, Any]) -> Optional[str]:
headers = await _auth_headers()
if not headers:
headers = await _auth_headers(force=True)
if not headers:
return None
async with await _client() as client:
filt = f'sqlite_id="{sqlite_id}"'
found = await client.get(
f"/api/collections/{collection}/records",
headers=headers,
params={"filter": filt, "perPage": 1},
)
if found.status_code == 401:
headers = await _auth_headers(force=True)
if not headers:
return None
found = await client.get(
f"/api/collections/{collection}/records",
headers=headers,
params={"filter": filt, "perPage": 1},
)
body = {**data, "sqlite_id": sqlite_id}
if found.status_code == 200 and (found.json().get("items") or []):
rid = found.json()["items"][0]["id"]
resp = await client.patch(
f"/api/collections/{collection}/records/{rid}",
headers=headers,
json=body,
)
if resp.status_code in (200, 204):
return rid
return None
# PocketBase text PK collections require explicit id on create
body["id"] = _pb_id(sqlite_id)
resp = await client.post(
f"/api/collections/{collection}/records",
headers=headers,
json=body,
)
if resp.status_code in (200, 201):
return resp.json().get("id") or body["id"]
# conflict: try fetch again / patch
if resp.status_code in (400, 409):
found2 = await client.get(
f"/api/collections/{collection}/records",
headers=headers,
params={"filter": filt, "perPage": 1},
)
if found2.status_code == 200 and (found2.json().get("items") or []):
rid = found2.json()["items"][0]["id"]
await client.patch(
f"/api/collections/{collection}/records/{rid}",
headers=headers,
json={k: v for k, v in body.items() if k != "id"},
)
return rid
return None
async def delete_record(collection: str, sqlite_id: str) -> bool:
headers = await _auth_headers()
if not headers:
return False
async with await _client() as client:
filt = f'sqlite_id="{sqlite_id}"'
found = await client.get(
f"/api/collections/{collection}/records",
headers=headers,
params={"filter": filt, "perPage": 5},
)
if found.status_code != 200:
return False
ok = False
for item in found.json().get("items") or []:
rid = item.get("id")
if not rid:
continue
resp = await client.delete(f"/api/collections/{collection}/records/{rid}", headers=headers)
if resp.status_code in (200, 204):
ok = True
return ok
def _http_url(raw: Any) -> str:
text = str(raw or "").strip()
if text.startswith("http://") or text.startswith("https://"):
return text
return ""
def _meta_dict(row: dict[str, Any]) -> dict[str, Any]:
meta = row.get("meta") or row.get("metadata") or {}
if isinstance(meta, str):
try:
import json
meta = json.loads(meta or "{}")
except Exception:
meta = {}
return meta if isinstance(meta, dict) else {}
async def sync_room(room: dict[str, Any]) -> None:
tags = room.get("tags") or ""
if isinstance(tags, list):
tags = ",".join(str(t) for t in tags)
await upsert_record(
"dy_rooms",
room["id"],
{
"url": room.get("url") or "",
"room_id": room.get("room_id") or "",
"note": room.get("note") or "",
"tags": tags,
"enabled": bool(room.get("enabled")),
"last_status": room.get("last_status") or "",
"last_anchor": room.get("last_anchor") or "",
"last_title": room.get("last_title") or "",
},
)
async def sync_session(session: dict[str, Any]) -> None:
cover = _http_url(session.get("cover_path") or session.get("cover_url"))
meta = _meta_dict(session)
platform = str(meta.get("platform") or session.get("platform") or "")
if not platform and str(session.get("room_id") or "").startswith("yt:"):
platform = "youtube"
if not platform:
platform = "douyin"
source_url = _http_url(session.get("source_url")) or ""
payload: dict[str, Any] = {
"room_id": session.get("room_id") or "",
"room_pk": session.get("room_pk") or "",
"anchor_name": session.get("anchor_name") or "",
"title": session.get("title") or "",
"started_at": session.get("started_at") or 0,
"ended_at": session.get("ended_at") or 0,
"duration_seconds": session.get("duration_seconds") or 0,
"push_date": session.get("push_date") or "",
"status": session.get("status") or "",
"end_reason": session.get("end_reason") or "",
"cover_path": session.get("cover_path") or "",
"platform": platform,
"group_id": str(meta.get("group_id") or (session.get("room_pk") if platform == "youtube" else "") or ""),
"video_id": str(meta.get("video_id") or ""),
}
if source_url:
payload["source_url"] = source_url
if cover:
payload["cover_url"] = cover
await upsert_record("dy_sessions", session["id"], payload)
async def sync_event(event: dict[str, Any]) -> None:
eid = str(event.get("id") or "")
if not eid:
return
meta = _meta_dict(event)
platform = str(meta.get("platform") or event.get("platform") or "")
if not platform and str(event.get("room_id") or "").startswith("yt:"):
platform = "youtube"
if not platform:
platform = "douyin"
await upsert_record(
"dy_events",
eid,
{
"ts": event.get("ts") or 0,
"kind": event.get("kind") or "",
"level": event.get("level") or "",
"message": event.get("message") or "",
"room_id": event.get("room_id") or "",
"session_id": event.get("session_id") or "",
"anchor_name": event.get("anchor_name") or "",
"platform": platform,
"group_id": str(meta.get("group_id") or ""),
},
)
async def sync_channel_group(group: dict[str, Any]) -> Optional[str]:
gid = str(group.get("id") or "")
if not gid:
return None
urls = group.get("urls") or []
if isinstance(urls, list):
urls_s = "\n".join(str(u) for u in urls if str(u).strip())
url_count = len([u for u in urls if str(u).strip()])
else:
urls_s = str(urls)
url_count = int(group.get("url_count") or 0)
channel_url = _http_url(group.get("channel_url"))
live_url = _http_url(group.get("last_live_url"))
payload: dict[str, Any] = {
"name": group.get("name") or "",
"platform": group.get("platform") or "youtube",
"channel_key": group.get("channel_key") or "",
"channel_id": group.get("channel_id") or "",
"handle": group.get("handle") or "",
"urls": urls_s,
"url_count": url_count,
"note": group.get("note") or "",
"enabled": bool(group.get("enabled")),
"last_status": group.get("last_status") or "",
"last_title": group.get("last_title") or "",
"last_live_video_id": group.get("last_live_video_id") or "",
"last_checked_at": float(group.get("last_checked_at") or 0),
"next_check_at": float(group.get("next_check_at") or 0),
"error_count": int(group.get("error_count") or 0),
"last_error": group.get("last_error") or "",
"active_session_id": group.get("active_session_id") or "",
}
if channel_url:
payload["channel_url"] = channel_url
if live_url:
payload["last_live_url"] = live_url
return await upsert_record("yt_groups", gid, payload)
async def delete_channel_group(sqlite_id: str) -> bool:
return await delete_record("yt_groups", sqlite_id)
async def health() -> dict[str, Any]:
try:
async with await _client() as client:
resp = await client.get("/api/health")
ok = resp.status_code == 200
body: Any
try:
body = resp.json()
except Exception:
body = resp.text[:200]
return {"ok": ok, "status_code": resp.status_code, "body": body}
except Exception as exc:
return {"ok": False, "error": str(exc)}