Files
TGLotteryBot/backend/app/api/routers/users.py
T
Stardream eace48732d
Build and Push Docker Images / build (push) Successful in 17s
Initial release
2026-06-02 12:02:02 +10:00

34 lines
1.2 KiB
Python

import time
from fastapi import APIRouter
from fastapi.responses import Response
router = APIRouter(tags=["users"])
# user_id → (bytes, content_type, expires_at)
_avatar_cache: dict[int, tuple[bytes, str, float]] = {}
@router.get("/users/{user_id}/avatar")
async def get_user_avatar(user_id: int) -> Response:
from app.core.config import settings
ttl = settings.avatar_cache_ttl
cached = _avatar_cache.get(user_id)
if cached and time.monotonic() < cached[2]:
return Response(content=cached[0], media_type=cached[1],
headers={"Cache-Control": f"public, max-age={ttl}"})
from app.bot.router import bot
try:
photos = await bot.get_user_profile_photos(user_id, limit=1)
if not photos.photos:
return Response(status_code=404)
file_id = photos.photos[0][-1].file_id
data = await bot.download(file_id)
content = data.read()
content_type = "image/jpeg"
_avatar_cache[user_id] = (content, content_type, time.monotonic() + ttl)
return Response(content=content, media_type=content_type,
headers={"Cache-Control": f"public, max-age={ttl}"})
except Exception:
return Response(status_code=404)