from __future__ import annotations import logging import httpx logger = logging.getLogger(__name__) class WorkplaceStatus: async def probe(self, account: dict) -> dict: token = account.get("access_token", "") app_id = account.get("app_id", "") app_secret = account.get("app_secret", "") api_version = account.get("graph_api_version", "v24.0") results = { "healthy": False, "token_valid": False, "community_accessible": False, "webhook_subscribed": False, "community_id": None, "page_id": None, "error": None, } base_url = f"https://graph.facebook.com/{api_version}" async with httpx.AsyncClient(timeout=15.0) as client: try: resp = await client.get( f"{base_url}/me", params={"access_token": token, "fields": "id,name"}, ) if resp.status_code == 200: data = resp.json() results["token_valid"] = True results["healthy"] = True results["page_id"] = data.get("id") logger.info("Workplace token valid, page_id=%s", data.get("id")) else: results["error"] = f"Token validation failed: {resp.status_code} {resp.text[:200]}" logger.warning("Workplace token invalid: %s", results["error"]) return results resp = await client.get( f"{base_url}/community", params={"access_token": token}, ) if resp.status_code == 200: data = resp.json() results["community_id"] = data.get("id") results["community_accessible"] = True logger.info("Workplace community accessible: id=%s", data.get("id")) if app_id and app_secret: app_token = f"{app_id}|{app_secret}" resp = await client.get( f"{base_url}/{app_id}/subscriptions", params={"access_token": app_token}, ) if resp.status_code == 200: data = resp.json() subscriptions = data.get("data", []) if subscriptions: results["webhook_subscribed"] = True logger.info("Workplace webhook subscribed: %d subscriptions", len(subscriptions)) except httpx.RequestError as exc: results["error"] = str(exc) results["healthy"] = False logger.error("Workplace probe network error: %s", exc) return results @staticmethod def build_summary(snapshot) -> dict: if snapshot is None: return {"state": "unknown"} return { "channel": "workplace", "state": "running" if getattr(snapshot, "running", False) else "stopped", "account_id": getattr(snapshot, "account_id", ""), "last_probe_at": getattr(snapshot, "last_probe_at", None), "last_message_at": getattr(snapshot, "last_message_at", None), }