"""统一数据访问层(Repository)。商用切库只动这里和 DATABASE_URL。""" from sqlalchemy import select, delete from sqlalchemy.ext.asyncio import AsyncSession from ..models import entities as E def enc(key: bytes | None, text: str) -> str: from ..core.security import encrypt_text return encrypt_text(key, text) if key else text def dec(key: bytes | None, stored: str) -> str: from ..core.security import decrypt_text if not key: return stored try: return decrypt_text(key, stored) except Exception: # 密码重置/盐变更导致的旧密文:降级显示,不让整个请求 500 return "[旧加密内容已失效]" class UserRepo: @staticmethod async def by_username(db: AsyncSession, username: str): return (await db.execute(select(E.User).where(E.User.username == username))).scalar_one_or_none() @staticmethod async def by_id(db: AsyncSession, uid: int): return await db.get(E.User, uid) @staticmethod async def all(db: AsyncSession): return (await db.execute(select(E.User).order_by(E.User.id))).scalars().all() class SettingRepo: DEFAULTS = { "allow_register": "true", "allow_delete_account": "true", "allow_byok": "true", "admin_data_visible": "true", # 默认明文;关闭后加密落库 } _cache: dict | None = None # 进程内缓存(读多写少),写入即失效 @staticmethod async def get(db: AsyncSession, key: str) -> str: cache = SettingRepo._cache if cache is not None: return cache.get(key, SettingRepo.DEFAULTS.get(key, "")) rows = (await db.execute(select(E.SiteSetting))).scalars().all() cache = dict(SettingRepo.DEFAULTS) cache.update({r.key: r.value for r in rows}) SettingRepo._cache = cache return cache.get(key, "") @staticmethod async def set(db: AsyncSession, key: str, value: str): row = (await db.execute(select(E.SiteSetting).where(E.SiteSetting.key == key))).scalar_one_or_none() if row: row.value = value else: db.add(E.SiteSetting(key=key, value=value)) await db.commit() SettingRepo._cache = None @staticmethod async def all(db: AsyncSession) -> dict: if SettingRepo._cache is not None: return SettingRepo._cache rows = (await db.execute(select(E.SiteSetting))).scalars().all() out = dict(SettingRepo.DEFAULTS) out.update({r.key: r.value for r in rows}) SettingRepo._cache = out return out class ChannelRepo: @staticmethod async def visible_to(db: AsyncSession, user: E.User) -> list[E.Channel]: q = select(E.Channel) if user.is_admin: rows = (await db.execute(q)).scalars().all() else: rows = (await db.execute(q.where(E.Channel.owner_id == user.id))).scalars().all() pub = (await db.execute(q.where(E.Channel.visibility == "public"))).scalars().all() granted_ids = (await db.execute( select(E.ChannelGrant.channel_id).where(E.ChannelGrant.user_id == user.id))).scalars().all() granted = [await db.get(E.Channel, cid) for cid in granted_ids] merged = {c.id: c for c in [*rows, *pub]} for c in granted: if c: merged[c.id] = c rows = list(merged.values()) return rows @staticmethod async def can_use(db: AsyncSession, user: E.User, channel_id: int) -> E.Channel | None: c = await db.get(E.Channel, channel_id) if not c: return None if user.is_admin or c.owner_id == user.id or c.visibility == "public": return c g = (await db.execute(select(E.ChannelGrant).where( E.ChannelGrant.channel_id == channel_id, E.ChannelGrant.user_id == user.id))).scalar_one_or_none() return c if g else None class CharacterRepo: @staticmethod async def list_for(db: AsyncSession, uid: int): return (await db.execute(select(E.Character).where( E.Character.user_id == uid).order_by(E.Character.id.desc()))).scalars().all() class MemoryRepo: @staticmethod async def list_for(db: AsyncSession, uid: int, character_id: int): return (await db.execute(select(E.Memory).where( E.Memory.user_id == uid, E.Memory.character_id == character_id))).scalars().all() class WorldbookRepo: @staticmethod async def list_for(db: AsyncSession, uid: int): return (await db.execute(select(E.WorldbookEntry).where( E.WorldbookEntry.user_id == uid))).scalars().all() class SessionRepo: @staticmethod async def list_for(db: AsyncSession, uid: int): return (await db.execute(select(E.ChatSession).where( E.ChatSession.user_id == uid).order_by(E.ChatSession.id.desc()))).scalars().all() class MessageRepo: @staticmethod async def history(db: AsyncSession, uid: int, session_id: int, limit: int = 60): rows = (await db.execute(select(E.Message).where( E.Message.user_id == uid, E.Message.session_id == session_id ).order_by(E.Message.id.desc()).limit(limit))).scalars().all() return list(reversed(rows))