diff --git a/src/aiogram_dialog/context/media_storage.py b/src/aiogram_dialog/context/media_storage.py index 40425b3a..3af4a84a 100644 --- a/src/aiogram_dialog/context/media_storage.py +++ b/src/aiogram_dialog/context/media_storage.py @@ -1,5 +1,5 @@ import os -from typing import Optional +from typing import NamedTuple, Optional, cast from aiogram.types import ContentType from cachetools import LRUCache @@ -8,6 +8,11 @@ from aiogram_dialog.api.protocols import MediaIdStorageProtocol +class CachedMediaId(NamedTuple): + media_id: MediaId + mtime: Optional[float] + + class MediaIdStorage(MediaIdStorageProtocol): def __init__(self, maxsize=10240): self.cache = LRUCache(maxsize=maxsize) @@ -20,14 +25,18 @@ async def get_media_id( ) -> Optional[MediaId]: if not path and not url: return None - cached = self.cache.get((path, url, type)) + cached = cast( + Optional[CachedMediaId], + self.cache.get((path, url, type)), + ) if cached is None: return None - if cached[1] is not None: + + if cached.mtime is not None: mtime = self._get_file_mtime(path) - if mtime is not None and mtime != cached[1]: + if mtime is not None and mtime != cached.mtime: return None - return cached[0] + return cached.media_id def _get_file_mtime(self, path: Optional[str]) -> Optional[float]: if not path: @@ -45,4 +54,7 @@ async def save_media_id( ) -> None: if not path and not url: return - self.cache[(path, url, type)] = (media_id, self._get_file_mtime(path)) + self.cache[(path, url, type)] = CachedMediaId( + media_id, + self._get_file_mtime(path), + )