import html import json import os import re import sqlite3 from datetime import datetime, timezone BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEFAULT_DB = os.path.join(BASE_DIR, "steam.db") SCHEMA_PATH = os.path.join(BASE_DIR, "tools", "schema.sql") SCHEMA_VERSION = 2 MOOD_PRESETS = { "adventure-rpg-party": { "description": "Приключение + RPG, прокачка героя/группы, исследование, подземелья", "genres": ["RPG", "Adventure"], "tags": { "RPG": 1.0, "Adventure": 1.0, "Party-Based RPG": 1.3, "Character Customization": 1.0, "Dungeon Crawler": 1.2, "Exploration": 1.0, "Story Rich": 0.8, "Turn-Based Combat": 0.7, "CRPG": 0.9, "Loot": 0.7, "Choices Matter": 0.6, "Fantasy": 0.5, "Open World": 0.4, }, }, "dungeon-crawler": { "description": "Подземелья, пошаговые бои, лут, рогалик", "genres": ["RPG", "Adventure"], "tags": { "Dungeon Crawler": 1.5, "Roguelike": 1.0, "Turn-Based Combat": 1.2, "Loot": 1.1, "CRPG": 0.8, "RPG": 1.0, "Party-Based RPG": 0.8, "Exploration": 0.7, }, }, "colony-management": { "description": "Колонии, базы, менеджмент, строительство", "genres": ["Simulation", "Strategy"], "tags": { "Colony Sim": 1.5, "Base Building": 1.2, "Management": 1.2, "Building": 1.0, "City Builder": 1.0, "Resource Management": 1.0, "Sandbox": 0.6, "Strategy": 0.7, "Simulation": 0.7, }, }, "survival-craft": { "description": "Выживание, крафт, открытый мир, кооп", "genres": ["Action", "Adventure", "Simulation"], "tags": { "Survival": 1.5, "Open World Survival Craft": 1.5, "Crafting": 1.2, "Base Building": 1.0, "Exploration": 0.8, "Open World": 0.7, "Co-op": 0.7, "Survival Horror": 0.4, }, }, "story-heavy": { "description": "Сюжет, выборы, атмосфера", "genres": ["Adventure", "RPG"], "tags": { "Story Rich": 1.5, "Narrative": 1.2, "Choices Matter": 1.1, "Adventure": 0.9, "Atmospheric": 0.8, "Exploration": 0.6, "RPG": 0.6, }, }, "dark-fantasy": { "description": "Тёмное фэнтези, сложность, атмосфера", "genres": ["RPG", "Adventure", "Action"], "tags": { "Dark Fantasy": 1.5, "Souls-like": 1.2, "Atmospheric": 1.0, "Lore-Rich": 0.9, "Difficult": 0.8, "Action RPG": 0.8, "RPG": 0.9, "Story Rich": 0.5, "Medieval": 0.5, }, }, "relaxing-evening": { "description": "Спокойный вечер: уютно и без спешки", "genres": ["Casual", "Simulation", "Adventure"], "tags": { "Relaxing": 1.5, "Cozy": 1.3, "Farming Sim": 1.2, "Life Sim": 0.9, "Casual": 1.0, "Atmospheric": 0.6, "Building": 0.5, "Cute": 0.5, }, }, "coop-friends": { "description": "Кооп с друзьями", "genres": ["Action", "Adventure", "RPG"], "tags": { "Co-op": 1.5, "Online Co-Op": 1.3, "Multiplayer": 1.0, "Co-op Campaign": 1.0, "PvE": 0.8, "Survival": 0.7, "Open World": 0.6, "Local Co-Op": 0.7, }, }, "sci-fi-exploration": { "description": "Космос, научная фантастика, исследование", "genres": ["Adventure", "Simulation", "Action"], "tags": { "Sci-fi": 1.4, "Space": 1.3, "Exploration": 1.2, "Open World": 0.8, "Survival": 0.7, "Atmospheric": 0.7, "Cyberpunk": 0.6, }, }, "tactical-turn-based": { "description": "Тактика, пошаговые бои, продуманные решения", "genres": ["Strategy", "RPG"], "tags": { "Turn-Based Tactics": 1.4, "Turn-Based Combat": 1.2, "Tactical": 1.2, "Turn-Based Strategy": 1.0, "Strategy": 0.9, "RPG": 0.6, "CRPG": 0.6, }, }, "horror-night": { "description": "Хоррор на ночь", "genres": ["Adventure", "Action"], "tags": { "Horror": 1.5, "Survival Horror": 1.3, "Psychological Horror": 0.9, "Atmospheric": 1.0, "Dark": 0.8, "Story Rich": 0.5, }, }, "city-builder": { "description": "Город, поселение, экономика, строительство", "genres": ["Simulation", "Strategy"], "tags": { "City Builder": 1.5, "Building": 1.2, "Management": 1.1, "Economy": 1.0, "Resource Management": 0.9, "Sandbox": 0.5, "Colony Sim": 0.6, }, }, "roguelike-run": { "description": "Рогалик на один забег", "genres": ["RPG", "Action", "Indie"], "tags": { "Roguelike": 1.4, "Roguelite": 1.3, "Action Roguelike": 0.9, "Replay Value": 0.9, "Dungeon Crawler": 0.7, "Loot": 0.6, }, }, "short-session": { "description": "Короткие сессии на вечер", "genres": ["Indie", "Casual", "Adventure"], "tags": { "Short": 1.5, "Casual": 1.2, "Relaxing": 0.8, "Puzzle": 0.8, "Atmospheric": 0.5, "Story Rich": 0.5, "Minimalist": 0.3, }, }, "mystery-detective": { "description": "Детектив, загадка, расследование", "genres": ["Adventure", "RPG"], "tags": { "Mystery": 1.5, "Detective": 1.4, "Story Rich": 1.0, "Point & Click": 0.8, "Visual Novel": 0.7, "Atmospheric": 0.6, "Puzzle": 0.5, }, }, } def connect(path=None): path = path or DEFAULT_DB con = sqlite3.connect(path, timeout=10) con.row_factory = sqlite3.Row con.execute("PRAGMA foreign_keys = ON") con.execute("PRAGMA busy_timeout = 8000") return con def _ensure_column(con, table, column, declaration): columns = {row[1] for row in con.execute(f"PRAGMA table_info({table})")} if column not in columns: con.execute(f"ALTER TABLE {table} ADD COLUMN {column} {declaration}") def _get_schema_version(con): try: row = con.execute("SELECT value FROM schema_meta WHERE key = 'schema_version'").fetchone() except sqlite3.OperationalError: return 0 if not row or row[0] is None: return 0 try: return int(row[0]) except (TypeError, ValueError): return 0 def _migration_1(con): """Add game_details.source_appid, introduced before schema versioning.""" _ensure_column(con, "game_details", "source_appid", "INTEGER") def _plain_text(*parts): text = " ".join(str(part) for part in parts if part) text = re.sub(r"<[^>]+>", " ", text) return " ".join(html.unescape(text).split()) def _search_tags(con, appid): row = con.execute( """SELECT GROUP_CONCAT(tn.name, ' ') AS names FROM game_tags gt JOIN tag_names tn ON tn.tag_id = gt.tag_id WHERE gt.appid = ?""", (appid,)).fetchone() return (row[0] if row and row[0] else "") if row else "" def refresh_search_index(con): """Rebuild the FTS5 index for every game.""" rows = con.execute(""" SELECT g.appid, g.name, d.short_description, d.about, t.short_description AS short_ru, t.about AS about_ru FROM games g LEFT JOIN game_details d ON d.appid = g.appid LEFT JOIN game_translations t ON t.appid = g.appid WHERE LOWER(g.type) = 'game' """).fetchall() tags = {r[0]: r[1] for r in con.execute(""" SELECT gt.appid, GROUP_CONCAT(tn.name, ' ') FROM game_tags gt JOIN tag_names tn ON tn.tag_id = gt.tag_id GROUP BY gt.appid """)} con.execute("DELETE FROM game_fts") con.executemany( "INSERT INTO game_fts(rowid, appid, name, description, tags) VALUES (?, ?, ?, ?, ?)", [(r["appid"], r["appid"], r["name"], _plain_text(r["short_description"], r["about"], r["short_ru"], r["about_ru"]), tags.get(r["appid"], "")) for r in rows], ) con.commit() def refresh_search_game(con, appid): """Update one FTS5 row after details or tags change.""" row = con.execute(""" SELECT g.appid, g.name, d.short_description, d.about, t.short_description AS short_ru, t.about AS about_ru FROM games g LEFT JOIN game_details d ON d.appid = g.appid LEFT JOIN game_translations t ON t.appid = g.appid WHERE g.appid = ? AND LOWER(g.type) = 'game' """, (appid,)).fetchone() con.execute("DELETE FROM game_fts WHERE rowid = ?", (appid,)) if row: con.execute( "INSERT INTO game_fts(rowid, appid, name, description, tags) VALUES (?, ?, ?, ?, ?)", (appid, appid, row["name"], _plain_text(row["short_description"], row["about"], row["short_ru"], row["about_ru"]), _search_tags(con, appid)), ) con.commit() def _migration_2(con): """Add the FTS5 search index over names, descriptions and tags.""" con.execute(""" CREATE VIRTUAL TABLE IF NOT EXISTS game_fts USING fts5( appid UNINDEXED, name, description, tags, tokenize = 'unicode61 remove_diacritics 2' ) """) refresh_search_index(con) MIGRATIONS = { 1: _migration_1, 2: _migration_2, } def init(con): """Create or upgrade the database schema. Migrations run in order from the stored ``schema_meta.schema_version``. A database created by a newer release is rejected instead of being silently modified by an older one. """ version = _get_schema_version(con) if version > SCHEMA_VERSION: raise RuntimeError( f"database schema version {version} is newer than supported {SCHEMA_VERSION}") with open(SCHEMA_PATH, encoding="utf-8") as f: con.executescript(f.read()) for target in range(version + 1, SCHEMA_VERSION + 1): MIGRATIONS[target](con) con.execute("INSERT OR REPLACE INTO schema_meta (key, value) VALUES ('schema_version', ?)", (str(SCHEMA_VERSION),)) con.commit() def seed_moods(con): now = datetime.now(timezone.utc).isoformat(timespec="seconds") for name, preset in MOOD_PRESETS.items(): con.execute( """INSERT INTO moods (name, description, genres, tags, updated_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(name) DO UPDATE SET description = excluded.description, genres = excluded.genres, tags = excluded.tags, updated_at = excluded.updated_at""", (name, preset["description"], json.dumps(preset["genres"]), json.dumps(preset["tags"]), now), ) con.commit()