54 lines
1.8 KiB
Python
54 lines
1.8 KiB
Python
from __future__ import annotations
|
|
|
|
from app.db import Database
|
|
from app.models import ChatRecord, utc_now_iso
|
|
|
|
|
|
class ChatRepository:
|
|
def __init__(self, db: Database) -> None:
|
|
self._db = db
|
|
|
|
def upsert(
|
|
self,
|
|
chat_id: int,
|
|
chat_type: str,
|
|
title: str | None = None,
|
|
username: str | None = None,
|
|
is_active: int = 1,
|
|
) -> None:
|
|
with self._db.connect() as conn:
|
|
conn.execute(
|
|
"""
|
|
INSERT INTO bot_chats (chat_id, chat_type, title, username, last_seen_at, is_active)
|
|
VALUES (?, ?, ?, ?, ?, ?)
|
|
ON CONFLICT(chat_id) DO UPDATE SET
|
|
chat_type = excluded.chat_type,
|
|
title = COALESCE(excluded.title, bot_chats.title),
|
|
username = COALESCE(excluded.username, bot_chats.username),
|
|
last_seen_at = excluded.last_seen_at,
|
|
is_active = excluded.is_active
|
|
""",
|
|
(chat_id, chat_type, title, username, utc_now_iso(), is_active),
|
|
)
|
|
conn.commit()
|
|
|
|
def deactivate(self, chat_id: int) -> None:
|
|
with self._db.connect() as conn:
|
|
conn.execute(
|
|
"UPDATE bot_chats SET is_active = 0, last_seen_at = ? WHERE chat_id = ?",
|
|
(utc_now_iso(), chat_id),
|
|
)
|
|
conn.commit()
|
|
|
|
def list(self, limit: int = 200) -> list[ChatRecord]:
|
|
with self._db.connect() as conn:
|
|
rows = conn.execute(
|
|
"""
|
|
SELECT * FROM bot_chats
|
|
ORDER BY last_seen_at DESC
|
|
LIMIT ?
|
|
""",
|
|
(limit,),
|
|
).fetchall()
|
|
return [ChatRecord(**dict(row)) for row in rows]
|
|
|