fix: support new Steam cover layout
This commit is contained in:
1 parent
e433ca3842
commit
0784d4c143
12 files changed
+200
-76
No files matched your search
+9
-1
@@ -34,4 +34,12 @@
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
- Планируется: экспорт рекомендаций, расширенные фильтры по длительности, тёмная/светлая темы.
|
||||
### Исправлено
|
||||
|
||||
- Обложки новых игр: поддержан хешированный layout Steam (`library_capsule.jpg`,
|
||||
`library_header.jpg`) и фолбэк на `header_image` из Store API.
|
||||
- Обложка в карточке игры больше не обрезается: `object-fit: contain` + размытый фон.
|
||||
|
||||
### Планируется
|
||||
|
||||
- Экспорт рекомендаций, расширенные фильтры по длительности, тёмная/светлая темы.
|
||||
@@ -86,11 +86,15 @@ mood → tags + genres → IDF по библиотеке → score =
|
||||
|
||||
`GET /api/cover/<appid>`:
|
||||
|
||||
1. `cache/covers/<appid>/library_600x900.jpg` или `header.jpg`;
|
||||
2. `Steam/appcache/librarycache/<appid>/...`;
|
||||
3. скачивание с CDN и сохранение в кэш.
|
||||
1. `cache/covers/<appid>/` (любое имя из `COVER_ORDER`);
|
||||
2. `Steam/appcache/librarycache/<appid>/` — старый плоский layout
|
||||
(`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 |
@@ -123,11 +123,16 @@ GET https://store.steampowered.com/api/appdetails
|
||||
`/api/cover/<appid>`:
|
||||
|
||||
1. `cache/covers/<appid>/`;
|
||||
2. `Steam/appcache/librarycache/<appid>/`;
|
||||
3. Steam CDN (`library_600x900.jpg`, затем `header.jpg`).
|
||||
2. `Steam/appcache/librarycache/<appid>/` — оба layout:
|
||||
- старый: `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 дней.
|
||||
`cache_covers.py --all` прогревает кэш заранее.
|
||||
Приоритет обложек: `library_600x900` → `library_capsule` → `header` → `library_header`
|
||||
→ `library_hero` → `logo`. Скачанное сохраняется в `cache/covers`; ответ кэшируется
|
||||
браузером на 30 дней. `cache_covers.py --all` прогревает кэш заранее.
|
||||
|
||||
## Ограничения
|
||||
|
||||
|
||||
+5
-3
@@ -274,9 +274,11 @@ python tools/cache_covers.py --all
|
||||
python tools/cache_covers.py --limit 200
|
||||
```
|
||||
|
||||
Веб-сервер кэширует обложки автоматически при первом запросе. Скрипт нужен, чтобы
|
||||
прогреть кэш заранее. Если обложки нет ни в кэше Steam, ни на CDN, карточка показывает
|
||||
заглушку с инициалами.
|
||||
Веб-сервер кэширует обложки автоматически при первом запросе. Поддерживаются оба layout
|
||||
Steam: старый (`library_600x900.jpg`, `header.jpg`) и новый с хешированными подпапками
|
||||
(`library_capsule.jpg`, `library_header.jpg`, ...). Если локальной обложки нет,
|
||||
используется `header_image` из Store API или старые имена CDN. Скрипт нужен, чтобы прогреть
|
||||
кэш заранее. Если обложки нет нигде, карточка показывает заглушку с инициалами.
|
||||
|
||||
### Перевод
|
||||
|
||||
|
||||
+4
-3
@@ -327,9 +327,10 @@ SELECT g.name, d.source_appid, s.name AS source_name
|
||||
|
||||
Обложки не хранятся в SQLite. Веб-сервер отдаёт их через `/api/cover/<appid>`:
|
||||
|
||||
1. `cache/covers/<appid>/library_600x900.jpg` или `header.jpg`;
|
||||
2. `Steam/appcache/librarycache/<appid>/...` (файлы клиента Steam);
|
||||
3. скачивание с CDN и сохранение в `cache/covers`.
|
||||
1. `cache/covers/<appid>/` (имена из `COVER_ORDER`);
|
||||
2. `Steam/appcache/librarycache/<appid>/` — плоский или новый хешированный layout;
|
||||
3. `game_details.header_image` (URL из Store API);
|
||||
4. старые CDN-имена, скачанное сохраняется в `cache/covers`.
|
||||
|
||||
Каталог `cache/` исключён из git. Прогрев: `tools/cache_covers.py`.
|
||||
|
||||
|
||||
@@ -83,8 +83,12 @@ python tools/translate_details.py --limit 100 --about
|
||||
```
|
||||
cache/covers/<appid>/
|
||||
Steam/appcache/librarycache/<appid>/
|
||||
Steam/appcache/librarycache/<appid>/<hash>/library_capsule.jpg
|
||||
```
|
||||
|
||||
Новые версии Steam кладут обложки в хешированные подпапки; сервер поддерживает оба layout.
|
||||
Если локальной обложки нет, используется `game_details.header_image` или старые имена CDN.
|
||||
|
||||
Затем:
|
||||
|
||||
```powershell
|
||||
|
||||
+47
-34
@@ -25,16 +25,35 @@ import db
|
||||
import steam_source
|
||||
|
||||
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):
|
||||
for directory, names in paths:
|
||||
if not directory:
|
||||
continue
|
||||
for name in names:
|
||||
if os.path.isfile(os.path.join(directory, name)):
|
||||
def has_cached(path):
|
||||
return any(os.path.isfile(os.path.join(path, name)) for name in CACHE_NAMES)
|
||||
|
||||
|
||||
def download(url, path):
|
||||
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
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
@@ -56,8 +75,13 @@ def main():
|
||||
|
||||
con = db.connect(args.db)
|
||||
db.init(con)
|
||||
rows = con.execute("""SELECT appid, name FROM games
|
||||
WHERE LOWER(type)='game' ORDER BY review_pct DESC""").fetchall()
|
||||
rows = con.execute("""
|
||||
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:
|
||||
rows = rows[: args.limit]
|
||||
print(f"Games: {len(rows)}")
|
||||
@@ -66,31 +90,24 @@ def main():
|
||||
for row in rows:
|
||||
appid = row["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_any([(cached, NAMES), (steam_art, steam_source_names())]):
|
||||
if has_cached(cached) or steam_source.find_cover(appid, lib_cache):
|
||||
skipped += 1
|
||||
continue
|
||||
|
||||
got = False
|
||||
for name in NAMES:
|
||||
url = f"{CDN}/{appid}/{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:
|
||||
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:
|
||||
header_image = row["header_image"]
|
||||
if header_image:
|
||||
got = download(header_image, os.path.join(cached, "header.jpg"))
|
||||
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:
|
||||
downloaded += 1
|
||||
else:
|
||||
@@ -100,9 +117,5 @@ def main():
|
||||
print(f"cache: {cache_dir}")
|
||||
|
||||
|
||||
def steam_source_names():
|
||||
return ("library_600x900.jpg", "header.jpg", "library_hero.jpg", "logo.png")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -43,6 +43,46 @@ DEFAULT_ROOTS = (
|
||||
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():
|
||||
try:
|
||||
|
||||
+51
-24
@@ -44,8 +44,15 @@ except SystemExit:
|
||||
LIB_CACHE = os.path.join(STEAM_ROOT, "appcache", "librarycache") if STEAM_ROOT else None
|
||||
CACHE_DIR = os.path.join(BASE, "cache", "covers")
|
||||
IMAGE_LOCK = threading.Lock()
|
||||
COVER_NAMES = ("library_600x900.jpg", "header.jpg")
|
||||
STEAM_COVER_NAMES = ("library_600x900.jpg", "header.jpg", "library_hero.jpg", "logo.png")
|
||||
CACHE_COVER_NAMES = steam_source.COVER_ORDER
|
||||
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")
|
||||
STATUSES = {"backlog", "playing", "played", "tribute", "nostalgia", "ignore"}
|
||||
@@ -424,30 +431,11 @@ class Handler(BaseHTTPRequestHandler):
|
||||
self._send(200, data, CONTENT_TYPES.get(ext, "image/jpeg"),
|
||||
cache=True, max_age=2592000)
|
||||
|
||||
def _cover(self, appid):
|
||||
# 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
|
||||
def _download_cover(self, url, path):
|
||||
with IMAGE_LOCK:
|
||||
if os.path.isfile(path):
|
||||
with open(path, "rb") as f:
|
||||
data = f.read()
|
||||
else:
|
||||
url = f"https://cdn.cloudflare.steamstatic.com/steam/apps/{appid}/{name}"
|
||||
return f.read()
|
||||
try:
|
||||
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
|
||||
with urllib.request.urlopen(req, timeout=20) as resp:
|
||||
@@ -458,11 +446,50 @@ class Handler(BaseHTTPRequestHandler):
|
||||
with open(tmp, "wb") as f:
|
||||
f.write(data)
|
||||
os.replace(tmp, path)
|
||||
return data
|
||||
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:
|
||||
self._send(200, data, "image/jpeg", cache=True, max_age=2592000)
|
||||
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")
|
||||
|
||||
def _api_get(self, path, qs):
|
||||
|
||||
@@ -545,6 +545,7 @@ function renderModal(g) {
|
||||
$("#modalBody").innerHTML = `
|
||||
<div class="modal-grid">
|
||||
<div class="modal-cover" id="modalCover">
|
||||
<div class="cover-blur" id="modalCoverBlur"></div>
|
||||
<img data-appid="${g.appid}" src="${coverUrl(g.appid)}" alt="">
|
||||
<div class="fallback">${esc(g.name)}</div>
|
||||
</div>
|
||||
@@ -575,6 +576,7 @@ function renderModal(g) {
|
||||
</div>
|
||||
</div>`;
|
||||
|
||||
$("#modalCoverBlur").style.backgroundImage = `url("${coverUrl(g.appid)}")`;
|
||||
attachCoverFallback($("#modalCover img"));
|
||||
|
||||
$("#modalClose").addEventListener("click", () => $("#modal").close());
|
||||
|
||||
+21
-3
@@ -554,11 +554,29 @@ textarea { resize: vertical; min-height: 54px; }
|
||||
grid-template-columns: 300px minmax(0, 1fr);
|
||||
max-height: calc(100vh - 36px);
|
||||
}
|
||||
.modal-cover { position: relative; background: var(--bg-2); }
|
||||
.modal-cover img { width: 100%; height: 100%; object-fit: cover; display: block; }
|
||||
.modal-cover { position: relative; overflow: hidden; background: var(--bg-2); }
|
||||
.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.noimg .cover-blur { display: none; }
|
||||
.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);
|
||||
font-size: 22px; font-weight: 700; text-align: center; padding: 20px;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user