Files
beavergram/backend/src/utils/read/avatars.py
T

51 lines
1.5 KiB
Python

import asyncpg
from utils.read.models import AvatarHistoryView, AvatarRef
_PEER_UNIQUE_ID = """
SELECT photo_unique_id FROM peers
WHERE account_id = $1 AND peer_id = $2
"""
_CHAT_UNIQUE_ID = """
SELECT photo_unique_id FROM chat_history
WHERE account_id = $1 AND chat_id = $2 AND photo_unique_id IS NOT NULL
ORDER BY ts DESC LIMIT 1
"""
_AVATAR = """
SELECT unique_id, storage_key, downloaded, mime FROM avatars
WHERE account_id = $1 AND owner_id = $2 AND unique_id = $3
"""
_AVATAR_HISTORY = """
SELECT unique_id, first_seen_at, downloaded FROM avatars
WHERE account_id = $1 AND owner_id = $2
ORDER BY first_seen_at DESC
"""
async def current_avatar(
pool: asyncpg.Pool, account_id: int, owner_kind: str, owner_id: int
) -> AvatarRef | None:
query = _PEER_UNIQUE_ID if owner_kind == "peer" else _CHAT_UNIQUE_ID
unique_id = await pool.fetchval(query, account_id, owner_id)
if unique_id is None:
return None
row = await pool.fetchrow(_AVATAR, account_id, owner_id, unique_id)
return AvatarRef(**dict(row)) if row else None
async def avatar_by_unique_id(
pool: asyncpg.Pool, account_id: int, owner_id: int, unique_id: str
) -> AvatarRef | None:
row = await pool.fetchrow(_AVATAR, account_id, owner_id, unique_id)
return AvatarRef(**dict(row)) if row else None
async def avatar_history(
pool: asyncpg.Pool, account_id: int, owner_id: int
) -> list[AvatarHistoryView]:
rows = await pool.fetch(_AVATAR_HISTORY, account_id, owner_id)
return [AvatarHistoryView(**dict(row)) for row in rows]