Files
OpenMaopaoya/app/db/repos.py
T

128 lines
4.6 KiB
Python

"""统一数据访问层(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
return decrypt_text(key, stored) if key else stored
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", # 默认明文;关闭后加密落库
}
@staticmethod
async def get(db: AsyncSession, key: str) -> str:
v = (await db.execute(select(E.SiteSetting).where(E.SiteSetting.key == key))).scalar_one_or_none()
return v.value if v else SettingRepo.DEFAULTS.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()
@staticmethod
async def all(db: AsyncSession) -> dict:
rows = (await db.execute(select(E.SiteSetting))).scalars().all()
out = dict(SettingRepo.DEFAULTS)
out.update({r.key: r.value for r in rows})
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))