import io import mimetypes from typing import Dict, Optional, Tuple from aiohttp import web import db from cfg import bot, logger # Кэш в памяти: file_id -> (байты, content-type). _cache: Dict[str, Tuple[bytes, str]] = {} async def get_media(file_id: str) -> Optional[Tuple[bytes, str]]: if file_id in _cache: return _cache[file_id] try: f = await bot.get_file(file_id) buf = io.BytesIO() await bot.download_file(f.file_path, buf) data = buf.getvalue() except Exception as e: logger.warning("media download: %s", e) return None ctype = mimetypes.guess_type(f.file_path or "")[0] or "application/octet-stream" _cache[file_id] = (data, ctype) return data, ctype async def media_handler(request) -> web.Response: try: msg_id = int(request.match_info["msg_id"]) except ValueError: raise web.HTTPNotFound() row = await db.get_msg(msg_id) if not row or not row.get("media_file_id"): raise web.HTTPNotFound() result = await get_media(row["media_file_id"]) if not result: raise web.HTTPNotFound() data, ctype = result return web.Response( body=data, content_type=ctype, headers={"Cache-Control": "public, max-age=86400"} )