diff --git a/CHANGELOG.md b/CHANGELOG.md index 9698403..b58b430 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -34,4 +34,12 @@ ## [Unreleased] -- Планируется: экспорт рекомендаций, расширенные фильтры по длительности, тёмная/светлая темы. +### Исправлено + +- Обложки новых игр: поддержан хешированный layout Steam (`library_capsule.jpg`, + `library_header.jpg`) и фолбэк на `header_image` из Store API. +- Обложка в карточке игры больше не обрезается: `object-fit: contain` + размытый фон. + +### Планируется + +- Экспорт рекомендаций, расширенные фильтры по длительности, тёмная/светлая темы. diff --git a/docs/architecture.md b/docs/architecture.md index 1507e0c..4b3b7b2 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -86,11 +86,15 @@ mood → tags + genres → IDF по библиотеке → score = `GET /api/cover/`: -1. `cache/covers//library_600x900.jpg` или `header.jpg`; -2. `Steam/appcache/librarycache//...`; -3. скачивание с CDN и сохранение в кэш. +1. `cache/covers//` (любое имя из `COVER_ORDER`); +2. `Steam/appcache/librarycache//` — старый плоский layout + (`library_600x900.jpg`, `header.jpg`) или новый хешированный + (`/library_capsule.jpg`, `/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 дней. ## Веб-сервер diff --git a/docs/assets/game.png b/docs/assets/game.png index 1669f21..288264c 100644 Binary files a/docs/assets/game.png and b/docs/assets/game.png differ diff --git a/docs/data-sources.md b/docs/data-sources.md index 7cfc423..0359df4 100644 --- a/docs/data-sources.md +++ b/docs/data-sources.md @@ -123,11 +123,16 @@ GET https://store.steampowered.com/api/appdetails `/api/cover/`: 1. `cache/covers//`; -2. `Steam/appcache/librarycache//`; -3. Steam CDN (`library_600x900.jpg`, затем `header.jpg`). +2. `Steam/appcache/librarycache//` — оба layout: + - старый: `library_600x900.jpg`, `header.jpg`, `library_hero.jpg`; + - новый: `/library_capsule.jpg`, `/library_header.jpg`, + `/library_hero.jpg`, `/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` прогревает кэш заранее. ## Ограничения diff --git a/docs/manual.md b/docs/manual.md index 165f5a9..7ba0cdd 100644 --- a/docs/manual.md +++ b/docs/manual.md @@ -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. Скрипт нужен, чтобы прогреть +кэш заранее. Если обложки нет нигде, карточка показывает заглушку с инициалами. ### Перевод diff --git a/docs/schema.md b/docs/schema.md index 9d69aa7..41d7344 100644 --- a/docs/schema.md +++ b/docs/schema.md @@ -327,9 +327,10 @@ SELECT g.name, d.source_appid, s.name AS source_name Обложки не хранятся в SQLite. Веб-сервер отдаёт их через `/api/cover/`: -1. `cache/covers//library_600x900.jpg` или `header.jpg`; -2. `Steam/appcache/librarycache//...` (файлы клиента Steam); -3. скачивание с CDN и сохранение в `cache/covers`. +1. `cache/covers//` (имена из `COVER_ORDER`); +2. `Steam/appcache/librarycache//` — плоский или новый хешированный layout; +3. `game_details.header_image` (URL из Store API); +4. старые CDN-имена, скачанное сохраняется в `cache/covers`. Каталог `cache/` исключён из git. Прогрев: `tools/cache_covers.py`. diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index f550e85..7445687 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -83,8 +83,12 @@ python tools/translate_details.py --limit 100 --about ``` cache/covers// Steam/appcache/librarycache// +Steam/appcache/librarycache///library_capsule.jpg ``` +Новые версии Steam кладут обложки в хешированные подпапки; сервер поддерживает оба layout. +Если локальной обложки нет, используется `game_details.header_image` или старые имена CDN. + Затем: ```powershell diff --git a/tools/cache_covers.py b/tools/cache_covers.py index 1f6da54..d88bfc7 100644 --- a/tools/cache_covers.py +++ b/tools/cache_covers.py @@ -25,17 +25,36 @@ 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)): - return True - return False +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 def main(): @@ -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() diff --git a/tools/steam_source.py b/tools/steam_source.py index b3a48b6..6dfa96f 100644 --- a/tools/steam_source.py +++ b/tools/steam_source.py @@ -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: + //library_capsule.jpg + Older clients use flat names: + /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: diff --git a/web/server.py b/web/server.py index 3adeda0..c76ee10 100644 --- a/web/server.py +++ b/web/server.py @@ -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,45 +431,65 @@ class Handler(BaseHTTPRequestHandler): self._send(200, data, CONTENT_TYPES.get(ext, "image/jpeg"), cache=True, max_age=2592000) + def _download_cover(self, url, path): + with IMAGE_LOCK: + if os.path.isfile(path): + with open(path, "rb") as f: + return f.read() + 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 data: + 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 data + except Exception: + return None + return None + def _cover(self, appid): - # 1. our own cache - for name in COVER_NAMES: - path = os.path.join(CACHE_DIR, str(appid), name) + 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 - 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: - 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}" - 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 data: - 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) - except Exception: - data = None + + # 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): diff --git a/web/static/app.js b/web/static/app.js index d87f00f..1daeed4 100644 --- a/web/static/app.js +++ b/web/static/app.js @@ -545,6 +545,7 @@ function renderModal(g) { $("#modalBody").innerHTML = ` `; + $("#modalCoverBlur").style.backgroundImage = `url("${coverUrl(g.appid)}")`; attachCoverFallback($("#modalCover img")); $("#modalClose").addEventListener("click", () => $("#modal").close()); diff --git a/web/static/styles.css b/web/static/styles.css index 58dc625..3e9395b 100644 --- a/web/static/styles.css +++ b/web/static/styles.css @@ -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; }