This commit is contained in:
@@ -0,0 +1,33 @@
|
||||
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)
|
||||
Reference in New Issue
Block a user