forked from mtusi2026/mtusi2026lab2
44 lines
1.3 KiB
Python
44 lines
1.3 KiB
Python
import base64
|
|
import json
|
|
import re
|
|
import uuid
|
|
from datetime import datetime, timezone
|
|
|
|
TS_RE = re.compile(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}Z")
|
|
TS_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ"
|
|
|
|
|
|
class BadCursor(Exception):
|
|
pass
|
|
|
|
|
|
def fmt(ts: datetime) -> str:
|
|
return ts.astimezone(timezone.utc).strftime(TS_FORMAT)
|
|
|
|
|
|
def encode_cursor(scope: str, created_at: str, item_id: str) -> str:
|
|
raw = json.dumps({"s": scope, "t": created_at, "i": item_id}, separators=(",", ":")).encode()
|
|
return base64.urlsafe_b64encode(raw).decode().rstrip("=")
|
|
|
|
|
|
def decode_cursor(scope: str, cursor: str):
|
|
try:
|
|
raw = base64.urlsafe_b64decode(cursor + "=" * (-len(cursor) % 4))
|
|
data = json.loads(raw)
|
|
except Exception:
|
|
raise BadCursor() from None
|
|
if not isinstance(data, dict) or set(data) != {"s", "t", "i"} or data["s"] != scope:
|
|
raise BadCursor()
|
|
ts, item_id = data["t"], data["i"]
|
|
if not isinstance(ts, str) or not TS_RE.fullmatch(ts) or not isinstance(item_id, str):
|
|
raise BadCursor()
|
|
try:
|
|
parsed = datetime.strptime(ts, TS_FORMAT).replace(tzinfo=timezone.utc)
|
|
if str(uuid.UUID(item_id)) != item_id:
|
|
raise BadCursor()
|
|
except ValueError:
|
|
raise BadCursor() from None
|
|
if encode_cursor(scope, ts, item_id) != cursor:
|
|
raise BadCursor()
|
|
return parsed, item_id
|