Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add check modified time for path #460

Merged
merged 7 commits into from
Jan 22, 2025
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 17 additions & 2 deletions src/aiogram_dialog/context/media_storage.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import os
from typing import Optional

from aiogram.types import ContentType
Expand All @@ -19,7 +20,21 @@ async def get_media_id(
) -> Optional[MediaId]:
if not path and not url:
return None
return self.cache.get((path, url, type))
cached = self.cache.get((path, url, type))
if cached is None:
return None
if cached[1] is not None:
mtime = self._get_file_mtime(path)
if mtime is not None and mtime != cached[1]:
return None
return cached[0]

def _get_file_mtime(self, path: Optional[str]) -> Optional[float]:
if not path:
return None
if not os.path.exists(path): # noqa: PTH110
return None
return os.path.getmtime(path) # noqa: PTH204

async def save_media_id(
self,
Expand All @@ -30,4 +45,4 @@ async def save_media_id(
) -> None:
if not path and not url:
return
self.cache[(path, url, type)] = media_id
self.cache[(path, url, type)] = (media_id, self._get_file_mtime(path))
50 changes: 50 additions & 0 deletions tests/widgets/media/test_media_storage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import asyncio
import os
import tempfile

import pytest
from aiogram.enums import ContentType

from aiogram_dialog.context.media_storage import MediaIdStorage


@pytest.mark.asyncio
async def test_get_media_id():
manager = MediaIdStorage()
with tempfile.TemporaryDirectory() as d:
filename = os.path.join(d, "file_test") # noqa: PTH118
media_id = await manager.get_media_id(
filename,
None,
ContentType.DOCUMENT,
)
assert media_id is None

with open(filename, "w") as file: # noqa: PTH123
file.write("test1")

await manager.save_media_id(
filename,
None,
ContentType.DOCUMENT,
"test1",
)

media_id = await manager.get_media_id(
filename,
None,
ContentType.DOCUMENT,
)
assert media_id == "test1"

await asyncio.sleep(0.1)

with open(filename, "w") as file: # noqa: PTH123
file.write("test2")

media_id = await manager.get_media_id(
filename,
None,
ContentType.DOCUMENT,
)
assert media_id is None
Loading