""" PocketBase bootstrap + lightweight sync helpers. Local SQLite is the hot path for the monitor worker. PocketBase is used as the admin-facing datastore / backup mirror. """ from __future__ import annotations import time from typing import Any, Optional import httpx from .config import settings _token: str = "" _token_expire: float = 0 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 login 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 # first-time install 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 except Exception: pass async def _auth_headers() -> dict[str, str]: global _token, _token_expire if 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": "enabled", "type": "bool"}, {"name": "last_status", "type": "text"}, {"name": "last_anchor", "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": "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": "sqlite_id", "type": "text"}, ], }, ] async def ensure_collections() -> dict[str, Any]: await ensure_admin() headers = await _auth_headers() created: list[str] = [] skipped: list[str] = [] errors: list[str] = [] async with await _client() as client: existing = await client.get("/api/collections", headers=headers) names = set() if existing.status_code == 200: for item in existing.json().get("items") or []: names.add(item.get("name")) for col in COLLECTION_DEFS: if col["name"] in names: skipped.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, "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: 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}, ) body = {**data, "sqlite_id": sqlite_id} if found.status_code == 200 and (found.json().get("items") or []): rid = found.json()["items"][0]["id"] await client.patch( f"/api/collections/{collection}/records/{rid}", headers=headers, json=body, ) return rid 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") return None async def sync_room(room: dict[str, Any]) -> None: await upsert_record( "dy_rooms", room["id"], { "url": room.get("url") or "", "room_id": room.get("room_id") or "", "note": room.get("note") or "", "enabled": bool(room.get("enabled")), "last_status": room.get("last_status") or "", "last_anchor": room.get("last_anchor") or "", }, ) async def sync_session(session: dict[str, Any]) -> None: await upsert_record( "dy_sessions", session["id"], { "room_id": session.get("room_id") or "", "source_url": session.get("source_url") 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 "", }, ) 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)}