57 lines
1.7 KiB
Python
57 lines
1.7 KiB
Python
import threading
|
|
|
|
from server.services.device import DeviceProfile
|
|
|
|
|
|
class SessionStore:
|
|
def __init__(self) -> None:
|
|
self._lock = threading.Lock()
|
|
self._devices: dict[str, DeviceProfile] = {}
|
|
self._active = ""
|
|
self._profile: dict | None = None
|
|
self._revision = 0
|
|
|
|
def bind(self, token: str, device: DeviceProfile, replace: bool = False) -> DeviceProfile:
|
|
with self._lock:
|
|
if replace or token not in self._devices:
|
|
self._devices[token] = device
|
|
return self._devices[token]
|
|
|
|
def device_for(self, token: str) -> DeviceProfile | None:
|
|
with self._lock:
|
|
return self._devices.get(token)
|
|
|
|
def remember(self, token: str, profile: dict) -> None:
|
|
with self._lock:
|
|
self._active = token
|
|
self._profile = dict(profile)
|
|
self._revision += 1
|
|
|
|
def set_profile(self, token: str, profile: dict) -> bool:
|
|
with self._lock:
|
|
if token != self._active:
|
|
return False
|
|
self._profile = dict(profile)
|
|
self._revision += 1
|
|
return True
|
|
|
|
def active_token(self) -> str:
|
|
with self._lock:
|
|
return self._active
|
|
|
|
def snapshot(self) -> dict | None:
|
|
with self._lock:
|
|
if not self._active or self._profile is None:
|
|
return None
|
|
return {"profile": dict(self._profile), "revision": self._revision}
|
|
|
|
def clear(self, token: str) -> None:
|
|
with self._lock:
|
|
self._devices.pop(token, None)
|
|
if self._active == token:
|
|
self._active = ""
|
|
self._profile = None
|
|
|
|
|
|
sessions = SessionStore()
|