import base64 import json from datetime import datetime from typing import Any from uuid import UUID def encode_cursor(chat_id: str, created_at: str, entity_id: str) -> str: payload = json.dumps({"c": chat_id, "t": created_at, "i": entity_id}, separators=(",", ":")) return base64.urlsafe_b64encode(payload.encode("utf-8")).decode("ascii").rstrip("=") def _validate_cursor_timestamp(value: str) -> None: if not value.endswith("Z"): raise ValueError("invalid cursor timestamp") try: datetime.fromisoformat(value[:-1] + "+00:00") except ValueError as exc: raise ValueError("invalid cursor timestamp") from exc def _require_str_field(data: dict, key: str) -> str: if key not in data: raise ValueError("invalid cursor") value = data[key] if not isinstance(value, str): raise ValueError("invalid cursor") return value def decode_cursor(cursor: str, expected_chat_id: str) -> tuple[str, str]: pad = "=" * (-len(cursor) % 4) try: raw = base64.urlsafe_b64decode((cursor + pad).encode("ascii")) data: Any = json.loads(raw.decode("utf-8")) except (ValueError, json.JSONDecodeError, UnicodeDecodeError) as exc: raise ValueError("invalid cursor") from exc if not isinstance(data, dict): raise ValueError("invalid cursor") try: chat_id = _require_str_field(data, "c") created_at = _require_str_field(data, "t") entity_id = _require_str_field(data, "i") except ValueError as exc: raise ValueError("invalid cursor") from exc if chat_id != expected_chat_id: raise ValueError("cursor chat mismatch") try: UUID(entity_id) except ValueError as exc: raise ValueError("invalid cursor") from exc try: _validate_cursor_timestamp(created_at) except ValueError as exc: raise ValueError("invalid cursor") from exc return created_at, entity_id