75 lines
2.3 KiB
Python
75 lines
2.3 KiB
Python
from __future__ import annotations
|
|
|
|
import json
|
|
from pathlib import Path
|
|
|
|
from app.models import Offer
|
|
|
|
|
|
class SentOffersStore:
|
|
def __init__(self, file_path: Path) -> None:
|
|
self._file_path = file_path
|
|
self._file_path.parent.mkdir(parents=True, exist_ok=True)
|
|
self._sent_keys = self._load()
|
|
|
|
def has(self, key: str) -> bool:
|
|
return key in self._sent_keys
|
|
|
|
def add(self, key: str) -> None:
|
|
self._sent_keys.add(key)
|
|
self._persist()
|
|
|
|
def _load(self) -> set[str]:
|
|
if not self._file_path.exists():
|
|
return set()
|
|
|
|
with self._file_path.open("r", encoding="utf-8") as file:
|
|
data = json.load(file)
|
|
|
|
return set(data)
|
|
|
|
def _persist(self) -> None:
|
|
with self._file_path.open("w", encoding="utf-8") as file:
|
|
json.dump(sorted(self._sent_keys), file, ensure_ascii=False, indent=2)
|
|
|
|
|
|
class PublishedOffersStore:
|
|
def __init__(self, file_path: Path) -> None:
|
|
self._file_path = file_path
|
|
self._file_path.parent.mkdir(parents=True, exist_ok=True)
|
|
self._offers_by_message_key = self._load()
|
|
|
|
def add(self, chat_id: int, message_id: int, offer: Offer) -> None:
|
|
self._offers_by_message_key[self._message_key(chat_id, message_id)] = offer.to_dict()
|
|
self._persist()
|
|
|
|
def get(self, chat_id: int, message_id: int) -> Offer | None:
|
|
data = self._offers_by_message_key.get(self._message_key(chat_id, message_id))
|
|
if data is None:
|
|
return None
|
|
return Offer.from_dict(data)
|
|
|
|
def remove(self, chat_id: int, message_id: int) -> None:
|
|
removed = self._offers_by_message_key.pop(self._message_key(chat_id, message_id), None)
|
|
if removed is not None:
|
|
self._persist()
|
|
|
|
def _load(self) -> dict[str, dict[str, str | int | None]]:
|
|
if not self._file_path.exists():
|
|
return {}
|
|
|
|
with self._file_path.open("r", encoding="utf-8") as file:
|
|
data = json.load(file)
|
|
|
|
if not isinstance(data, dict):
|
|
return {}
|
|
return data
|
|
|
|
def _persist(self) -> None:
|
|
with self._file_path.open("w", encoding="utf-8") as file:
|
|
json.dump(self._offers_by_message_key, file, ensure_ascii=False, indent=2)
|
|
|
|
@staticmethod
|
|
def _message_key(chat_id: int, message_id: int) -> str:
|
|
return f"{chat_id}:{message_id}"
|