fix: support new Steam cover layout

This commit is contained in:
strsv committed 2026-11-06 06:35:33 +03:00
1 parent e433ca3842
commit 0784d4c143
12 files changed
+200 -76

No files matched your search

+9 -1
View File
@@ -34,4 +34,12 @@
## [Unreleased] ## [Unreleased]
- Планируется: экспорт рекомендаций, расширенные фильтры по длительности, тёмная/светлая темы. ### Исправлено
- Обложки новых игр: поддержан хешированный layout Steam (`library_capsule.jpg`,
`library_header.jpg`) и фолбэк на `header_image` из Store API.
- Обложка в карточке игры больше не обрезается: `object-fit: contain` + размытый фон.
### Планируется
- Экспорт рекомендаций, расширенные фильтры по длительности, тёмная/светлая темы.
+8 -4
View File
@@ -86,11 +86,15 @@ mood → tags + genres → IDF по библиотеке → score =
`GET /api/cover/<appid>`: `GET /api/cover/<appid>`:
1. `cache/covers/<appid>/library_600x900.jpg` или `header.jpg`; 1. `cache/covers/<appid>/` (любое имя из `COVER_ORDER`);
2. `Steam/appcache/librarycache/<appid>/...`; 2. `Steam/appcache/librarycache/<appid>/` — старый плоский layout
3. скачивание с CDN и сохранение в кэш. (`library_600x900.jpg`, `header.jpg`) или новый хешированный
(`<hash>/library_capsule.jpg`, `<hash>/library_header.jpg`, ...);
3. `game_details.header_image` — новый URL Steam CDN;
4. старые CDN-имена (`library_600x900.jpg`, `library_capsule.jpg`, `header.jpg`,
`library_header.jpg`, `library_hero.jpg`).
Ответ кэшируется браузером на 30 дней. Скачанное сохраняется в `cache/covers`; ответ кэшируется браузером на 30 дней.
## Веб-сервер ## Веб-сервер
Binary file not shown.

Before

Width:  |  Height:  |  Size: 796 KiB

After

Width:  |  Height:  |  Size: 657 KiB

+9 -4
View File
@@ -123,11 +123,16 @@ GET https://store.steampowered.com/api/appdetails
`/api/cover/<appid>`: `/api/cover/<appid>`:
1. `cache/covers/<appid>/`; 1. `cache/covers/<appid>/`;
2. `Steam/appcache/librarycache/<appid>/`; 2. `Steam/appcache/librarycache/<appid>/` — оба layout:
3. Steam CDN (`library_600x900.jpg`, затем `header.jpg`). - старый: `library_600x900.jpg`, `header.jpg`, `library_hero.jpg`;
- новый: `<hash>/library_capsule.jpg`, `<hash>/library_header.jpg`,
`<hash>/library_hero.jpg`, `<hash>/logo.png`;
3. `game_details.header_image` — URL из Steam Store API (новый хешированный CDN);
4. старые CDN-имена (включая `library_hero.jpg`).
Скачанное сохраняется в `cache/covers`; ответ кэшируется браузером на 30 дней. Приоритет обложек: `library_600x900` → `library_capsule` → `header` → `library_header`
`cache_covers.py --all` прогревает кэш заранее. → `library_hero` → `logo`. Скачанное сохраняется в `cache/covers`; ответ кэшируется
браузером на 30 дней. `cache_covers.py --all` прогревает кэш заранее.
## Ограничения ## Ограничения
+5 -3
View File
@@ -274,9 +274,11 @@ python tools/cache_covers.py --all
python tools/cache_covers.py --limit 200 python tools/cache_covers.py --limit 200
``` ```
Веб-сервер кэширует обложки автоматически при первом запросе. Скрипт нужен, чтобы Веб-сервер кэширует обложки автоматически при первом запросе. Поддерживаются оба layout
прогреть кэш заранее. Если обложки нет ни в кэше Steam, ни на CDN, карточка показывает Steam: старый (`library_600x900.jpg`, `header.jpg`) и новый с хешированными подпапками
заглушку с инициалами. (`library_capsule.jpg`, `library_header.jpg`, ...). Если локальной обложки нет,
используется `header_image` из Store API или старые имена CDN. Скрипт нужен, чтобы прогреть
кэш заранее. Если обложки нет нигде, карточка показывает заглушку с инициалами.
### Перевод ### Перевод
+4 -3
View File
@@ -327,9 +327,10 @@ SELECT g.name, d.source_appid, s.name AS source_name
Обложки не хранятся в SQLite. Веб-сервер отдаёт их через `/api/cover/<appid>`: Обложки не хранятся в SQLite. Веб-сервер отдаёт их через `/api/cover/<appid>`:
1. `cache/covers/<appid>/library_600x900.jpg` или `header.jpg`; 1. `cache/covers/<appid>/` (имена из `COVER_ORDER`);
2. `Steam/appcache/librarycache/<appid>/...` (файлы клиента Steam); 2. `Steam/appcache/librarycache/<appid>/` — плоский или новый хешированный layout;
3. скачивание с CDN и сохранение в `cache/covers`. 3. `game_details.header_image` (URL из Store API);
4. старые CDN-имена, скачанное сохраняется в `cache/covers`.
Каталог `cache/` исключён из git. Прогрев: `tools/cache_covers.py`. Каталог `cache/` исключён из git. Прогрев: `tools/cache_covers.py`.
+4
View File
@@ -83,8 +83,12 @@ python tools/translate_details.py --limit 100 --about
``` ```
cache/covers/<appid>/ cache/covers/<appid>/
Steam/appcache/librarycache/<appid>/ Steam/appcache/librarycache/<appid>/
Steam/appcache/librarycache/<appid>/<hash>/library_capsule.jpg
``` ```
Новые версии Steam кладут обложки в хешированные подпапки; сервер поддерживает оба layout.
Если локальной обложки нет, используется `game_details.header_image` или старые имена CDN.
Затем: Затем:
```powershell ```powershell
+47 -34
View File
@@ -25,16 +25,35 @@ import db
import steam_source import steam_source
CDN = "https://cdn.cloudflare.steamstatic.com/steam/apps" CDN = "https://cdn.cloudflare.steamstatic.com/steam/apps"
NAMES = ("library_600x900.jpg", "header.jpg") CACHE_NAMES = steam_source.COVER_ORDER
CDN_NAMES = (
"library_600x900.jpg",
"library_capsule.jpg",
"header.jpg",
"library_header.jpg",
"library_hero.jpg",
"logo.png",
)
def has_any(paths): def has_cached(path):
for directory, names in paths: return any(os.path.isfile(os.path.join(path, name)) for name in CACHE_NAMES)
if not directory:
continue
for name in names: def download(url, path):
if os.path.isfile(os.path.join(directory, name)): try:
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
with urllib.request.urlopen(req, timeout=20) as resp:
data = resp.read()
if not data:
return False
os.makedirs(os.path.dirname(path), exist_ok=True)
tmp = path + ".tmp"
with open(tmp, "wb") as f:
f.write(data)
os.replace(tmp, path)
return True return True
except Exception:
return False return False
@@ -56,8 +75,13 @@ def main():
con = db.connect(args.db) con = db.connect(args.db)
db.init(con) db.init(con)
rows = con.execute("""SELECT appid, name FROM games rows = con.execute("""
WHERE LOWER(type)='game' ORDER BY review_pct DESC""").fetchall() SELECT g.appid, g.name, d.header_image
FROM games g
LEFT JOIN game_details d ON d.appid = g.appid
WHERE LOWER(g.type) = 'game'
ORDER BY COALESCE(g.review_pct, 0) DESC
""").fetchall()
if not args.all and args.limit: if not args.all and args.limit:
rows = rows[: args.limit] rows = rows[: args.limit]
print(f"Games: {len(rows)}") print(f"Games: {len(rows)}")
@@ -66,31 +90,24 @@ def main():
for row in rows: for row in rows:
appid = row["appid"] appid = row["appid"]
cached = os.path.join(cache_dir, str(appid)) cached = os.path.join(cache_dir, str(appid))
steam_art = os.path.join(lib_cache, str(appid)) if lib_cache else None if has_cached(cached) or steam_source.find_cover(appid, lib_cache):
if has_any([(cached, NAMES), (steam_art, steam_source_names())]):
skipped += 1 skipped += 1
continue continue
got = False got = False
for name in NAMES: header_image = row["header_image"]
url = f"{CDN}/{appid}/{name}" if header_image:
try: got = download(header_image, os.path.join(cached, "header.jpg"))
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
with urllib.request.urlopen(req, timeout=20) as resp:
data = resp.read()
if not data:
continue
os.makedirs(cached, exist_ok=True)
path = os.path.join(cached, name)
tmp = path + ".tmp"
with open(tmp, "wb") as f:
f.write(data)
os.replace(tmp, path)
got = True
break
except Exception:
continue
finally:
time.sleep(args.delay) time.sleep(args.delay)
if not got:
for name in CDN_NAMES:
url = f"{CDN}/{appid}/{name}"
got = download(url, os.path.join(cached, name))
time.sleep(args.delay)
if got:
break
if got: if got:
downloaded += 1 downloaded += 1
else: else:
@@ -100,9 +117,5 @@ def main():
print(f"cache: {cache_dir}") print(f"cache: {cache_dir}")
def steam_source_names():
return ("library_600x900.jpg", "header.jpg", "library_hero.jpg", "logo.png")
if __name__ == "__main__": if __name__ == "__main__":
main() main()
+40
View File
@@ -43,6 +43,46 @@ DEFAULT_ROOTS = (
r"C:\Program Files\Steam", r"C:\Program Files\Steam",
) )
COVER_ORDER = (
"library_600x900.jpg",
"library_capsule.jpg",
"header.jpg",
"library_header.jpg",
"library_hero.jpg",
"logo.png",
)
def find_cover(appid, lib_cache):
"""Find a cover in both Steam librarycache layouts.
Newer clients store art in hashed subdirectories:
<appid>/<hash>/library_capsule.jpg
Older clients use flat names:
<appid>/library_600x900.jpg
"""
if not lib_cache:
return None
app_dir = os.path.join(lib_cache, str(appid))
if not os.path.isdir(app_dir):
return None
try:
dirs = [app_dir]
for sub in os.listdir(app_dir):
sub_dir = os.path.join(app_dir, sub)
if os.path.isdir(sub_dir):
dirs.append(sub_dir)
# Prefer the best cover type across every layout, not the first
# subdirectory that happens to contain any image.
for name in COVER_ORDER:
for directory in dirs:
path = os.path.join(directory, name)
if os.path.isfile(path):
return path
except OSError:
return None
return None
def find_steam_root(): def find_steam_root():
try: try:
+51 -24
View File
@@ -44,8 +44,15 @@ except SystemExit:
LIB_CACHE = os.path.join(STEAM_ROOT, "appcache", "librarycache") if STEAM_ROOT else None LIB_CACHE = os.path.join(STEAM_ROOT, "appcache", "librarycache") if STEAM_ROOT else None
CACHE_DIR = os.path.join(BASE, "cache", "covers") CACHE_DIR = os.path.join(BASE, "cache", "covers")
IMAGE_LOCK = threading.Lock() IMAGE_LOCK = threading.Lock()
COVER_NAMES = ("library_600x900.jpg", "header.jpg") CACHE_COVER_NAMES = steam_source.COVER_ORDER
STEAM_COVER_NAMES = ("library_600x900.jpg", "header.jpg", "library_hero.jpg", "logo.png") CDN_COVER_NAMES = (
"library_600x900.jpg",
"library_capsule.jpg",
"header.jpg",
"library_header.jpg",
"library_hero.jpg",
"logo.png",
)
STATIC = os.path.join(os.path.dirname(os.path.abspath(__file__)), "static") STATIC = os.path.join(os.path.dirname(os.path.abspath(__file__)), "static")
STATUSES = {"backlog", "playing", "played", "tribute", "nostalgia", "ignore"} STATUSES = {"backlog", "playing", "played", "tribute", "nostalgia", "ignore"}
@@ -424,30 +431,11 @@ class Handler(BaseHTTPRequestHandler):
self._send(200, data, CONTENT_TYPES.get(ext, "image/jpeg"), self._send(200, data, CONTENT_TYPES.get(ext, "image/jpeg"),
cache=True, max_age=2592000) cache=True, max_age=2592000)
def _cover(self, appid): def _download_cover(self, url, path):
# 1. our own cache
for name in COVER_NAMES:
path = os.path.join(CACHE_DIR, str(appid), name)
if os.path.isfile(path):
self._serve_image(path)
return
# 2. art already downloaded by the Steam client
if LIB_CACHE:
for name in STEAM_COVER_NAMES:
path = os.path.join(LIB_CACHE, str(appid), name)
if os.path.isfile(path):
self._serve_image(path)
return
# 3. download once from the CDN and keep it on disk
for name in COVER_NAMES:
path = os.path.join(CACHE_DIR, str(appid), name)
data = None
with IMAGE_LOCK: with IMAGE_LOCK:
if os.path.isfile(path): if os.path.isfile(path):
with open(path, "rb") as f: with open(path, "rb") as f:
data = f.read() return f.read()
else:
url = f"https://cdn.cloudflare.steamstatic.com/steam/apps/{appid}/{name}"
try: try:
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"}) req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
with urllib.request.urlopen(req, timeout=20) as resp: with urllib.request.urlopen(req, timeout=20) as resp:
@@ -458,11 +446,50 @@ class Handler(BaseHTTPRequestHandler):
with open(tmp, "wb") as f: with open(tmp, "wb") as f:
f.write(data) f.write(data)
os.replace(tmp, path) os.replace(tmp, path)
return data
except Exception: except Exception:
data = None return None
return None
def _cover(self, appid):
app_cache = os.path.join(CACHE_DIR, str(appid))
# 1. our own cache (including new-style names)
for name in CACHE_COVER_NAMES:
path = os.path.join(app_cache, name)
if os.path.isfile(path):
self._serve_image(path)
return
# 2. art already downloaded by the Steam client (old and new layout)
local = steam_source.find_cover(appid, LIB_CACHE)
if local:
self._serve_image(local)
return
# 3. header_image from the cached store details (new hashed CDN URL)
con = connect()
try:
row = con.execute(
"SELECT header_image FROM game_details WHERE appid = ? AND COALESCE(header_image, '') <> ''",
(appid,)).fetchone()
finally:
con.close()
if row:
data = self._download_cover(row["header_image"], os.path.join(app_cache, "header.jpg"))
if data: if data:
self._send(200, data, "image/jpeg", cache=True, max_age=2592000) self._send(200, data, "image/jpeg", cache=True, max_age=2592000)
return return
# 4. legacy CDN names, kept on disk
for name in CDN_COVER_NAMES:
path = os.path.join(app_cache, name)
url = f"https://cdn.cloudflare.steamstatic.com/steam/apps/{appid}/{name}"
data = self._download_cover(url, path)
if data:
self._send(200, data, "image/jpeg", cache=True, max_age=2592000)
return
self._error(404, "no cover") self._error(404, "no cover")
def _api_get(self, path, qs): def _api_get(self, path, qs):
+2
View File
@@ -545,6 +545,7 @@ function renderModal(g) {
$("#modalBody").innerHTML = ` $("#modalBody").innerHTML = `
<div class="modal-grid"> <div class="modal-grid">
<div class="modal-cover" id="modalCover"> <div class="modal-cover" id="modalCover">
<div class="cover-blur" id="modalCoverBlur"></div>
<img data-appid="${g.appid}" src="${coverUrl(g.appid)}" alt=""> <img data-appid="${g.appid}" src="${coverUrl(g.appid)}" alt="">
<div class="fallback">${esc(g.name)}</div> <div class="fallback">${esc(g.name)}</div>
</div> </div>
@@ -575,6 +576,7 @@ function renderModal(g) {
</div> </div>
</div>`; </div>`;
$("#modalCoverBlur").style.backgroundImage = `url("${coverUrl(g.appid)}")`;
attachCoverFallback($("#modalCover img")); attachCoverFallback($("#modalCover img"));
$("#modalClose").addEventListener("click", () => $("#modal").close()); $("#modalClose").addEventListener("click", () => $("#modal").close());
+21 -3
View File
@@ -554,11 +554,29 @@ textarea { resize: vertical; min-height: 54px; }
grid-template-columns: 300px minmax(0, 1fr); grid-template-columns: 300px minmax(0, 1fr);
max-height: calc(100vh - 36px); max-height: calc(100vh - 36px);
} }
.modal-cover { position: relative; background: var(--bg-2); } .modal-cover { position: relative; overflow: hidden; background: var(--bg-2); }
.modal-cover img { width: 100%; height: 100%; object-fit: cover; display: block; } .modal-cover .cover-blur {
position: absolute;
inset: -24px;
background-size: cover;
background-position: center;
filter: blur(24px) saturate(1.2);
opacity: .48;
transform: scale(1.08);
z-index: 0;
}
.modal-cover img {
position: relative;
z-index: 1;
width: 100%;
height: 100%;
object-fit: contain;
display: block;
}
.modal-cover .fallback { display: none; } .modal-cover .fallback { display: none; }
.modal-cover.noimg .cover-blur { display: none; }
.modal-cover.noimg .fallback { .modal-cover.noimg .fallback {
position: absolute; inset: 0; display: grid; place-items: center; position: absolute; inset: 0; display: grid; place-items: center; z-index: 2;
background: linear-gradient(145deg, rgba(243, 180, 92, .25), rgba(94, 234, 212, .12)), var(--bg-2); background: linear-gradient(145deg, rgba(243, 180, 92, .25), rgba(94, 234, 212, .12)), var(--bg-2);
font-size: 22px; font-weight: 700; text-align: center; padding: 20px; font-size: 22px; font-weight: 700; text-align: center; padding: 20px;
} }