89 lines
2.0 KiB
Python
89 lines
2.0 KiB
Python
from datetime import datetime
|
|
|
|
import asyncpg
|
|
|
|
_INSERT_CHAT_HISTORY = """
|
|
INSERT INTO chat_history
|
|
(account_id, chat_id, message_id, event, title, photo_unique_id, actor_id,
|
|
ts, raw)
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9::jsonb)
|
|
ON CONFLICT (account_id, chat_id, message_id) DO NOTHING
|
|
"""
|
|
|
|
_INSERT_MEMBERSHIP = """
|
|
INSERT INTO memberships
|
|
(account_id, chat_id, message_id, user_id, event, actor_id, ts, raw)
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8::jsonb)
|
|
ON CONFLICT (account_id, chat_id, message_id, user_id) DO NOTHING
|
|
"""
|
|
|
|
_LATEST_TITLE = """
|
|
SELECT title FROM chat_history
|
|
WHERE account_id = $1 AND chat_id = $2 AND title IS NOT NULL
|
|
ORDER BY ts DESC LIMIT 1
|
|
"""
|
|
|
|
_LATEST_PHOTO = """
|
|
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
|
|
"""
|
|
|
|
|
|
async def get_latest_chat_meta(
|
|
pool: asyncpg.Pool, account_id: int, chat_id: int
|
|
) -> tuple[str | None, str | None]:
|
|
title = await pool.fetchval(_LATEST_TITLE, account_id, chat_id)
|
|
photo_unique_id = await pool.fetchval(_LATEST_PHOTO, account_id, chat_id)
|
|
return title, photo_unique_id
|
|
|
|
|
|
async def insert_chat_history( # noqa: PLR0913
|
|
pool: asyncpg.Pool,
|
|
account_id: int,
|
|
chat_id: int,
|
|
message_id: int,
|
|
event: str,
|
|
title: str | None,
|
|
photo_unique_id: str | None,
|
|
actor_id: int | None,
|
|
ts: datetime,
|
|
raw: str,
|
|
) -> None:
|
|
await pool.execute(
|
|
_INSERT_CHAT_HISTORY,
|
|
account_id,
|
|
chat_id,
|
|
message_id,
|
|
event,
|
|
title,
|
|
photo_unique_id,
|
|
actor_id,
|
|
ts,
|
|
raw,
|
|
)
|
|
|
|
|
|
async def insert_membership( # noqa: PLR0913
|
|
pool: asyncpg.Pool,
|
|
account_id: int,
|
|
chat_id: int,
|
|
message_id: int,
|
|
user_id: int,
|
|
event: str,
|
|
actor_id: int | None,
|
|
ts: datetime,
|
|
raw: str,
|
|
) -> None:
|
|
await pool.execute(
|
|
_INSERT_MEMBERSHIP,
|
|
account_id,
|
|
chat_id,
|
|
message_id,
|
|
user_id,
|
|
event,
|
|
actor_id,
|
|
ts,
|
|
raw,
|
|
)
|