| 170 | |
| 171 | @app.get("/live") |
| 172 | async def live_status(): |
| 173 | import time |
| 174 | now = time.monotonic() |
| 175 | if now - _live_cache["last_checked"] < LIVE_CACHE_TTL: |
| 176 | return {"live": _live_cache["live"], "videoId": _live_cache["videoId"]} |
| 177 | |
| 178 | api_key = os.environ.get("YOUTUBE_API_KEY") |
| 179 | if not api_key: |
| 180 | return {"live": False, "videoId": None} |
| 181 | |
| 182 | url = "https://www.googleapis.com/youtube/v3/search" |
| 183 | params = { |
| 184 | "part": "id", |
| 185 | "channelId": YOUTUBE_CHANNEL_ID, |
| 186 | "eventType": "live", |
| 187 | "type": "video", |
| 188 | "key": api_key, |
| 189 | } |
| 190 | async with httpx.AsyncClient() as client: |
| 191 | resp = await client.get(url, params=params, timeout=10) |
| 192 | |
| 193 | if resp.status_code != 200: |
| 194 | _live_cache["last_checked"] = now |
| 195 | return {"live": False, "videoId": None} |
| 196 | |
| 197 | items = resp.json().get("items", []) |
| 198 | result = {"live": bool(items), "videoId": items[0]["id"]["videoId"] if items else None} |
| 199 | _live_cache.update({**result, "last_checked": now}) |
| 200 | return result |
| 201 | |
| 202 | |
| 203 | # Root path to check if service is running |