Files
beavergram/backend/src/userbot/modules/stories/repository.py
T

74 lines
1.9 KiB
Python

from datetime import datetime
import asyncpg
_UPSERT_STORY = """
INSERT INTO stories
(account_id, peer_id, story_id, date, expire_date, caption, media_kind,
storage_key, file_size, downloaded, views, pinned, deleted, raw, observed_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14::jsonb, now())
ON CONFLICT (account_id, peer_id, story_id) DO UPDATE SET
date = EXCLUDED.date,
expire_date = EXCLUDED.expire_date,
caption = EXCLUDED.caption,
media_kind = EXCLUDED.media_kind,
storage_key = COALESCE(EXCLUDED.storage_key, stories.storage_key),
file_size = COALESCE(EXCLUDED.file_size, stories.file_size),
downloaded = stories.downloaded OR EXCLUDED.downloaded,
views = EXCLUDED.views,
pinned = EXCLUDED.pinned,
deleted = EXCLUDED.deleted,
raw = EXCLUDED.raw
"""
async def is_downloaded(
pool: asyncpg.Pool, account_id: int, peer_id: int, story_id: int
) -> bool:
return bool(
await pool.fetchval(
"SELECT downloaded FROM stories "
"WHERE account_id = $1 AND peer_id = $2 AND story_id = $3",
account_id,
peer_id,
story_id,
)
)
async def upsert_story( # noqa: PLR0913
pool: asyncpg.Pool,
account_id: int,
peer_id: int,
story_id: int,
date: datetime | None,
expire_date: datetime | None,
caption: str | None,
media_kind: str | None,
storage_key: str | None,
file_size: int | None,
views: int | None,
raw: str,
*,
pinned: bool,
deleted: bool,
downloaded: bool,
) -> None:
await pool.execute(
_UPSERT_STORY,
account_id,
peer_id,
story_id,
date,
expire_date,
caption,
media_kind,
storage_key,
file_size,
downloaded,
views,
pinned,
deleted,
raw,
)