Skip to content

Commit

Permalink
named tuple for cached media id
Browse files Browse the repository at this point in the history
  • Loading branch information
KurosawaAngel committed Jan 22, 2025
1 parent b3fab2d commit 99b8d88
Showing 1 changed file with 18 additions and 6 deletions.
24 changes: 18 additions & 6 deletions src/aiogram_dialog/context/media_storage.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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)
Expand All @@ -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:
Expand All @@ -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),
)

0 comments on commit 99b8d88

Please sign in to comment.