import logging import httpx logger = logging.getLogger(__name__) DOWNLOAD_URL = "https://upload.api.weibo.com/2/mss/msget" class WeiboMedia: def __init__(self, access_token_provider): self._token_provider = access_token_provider self._http: httpx.AsyncClient | None = None async def _client(self) -> httpx.AsyncClient: if self._http is None: self._http = httpx.AsyncClient(timeout=30.0) return self._http async def download(self, tovfid: str) -> dict: token = self._token_provider() if not token: return {"success": False, "error": "no access_token"} url = f"{DOWNLOAD_URL}?access_token={token}&fid={tovfid}" try: client = await self._client() resp = await client.get(url) content_type = resp.headers.get("content-type", "") if "application/json" in content_type or resp.text.startswith("{"): data = resp.json() if "error_code" in data: logger.warning("Weibo media download failed: error_code=%s", data.get("error_code")) return {"success": False, "error": data.get("error", "download failed")} return { "success": True, "data": resp.content, "content_type": content_type, } except Exception as e: logger.exception("Weibo media download exception") return {"success": False, "error": str(e)} async def close(self): if self._http: await self._http.aclose() self._http = None