LichessStatTgWeb/LichessClientTG_bot/database.py
vrubelroman b4c63aa79a
Some checks failed
CI/CD Pipeline / build-and-deploy (push) Failing after 2s
v1.8.0: Uzbek, Turkish, Persian and Arabic locales, auto-detected for new users
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 21:36:05 +00:00

856 lines
38 KiB
Python

import sqlite3
import logging
from typing import Optional, List, Dict, Any
from config import DATABASE_PATH
from i18n import LANGUAGES
logger = logging.getLogger(__name__)
def bot_language_for_code(language_code: Optional[str]) -> str:
"""
Bot language of a NEW user from the Telegram language_code: the primary
subtag ('uz' of 'uz-UZ', 'ar' of 'ar_SA') when it is one of
i18n.LANGUAGES, else 'en'. A code merely starting with 'ru' keeps mapping
to ru, as it always did.
"""
if not language_code:
return 'en'
code = language_code.lower()
base = code.replace('_', '-').split('-')[0]
if base in LANGUAGES:
return base
if code.startswith('ru'):
return 'ru'
return 'en'
class Database:
def __init__(self, db_path: str = DATABASE_PATH):
self.db_path = db_path
self.init_database()
def init_database(self):
"""Initialize database tables"""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
logger.info(f"Using database at: {self.db_path}")
# Create telegram_users table (Telegram bot users)
cursor.execute('''
CREATE TABLE IF NOT EXISTS telegram_users (
user_id INTEGER PRIMARY KEY,
username TEXT,
first_name TEXT,
last_name TEXT,
language_code TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
# Add language_code column if it doesn't exist (Telegram language)
try:
cursor.execute("ALTER TABLE telegram_users ADD COLUMN language_code TEXT")
except sqlite3.OperationalError:
# Column already exists
pass
# Add bot_language column if it doesn't exist (user-selected bot language)
try:
cursor.execute("ALTER TABLE telegram_users ADD COLUMN bot_language TEXT DEFAULT 'en'")
# Set default value for existing users
cursor.execute("UPDATE telegram_users SET bot_language = 'en' WHERE bot_language IS NULL")
conn.commit()
except sqlite3.OperationalError:
# Column already exists
pass
# Create gamers table (Lichess players only)
cursor.execute('''
CREATE TABLE IF NOT EXISTS gamers (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
token TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
# Create user_gamers table (relationship between users and gamers)
cursor.execute('''
CREATE TABLE IF NOT EXISTS user_gamers (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
gamer_id INTEGER NOT NULL,
token TEXT,
is_active BOOLEAN DEFAULT FALSE,
period_minutes INTEGER DEFAULT 0,
last_period_end_ts INTEGER,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES telegram_users(user_id),
FOREIGN KEY (gamer_id) REFERENCES gamers(id),
UNIQUE(user_id, gamer_id)
)
''')
# Add token column to user_gamers if it doesn't exist
try:
cursor.execute("ALTER TABLE user_gamers ADD COLUMN token TEXT")
except sqlite3.OperationalError:
# Column already exists
pass
# Add last_period_end_ts column to persist periodic checkpoint across restarts
try:
cursor.execute("ALTER TABLE user_gamers ADD COLUMN last_period_end_ts INTEGER")
except sqlite3.OperationalError:
# Column already exists
pass
# Bulk player status (see player_status.py): games_total of the player as
# of the pair's last successful games request. If the refreshed total is
# the same, no game was finished since, and the periodic games request for
# that window is skipped.
try:
cursor.execute("ALTER TABLE user_gamers ADD COLUMN last_games_total INTEGER")
except sqlite3.OperationalError:
# Column already exists
pass
# Whether the owner was already told that this player's Lichess account is
# closed (sent once; cleared when the account is seen active again).
try:
cursor.execute("ALTER TABLE user_gamers ADD COLUMN closed_notice_sent INTEGER NOT NULL DEFAULT 0")
except sqlite3.OperationalError:
# Column already exists
pass
# Latest bulk status of each tracked player from POST /api/users
# (player_status.py refreshes it every PLAYER_STATUS_REFRESH_MINUTES).
# One row per gamer, not per pair: the status is a property of the
# Lichess account, shared by everyone who tracks it.
cursor.execute('''
CREATE TABLE IF NOT EXISTS gamer_status (
gamer_id INTEGER PRIMARY KEY REFERENCES gamers(id),
disabled INTEGER NOT NULL DEFAULT 0,
seen_at INTEGER,
games_total INTEGER,
checked_at INTEGER NOT NULL,
missing_count INTEGER NOT NULL DEFAULT 0,
not_found INTEGER NOT NULL DEFAULT 0
)
''')
# Players Lichess does not know any more (deleted or renamed accounts)
# are simply absent from a successful POST /api/users answer. Count
# how many consecutive refreshes did not return the player
# (missing_count); from the second one on the player is flagged
# not_found and its pairs are paused like a closed account. Both are
# reset as soon as the name is in an answer again (see
# player_status.py).
for column_sql in ("missing_count INTEGER NOT NULL DEFAULT 0",
"not_found INTEGER NOT NULL DEFAULT 0"):
try:
cursor.execute(f"ALTER TABLE gamer_status ADD COLUMN {column_sql}")
except sqlite3.OperationalError:
# Column already exists
pass
# Create admin_settings table for admin bot configuration
cursor.execute('''
CREATE TABLE IF NOT EXISTS admin_settings (
key TEXT PRIMARY KEY,
value TEXT,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
# Create message_counters table for tracking sent messages
cursor.execute('''
CREATE TABLE IF NOT EXISTS message_counters (
command TEXT PRIMARY KEY,
total_count INTEGER DEFAULT 0,
today_count INTEGER DEFAULT 0,
last_reset_date DATE DEFAULT CURRENT_DATE
)
''')
# Initialize counters for all commands
commands = ['start', 'addgamer', 'addtoken', 'getgamers', 'delgamer',
'today', 'yesterday', 'week', 'setperiod', 'lang', 'resetlang',
'periodic_notification', 'gamer_added']
for cmd in commands:
cursor.execute('''
INSERT OR IGNORE INTO message_counters (command, total_count, today_count, last_reset_date)
VALUES (?, 0, 0, CURRENT_DATE)
''', (cmd,))
conn.commit()
# Migrate tokens from gamers to user_gamers if needed
self._migrate_tokens_from_gamers()
# Lichess usernames are case-insensitive, but gamers.username UNIQUE is
# case-sensitive, so "Zhigalko_Sergei" and "Zhigalko_sergei" ended up as
# two players checked separately every hour. Merge such duplicates and
# forbid new ones with a case-insensitive unique index.
self._merge_case_duplicate_gamers()
with sqlite3.connect(self.db_path) as conn:
conn.execute(
"CREATE UNIQUE INDEX IF NOT EXISTS idx_gamers_username_nocase ON gamers(lower(username))"
)
conn.commit()
logger.info("Database initialized successfully")
def _merge_case_duplicate_gamers(self):
"""Merge gamers rows whose usernames differ only by case into the oldest row."""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute(
"SELECT lower(username) FROM gamers GROUP BY lower(username) HAVING COUNT(*) > 1"
)
groups = [row[0] for row in cursor.fetchall()]
if not groups:
return
merged_links = 0
for lowered in groups:
cursor.execute(
"SELECT id, username FROM gamers WHERE lower(username) = ? ORDER BY id",
(lowered,)
)
rows = cursor.fetchall()
keep_id, keep_name = rows[0]
for dup_id, dup_name in rows[1:]:
cursor.execute(
"SELECT id, user_id, token, is_active, period_minutes, last_period_end_ts "
"FROM user_gamers WHERE gamer_id = ?",
(dup_id,)
)
for link_id, user_id, token, is_active, period, checkpoint in cursor.fetchall():
cursor.execute(
"SELECT id, token, is_active, period_minutes FROM user_gamers "
"WHERE user_id = ? AND gamer_id = ?",
(user_id, keep_id)
)
existing = cursor.fetchone()
if existing is None:
cursor.execute(
"UPDATE user_gamers SET gamer_id = ? WHERE id = ?",
(keep_id, link_id)
)
else:
# Same user tracks both spellings: keep one link, but don't
# lose a token / enabled period / active flag from the other.
ex_id, ex_token, ex_active, ex_period = existing
cursor.execute(
"UPDATE user_gamers SET token = COALESCE(token, ?), "
"is_active = (is_active OR ?), "
"period_minutes = CASE WHEN period_minutes > 0 THEN period_minutes ELSE ? END, "
"last_period_end_ts = COALESCE(last_period_end_ts, ?) WHERE id = ?",
(token, 1 if is_active else 0, period or 0, checkpoint, ex_id)
)
cursor.execute("DELETE FROM user_gamers WHERE id = ?", (link_id,))
merged_links += 1
cursor.execute("DELETE FROM gamers WHERE id = ?", (dup_id,))
logger.info(f"Merged duplicate gamer '{dup_name}' (id={dup_id}) into '{keep_name}' (id={keep_id})")
conn.commit()
logger.info(f"Merged {len(groups)} case-duplicate gamer groups, {merged_links} user links re-pointed")
def _migrate_tokens_from_gamers(self):
"""Migrate tokens from old gamers table to user_gamers table if needed"""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
# Check if there are tokens in gamers table that need migration
cursor.execute("SELECT COUNT(*) FROM gamers WHERE token IS NOT NULL")
gamers_with_tokens = cursor.fetchone()[0]
if gamers_with_tokens == 0:
return # No tokens to migrate
# Check if user_gamers already has tokens
cursor.execute("SELECT COUNT(*) FROM user_gamers WHERE token IS NOT NULL")
user_gamers_with_tokens = cursor.fetchone()[0]
if user_gamers_with_tokens > 0:
return # Migration already done
# Migrate tokens from gamers to user_gamers
cursor.execute("SELECT id, token FROM gamers WHERE token IS NOT NULL")
gamers_tokens = cursor.fetchall()
migrated = 0
for gamer_id, token in gamers_tokens:
# Update all user-gamer relationships for this gamer
cursor.execute(
"UPDATE user_gamers SET token = ? WHERE gamer_id = ? AND token IS NULL",
(token, gamer_id)
)
migrated += cursor.rowcount
conn.commit()
if migrated > 0:
logger.info(f"Migrated {migrated} tokens from gamers to user_gamers")
def add_or_get_telegram_user(self, user_id: int, username: Optional[str] = None,
first_name: Optional[str] = None, last_name: Optional[str] = None,
language_code: Optional[str] = None) -> bool:
"""
Add or update Telegram user.
For new users, automatically sets bot_language based on Telegram language_code
(bot_language_for_code): 'ru', 'uz', 'tr', 'fa', 'ar' (also with a region,
'uz-UZ', 'ar-SA') -> that language, anything else (or none) -> 'en'.
Existing users keep their bot_language.
"""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute("SELECT user_id, bot_language FROM telegram_users WHERE user_id = ?", (user_id,))
existing = cursor.fetchone()
if not existing:
# New user - determine bot language from Telegram language_code
bot_language = bot_language_for_code(language_code)
cursor.execute(
"INSERT INTO telegram_users (user_id, username, first_name, last_name, language_code, bot_language) VALUES (?, ?, ?, ?, ?, ?)",
(user_id, username, first_name, last_name, language_code, bot_language)
)
conn.commit()
logger.info(f"New user {user_id} added with bot_language={bot_language} (from Telegram language_code={language_code})")
return True
else:
# Existing user - update language_code but keep bot_language unchanged
cursor.execute(
"UPDATE telegram_users SET language_code = ? WHERE user_id = ?",
(language_code, user_id)
)
conn.commit()
return False
def get_user_language(self, user_id: int) -> str:
"""Get user's selected bot language from database"""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute("SELECT bot_language FROM telegram_users WHERE user_id = ?", (user_id,))
result = cursor.fetchone()
if result and result[0]:
return result[0]
# Default to English if not set
return 'en'
def set_user_language(self, user_id: int, language: str) -> bool:
"""Set user's selected bot language"""
if language not in LANGUAGES:
return False
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute(
"UPDATE telegram_users SET bot_language = ? WHERE user_id = ?",
(language, user_id)
)
conn.commit()
return cursor.rowcount > 0
def gamer_exists(self, username: str) -> bool:
"""Whether this username (case-insensitive, like Lichess) is already in the global gamers table."""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute("SELECT 1 FROM gamers WHERE lower(username) = lower(?)", (username,))
return cursor.fetchone() is not None
def get_counts(self) -> Dict[str, int]:
"""Total Telegram users and distinct tracked gamers (startup statistics line, admin TTS announcements)."""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute("SELECT COUNT(*) FROM telegram_users")
users = cursor.fetchone()[0]
cursor.execute("SELECT COUNT(DISTINCT username) FROM gamers")
gamers = cursor.fetchone()[0]
return {'users': users, 'gamers': gamers}
def get_admin_overview(self, today_iso: str, yesterday_iso: str, week_start_iso: str) -> Dict[str, Any]:
"""
The numbers behind the admin bot's /status. The three dates are UTC
days (YYYY-MM-DD, compared with DATE(created_at), which is UTC too:
CURRENT_TIMESTAMP); week = DATE(created_at) >= week_start_iso, i.e. the
last 7 UTC days including today.
{'users': {'total', 'today', 'yesterday', 'week'}, # telegram_users
'gamers': {'total', 'today', 'yesterday', 'week'}, # gamers (a row is deleted when
# nobody tracks the player any more)
'pairs': {'active', 'today', 'yesterday', 'week'}, # user_gamers: active = period_minutes > 0,
# the +... are links created (not net of deletions)
'users_without_gamers': int,
'status': {'closed': int, 'not_found': int, 'last_checked_at': Optional[int]}}
# gamer_status: SUM(disabled), SUM(not_found), MAX(checked_at)
One connection, five queries.
"""
dates = (today_iso, yesterday_iso, week_start_iso)
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
def created_counts(table: str):
# COALESCE: SUM over an empty table is NULL, not 0
cursor.execute(
f"SELECT COUNT(*), "
f"COALESCE(SUM(DATE(created_at) = ?), 0), "
f"COALESCE(SUM(DATE(created_at) = ?), 0), "
f"COALESCE(SUM(DATE(created_at) >= ?), 0) FROM {table}",
dates,
)
return cursor.fetchone()
users = created_counts("telegram_users")
gamers = created_counts("gamers")
pairs = created_counts("user_gamers")
cursor.execute("SELECT COUNT(*) FROM user_gamers WHERE period_minutes > 0")
pairs_active = cursor.fetchone()[0]
cursor.execute("""
SELECT COUNT(DISTINCT tu.user_id)
FROM telegram_users tu
LEFT JOIN user_gamers ug ON tu.user_id = ug.user_id
WHERE ug.id IS NULL
""")
users_without_gamers = cursor.fetchone()[0]
cursor.execute("SELECT COALESCE(SUM(disabled), 0), COALESCE(SUM(not_found), 0), MAX(checked_at) FROM gamer_status")
closed, not_found, last_checked_at = cursor.fetchone()
return {
'users': {'total': users[0], 'today': users[1], 'yesterday': users[2], 'week': users[3]},
'gamers': {'total': gamers[0], 'today': gamers[1], 'yesterday': gamers[2], 'week': gamers[3]},
'pairs': {'active': pairs_active, 'today': pairs[1], 'yesterday': pairs[2], 'week': pairs[3]},
'users_without_gamers': users_without_gamers,
'status': {'closed': int(closed), 'not_found': int(not_found),
'last_checked_at': int(last_checked_at) if last_checked_at is not None else None},
}
def add_gamer(self, username: str) -> int:
"""Add a new gamer to the database (return gamer_id)"""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
# Check if gamer already exists (Lichess usernames are case-insensitive)
cursor.execute("SELECT id FROM gamers WHERE lower(username) = lower(?)", (username,))
existing = cursor.fetchone()
if existing:
gamer_id = existing[0]
else:
# Add new gamer (without token - tokens are stored in user_gamers)
cursor.execute(
"INSERT INTO gamers (username) VALUES (?)",
(username,)
)
gamer_id = cursor.lastrowid
conn.commit()
return gamer_id
def add_user_gamer(self, user_id: int, gamer_id: int, token: Optional[str] = None) -> bool:
"""Add relationship between user and gamer with optional token"""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
try:
cursor.execute(
"INSERT INTO user_gamers (user_id, gamer_id, token) VALUES (?, ?, ?)",
(user_id, gamer_id, token)
)
conn.commit()
return True
except sqlite3.IntegrityError:
# Already exists - update token if provided
if token:
cursor.execute(
"UPDATE user_gamers SET token = ? WHERE user_id = ? AND gamer_id = ?",
(token, user_id, gamer_id)
)
conn.commit()
return False
def get_user_gamers(self, user_id: int) -> List[Dict[str, Any]]:
"""Get all gamers for a specific user"""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute('''
SELECT g.id, g.username, ug.token, ug.is_active, ug.period_minutes
FROM user_gamers ug
JOIN gamers g ON ug.gamer_id = g.id
WHERE ug.user_id = ?
ORDER BY ug.id
''', (user_id,))
gamers = []
for row in cursor.fetchall():
gamers.append({
'id': row[0],
'username': row[1],
'token': row[2], # Token from user_gamers, not gamers
'is_active': bool(row[3]),
'period_minutes': row[4]
})
return gamers
def get_user_active_gamer(self, user_id: int) -> Optional[Dict[str, Any]]:
"""Get the active gamer for a specific user"""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute('''
SELECT g.id, g.username, ug.token
FROM user_gamers ug
JOIN gamers g ON ug.gamer_id = g.id
WHERE ug.user_id = ? AND ug.is_active = TRUE
LIMIT 1
''', (user_id,))
row = cursor.fetchone()
if row:
return {
'id': row[0],
'username': row[1],
'token': row[2] # Token from user_gamers
}
return None
def set_user_active_gamer(self, user_id: int, gamer_id: int):
"""Set active gamer for a specific user"""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
# Deactivate all gamers for this user
cursor.execute(
"UPDATE user_gamers SET is_active = FALSE WHERE user_id = ?",
(user_id,)
)
# Activate the selected gamer
cursor.execute(
"UPDATE user_gamers SET is_active = TRUE WHERE user_id = ? AND gamer_id = ?",
(user_id, gamer_id)
)
conn.commit()
def set_user_gamer_period(self, user_id: int, gamer_id: int, period_minutes: int):
"""Set period for a gamer for a specific user"""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute(
"UPDATE user_gamers SET period_minutes = ? WHERE user_id = ? AND gamer_id = ?",
(period_minutes, user_id, gamer_id)
)
conn.commit()
def clear_user_gamer_token(self, user_id: int, gamer_id: int):
"""Clear a rejected/expired token so periodic checks stop sending it (games-only monitoring continues)."""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute(
"UPDATE user_gamers SET token = NULL WHERE user_id = ? AND gamer_id = ?",
(user_id, gamer_id)
)
conn.commit()
def get_period_checkpoint(self, user_id: int, gamer_id: int) -> Optional[int]:
"""Get persisted period checkpoint timestamp (seconds since epoch)."""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute(
"SELECT last_period_end_ts FROM user_gamers WHERE user_id = ? AND gamer_id = ?",
(user_id, gamer_id)
)
row = cursor.fetchone()
if not row or row[0] is None:
return None
return int(row[0])
def set_period_checkpoint(self, user_id: int, gamer_id: int, checkpoint_ts: int):
"""Persist period checkpoint timestamp (seconds since epoch)."""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute(
"UPDATE user_gamers SET last_period_end_ts = ? WHERE user_id = ? AND gamer_id = ?",
(checkpoint_ts, user_id, gamer_id)
)
conn.commit()
def clear_period_checkpoint(self, user_id: int, gamer_id: int):
"""Clear persisted period checkpoint."""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute(
"UPDATE user_gamers SET last_period_end_ts = NULL WHERE user_id = ? AND gamer_id = ?",
(user_id, gamer_id)
)
conn.commit()
def remove_user_gamer(self, user_id: int, gamer_id: int) -> bool:
"""Remove gamer from user's tracked list"""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
# Delete the user-gamer relationship
cursor.execute(
"DELETE FROM user_gamers WHERE user_id = ? AND gamer_id = ?",
(user_id, gamer_id)
)
deleted = cursor.rowcount > 0
# Check if this gamer is still tracked by any other user
cursor.execute(
"SELECT COUNT(*) FROM user_gamers WHERE gamer_id = ?",
(gamer_id,)
)
other_users_count = cursor.fetchone()[0]
# If no other users track this gamer, remove from gamers table
# (and its bulk-status row, which references it)
if other_users_count == 0:
cursor.execute("DELETE FROM gamer_status WHERE gamer_id = ?", (gamer_id,))
cursor.execute("DELETE FROM gamers WHERE id = ?", (gamer_id,))
conn.commit()
return deleted
def get_user_gamers_with_periods(self, user_id: int) -> List[Dict[str, Any]]:
"""Get all gamers for a user that have periods set"""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute('''
SELECT g.id, g.username, ug.token, ug.period_minutes
FROM user_gamers ug
JOIN gamers g ON ug.gamer_id = g.id
WHERE ug.user_id = ? AND ug.period_minutes > 0
''', (user_id,))
gamers = []
for row in cursor.fetchall():
gamers.append({
'id': row[0],
'username': row[1],
'token': row[2], # Token from user_gamers
'period_minutes': row[3]
})
return gamers
def get_all_gamers_with_periods(self) -> List[Dict[str, Any]]:
"""Get all user-gamer pairs that have periods set (for periodic checks across all users)"""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute('''
SELECT ug.user_id, g.id, g.username, ug.token, ug.period_minutes
FROM user_gamers ug
JOIN gamers g ON ug.gamer_id = g.id
WHERE ug.period_minutes > 0
''')
gamers = []
for row in cursor.fetchall():
gamers.append({
'user_id': row[0],
'id': row[1],
'username': row[2],
'token': row[3], # Token from user_gamers
'period_minutes': row[4]
})
return gamers
# ------------------------------------------------------------------
# Bulk player status (gamer_status) and per-pair skip state
# ------------------------------------------------------------------
def get_all_tracked_gamers(self) -> List[Dict[str, Any]]:
"""Distinct gamers that at least one user tracks with a period set (the set the bulk status refresh asks Lichess about)."""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute('''
SELECT DISTINCT g.id, g.username
FROM gamers g
JOIN user_gamers ug ON ug.gamer_id = g.id
WHERE ug.period_minutes > 0
ORDER BY g.id
''')
return [{'id': row[0], 'username': row[1]} for row in cursor.fetchall()]
def upsert_gamer_statuses(self, rows: List[Dict[str, Any]]):
"""
Insert or replace gamer_status rows for players Lichess DID answer for.
Each row: {'gamer_id', 'disabled', 'seen_at', 'games_total', 'checked_at'}
(seen_at / games_total may be None). A present player is by definition
known to Lichess, so missing_count / not_found are reset to 0.
"""
if not rows:
return
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.executemany(
"INSERT OR REPLACE INTO gamer_status "
"(gamer_id, disabled, seen_at, games_total, checked_at, missing_count, not_found) "
"VALUES (?, ?, ?, ?, ?, 0, 0)",
[
(
int(r['gamer_id']),
1 if r.get('disabled') else 0,
r.get('seen_at'),
r.get('games_total'),
int(r['checked_at']),
)
for r in rows
]
)
conn.commit()
# From this many consecutive refreshes without the player in Lichess's
# answer the account is treated as gone (not_found). Two, not one: a single
# absence could still be a partial answer; two refreshes are 30 minutes.
NOT_FOUND_AFTER_MISSES = 2
def mark_gamer_statuses_missing(self, gamer_ids: List[int], checked_at: int) -> int:
"""
The refresh asked Lichess about these players and a successful answer
did not contain them: missing_count += 1 (a row is created if needed:
disabled=0, games_total/seen_at untouched or NULL), checked_at=now, and
not_found=1 once missing_count reaches NOT_FOUND_AFTER_MISSES. Returns
how many of the given players are now flagged not_found.
"""
if not gamer_ids:
return 0
ids = [int(g) for g in gamer_ids]
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.executemany(
"INSERT INTO gamer_status (gamer_id, disabled, seen_at, games_total, checked_at, missing_count, not_found) "
"VALUES (?, 0, NULL, NULL, ?, 1, 0) "
"ON CONFLICT(gamer_id) DO UPDATE SET "
"missing_count = missing_count + 1, "
"not_found = CASE WHEN missing_count + 1 >= ? THEN 1 ELSE 0 END, "
"disabled = 0, "
"checked_at = excluded.checked_at",
[(gid, int(checked_at), self.NOT_FOUND_AFTER_MISSES) for gid in ids]
)
placeholders = ",".join("?" for _ in ids)
cursor.execute(
f"SELECT COUNT(*) FROM gamer_status WHERE not_found = 1 AND gamer_id IN ({placeholders})",
ids
)
flagged = cursor.fetchone()[0]
conn.commit()
return int(flagged)
def get_gamer_status(self, gamer_id: int) -> Optional[Dict[str, Any]]:
"""Latest bulk status of a gamer, or None if it was never refreshed."""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute(
"SELECT disabled, seen_at, games_total, checked_at, missing_count, not_found "
"FROM gamer_status WHERE gamer_id = ?",
(gamer_id,)
)
row = cursor.fetchone()
if not row:
return None
return {
'disabled': bool(row[0]),
'seen_at': row[1],
'games_total': row[2],
'checked_at': int(row[3]),
'missing_count': int(row[4] or 0),
'not_found': bool(row[5]),
}
def get_gamer_statuses(self, gamer_ids: List[int]) -> Dict[int, Dict[str, Any]]:
"""
get_gamer_status for several gamers in one query: {gamer_id: status};
gamers without a status row are absent from the result.
"""
ids = [int(g) for g in gamer_ids]
if not ids:
return {}
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
placeholders = ",".join("?" for _ in ids)
cursor.execute(
"SELECT gamer_id, disabled, seen_at, games_total, checked_at, missing_count, not_found "
f"FROM gamer_status WHERE gamer_id IN ({placeholders})",
ids
)
return {
int(row[0]): {
'disabled': bool(row[1]),
'seen_at': row[2],
'games_total': row[3],
'checked_at': int(row[4]),
'missing_count': int(row[5] or 0),
'not_found': bool(row[6]),
}
for row in cursor.fetchall()
}
def get_pair_check_state(self, user_id: int, gamer_id: int) -> Dict[str, Any]:
"""
Per-pair skip state: games_total baseline from the last games request
and whether the closed-account notice went out.
"""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute(
"SELECT last_games_total, closed_notice_sent FROM user_gamers "
"WHERE user_id = ? AND gamer_id = ?",
(user_id, gamer_id)
)
row = cursor.fetchone()
if not row:
return {'last_games_total': None, 'closed_notice_sent': False}
return {
'last_games_total': int(row[0]) if row[0] is not None else None,
'closed_notice_sent': bool(row[1]),
}
def set_pair_last_games_total(self, user_id: int, gamer_id: int, games_total: Optional[int]):
"""Remember the player's games_total as of this pair's last successful games request."""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute(
"UPDATE user_gamers SET last_games_total = ? WHERE user_id = ? AND gamer_id = ?",
(games_total, user_id, gamer_id)
)
conn.commit()
def set_pair_closed_notice_sent(self, user_id: int, gamer_id: int, flag: bool):
"""Mark whether the owner has been told that this player's account is closed."""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute(
"UPDATE user_gamers SET closed_notice_sent = ? WHERE user_id = ? AND gamer_id = ?",
(1 if flag else 0, user_id, gamer_id)
)
conn.commit()
def get_admin_chat_id(self) -> Optional[int]:
"""Get admin chat ID from database"""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute("SELECT value FROM admin_settings WHERE key = 'admin_chat_id'")
result = cursor.fetchone()
if result:
try:
return int(result[0])
except (ValueError, TypeError):
return None
return None
def set_admin_chat_id(self, chat_id: int):
"""Set admin chat ID in database"""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute('''
INSERT OR REPLACE INTO admin_settings (key, value, updated_at)
VALUES ('admin_chat_id', ?, CURRENT_TIMESTAMP)
''', (str(chat_id),))
conn.commit()
logger.info(f"Admin chat ID saved to database: {chat_id}")