yahtzee-server/models/server_db.py

165 lines
6.1 KiB
Python
Raw Permalink Normal View History

# -*- coding: utf-8 -*-
import os
import sys
2026-11-03 21:36:32 +00:00
import sqlite3
import threading
from datetime import datetime
from models.server_config import ServerConfig
def get_writable_server_db_path(filename="yahtzee_server.db") -> str:
"""
Ermittelt einen beschreibbaren Pfad für die Server-Datenbank auf Linux, Windows und macOS.
"""
if sys.platform == "darwin" and getattr(sys, "frozen", False):
app_support = os.path.expanduser("~/Library/Application Support/YahtzeeServer")
os.makedirs(app_support, exist_ok=True)
return os.path.join(app_support, filename)
if getattr(sys, "frozen", False):
base_dir = os.path.dirname(sys.executable)
else:
base_dir = os.path.abspath(".")
candidate = os.path.join(base_dir, filename)
if os.access(base_dir, os.W_OK):
return candidate
fallback_dir = os.path.expanduser("~/.yahtzee_server")
os.makedirs(fallback_dir, exist_ok=True)
return os.path.join(fallback_dir, filename)
2026-11-03 21:36:32 +00:00
class ServerDatabase:
"""Thread-sichere SQLite-Datenbank für Spieler-Accounts und Match-Statistiken auf dem Server."""
DB_FILE = get_writable_server_db_path("yahtzee_server.db")
2026-11-03 21:36:32 +00:00
_lock = threading.Lock()
@classmethod
def get_conn(cls):
return sqlite3.connect(cls.DB_FILE, check_same_thread=False)
@classmethod
def init_db(cls):
with cls._lock:
with cls.get_conn() as conn:
conn.execute("""
CREATE TABLE IF NOT EXISTS accounts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username_lower TEXT UNIQUE NOT NULL,
display_name TEXT NOT NULL,
pw_hash TEXT NOT NULL,
pw_salt TEXT NOT NULL,
games_played INTEGER DEFAULT 0,
wins INTEGER DEFAULT 0,
highscore INTEGER DEFAULT 0,
created_at TEXT NOT NULL,
last_login TEXT
)
""")
conn.commit()
@classmethod
def register_account(cls, username: str, password: str) -> tuple[bool, str, dict]:
"""
Legt einen neuen Spieler-Account an.
Prüft den Namen case-insensitiv, speichert aber exakt den angegebenen display_name.
2026-11-03 21:36:32 +00:00
"""
clean_name = username.strip()
if len(clean_name) < 2 or len(clean_name) > 20:
return False, "ERR_INVALID_NAME_LENGTH", {}
if not password or len(password) < 4:
return False, "ERR_PASSWORD_TOO_SHORT", {}
uname_lower = clean_name.lower()
pw_hash, pw_salt = ServerConfig.hash_password(password)
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with cls._lock:
with cls.get_conn() as conn:
cur = conn.cursor()
cur.execute("SELECT id FROM accounts WHERE username_lower = ?", (uname_lower,))
if cur.fetchone():
return False, "ERR_NAME_TAKEN", {}
cur.execute("""
INSERT INTO accounts (username_lower, display_name, pw_hash, pw_salt, created_at, last_login)
VALUES (?, ?, ?, ?, ?, ?)
""", (uname_lower, clean_name, pw_hash, pw_salt, now, now))
conn.commit()
acc_id = cur.lastrowid
return True, "OK", {
"id": acc_id,
"display_name": clean_name,
"games_played": 0,
"wins": 0,
"highscore": 0
}
@classmethod
def login_account(cls, username: str, password: str) -> tuple[bool, str, dict]:
"""
Prüft Nutzername (case-insensitiv) und Passwort.
Gibt bei Erfolg den originalen display_name zurück.
"""
uname_lower = username.strip().lower()
if not uname_lower or not password:
return False, "ERR_EMPTY_CREDENTIALS", {}
with cls._lock:
with cls.get_conn() as conn:
cur = conn.cursor()
cur.execute("""
SELECT id, display_name, pw_hash, pw_salt, games_played, wins, highscore
FROM accounts WHERE username_lower = ?
""", (uname_lower,))
row = cur.fetchone()
if not row:
return False, "ERR_ACCOUNT_NOT_FOUND", {}
acc_id, display_name, pw_hash, pw_salt, games, wins, highscore = row
if not ServerConfig.verify_password(password, pw_hash, pw_salt):
return False, "ERR_WRONG_PASSWORD", {}
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
cur.execute("UPDATE accounts SET last_login = ? WHERE id = ?", (now, acc_id))
conn.commit()
return True, "OK", {
"id": acc_id,
"display_name": display_name,
"games_played": games,
"wins": wins,
"highscore": highscore
}
@classmethod
def record_match_result(cls, account_id: int, won: bool, score: int):
"""Aktualisiert Spiele, Siege und Highscore eines Spielers nach Match-Ende."""
2026-11-03 21:36:32 +00:00
with cls._lock:
with cls.get_conn() as conn:
cur = conn.cursor()
cur.execute("SELECT games_played, wins, highscore FROM accounts WHERE id = ?", (account_id,))
row = cur.fetchone()
if not row:
return
games, wins, high = row[0] or 0, row[1] or 0, row[2] or 0
2026-11-03 21:36:32 +00:00
new_games = games + 1
new_wins = wins + (1 if won else 0)
new_high = max(high, score)
cur.execute("""
UPDATE accounts
SET games_played = ?, wins = ?, highscore = ?
WHERE id = ?
""", (new_games, new_wins, new_high, account_id))
conn.commit()
@classmethod
def count_accounts(cls) -> int:
with cls._lock:
with cls.get_conn() as conn:
cur = conn.cursor()
cur.execute("SELECT COUNT(*) FROM accounts")
return cur.fetchone()[0]