208 lines
10 KiB
Python
208 lines
10 KiB
Python
"""Small configurable identity directory used by interactive character entry."""
|
||
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import os
|
||
import sqlite3
|
||
from dataclasses import dataclass
|
||
from pathlib import Path
|
||
from typing import Any
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class Identity:
|
||
"""Связка имени и ID персонажа из справочника."""
|
||
name: str
|
||
character_id: int
|
||
|
||
|
||
class IdentityDirectory:
|
||
"""
|
||
Справочник персонажей: разрешение и сохранение связок имя/ID.
|
||
|
||
Использует PostgreSQL (production) или SQLite (локально).
|
||
В памяти индексирует по ID и по имени (casefold).
|
||
"""
|
||
|
||
def __init__(self, identities: list[Identity] | None = None, db_path: str | Path | None = None,
|
||
database_url: str | None = None) -> None:
|
||
"""
|
||
Инициализация справочника с загрузкой из БД или JSON-переменной окружения.
|
||
|
||
Args:
|
||
identities: Предзагруженные идентичности (для тестов)
|
||
db_path: Путь к локальному SQLite-файлу
|
||
database_url: URL PostgreSQL-БД
|
||
"""
|
||
self.db_path = Path(db_path) if db_path else None
|
||
self.database_url = database_url or ""
|
||
self._by_id: dict[int, Identity] = {}
|
||
self._by_name: dict[str, Identity] = {}
|
||
self._profiles: dict[int, Identity] = {}
|
||
if self.database_url.startswith(("postgres://", "postgresql://")):
|
||
import psycopg
|
||
self._psycopg = psycopg
|
||
with psycopg.connect(self.database_url) as connection:
|
||
connection.execute(
|
||
"CREATE TABLE IF NOT EXISTS identities (character_id BIGINT PRIMARY KEY, name TEXT NOT NULL)"
|
||
)
|
||
connection.execute(
|
||
"CREATE TABLE IF NOT EXISTS profiles (actor_id BIGINT PRIMARY KEY, name TEXT NOT NULL, character_id BIGINT NOT NULL)"
|
||
)
|
||
identities = [Identity(name, character_id) for character_id, name in connection.execute(
|
||
"SELECT character_id, name FROM identities"
|
||
)]
|
||
elif self.db_path:
|
||
self.db_path.parent.mkdir(parents=True, exist_ok=True)
|
||
with sqlite3.connect(self.db_path) as connection:
|
||
connection.execute(
|
||
"CREATE TABLE IF NOT EXISTS identities (character_id INTEGER PRIMARY KEY, name TEXT NOT NULL)"
|
||
)
|
||
connection.execute(
|
||
"CREATE TABLE IF NOT EXISTS profiles (actor_id INTEGER PRIMARY KEY, name TEXT NOT NULL, character_id INTEGER NOT NULL)"
|
||
)
|
||
identities = [Identity(name, character_id) for character_id, name in connection.execute(
|
||
"SELECT character_id, name FROM identities"
|
||
)]
|
||
for item in identities or []:
|
||
self._index(item)
|
||
|
||
@classmethod
|
||
def from_environment(cls, *, persistent: bool = True) -> "IdentityDirectory":
|
||
"""
|
||
Создаёт справочник из переменных окружения.
|
||
|
||
Порядок загрузки:
|
||
1. BELKI_IDENTITIES_JSON — JSON со списком {name, id}
|
||
2. BELKI_DATABASE_URL — PostgreSQL (если persistent=True)
|
||
3. BELKI_IDENTITIES_DB — локальный SQLite-файл
|
||
|
||
Args:
|
||
persistent: Сохранять ли изменения в БД
|
||
"""
|
||
raw = os.getenv("BELKI_IDENTITIES_JSON", "")
|
||
identities: list[Identity] = []
|
||
try:
|
||
if raw:
|
||
data: Any = json.loads(raw)
|
||
rows = data.get("characters", data) if isinstance(data, dict) else data
|
||
identities = [Identity(name=str(row["name"]), character_id=int(row["id"])) for row in rows]
|
||
except (TypeError, ValueError, KeyError, json.JSONDecodeError) as exc:
|
||
raise ValueError("BELKI_IDENTITIES_JSON должен содержать список {name,id}") from exc
|
||
database_url = os.getenv("BELKI_DATABASE_URL", "") if persistent else ""
|
||
db_path = os.getenv("BELKI_IDENTITIES_DB", "data/belki.sqlite3") if persistent and not database_url else None
|
||
directory = cls(identities, db_path=db_path, database_url=database_url)
|
||
for item in identities:
|
||
directory.remember(name=item.name, character_id=item.character_id)
|
||
return directory
|
||
|
||
def _index(self, identity: Identity) -> None:
|
||
"""Добавляет идентичность в оба индекса (по ID и по имени)."""
|
||
self._by_id[identity.character_id] = identity
|
||
self._by_name[identity.name.casefold()] = identity
|
||
|
||
def resolve(self, *, name: str | None = None, character_id: int | None = None) -> Identity | None:
|
||
"""
|
||
Находит идентичность по имени или ID.
|
||
|
||
Если найдено несколько совпадений, приоритет у точного совпадения по ID.
|
||
|
||
Args:
|
||
name: Имя персонажа (case-insensitive)
|
||
character_id: ID персонажа
|
||
|
||
Returns:
|
||
Identity или None, если не найдено
|
||
"""
|
||
if character_id is not None and character_id in self._by_id:
|
||
return self._by_id[character_id]
|
||
if name and name.casefold() in self._by_name:
|
||
return self._by_name[name.casefold()]
|
||
return None
|
||
|
||
def remember(self, *, name: str, character_id: int) -> Identity:
|
||
"""
|
||
Сохраняет новую связку имени и ID в БД и памяти.
|
||
|
||
При конфликте по ID обновляет имя (ON CONFLICT DO UPDATE).
|
||
"""
|
||
identity = Identity(name=name.strip(), character_id=character_id)
|
||
if self.database_url.startswith(("postgres://", "postgresql://")):
|
||
with self._psycopg.connect(self.database_url) as connection:
|
||
connection.execute(
|
||
"INSERT INTO identities(character_id, name) VALUES (%s, %s) "
|
||
"ON CONFLICT(character_id) DO UPDATE SET name=excluded.name",
|
||
(identity.character_id, identity.name),
|
||
)
|
||
elif self.db_path:
|
||
with sqlite3.connect(self.db_path) as connection:
|
||
connection.execute(
|
||
"INSERT INTO identities(character_id, name) VALUES (?, ?) "
|
||
"ON CONFLICT(character_id) DO UPDATE SET name=excluded.name",
|
||
(identity.character_id, identity.name),
|
||
)
|
||
self._index(identity)
|
||
return identity
|
||
|
||
def remember_profile(self, *, actor_id: int, name: str, character_id: int) -> Identity:
|
||
"""
|
||
Сохраняет профиль пользователя (кто — кто).
|
||
|
||
Запоминает, что actor_id представляет персонажа character_id с именем name.
|
||
"""
|
||
identity = self.remember(name=name, character_id=character_id)
|
||
self._profiles[actor_id] = identity
|
||
if self.database_url.startswith(("postgres://", "postgresql://")):
|
||
with self._psycopg.connect(self.database_url) as connection:
|
||
connection.execute(
|
||
"INSERT INTO profiles(actor_id, name, character_id) VALUES (%s, %s, %s) "
|
||
"ON CONFLICT(actor_id) DO UPDATE SET name=excluded.name, character_id=excluded.character_id",
|
||
(actor_id, identity.name, identity.character_id),
|
||
)
|
||
elif self.db_path:
|
||
with sqlite3.connect(self.db_path) as connection:
|
||
connection.execute(
|
||
"INSERT INTO profiles(actor_id, name, character_id) VALUES (?, ?, ?) "
|
||
"ON CONFLICT(actor_id) DO UPDATE SET name=excluded.name, character_id=excluded.character_id",
|
||
(actor_id, identity.name, identity.character_id),
|
||
)
|
||
return identity
|
||
|
||
def profile(self, *, actor_id: int) -> Identity | None:
|
||
"""
|
||
Получает профиль пользователя (сохранённую связку actor_id → персонаж).
|
||
|
||
Загружает из БД при первом запросе и кэширует в памяти.
|
||
"""
|
||
if actor_id in self._profiles:
|
||
return self._profiles[actor_id]
|
||
if self.database_url.startswith(("postgres://", "postgresql://")):
|
||
with self._psycopg.connect(self.database_url) as connection:
|
||
row = connection.execute(
|
||
"SELECT name, character_id FROM profiles WHERE actor_id = %s", (actor_id,)
|
||
).fetchone()
|
||
elif self.db_path:
|
||
with sqlite3.connect(self.db_path) as connection:
|
||
row = connection.execute(
|
||
"SELECT name, character_id FROM profiles WHERE actor_id = ?", (actor_id,)
|
||
).fetchone()
|
||
else:
|
||
return None
|
||
identity = Identity(row[0], row[1]) if row else None
|
||
if identity:
|
||
self._profiles[actor_id] = identity
|
||
return identity
|
||
|
||
def suggest(self, *, name: str | None = None, character_id: int | None = None) -> str:
|
||
"""
|
||
Возвращает подсказку пользователю при неполной связке.
|
||
|
||
Если известно имя — просит ID, если известен ID — просит имя.
|
||
"""
|
||
if name and character_id is None:
|
||
return f"Для «{name}» не найдена связка. Введите ID или добавьте её в справочник."
|
||
if character_id is not None and not name:
|
||
return f"Для ID {character_id} не найдена связка. Введите имя или добавьте её в справочник."
|
||
return "Связка имени и ID не найдена. Добавьте недостающее значение или настройте справочник."
|