the_goth_cardgame_collection/models/db_locator.py

163 lines
5.6 KiB
Python
Raw Normal View History

# -*- coding: utf-8 -*-
# models/db_locator.py
from __future__ import annotations
import json
import os
import sqlite3
import sys
from pathlib import Path
from resources.code_res.game_constants import USER_DB_FILENAME
APP_CONFIG_DIR_WIN = "TheGothCardgameCollection"
APP_CONFIG_DIR_UNIX = "the_goth_cardgame_collection"
LOCATOR_FILENAME = "db_locator.json"
class DbLocator:
"""
Speichert außerhalb des Installationsordners (im OS-Nutzerprofil), wo die aktive
user_data.db liegt und welche Online-Serveradresse zuletzt verwendet wurde.
"""
@staticmethod
def get_os_config_dir() -> Path:
if sys.platform.startswith("win"):
base = Path(os.environ.get("APPDATA", Path.home() / "AppData" / "Roaming"))
cfg_dir = base / APP_CONFIG_DIR_WIN
elif sys.platform == "darwin":
cfg_dir = Path.home() / "Library" / "Application Support" / APP_CONFIG_DIR_WIN
else:
xdg = os.environ.get("XDG_CONFIG_HOME")
base = Path(xdg) if xdg else (Path.home() / ".config")
cfg_dir = base / APP_CONFIG_DIR_UNIX
cfg_dir.mkdir(parents=True, exist_ok=True)
return cfg_dir
@classmethod
def get_locator_file(cls) -> Path:
return cls.get_os_config_dir() / LOCATOR_FILENAME
@classmethod
def load_config(cls) -> dict:
p = cls.get_locator_file()
if p.is_file():
try:
data = json.loads(p.read_text(encoding="utf-8"))
if isinstance(data, dict):
return data
except Exception:
pass
return {}
@classmethod
def save_config(cls, updates: dict) -> None:
cfg = cls.load_config()
cfg.update(updates)
try:
cls.get_locator_file().write_text(
json.dumps(cfg, indent=2, ensure_ascii=False),
encoding="utf-8",
)
except Exception:
pass
@staticmethod
def _is_volatile_tmp_path(p: Path) -> bool:
s = str(p).replace("\\", "/")
return s == "/tmp" or s.startswith("/tmp/") or "/_MEI" in s
@staticmethod
def _db_has_profiles(db_file: Path) -> bool:
if not db_file.is_file():
return False
try:
with sqlite3.connect(str(db_file)) as c:
row = c.execute("SELECT COUNT(*) FROM profiles;").fetchone()
return bool(row and int(row[0]) > 0)
except Exception:
return False
@classmethod
def resolve_initial_db_path(cls, default_fallback_dir: Path) -> Path:
cfg = cls.load_config()
saved_raw = str(cfg.get("user_db_path", "")).strip()
if saved_raw:
cand = Path(saved_raw).expanduser()
try:
resolved = cand.resolve()
# Leere /tmp-Datenbank aus früherem PyInstaller-Lauf ignorieren!
if cls._is_volatile_tmp_path(resolved) and not cls._db_has_profiles(resolved):
pass
elif resolved.is_file():
return resolved
elif not cls._is_volatile_tmp_path(resolved):
resolved.parent.mkdir(parents=True, exist_ok=True)
if os.access(resolved.parent, os.W_OK):
return resolved
except Exception:
pass
legacy_file = (default_fallback_dir / USER_DB_FILENAME).resolve()
if not cls._is_volatile_tmp_path(legacy_file) and legacy_file.is_file():
cls.remember_db_path(legacy_file)
return legacy_file
if getattr(sys, "frozen", False) or cls._is_volatile_tmp_path(legacy_file):
os_data_dir = cls._default_installed_data_dir()
return (os_data_dir / USER_DB_FILENAME).resolve()
return legacy_file
@staticmethod
def _default_installed_data_dir() -> Path:
if sys.platform.startswith("win"):
base = Path(os.environ.get("LOCALAPPDATA", Path.home() / "AppData" / "Local"))
d = base / APP_CONFIG_DIR_WIN
elif sys.platform == "darwin":
d = Path.home() / "Library" / "Application Support" / APP_CONFIG_DIR_WIN
else:
xdg = os.environ.get("XDG_DATA_HOME")
base = Path(xdg) if xdg else (Path.home() / ".local" / "share")
d = base / APP_CONFIG_DIR_UNIX
d.mkdir(parents=True, exist_ok=True)
return d
@classmethod
def remember_db_path(cls, db_file_path: Path) -> None:
resolved = db_file_path.expanduser().resolve()
cfg = cls.load_config()
history: list[str] = list(cfg.get("known_db_paths", []))
s_path = str(resolved)
if s_path in history:
history.remove(s_path)
history.insert(0, s_path)
cls.save_config({
"user_db_path": s_path,
"user_db_dir": str(resolved.parent),
"known_db_paths": history[:8],
})
@classmethod
def load_online_prefs(cls) -> dict:
cfg = cls.load_config()
return {
"addr_mode": cfg.get("online_addr_mode", "url"),
"url": cfg.get("online_url", "https://"),
"ip": cfg.get("online_ip", "127.0.0.1"),
"port": str(cfg.get("online_port", "8443")),
"username": cfg.get("online_username", ""),
}
@classmethod
def save_online_prefs(
cls, addr_mode: str, url: str, ip: str, port: str, username: str
) -> None:
cls.save_config({
"online_addr_mode": addr_mode,
"online_url": url.strip(),
"online_ip": ip.strip(),
"online_port": str(port).strip(),
"online_username": username.strip(),
})