Initialize local project and fix ranch growth synchronization
This commit is contained in:
@@ -0,0 +1,68 @@
|
||||
"""Per-account and per-role encrypted sessions, including request high-water marks."""
|
||||
import base64
|
||||
from dataclasses import asdict
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import threading
|
||||
|
||||
from .api import Session
|
||||
from .credentials import crypt
|
||||
|
||||
|
||||
def identity(session):
|
||||
owner = session.account_id or session.server_url.rstrip("/")
|
||||
raw = json.dumps([owner, session.channel, session.platform, session.server_id, session.role_id], separators=(",", ":"))
|
||||
return hashlib.sha256(raw.encode()).hexdigest()
|
||||
|
||||
|
||||
class SessionStore:
|
||||
def __init__(self, root):
|
||||
self.folder = Path(root) / "sessions"
|
||||
self.lock = threading.RLock()
|
||||
|
||||
def save(self, session, label):
|
||||
if not session.token or not session.server_url or not session.role_id:
|
||||
return None
|
||||
key = identity(session)
|
||||
payload = json.dumps(asdict(session), ensure_ascii=False).encode("utf-8")
|
||||
record = {"schema": 1, "session_id": key, "label": label,
|
||||
"saved_at": datetime.now(timezone(timedelta(hours=8))).isoformat(timespec="seconds"),
|
||||
"protected": base64.b64encode(crypt(payload)).decode("ascii")}
|
||||
with self.lock:
|
||||
self.folder.mkdir(parents=True, exist_ok=True)
|
||||
path = self.folder / (key + ".json")
|
||||
temporary = path.with_suffix(".tmp")
|
||||
temporary.write_text(json.dumps(record, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
temporary.replace(path)
|
||||
return key
|
||||
|
||||
def entries(self):
|
||||
result = []
|
||||
with self.lock:
|
||||
for path in self.folder.glob("*.json"):
|
||||
try:
|
||||
record = json.loads(path.read_text(encoding="utf-8"))
|
||||
if record.get("schema") == 1 and record.get("session_id") == path.stem:
|
||||
result.append({k: record[k] for k in ("session_id", "label", "saved_at")})
|
||||
except (OSError, ValueError, KeyError):
|
||||
continue
|
||||
return sorted(result, key=lambda record: record["saved_at"], reverse=True)
|
||||
|
||||
def load(self, key):
|
||||
if not isinstance(key, str) or len(key) != 64 or any(c not in "0123456789abcdef" for c in key):
|
||||
raise ValueError("无效的会话编号")
|
||||
with self.lock:
|
||||
record = json.loads((self.folder / (key + ".json")).read_text(encoding="utf-8"))
|
||||
payload = crypt(base64.b64decode(record["protected"], validate=True), decrypt=True)
|
||||
session = Session(**json.loads(payload))
|
||||
if identity(session) != key or not session.role_id or not session.token:
|
||||
raise ValueError("保存的账号/区服/角色信息不一致")
|
||||
return session
|
||||
|
||||
def remove(self, key):
|
||||
# load() validates the identifier before constructing any removable path.
|
||||
self.load(key)
|
||||
with self.lock:
|
||||
(self.folder / (key + ".json")).unlink()
|
||||
Reference in New Issue
Block a user