import aiohttp import logging from typing import Optional, Dict, Any from config import LICHESS_API_BASE_URL, LICHESS_STATS_API_BASE_URL from rate_limiter import get_rate_limiter logger = logging.getLogger(__name__) class InvalidTokenError(Exception): """Raised when Lichess rejects a stored token (401) — permanent, not worth retrying.""" pass class LichessAPI: def __init__(self): self.lichess_base_url = LICHESS_API_BASE_URL self.stats_base_url = LICHESS_STATS_API_BASE_URL # Only for calls that go to lichess.org directly (anonymous / user-token # endpoints with their own Lichess limits). Calls to our local stats service # are not paced here: its SharedTokenGate (LichessWebServices/rate_limiter.py) # is the real limiter for the shared Lichess token, and a bot-side delay in # front of it only added latency. self.rate_limiter = get_rate_limiter() async def get_user_profile(self, token: str) -> Optional[Dict[str, Any]]: """Get user profile from Lichess API using token""" await self.rate_limiter.wait_if_needed() headers = {"Authorization": f"Bearer {token}"} try: async with aiohttp.ClientSession() as session: async with session.get( f"{self.lichess_base_url}/account", headers=headers ) as response: if response.status == 200: return await response.json() else: error_text = await response.text() logger.error(f"Failed to get user profile: {response.status} - {error_text}") return None except Exception as e: logger.error(f"Error getting user profile: {e}") import traceback logger.error(traceback.format_exc()) return None async def get_today_stats(self, username: str) -> Optional[Dict[str, Any]]: """Get today's statistics from our stats API""" logger.info(f"🔍 LichessAPI.get_today_stats: username={username}, stats_base_url={self.stats_base_url}") url = f"{self.stats_base_url}/stats/{username}/today" logger.info(f"🔍 Making request to: {url}") try: async with aiohttp.ClientSession() as session: async with session.get(url) as response: logger.info(f"🔍 Response status: {response.status} for {username}") if response.status == 200: result = await response.json() logger.info(f"🔍 Successfully got stats for {username}: {result.get('message', 'no message')}") return result else: error_text = await response.text() logger.error(f"❌ Failed to get today stats for {username}: status={response.status}, error={error_text[:200]}") return None except aiohttp.ClientError as e: logger.error(f"❌ Client error getting today stats for {username}: {e}") import traceback logger.error(traceback.format_exc()) return None except Exception as e: logger.error(f"❌ Error getting today stats for {username}: {e}") import traceback logger.error(traceback.format_exc()) return None async def get_yesterday_stats(self, username: str) -> Optional[Dict[str, Any]]: """Get yesterday's statistics from our stats API""" try: async with aiohttp.ClientSession() as session: async with session.get( f"{self.stats_base_url}/stats/{username}/yesterday" ) as response: if response.status == 200: return await response.json() else: logger.error(f"Failed to get yesterday stats: {response.status}") return None except Exception as e: logger.error(f"Error getting yesterday stats: {e}") return None async def get_week_stats(self, username: str) -> Optional[Dict[str, Any]]: """Get week's statistics from our stats API""" try: async with aiohttp.ClientSession() as session: async with session.get( f"{self.stats_base_url}/stats/{username}/week" ) as response: if response.status == 200: return await response.json() else: logger.error(f"Failed to get week stats: {response.status}") return None except Exception as e: logger.error(f"Error getting week stats: {e}") return None async def get_games_period(self, username: str, since: int, until: int, rated_only: Optional[bool] = None, include_games: bool = False, priority: str = "background", by_finish: bool = False) -> Optional[Dict[str, Any]]: """ Get games for a specific period. priority="interactive" (e.g. the accuracy fetch behind /today, /yesterday, /week) jumps ahead of "background" (periodic_check) in the stats service's shared Lichess-token queue, so an on-demand command doesn't wait behind the whole periodic-check backlog. by_finish=True selects games by the time they FINISHED (lastMoveAt in (since, until]) instead of by creation time, which is what Lichess's own since/until filter uses; see the stats service for the semantics. periodic_check uses it so that a game is reported in the window in which it ended. Default False keeps creation-time semantics. """ try: url = f"{self.stats_base_url}/games/{username}/period" params = {"since": since, "until": until, "priority": priority} if rated_only is not None: params["rated_only"] = "true" if rated_only else "false" if include_games: params["include_games"] = "true" if by_finish: params["by_finish"] = "true" logger.debug(f"🔍 LichessAPI.get_games_period: URL={url}, params={params}") async with aiohttp.ClientSession() as session: async with session.get(url, params=params) as response: logger.debug(f"🔍 LichessAPI.get_games_period: response.status={response.status}") if response.status == 200: result = await response.json() logger.debug(f"🔍 LichessAPI.get_games_period: result={result}") return result elif response.status == 404: # The stats service answers 404 only for "user not found" on # Lichess (deleted / renamed account). Not an error of ours: # periodic_check backs off as for any None, and the bulk # status refresh pauses the pair within two refreshes. logger.warning(f"{username} not found on Lichess (404)") return None else: logger.error(f"Failed to get games period: {response.status}") return None except Exception as e: logger.error(f"Error getting games period: {e}") return None async def get_service_health(self, timeout: float = 10.0) -> Optional[Dict[str, Any]]: """ GET /health of our stats service: {'status', 'timestamp', 'service', 'lichess_429_24h', 'lichess_429_total'} or None when it does not answer (used for the lichess_429 field of the daily SUMMARY line and by the admin bot's /status, which passes a short timeout: it is interactive). Never raises. """ try: async with aiohttp.ClientSession() as session: async with session.get( f"{self.stats_base_url}/health", timeout=aiohttp.ClientTimeout(total=timeout) ) as response: if response.status == 200: return await response.json() logger.warning(f"Stats service /health answered {response.status}") return None except Exception as e: logger.warning(f"Stats service /health unavailable: {e}") return None async def get_puzzles_period(self, token: str, since: int, until: int, max_puzzles: int = 150) -> Optional[Dict[str, Any]]: """ Get puzzles for a specific period. Raises InvalidTokenError on a 401 (Lichess rejected the token — permanent, the caller should stop retrying with this token) instead of returning None, so callers can tell that apart from a transient failure (network error, Lichess hiccup) where retrying the same window later makes sense. """ headers = {"Authorization": f"Bearer {token}"} try: async with aiohttp.ClientSession() as session: async with session.get( f"{self.stats_base_url}/puzzle/period", headers=headers, params={"since": since, "until": until, "max": max_puzzles} ) as response: if response.status == 200: return await response.json() elif response.status == 401: logger.warning(f"Puzzles period: token rejected by Lichess (401)") raise InvalidTokenError("Lichess rejected the token") else: logger.error(f"Failed to get puzzles period: {response.status}") return None except InvalidTokenError: raise except Exception as e: logger.error(f"Error getting puzzles period: {e}") return None async def get_users_status(self, usernames) -> Optional[list]: """ Bulk status of up to 300 players from our stats API (POST /users/status, one Lichess request behind it). Returns the list of {'username', 'id', 'disabled', 'seen_at', 'games_total'} dicts for the names Lichess knows (unknown names are simply absent), or None on any failure. Local-service call: not paced by the bot-side rate limiter. """ usernames = list(usernames) if not usernames: return [] try: async with aiohttp.ClientSession() as session: async with session.post( f"{self.stats_base_url}/users/status", json={"usernames": usernames} ) as response: if response.status == 200: result = await response.json() return result.get('players') or [] else: error_text = await response.text() logger.error(f"Failed to get users status: {response.status} - {error_text[:200]}") return None except Exception as e: logger.error(f"Error getting users status: {e}") return None async def check_user_exists(self, username: str) -> Optional[Dict[str, Any]]: """ Check if user exists on Lichess. Returns a dict for an existing account: {'username': , 'disabled': bool} (Lichess answers 200 for closed accounts too, with "disabled": true — the caller must reject those, they can't be tracked), False for a definitive "not found" (404), or None if the check itself failed (rate limit, network error, unexpected status) — callers must not treat None as "not found", since the username may well be valid. """ await self.rate_limiter.wait_if_needed() try: async with aiohttp.ClientSession() as session: async with session.get( f"{self.lichess_base_url}/user/{username}" ) as response: if response.status == 200: data = await response.json() return { 'username': data.get('username') or username, 'disabled': bool(data.get('disabled', False)), } elif response.status == 404: logger.warning(f"User {username} not found on Lichess (404)") return False else: logger.error(f"Failed to check user existence: {response.status}") return None except Exception as e: logger.error(f"Error checking user existence: {e}") return None async def get_user_ratings(self, username: str) -> Optional[Dict[str, Any]]: """Get user ratings from Lichess API""" await self.rate_limiter.wait_if_needed() try: async with aiohttp.ClientSession() as session: async with session.get( f"{self.lichess_base_url}/user/{username}" ) as response: if response.status == 200: return await response.json() else: logger.error(f"Failed to get user ratings: {response.status}") return None except Exception as e: logger.error(f"Error getting user ratings: {e}") return None