from __future__ import annotations from typing import Any import httpx from app.config import settings class PocketBaseClient: """可选:将书籍配置同步到 PocketBase;本地默认 USE_POCKETBASE=false 用 SQLite。""" def __init__(self): self.base = settings.pb_url.rstrip("/") self.token = "" async def login(self) -> bool: try: async with httpx.AsyncClient(timeout=10) as client: r = await client.post( f"{self.base}/api/collections/_superusers/auth-with-password", json={ "identity": settings.pb_admin_email, "password": settings.pb_admin_password, }, ) if r.status_code >= 400: # 兼容旧版 admins 集合 r = await client.post( f"{self.base}/api/admins/auth-with-password", json={ "identity": settings.pb_admin_email, "password": settings.pb_admin_password, }, ) if r.status_code >= 400: return False self.token = r.json().get("token", "") return bool(self.token) except Exception: return False def _headers(self) -> dict[str, str]: return {"Authorization": self.token} if self.token else {} async def upsert_book(self, book: dict[str, Any]) -> None: if not settings.use_pocketbase: return if not self.token and not await self.login(): return async with httpx.AsyncClient(timeout=15) as client: # 简化:按 id 查找,没有则创建 q = await client.get( f"{self.base}/api/collections/books/records", params={"filter": f'book_id="{book["id"]}"'}, headers=self._headers(), ) if q.status_code >= 400: return items = q.json().get("items") or [] payload = { "book_id": book["id"], "title": book["title"], "unlock_percent": book["unlock_percent"], "price_fen": book["price_fen"], "product_id": book["product_id"], "payload": book, } if items: rid = items[0]["id"] await client.patch( f"{self.base}/api/collections/books/records/{rid}", json=payload, headers=self._headers(), ) else: await client.post( f"{self.base}/api/collections/books/records", json=payload, headers=self._headers(), ) async def upsert_wx_reader(self, user: dict[str, Any]) -> str | None: """按 openid 绑定微信读者到 PocketBase 自定义集合 wx_readers。 不用 auth 密码用户:小程序登录靠 code2session,openid 是稳定主键。 集合字段建议:openid(unique text), unionid, status, notes, nickname, last_login_at。 """ if not settings.use_pocketbase: return user.get("pb_record_id") if not self.token and not await self.login(): return None openid = user.get("openid") if not openid: return None payload = { "openid": openid, "unionid": user.get("unionid") or "", "status": user.get("status") or "active", "notes": user.get("notes") or "", "nickname": user.get("nickname") or "", "last_login_at": user.get("updated_at"), } async with httpx.AsyncClient(timeout=15) as client: rid = user.get("pb_record_id") if rid: r = await client.patch( f"{self.base}/api/collections/wx_readers/records/{rid}", json=payload, headers=self._headers(), ) if r.status_code < 400: return rid q = await client.get( f"{self.base}/api/collections/wx_readers/records", params={"filter": f'openid="{openid}"', "perPage": 1}, headers=self._headers(), ) if q.status_code >= 400: return None items = q.json().get("items") or [] if items: rid = items[0]["id"] await client.patch( f"{self.base}/api/collections/wx_readers/records/{rid}", json=payload, headers=self._headers(), ) return rid created = await client.post( f"{self.base}/api/collections/wx_readers/records", json=payload, headers=self._headers(), ) if created.status_code >= 400: return None return created.json().get("id") pb = PocketBaseClient()