Add snapshot.zip export with manifest/catalog/library, deterministic checksum, --no-notes/--include-dlc, plus an upload client with idempotency, token config and import polling.
This commit is contained in:
1 parent
1fc1aec825
commit
ffe9e76a5b
11 files changed
+850
-5
No files matched your search
@@ -52,6 +52,8 @@ SteamBase/
|
||||
│ ├── evaluate_reco.py # офлайн-метрики рекомендаций
|
||||
│ ├── compare_presets.py # сравнение двух пресетов
|
||||
│ ├── personal.py # статусы/оценки/заметки/атрибуты
|
||||
│ ├── export_snapshot.py # snapshot.zip для SteamBaseServer
|
||||
│ ├── upload_snapshot.py # экспорт + загрузка снимка на сервер
|
||||
│ └── check_links.py # проверка ссылок в Markdown
|
||||
├── tests/ # unittest (steam_source, import, reco, API, db)
|
||||
├── .gitea/workflows/ci.yml # CI: компиляция, тесты, ссылки
|
||||
@@ -73,6 +75,8 @@ python tools/import_steam.py
|
||||
python tools/import_steam.py --incremental
|
||||
python tools/import_steam.py --refresh-parents
|
||||
python tools/check_ownership.py
|
||||
python tools/export_snapshot.py --out snapshot.zip --handle strsv
|
||||
python tools/upload_snapshot.py --file snapshot.zip
|
||||
|
||||
# сервер
|
||||
python web/server.py --port 8765 --open
|
||||
@@ -136,6 +140,8 @@ Invoke-RestMethod http://127.0.0.1:8765/api/game/1086940
|
||||
- **SteamDB не использовать** (403). Источники перечислены в `docs/data-sources.md`.
|
||||
- Ключ Steam Web API не писать в БД, логи, ответы API и репозиторий; только env
|
||||
`STEAMBASE_STEAM_API_KEY` или `data/steam_api_key.txt`.
|
||||
- Upload-токен сервера — только env или `data/server.json`; не включать в снимок,
|
||||
логи и репозиторий.
|
||||
- Сервер по умолчанию слушает `127.0.0.1`; не выставлять в интернет.
|
||||
|
||||
## Архитектура в двух словах
|
||||
|
||||
@@ -181,6 +181,11 @@
|
||||
- UI/UX: в карточке игры прокручивается всё тело модалки, блок «Дополнения»
|
||||
ограничен по высоте.
|
||||
- HLTB: кнопка «Повторить» скрывается после успешного завершения задачи.
|
||||
- Экспорт снимка для сервера: `tools/export_snapshot.py` (`snapshot.zip`,
|
||||
manifest/catalog/library, checksum, `--no-notes`, `--include-dlc`,
|
||||
`--no-translations`).
|
||||
- Загрузка снимка: `tools/upload_snapshot.py` (URL/токен/handle, Idempotency-Key,
|
||||
ожидание импорта, конфиг `data/server.json`).
|
||||
- Сортировка таблицы по жанру и избранному; опции в селекторе сортировки.
|
||||
- Демо-скриншоты текущего UI в README.
|
||||
|
||||
|
||||
@@ -135,6 +135,8 @@ SteamBase/
|
||||
│ ├── evaluate_reco.py # офлайн-метрики рекомендаций
|
||||
│ ├── compare_presets.py # сравнение двух пресетов
|
||||
│ ├── personal.py # статусы, оценки, заметки, атрибуты
|
||||
│ ├── export_snapshot.py # snapshot.zip для SteamBaseServer
|
||||
│ ├── upload_snapshot.py # экспорт и загрузка снимка на сервер
|
||||
│ ├── reco.py # общая логика рекомендаций и похожих игр
|
||||
│ ├── steam_source.py # чтение appinfo.vdf / appmanifest / localconfig
|
||||
│ ├── db.py # подключение, схема, миграции, профили
|
||||
@@ -163,6 +165,16 @@ SteamBase/
|
||||
└── data/ # логи и временные файлы (не коммитится)
|
||||
```
|
||||
|
||||
## Снимок на сервер
|
||||
|
||||
```powershell
|
||||
python tools/export_snapshot.py --out snapshot.zip --handle strsv
|
||||
python tools/upload_snapshot.py --file snapshot.zip
|
||||
```
|
||||
|
||||
Формат и API описаны в репозитории
|
||||
[SteamBaseServer](https://gitea.strsv.ru/strsv/SteamBaseServer).
|
||||
|
||||
## Проверки
|
||||
|
||||
```powershell
|
||||
|
||||
+8
-3
@@ -122,6 +122,9 @@
|
||||
- UI-полировка: прокрутка модалки, лимит высоты DLC, высота сравнения друзей,
|
||||
«Повторить» только для ошибок/отмены.
|
||||
- MIT-лицензия (`LICENSE`, © 2026 strsv).
|
||||
- Снимок для сервера: `tools/export_snapshot.py` (manifest/catalog/library,
|
||||
checksum, `--no-notes`, `--include-dlc`) и `tools/upload_snapshot.py`
|
||||
(URL/токен/handle, Idempotency-Key, ожидание импорта).
|
||||
- Документация: README, manual, API, architecture, data sources, schema, development,
|
||||
troubleshooting, FAQ, ROADMAP, HANDOFF, AGENTS.
|
||||
|
||||
@@ -337,10 +340,12 @@ Invoke-RestMethod http://127.0.0.1:8765/api/meta
|
||||
66. MIT-лицензия.
|
||||
67. Справка «?» с поиском и содержанием.
|
||||
68. UI-полировка модалки, DLC, друзей и HLTB.
|
||||
69. Экспорт снимка `snapshot.zip` по контракту сервера.
|
||||
70. Загрузка снимка на сервер (`upload_snapshot.py`).
|
||||
|
||||
Дальше — отдельный сервер `SteamBaseServer` (auth, снимки, шаринг, публичные
|
||||
витрины), новые версии `appinfo.vdf`, все теги Steam, portable-сборка и ручной
|
||||
screen reader.
|
||||
Дальше — локальные настройки сервера в UI, отдельный сервер `SteamBaseServer`
|
||||
(auth, снимки, шаринг, публичные витрины), новые версии `appinfo.vdf`,
|
||||
все теги Steam, portable-сборка и ручной screen reader.
|
||||
|
||||
## 10. Чек-лист новой сессии
|
||||
|
||||
|
||||
+3
-2
@@ -235,8 +235,9 @@
|
||||
- [ ] Аккаунты по инвайтам, роли admin/user, сессии, CSRF, rate-limit.
|
||||
- [x] Формат снимка `snapshot.zip` (manifest + catalog + library) и его версия
|
||||
(контракт в `SteamBaseServer/docs/snapshot-contract.md`).
|
||||
- [ ] Экспорт снимка локально + загрузка по персональному токену.
|
||||
- [ ] Локальные настройки сервера: URL, upload-токен, проверка соединения,
|
||||
- [x] Экспорт снимка локально (`export_snapshot.py`) + загрузка по токену
|
||||
(`upload_snapshot.py`).
|
||||
- [ ] Локальные настройки сервера в UI: URL, upload-токен, проверка соединения,
|
||||
статус загрузки и ссылка на витрину.
|
||||
- [ ] Импорт: дедупликация каталога, замена личных данных пользователя
|
||||
(серверная часть — в `SteamBaseServer`).
|
||||
|
||||
@@ -463,6 +463,27 @@ $env:STEAMBASE_TRANSLATE_FALLBACK = "google" # порядок фолбэка
|
||||
Термы защищаются плейсхолдерами до перевода и восстанавливаются после.
|
||||
Отключить: `--no-glossary`; другой файл: `--glossary path.json`.
|
||||
|
||||
### Снимок для сервера
|
||||
|
||||
```powershell
|
||||
python tools/export_snapshot.py --out snapshot.zip --handle strsv
|
||||
python tools/export_snapshot.py --out snapshot.zip --no-notes
|
||||
python tools/export_snapshot.py --out snapshot.zip --include-dlc
|
||||
python tools/upload_snapshot.py --file snapshot.zip
|
||||
python tools/upload_snapshot.py --url https://steambase.strsv.ru --token ...
|
||||
```
|
||||
|
||||
- `export_snapshot.py` создаёт `snapshot.zip` по контракту `SteamBaseServer`:
|
||||
`manifest.json`, `catalog.jsonl`, `library.jsonl`, опционально
|
||||
`attributes.jsonl`, `feedback.jsonl`, `moods.json`.
|
||||
- Заметки включаются по умолчанию; `--no-notes` исключает их, `--include-dlc`
|
||||
добавляет DLC/саундтреки в каталог. API-ключи и токены в снимок не попадают.
|
||||
- `upload_snapshot.py` сам экспортирует снимок (если не передан `--file`),
|
||||
считает checksum, загружает с `Idempotency-Key` и ждёт завершения импорта.
|
||||
- URL, токен и handle берутся из флагов, env (`STEAMBASE_SERVER_URL`,
|
||||
`STEAMBASE_UPLOAD_TOKEN`, `STEAMBASE_SERVER_HANDLE`) или `data/server.json`
|
||||
(пример: `docs/server-config.example.json`). Токен не логируется.
|
||||
|
||||
## 10. Обновление данных
|
||||
|
||||
```powershell
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"url": "https://steambase.strsv.ru",
|
||||
"token": "PASTE_UPLOAD_TOKEN_HERE",
|
||||
"handle": "strsv"
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
"""Tests for the local snapshot exporter."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
import zipfile
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.insert(0, os.path.join(ROOT, "tools"))
|
||||
|
||||
import db
|
||||
import export_snapshot as exporter
|
||||
|
||||
|
||||
class ExportSnapshotTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.db_path = os.path.join(self.tmp.name, "snapshot.db")
|
||||
self.con = db.connect(self.db_path)
|
||||
self.addCleanup(self.con.close)
|
||||
db.init(self.con)
|
||||
self._seed()
|
||||
|
||||
def _seed(self):
|
||||
con = self.con
|
||||
con.executemany(
|
||||
"INSERT INTO games (appid, name, type, release_date, metacritic, review_pct, parent_appid) "
|
||||
"VALUES (?,?,?,?,?,?,?)",
|
||||
[
|
||||
(1, "Alpha", "game", "2020-01-01", 90, 95, None),
|
||||
(2, "Beta", "game", "2021-01-01", 80, 85, None),
|
||||
(3, "Gamma", "game", "2022-01-01", None, 75, None),
|
||||
(4, "Alpha DLC", "dlc", None, None, None, 1),
|
||||
])
|
||||
con.executemany(
|
||||
"INSERT INTO game_playtime (appid, minutes, last_played) VALUES (?,?,?)",
|
||||
[(1, 120, "2024-01-01"), (2, 0, None), (3, 30, None), (4, 0, None)])
|
||||
con.execute("INSERT INTO game_install (appid, installed, size_bytes) VALUES (1, 1, 1024)")
|
||||
con.executemany(
|
||||
"INSERT INTO personal (appid, status, rating, favorite, notes) VALUES (?,?,?,?,?)",
|
||||
[(1, "playing", 9, 1, "личная заметка"), (2, "backlog", None, 0, None)])
|
||||
con.executemany(
|
||||
"INSERT INTO game_ownership (appid, owned, checked_at) VALUES (?,?,?)",
|
||||
[(1, 1, "2026-01-01"), (2, 0, "2026-01-01")])
|
||||
con.executemany(
|
||||
"INSERT INTO game_genres (appid, genre) VALUES (?,?)",
|
||||
[(1, "RPG"), (1, "Adventure"), (2, "RPG")])
|
||||
con.executemany(
|
||||
"INSERT INTO tag_names (tag_id, name) VALUES (?,?)",
|
||||
[(1, "RPG"), (2, "Story Rich"), (3, "Cozy")])
|
||||
con.executemany(
|
||||
"INSERT INTO game_tags (appid, tag_id) VALUES (?,?)",
|
||||
[(1, 1), (1, 2), (2, 1), (3, 3)])
|
||||
con.execute(
|
||||
"INSERT INTO game_details (appid, short_description, about, header_image, "
|
||||
"developers, publishers, release_date, lang, status) "
|
||||
"VALUES (1, 'short', 'about', 'img', 'Dev', 'Pub', '2020', 'en', 'ok')")
|
||||
con.execute(
|
||||
"INSERT INTO game_translations (appid, lang, short_description, about, provider) "
|
||||
"VALUES (1, 'ru', 'кратко', 'полно', 'google')")
|
||||
con.execute(
|
||||
"UPDATE games SET hltb_main = 10.0, hltb_extra = 12.0, hltb_complete = 15.0, "
|
||||
"hltb_id = 42, hltb_checked_at = '2026-01-01', hltb_match = 1, "
|
||||
"hltb_updated_at = '2026-01-01' WHERE appid = 1")
|
||||
con.execute("INSERT INTO attributes (appid, key, value) VALUES (1, 'mood', 'calm')")
|
||||
con.execute(
|
||||
"INSERT INTO reco_feedback (appid, mood_key, verdict, created_at) "
|
||||
"VALUES (1, 'preset:dark-fantasy', 'like', '2026-01-01')")
|
||||
con.execute(
|
||||
"INSERT INTO moods (name, description, genres, tags, updated_at) "
|
||||
"VALUES ('custom-cozy', 'Уют', '[\"Simulation\"]', '{\"Cozy\": 1.5}', '2026-01-01')")
|
||||
con.execute(
|
||||
"INSERT INTO moods (name, description, genres, tags, updated_at) "
|
||||
"VALUES ('dark-fantasy', 'встроенный', '[]', '{}', '2026-01-01')")
|
||||
con.execute("INSERT OR REPLACE INTO schema_meta (key, value) VALUES ('steamid', '76561198000000000')")
|
||||
con.commit()
|
||||
|
||||
def test_collect_basic(self):
|
||||
manifest, files = exporter.collect(self.con, handle="tester")
|
||||
self.assertEqual(manifest["format"], "steambase-snapshot")
|
||||
self.assertEqual(manifest["format_version"], 1)
|
||||
self.assertEqual(manifest["user"]["handle"], "tester")
|
||||
self.assertEqual(manifest["user"]["steamid"], "76561198000000000")
|
||||
self.assertEqual(manifest["counts"], {
|
||||
"catalog": 3, "library": 3, "attributes": 1, "feedback": 1, "moods": 1})
|
||||
self.assertEqual(manifest["checksum_sha256"], exporter._checksum(files))
|
||||
|
||||
catalog = [json.loads(line) for line in files["catalog.jsonl"].decode().splitlines()]
|
||||
by_id = {item["appid"]: item for item in catalog}
|
||||
self.assertEqual(by_id[1]["tags"], ["RPG", "Story Rich"])
|
||||
self.assertEqual(by_id[1]["genres"], ["Adventure", "RPG"])
|
||||
self.assertEqual(by_id[1]["details"]["developers"], "Dev")
|
||||
self.assertEqual(by_id[1]["translation"]["lang"], "ru")
|
||||
self.assertEqual(by_id[1]["hltb"]["main"], 10.0)
|
||||
self.assertTrue(by_id[1]["hltb"]["match"])
|
||||
|
||||
library = [json.loads(line) for line in files["library.jsonl"].decode().splitlines()]
|
||||
alpha = next(item for item in library if item["appid"] == 1)
|
||||
self.assertEqual(alpha["minutes"], 120)
|
||||
self.assertEqual(alpha["status"], "playing")
|
||||
self.assertEqual(alpha["rating"], 9)
|
||||
self.assertTrue(alpha["favorite"])
|
||||
self.assertEqual(alpha["notes"], "личная заметка")
|
||||
self.assertTrue(alpha["installed"])
|
||||
self.assertTrue(alpha["owned"])
|
||||
|
||||
moods = json.loads(files["moods.json"])
|
||||
self.assertEqual([mood["name"] for mood in moods], ["custom-cozy"])
|
||||
|
||||
def test_write_without_notes_and_with_dlc(self):
|
||||
path = os.path.join(self.tmp.name, "snapshot.zip")
|
||||
manifest = exporter.write_snapshot(
|
||||
self.con, path, handle="tester", notes=False, include_dlc=True)
|
||||
self.assertEqual(manifest["counts"]["catalog"], 4)
|
||||
with zipfile.ZipFile(path) as archive:
|
||||
self.assertEqual(export_snapshot_names(archive), {
|
||||
"manifest.json", "catalog.jsonl", "library.jsonl",
|
||||
"attributes.jsonl", "feedback.jsonl", "moods.json"})
|
||||
library = [json.loads(line) for line in
|
||||
archive.read("library.jsonl").decode().splitlines()]
|
||||
self.assertTrue(all("notes" not in item for item in library))
|
||||
stored = json.loads(archive.read("manifest.json"))
|
||||
self.assertEqual(stored["checksum_sha256"], exporter.snapshot_checksum(path))
|
||||
|
||||
def test_no_translations(self):
|
||||
manifest, files = exporter.collect(self.con, handle="tester", translations=False)
|
||||
catalog = [json.loads(line) for line in files["catalog.jsonl"].decode().splitlines()]
|
||||
self.assertTrue(all("translation" not in item for item in catalog))
|
||||
|
||||
def test_mode_validation(self):
|
||||
with self.assertRaises(ValueError):
|
||||
exporter.collect(self.con, mode="bad")
|
||||
|
||||
def test_read_manifest(self):
|
||||
path = os.path.join(self.tmp.name, "snapshot.zip")
|
||||
exporter.write_snapshot(self.con, path, handle="tester")
|
||||
self.assertEqual(exporter.read_manifest(path)["user"]["handle"], "tester")
|
||||
|
||||
|
||||
def export_snapshot_names(archive):
|
||||
return set(archive.namelist())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,88 @@
|
||||
"""Tests for the snapshot upload client."""
|
||||
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
import urllib.error
|
||||
from unittest import mock
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.insert(0, os.path.join(ROOT, "tools"))
|
||||
|
||||
import upload_snapshot
|
||||
|
||||
|
||||
class UploadSnapshotTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.path = os.path.join(self.tmp.name, "snapshot.zip")
|
||||
with open(self.path, "wb") as handle:
|
||||
handle.write(b"zip-bytes")
|
||||
|
||||
def test_resolve_config_precedence(self):
|
||||
path = os.path.join(self.tmp.name, "server.json")
|
||||
with open(path, "w", encoding="utf-8") as handle:
|
||||
json.dump({"url": "file", "token": "file", "handle": "file"}, handle)
|
||||
with mock.patch.dict(os.environ, {
|
||||
"STEAMBASE_SERVER_URL": "env",
|
||||
"STEAMBASE_UPLOAD_TOKEN": "env",
|
||||
"STEAMBASE_SERVER_HANDLE": "env"}, clear=True):
|
||||
config = upload_snapshot.resolve_config(url="cli", path=path)
|
||||
self.assertEqual(config["url"], "cli")
|
||||
self.assertEqual(config["token"], "env")
|
||||
self.assertEqual(config["handle"], "env")
|
||||
|
||||
def test_upload_headers(self):
|
||||
with mock.patch.object(upload_snapshot.exporter, "snapshot_checksum",
|
||||
return_value="abc"), \
|
||||
mock.patch.object(upload_snapshot, "_request",
|
||||
return_value={"snapshot": {"id": "s1", "status": "pending"}}) as request:
|
||||
snapshot = upload_snapshot.upload("https://server/", "token", self.path,
|
||||
idempotency_key="key-1")
|
||||
self.assertEqual(snapshot["id"], "s1")
|
||||
args = request.call_args.args
|
||||
self.assertEqual(args[0], "https://server/api/v1/snapshots")
|
||||
self.assertEqual(args[1], "token")
|
||||
self.assertEqual(args[2], b"zip-bytes")
|
||||
self.assertEqual(args[3]["X-Snapshot-Checksum"], "sha256=abc")
|
||||
self.assertEqual(args[3]["Idempotency-Key"], "key-1")
|
||||
self.assertEqual(args[3]["Content-Type"], "application/zip")
|
||||
|
||||
def test_missing_credentials(self):
|
||||
with self.assertRaises(upload_snapshot.UploadError):
|
||||
upload_snapshot.upload("", "token", self.path)
|
||||
with self.assertRaises(upload_snapshot.UploadError):
|
||||
upload_snapshot.upload("https://server", "", self.path)
|
||||
|
||||
def test_wait(self):
|
||||
with mock.patch.object(upload_snapshot, "status",
|
||||
side_effect=[{"status": "running"}, {"status": "done"}]):
|
||||
result = upload_snapshot.wait("https://server", "token", "s1",
|
||||
interval=0.001, timeout=1)
|
||||
self.assertEqual(result["status"], "done")
|
||||
|
||||
def test_status_error_is_mapped(self):
|
||||
error = urllib.error.HTTPError(
|
||||
"https://server", 401, "Unauthorized", {},
|
||||
io.BytesIO(b'{"error": {"code": "invalid_credentials", "message": "bad"}}'))
|
||||
with mock.patch("urllib.request.urlopen", side_effect=error):
|
||||
with self.assertRaises(upload_snapshot.UploadError) as context:
|
||||
upload_snapshot._request("https://server", "token")
|
||||
self.assertEqual(context.exception.status, 401)
|
||||
self.assertIn("токен", str(context.exception))
|
||||
|
||||
def test_config_file(self):
|
||||
path = os.path.join(self.tmp.name, "server.json")
|
||||
with open(path, "w", encoding="utf-8") as handle:
|
||||
json.dump({"url": "https://s", "token": "t", "handle": "h"}, handle)
|
||||
with mock.patch.dict(os.environ, {}, clear=True):
|
||||
config = upload_snapshot.resolve_config(path=path)
|
||||
self.assertEqual(config, {"url": "https://s", "token": "t", "handle": "h"})
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,339 @@
|
||||
"""Export a SteamBase library snapshot for SteamBaseServer.
|
||||
|
||||
python tools/export_snapshot.py --out snapshot.zip --handle strsv
|
||||
python tools/export_snapshot.py --out snapshot.zip --no-notes
|
||||
python tools/export_snapshot.py --out snapshot.zip --include-dlc
|
||||
|
||||
The archive follows the server contract in SteamBaseServer/docs/snapshot-contract.md:
|
||||
manifest.json, catalog.jsonl, library.jsonl and optional attributes/feedback/moods.
|
||||
The snapshot never includes API keys, tokens, logs or the database file itself.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import zipfile
|
||||
from datetime import datetime, timezone
|
||||
|
||||
for stream in (sys.stdout, sys.stderr):
|
||||
try:
|
||||
stream.reconfigure(encoding="utf-8")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
import db
|
||||
|
||||
FORMAT = "steambase-snapshot"
|
||||
FORMAT_VERSION = 1
|
||||
CHECKSUM_FILES = ("catalog.jsonl", "library.jsonl", "attributes.jsonl",
|
||||
"feedback.jsonl", "moods.json")
|
||||
VERSION_FILE = os.path.join(BASE_DIR, "VERSION")
|
||||
|
||||
|
||||
def app_version():
|
||||
try:
|
||||
with open(VERSION_FILE, encoding="utf-8") as handle:
|
||||
return handle.read().strip() or "0.0.0"
|
||||
except OSError:
|
||||
return "0.0.0"
|
||||
|
||||
|
||||
def _line(value):
|
||||
return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + "\n"
|
||||
|
||||
|
||||
def _checksum(parts):
|
||||
digest = hashlib.sha256()
|
||||
for name in CHECKSUM_FILES:
|
||||
data = parts.get(name)
|
||||
if data is None:
|
||||
continue
|
||||
digest.update(name.encode("utf-8"))
|
||||
digest.update(b"\0")
|
||||
digest.update(str(len(data)).encode("ascii"))
|
||||
digest.update(b"\0")
|
||||
digest.update(data)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def _load_json(value, fallback):
|
||||
try:
|
||||
return json.loads(value)
|
||||
except (TypeError, ValueError):
|
||||
return fallback
|
||||
|
||||
|
||||
def _game_tags(con):
|
||||
tags = {}
|
||||
for row in con.execute("""
|
||||
SELECT gt.appid, tn.name
|
||||
FROM game_tags gt JOIN tag_names tn ON tn.tag_id = gt.tag_id
|
||||
ORDER BY gt.appid, tn.name
|
||||
"""):
|
||||
tags.setdefault(row["appid"], []).append(row["name"])
|
||||
return tags
|
||||
|
||||
|
||||
def _game_genres(con):
|
||||
genres = {}
|
||||
for row in con.execute("SELECT appid, genre FROM game_genres ORDER BY appid, genre"):
|
||||
genres.setdefault(row["appid"], []).append(row["genre"])
|
||||
return genres
|
||||
|
||||
|
||||
def _details_map(con):
|
||||
return {row["appid"]: row for row in con.execute("SELECT * FROM game_details")}
|
||||
|
||||
|
||||
def _translations_map(con):
|
||||
return {row["appid"]: row for row in con.execute("SELECT * FROM game_translations")}
|
||||
|
||||
|
||||
def collect(con, handle=None, steamid=None, notes=True, translations=True,
|
||||
include_dlc=False, mode="replace"):
|
||||
"""Build snapshot files in memory and return (manifest, files)."""
|
||||
if mode not in ("replace", "merge"):
|
||||
raise ValueError("mode must be replace or merge")
|
||||
handle = (handle or os.environ.get("STEAMBASE_SERVER_HANDLE") or "").strip()
|
||||
row = con.execute("SELECT value FROM schema_meta WHERE key = 'steamid'").fetchone()
|
||||
steamid = (steamid or (row[0] if row else "") or "").strip()
|
||||
|
||||
tags = _game_tags(con)
|
||||
genres = _game_genres(con)
|
||||
details = _details_map(con)
|
||||
translations = _translations_map(con) if translations else {}
|
||||
|
||||
where = "" if include_dlc else "WHERE LOWER(g.type) = 'game'"
|
||||
catalog_lines = []
|
||||
catalog_count = 0
|
||||
for game in con.execute(f"""
|
||||
SELECT g.* FROM games g {where} ORDER BY g.appid
|
||||
"""):
|
||||
appid = game["appid"]
|
||||
entry = {
|
||||
"appid": appid,
|
||||
"name": game["name"],
|
||||
"type": game["type"],
|
||||
"release_date": game["release_date"],
|
||||
"metacritic": game["metacritic"],
|
||||
"review_pct": game["review_pct"],
|
||||
"parent_appid": game["parent_appid"],
|
||||
"genres": genres.get(appid, []),
|
||||
"tags": tags.get(appid, []),
|
||||
}
|
||||
detail = details.get(appid)
|
||||
if detail:
|
||||
entry["details"] = {
|
||||
"short_description": detail["short_description"],
|
||||
"about": detail["about"],
|
||||
"header_image": detail["header_image"],
|
||||
"developers": detail["developers"],
|
||||
"publishers": detail["publishers"],
|
||||
"release_date": detail["release_date"],
|
||||
"lang": detail["lang"],
|
||||
"status": detail["status"],
|
||||
"source_appid": detail["source_appid"],
|
||||
}
|
||||
translation = translations.get(appid)
|
||||
if translation:
|
||||
entry["translation"] = {
|
||||
"lang": translation["lang"],
|
||||
"short_description": translation["short_description"],
|
||||
"about": translation["about"],
|
||||
"provider": translation["provider"],
|
||||
"translated_at": translation["translated_at"],
|
||||
}
|
||||
if any(game[key] is not None for key in
|
||||
("hltb_main", "hltb_extra", "hltb_complete", "hltb_id", "hltb_checked_at")):
|
||||
entry["hltb"] = {
|
||||
"main": game["hltb_main"],
|
||||
"extra": game["hltb_extra"],
|
||||
"complete": game["hltb_complete"],
|
||||
"hltb_id": game["hltb_id"],
|
||||
"checked_at": game["hltb_checked_at"],
|
||||
"match": bool(game["hltb_match"]),
|
||||
"updated_at": game["hltb_updated_at"],
|
||||
}
|
||||
catalog_lines.append(_line(entry))
|
||||
catalog_count += 1
|
||||
|
||||
library_lines = []
|
||||
library_count = 0
|
||||
for row in con.execute("""
|
||||
SELECT g.appid, COALESCE(p.minutes, 0) AS minutes, p.last_played,
|
||||
COALESCE(i.installed, 0) AS installed, i.size_bytes,
|
||||
COALESCE(pe.status, 'backlog') AS status, pe.rating,
|
||||
COALESCE(pe.favorite, 0) AS favorite, pe.notes, o.owned
|
||||
FROM games g
|
||||
LEFT JOIN game_playtime p ON p.appid = g.appid
|
||||
LEFT JOIN game_install i ON i.appid = g.appid
|
||||
LEFT JOIN personal pe ON pe.appid = g.appid
|
||||
LEFT JOIN game_ownership o ON o.appid = g.appid
|
||||
WHERE LOWER(g.type) = 'game'
|
||||
ORDER BY g.appid
|
||||
"""):
|
||||
item = {
|
||||
"appid": row["appid"],
|
||||
"minutes": row["minutes"],
|
||||
"last_played": row["last_played"],
|
||||
"installed": bool(row["installed"]),
|
||||
"size_bytes": row["size_bytes"],
|
||||
"status": row["status"],
|
||||
"rating": row["rating"],
|
||||
"favorite": bool(row["favorite"]),
|
||||
"owned": None if row["owned"] is None else bool(row["owned"]),
|
||||
}
|
||||
if notes:
|
||||
item["notes"] = row["notes"]
|
||||
library_lines.append(_line(item))
|
||||
library_count += 1
|
||||
|
||||
attributes = [
|
||||
_line({"appid": row["appid"], "key": row["key"], "value": row["value"]})
|
||||
for row in con.execute("""
|
||||
SELECT appid, key, value FROM attributes ORDER BY appid, key
|
||||
""")
|
||||
]
|
||||
feedback = [
|
||||
_line({"appid": row["appid"], "mood_key": row["mood_key"],
|
||||
"verdict": row["verdict"], "created_at": row["created_at"]})
|
||||
for row in con.execute("""
|
||||
SELECT appid, mood_key, verdict, created_at FROM reco_feedback
|
||||
ORDER BY appid, mood_key
|
||||
""")
|
||||
]
|
||||
builtins = set(db.MOOD_PRESETS)
|
||||
moods = []
|
||||
for row in con.execute("SELECT name, description, genres, tags, updated_at FROM moods ORDER BY name"):
|
||||
if row["name"] in builtins:
|
||||
continue
|
||||
moods.append({
|
||||
"name": row["name"],
|
||||
"description": row["description"],
|
||||
"genres": _load_json(row["genres"], []),
|
||||
"tags": _load_json(row["tags"], {}),
|
||||
"updated_at": row["updated_at"],
|
||||
})
|
||||
|
||||
files = {
|
||||
"catalog.jsonl": "".join(catalog_lines).encode("utf-8"),
|
||||
"library.jsonl": "".join(library_lines).encode("utf-8"),
|
||||
}
|
||||
if attributes:
|
||||
files["attributes.jsonl"] = "".join(attributes).encode("utf-8")
|
||||
if feedback:
|
||||
files["feedback.jsonl"] = "".join(feedback).encode("utf-8")
|
||||
if moods:
|
||||
files["moods.json"] = _line(moods).encode("utf-8")
|
||||
|
||||
manifest = {
|
||||
"format": FORMAT,
|
||||
"format_version": FORMAT_VERSION,
|
||||
"app_version": app_version(),
|
||||
"generated_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
|
||||
"user": {"handle": handle, "steamid": steamid, "display_name": handle or steamid},
|
||||
"mode": mode,
|
||||
"counts": {
|
||||
"catalog": catalog_count,
|
||||
"library": library_count,
|
||||
"attributes": len(attributes),
|
||||
"feedback": len(feedback),
|
||||
"moods": len(moods),
|
||||
},
|
||||
"checksum_sha256": _checksum(files),
|
||||
}
|
||||
return manifest, files
|
||||
|
||||
|
||||
def write_snapshot(con, out_path, **options):
|
||||
manifest, files = collect(con, **options)
|
||||
out_dir = os.path.dirname(os.path.abspath(out_path)) or "."
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
tmp_path = out_path + ".tmp"
|
||||
try:
|
||||
with zipfile.ZipFile(tmp_path, "w", zipfile.ZIP_DEFLATED) as archive:
|
||||
archive.writestr("manifest.json", _line(manifest))
|
||||
for name in CHECKSUM_FILES:
|
||||
data = files.get(name)
|
||||
if data is not None:
|
||||
archive.writestr(name, data)
|
||||
os.replace(tmp_path, out_path)
|
||||
finally:
|
||||
if os.path.exists(tmp_path):
|
||||
os.unlink(tmp_path)
|
||||
return manifest
|
||||
|
||||
|
||||
def snapshot_checksum(path):
|
||||
"""Recompute the checksum of an existing snapshot (manifest excluded)."""
|
||||
with zipfile.ZipFile(path) as archive:
|
||||
parts = {}
|
||||
for name in CHECKSUM_FILES:
|
||||
try:
|
||||
parts[name] = archive.read(name)
|
||||
except KeyError:
|
||||
continue
|
||||
return _checksum(parts)
|
||||
|
||||
|
||||
def read_manifest(path):
|
||||
with zipfile.ZipFile(path) as archive:
|
||||
return json.loads(archive.read("manifest.json").decode("utf-8"))
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description="Export a SteamBase snapshot")
|
||||
ap.add_argument("--db", default=db.DEFAULT_DB)
|
||||
ap.add_argument("--out", default="snapshot.zip")
|
||||
ap.add_argument("--handle", default=os.environ.get("STEAMBASE_SERVER_HANDLE"))
|
||||
ap.add_argument("--steamid")
|
||||
ap.add_argument("--no-notes", action="store_true", help="do not include personal notes")
|
||||
ap.add_argument("--no-translations", action="store_true", help="do not include translations")
|
||||
ap.add_argument("--include-dlc", action="store_true",
|
||||
help="include DLC, soundtracks and tools in the catalog")
|
||||
ap.add_argument("--mode", choices=("replace", "merge"), default="replace")
|
||||
ap.add_argument("--format-version", type=int, default=FORMAT_VERSION)
|
||||
ap.add_argument("--dry-run", action="store_true")
|
||||
args = ap.parse_args()
|
||||
|
||||
if args.format_version != FORMAT_VERSION:
|
||||
print(f"Unsupported format version: {args.format_version}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
con = db.connect(args.db)
|
||||
try:
|
||||
options = {
|
||||
"handle": args.handle,
|
||||
"steamid": args.steamid,
|
||||
"notes": not args.no_notes,
|
||||
"translations": not args.no_translations,
|
||||
"include_dlc": args.include_dlc,
|
||||
"mode": args.mode,
|
||||
}
|
||||
if args.dry_run:
|
||||
manifest, _ = collect(con, **options)
|
||||
print(json.dumps(manifest, ensure_ascii=False, indent=2))
|
||||
return 0
|
||||
manifest = write_snapshot(con, args.out, **options)
|
||||
size = os.path.getsize(args.out)
|
||||
print(f"Snapshot: {args.out}")
|
||||
print(f"Size: {size} bytes")
|
||||
print(f"Catalog: {manifest['counts']['catalog']} | "
|
||||
f"Library: {manifest['counts']['library']} | "
|
||||
f"Attributes: {manifest['counts']['attributes']} | "
|
||||
f"Feedback: {manifest['counts']['feedback']} | "
|
||||
f"Moods: {manifest['counts']['moods']}")
|
||||
print(f"Checksum: sha256={manifest['checksum_sha256']}")
|
||||
return 0
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,215 @@
|
||||
"""Export and upload a SteamBase snapshot to SteamBaseServer.
|
||||
|
||||
python tools/upload_snapshot.py --url https://steambase.strsv.ru --token ...
|
||||
python tools/upload_snapshot.py --file snapshot.zip
|
||||
|
||||
Configuration precedence: CLI > environment > data/server.json.
|
||||
The token is never printed or written to logs.
|
||||
|
||||
Environment:
|
||||
STEAMBASE_SERVER_URL
|
||||
STEAMBASE_UPLOAD_TOKEN
|
||||
STEAMBASE_SERVER_HANDLE
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
for stream in (sys.stdout, sys.stderr):
|
||||
try:
|
||||
stream.reconfigure(encoding="utf-8")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
import db
|
||||
import export_snapshot as exporter
|
||||
|
||||
CONFIG_FILE = os.path.join(BASE_DIR, "data", "server.json")
|
||||
DEFAULT_TIMEOUT = 60
|
||||
DEFAULT_POLL_INTERVAL = 2
|
||||
DEFAULT_POLL_TIMEOUT = 300
|
||||
|
||||
|
||||
class UploadError(RuntimeError):
|
||||
def __init__(self, message, status=None, code=None):
|
||||
super().__init__(message)
|
||||
self.status = status
|
||||
self.code = code
|
||||
|
||||
|
||||
def load_config(path=CONFIG_FILE):
|
||||
try:
|
||||
with open(path, encoding="utf-8") as handle:
|
||||
data = json.load(handle)
|
||||
except (OSError, ValueError):
|
||||
return {}
|
||||
return data if isinstance(data, dict) else {}
|
||||
|
||||
|
||||
def resolve_config(url=None, token=None, handle=None, path=CONFIG_FILE):
|
||||
saved = load_config(path)
|
||||
url = (url or os.environ.get("STEAMBASE_SERVER_URL") or saved.get("url") or "").strip()
|
||||
token = (token or os.environ.get("STEAMBASE_UPLOAD_TOKEN") or saved.get("token") or "").strip()
|
||||
handle = (handle or os.environ.get("STEAMBASE_SERVER_HANDLE") or saved.get("handle") or "").strip()
|
||||
return {"url": url.rstrip("/"), "token": token, "handle": handle}
|
||||
|
||||
|
||||
def _request(url, token, data=None, headers=None, timeout=DEFAULT_TIMEOUT):
|
||||
request_headers = {"Authorization": f"Bearer {token}"}
|
||||
request_headers.update(headers or {})
|
||||
request = urllib.request.Request(url, data=data, headers=request_headers,
|
||||
method="POST" if data is not None else "GET")
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=timeout) as response:
|
||||
return json.loads(response.read().decode("utf-8"))
|
||||
except urllib.error.HTTPError as exc:
|
||||
body = exc.read().decode("utf-8", "replace")
|
||||
try:
|
||||
payload = json.loads(body)
|
||||
error = payload.get("error") or {}
|
||||
message = error.get("message") or body or f"HTTP {exc.code}"
|
||||
code = error.get("code")
|
||||
except ValueError:
|
||||
message = body or f"HTTP {exc.code}"
|
||||
code = None
|
||||
if exc.code == 401:
|
||||
message = "токен неверный или отозван"
|
||||
elif exc.code == 403:
|
||||
message = "нет прав на загрузку"
|
||||
elif exc.code == 413:
|
||||
message = "снимок больше лимита сервера"
|
||||
elif exc.code == 429:
|
||||
message = "слишком частые загрузки, попробуйте позже"
|
||||
raise UploadError(message, status=exc.code, code=code) from None
|
||||
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
|
||||
raise UploadError(f"ошибка соединения: {type(exc).__name__}") from None
|
||||
|
||||
|
||||
def upload(url, token, path, timeout=DEFAULT_TIMEOUT, idempotency_key=None):
|
||||
if not url:
|
||||
raise UploadError("не задан URL сервера")
|
||||
if not token:
|
||||
raise UploadError("не задан upload-токен")
|
||||
with open(path, "rb") as handle:
|
||||
body = handle.read()
|
||||
checksum = exporter.snapshot_checksum(path)
|
||||
headers = {
|
||||
"Content-Type": "application/zip",
|
||||
"X-Snapshot-Checksum": f"sha256={checksum}",
|
||||
"Idempotency-Key": idempotency_key or str(uuid.uuid4()),
|
||||
}
|
||||
data = _request(f"{url.rstrip('/')}/api/v1/snapshots", token, body, headers, timeout)
|
||||
snapshot = data.get("snapshot") or data
|
||||
if not isinstance(snapshot, dict) or not snapshot.get("id"):
|
||||
raise UploadError("сервер вернул неожиданный ответ")
|
||||
return snapshot
|
||||
|
||||
|
||||
def status(url, token, snapshot_id, timeout=DEFAULT_TIMEOUT):
|
||||
data = _request(f"{url.rstrip('/')}/api/v1/snapshots/{snapshot_id}", token, timeout=timeout)
|
||||
return data.get("snapshot") or data
|
||||
|
||||
|
||||
def wait(url, token, snapshot_id, interval=DEFAULT_POLL_INTERVAL,
|
||||
timeout=DEFAULT_POLL_TIMEOUT, on_status=None):
|
||||
deadline = time.time() + timeout
|
||||
while True:
|
||||
data = status(url, token, snapshot_id)
|
||||
state = data.get("status")
|
||||
if on_status:
|
||||
on_status(data)
|
||||
if state in ("done", "failed", "cancelled"):
|
||||
return data
|
||||
if time.time() >= deadline:
|
||||
raise UploadError(f"импорт не завершился за {timeout} с")
|
||||
time.sleep(interval)
|
||||
|
||||
|
||||
def _print_status(data):
|
||||
state = data.get("status") or "?"
|
||||
counts = data.get("counts") or {}
|
||||
suffix = ""
|
||||
if counts:
|
||||
suffix = f" | catalog={counts.get('catalog', '?')} library={counts.get('library', '?')}"
|
||||
print(f" snapshot {data.get('id', '?')}: {state}{suffix}")
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description="Upload a SteamBase snapshot")
|
||||
ap.add_argument("--url", help="server URL, e.g. https://steambase.strsv.ru")
|
||||
ap.add_argument("--token", help="upload token")
|
||||
ap.add_argument("--handle", help="server handle for the manifest")
|
||||
ap.add_argument("--file", help="existing snapshot.zip (otherwise export now)")
|
||||
ap.add_argument("--db", default=db.DEFAULT_DB)
|
||||
ap.add_argument("--no-notes", action="store_true")
|
||||
ap.add_argument("--no-translations", action="store_true")
|
||||
ap.add_argument("--include-dlc", action="store_true")
|
||||
ap.add_argument("--mode", choices=("replace", "merge"), default="replace")
|
||||
ap.add_argument("--no-poll", action="store_true")
|
||||
ap.add_argument("--timeout", type=float, default=DEFAULT_POLL_TIMEOUT)
|
||||
args = ap.parse_args()
|
||||
|
||||
config = resolve_config(args.url, args.token, args.handle)
|
||||
if not config["url"] or not config["token"]:
|
||||
print("Задайте --url и --token (или data/server.json / env)", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
temp_dir = None
|
||||
path = args.file
|
||||
try:
|
||||
if not path:
|
||||
temp_dir = tempfile.TemporaryDirectory(prefix="steambase-snapshot-")
|
||||
path = os.path.join(temp_dir.name, "snapshot.zip")
|
||||
con = db.connect(args.db)
|
||||
try:
|
||||
manifest = exporter.write_snapshot(
|
||||
con, path,
|
||||
handle=config["handle"],
|
||||
notes=not args.no_notes,
|
||||
translations=not args.no_translations,
|
||||
include_dlc=args.include_dlc,
|
||||
mode=args.mode,
|
||||
)
|
||||
finally:
|
||||
con.close()
|
||||
print(f"Экспортировано: catalog={manifest['counts']['catalog']} "
|
||||
f"library={manifest['counts']['library']} "
|
||||
f"({os.path.getsize(path)} байт)")
|
||||
|
||||
snapshot = upload(config["url"], config["token"], path)
|
||||
print(f"Загружено: snapshot={snapshot['id']} status={snapshot.get('status')}")
|
||||
if args.no_poll:
|
||||
return 0
|
||||
if snapshot.get("status") in ("done", "failed", "cancelled"):
|
||||
_print_status(snapshot)
|
||||
return 0 if snapshot.get("status") == "done" else 1
|
||||
final = wait(config["url"], config["token"], snapshot["id"],
|
||||
timeout=args.timeout, on_status=None)
|
||||
_print_status(final)
|
||||
if final.get("status") == "done":
|
||||
print("Импорт завершён")
|
||||
return 0
|
||||
print(f"Импорт завершился со статусом: {final.get('status')}", file=sys.stderr)
|
||||
if final.get("error"):
|
||||
print(final["error"], file=sys.stderr)
|
||||
return 1
|
||||
except UploadError as exc:
|
||||
print(f"Ошибка: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
finally:
|
||||
if temp_dir is not None:
|
||||
temp_dir.cleanup()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in new issue
Block a user