feat(store): serve stock artwork and link official store media
Show the installed game artwork in the local store and marketplace. Use the official cover and gallery for each mapped product, with on-demand video playback. Include store cover images and screenshots in optional offline asset packs. Verified TypeScript, browser script syntax, local service startup, game artwork endpoints, a sample image pack, and BMD-4M WebM byte-range delivery. In-game verification is pending.
This commit is contained in:
1 parent
2dda694db0
commit
3c1210f249
14 files changed
+2580
-91
No files matched your search
@@ -6,16 +6,18 @@
|
|||||||
*
|
*
|
||||||
* node packages/local-service/src/asset-pack-cli.ts --data <data folder> [--concurrency 6]
|
* node packages/local-service/src/asset-pack-cli.ts --data <data folder> [--concurrency 6]
|
||||||
*
|
*
|
||||||
* Sources: web-ui/web/official-images.json (official market images per vehicle / decor / item,
|
* Sources: official marketplace art and vehicle renders, plus store covers and screenshots.
|
||||||
* from the official market snapshot) and the encyclopedia render of each of those vehicles.
|
* The storefront links videos directly.
|
||||||
* Files keep their host/path layout (static-ggc.gaijin.net/units/x.png); index.json lists them.
|
* Files keep their host/path layout (static-ggc.gaijin.net/units/x.png); index.json lists them.
|
||||||
* The pages read the pack first (web-ui/web/common.js `sourcesFor`).
|
* The pages read the pack first (web-ui/web/common.js `sourcesFor`).
|
||||||
*/
|
*/
|
||||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
import { existsSync, readFileSync } from 'node:fs';
|
||||||
import { dirname, join } from 'node:path';
|
import { join } from 'node:path';
|
||||||
import { parseArgs } from 'node:util';
|
import { parseArgs } from 'node:util';
|
||||||
|
import { writeFileAtomic } from './storage/atomic-file.ts';
|
||||||
|
|
||||||
const TABLE = new URL('./web-ui/web/official-images.json', import.meta.url);
|
const MARKET_IMAGES = new URL('./web-ui/web/official-images.json', import.meta.url);
|
||||||
|
const STORE_MEDIA = new URL('./web-ui/web/official-store-media.json', import.meta.url);
|
||||||
|
|
||||||
async function main(): Promise<number> {
|
async function main(): Promise<number> {
|
||||||
const { values } = parseArgs({ options: { data: { type: 'string' }, concurrency: { type: 'string', default: '6' } } });
|
const { values } = parseArgs({ options: { data: { type: 'string' }, concurrency: { type: 'string', default: '6' } } });
|
||||||
@@ -24,12 +26,20 @@ async function main(): Promise<number> {
|
|||||||
return 2;
|
return 2;
|
||||||
}
|
}
|
||||||
const packDir = join(values.data, 'asset-pack');
|
const packDir = join(values.data, 'asset-pack');
|
||||||
const table = JSON.parse(readFileSync(TABLE, 'utf8')) as { base: string; byKey: Record<string, string> };
|
const table = JSON.parse(readFileSync(MARKET_IMAGES, 'utf8')) as { base: string; byKey: Record<string, string> };
|
||||||
|
const store = JSON.parse(readFileSync(STORE_MEDIA, 'utf8')) as {
|
||||||
|
base: string;
|
||||||
|
byProduct: Record<string, { cover: string; screenshots?: string[] }>;
|
||||||
|
};
|
||||||
const urls = new Set<string>();
|
const urls = new Set<string>();
|
||||||
for (const [key, path] of Object.entries(table.byKey)) {
|
for (const [key, path] of Object.entries(table.byKey)) {
|
||||||
urls.add(table.base + path);
|
urls.add(table.base + path);
|
||||||
if (path.startsWith('units/')) urls.add(`https://static.encyclopedia.warthunder.com/images/${key.toLowerCase()}.png`);
|
if (path.startsWith('units/')) urls.add(`https://static.encyclopedia.warthunder.com/images/${key.toLowerCase()}.png`);
|
||||||
}
|
}
|
||||||
|
for (const { cover, screenshots = [] } of Object.values(store.byProduct)) {
|
||||||
|
urls.add(store.base + cover);
|
||||||
|
for (const screenshot of screenshots) urls.add(store.base + screenshot);
|
||||||
|
}
|
||||||
const indexFile = join(packDir, 'index.json');
|
const indexFile = join(packDir, 'index.json');
|
||||||
const done = new Set<string>(existsSync(indexFile) ? JSON.parse(readFileSync(indexFile, 'utf8')) as string[] : []);
|
const done = new Set<string>(existsSync(indexFile) ? JSON.parse(readFileSync(indexFile, 'utf8')) as string[] : []);
|
||||||
const queue = [...urls].filter((url) => !done.has(url.replace(/^https?:\/\//, '')));
|
const queue = [...urls].filter((url) => !done.has(url.replace(/^https?:\/\//, '')));
|
||||||
@@ -38,11 +48,13 @@ async function main(): Promise<number> {
|
|||||||
for (let url = queue.shift(); url; url = queue.shift()) {
|
for (let url = queue.shift(); url; url = queue.shift()) {
|
||||||
const relative = url.replace(/^https?:\/\//, '');
|
const relative = url.replace(/^https?:\/\//, '');
|
||||||
try {
|
try {
|
||||||
const response = await fetch(url);
|
const response = await fetch(url, { signal: AbortSignal.timeout(15000) });
|
||||||
if (!response.ok) { failed += 1; continue; }
|
if (!response.ok || !response.headers.get('content-type')?.startsWith('image/')) {
|
||||||
const target = join(packDir, relative);
|
await response.body?.cancel();
|
||||||
mkdirSync(dirname(target), { recursive: true });
|
failed += 1;
|
||||||
writeFileSync(target, Buffer.from(await response.arrayBuffer()));
|
continue;
|
||||||
|
}
|
||||||
|
writeFileAtomic(join(packDir, relative), Buffer.from(await response.arrayBuffer()));
|
||||||
done.add(relative);
|
done.add(relative);
|
||||||
} catch {
|
} catch {
|
||||||
failed += 1;
|
failed += 1;
|
||||||
@@ -50,8 +62,7 @@ async function main(): Promise<number> {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
await Promise.all(Array.from({ length: Math.max(1, Number(values.concurrency)) }, worker));
|
await Promise.all(Array.from({ length: Math.max(1, Number(values.concurrency)) }, worker));
|
||||||
mkdirSync(packDir, { recursive: true });
|
writeFileAtomic(indexFile, JSON.stringify([...done].sort()));
|
||||||
writeFileSync(indexFile, JSON.stringify([...done].sort(), null, 0));
|
|
||||||
console.log(`asset pack: ${done.size} file(s) in ${packDir}; ${failed} not available`);
|
console.log(`asset pack: ${done.size} file(s) in ${packDir}; ${failed} not available`);
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -100,7 +100,7 @@ function sorted(listings) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function listingImage(listing, className) {
|
function listingImage(listing, className) {
|
||||||
return listing.category === 'vehicle' ? WtoUi.vehicleImg(listing.targetKey, className) : WtoUi.itemImg(listing.targetKey, '', className);
|
return listing.category === 'vehicle' ? WtoUi.vehicleImg(listing.targetKey, className) : WtoUi.itemImg(listing.category, listing.targetKey, className);
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderGrid() {
|
function renderGrid() {
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ body { background: var(--bg); color: var(--text); font: 14px/18px var(--font); m
|
|||||||
.rarity { position: absolute; left: 0; right: 0; top: 0; height: 45%; opacity: 0.35; }
|
.rarity { position: absolute; left: 0; right: 0; top: 0; height: 45%; opacity: 0.35; }
|
||||||
.rarity::before { content: ""; position: absolute; left: 0; right: 0; top: 0; height: 2px; background: inherit; opacity: 1; }
|
.rarity::before { content: ""; position: absolute; left: 0; right: 0; top: 0; height: 2px; background: inherit; opacity: 1; }
|
||||||
.lot-image { position: relative; height: 180px; display: flex; align-items: center; justify-content: center; padding: 12px; }
|
.lot-image { position: relative; height: 180px; display: flex; align-items: center; justify-content: center; padding: 12px; }
|
||||||
.lot-image img { max-width: 100%; max-height: 100%; object-fit: contain; }
|
.lot-image img { width: 100%; height: 100%; object-fit: contain; }
|
||||||
.lot-meta { position: relative; padding: 0 14px; }
|
.lot-meta { position: relative; padding: 0 14px; }
|
||||||
.project { display: flex; align-items: center; gap: 6px; color: var(--muted); font-size: 12px; }
|
.project { display: flex; align-items: center; gap: 6px; color: var(--muted); font-size: 12px; }
|
||||||
.project img { width: 16px; height: 11px; }
|
.project img { width: 16px; height: 11px; }
|
||||||
@@ -77,7 +77,7 @@ body { background: var(--bg); color: var(--text); font: 14px/18px var(--font); m
|
|||||||
.detail-close { position: absolute; top: 2px; right: 0; width: 40px; height: 40px; border: none; background: #0000002b; color: #fff; font-size: 22px; cursor: pointer; }
|
.detail-close { position: absolute; top: 2px; right: 0; width: 40px; height: 40px; border: none; background: #0000002b; color: #fff; font-size: 22px; cursor: pointer; }
|
||||||
.detail-info { display: flex; gap: 24px; padding: 0 24px; }
|
.detail-info { display: flex; gap: 24px; padding: 0 24px; }
|
||||||
.detail-image { flex: none; width: 440px; height: 260px; display: flex; align-items: center; justify-content: center; border-radius: 5px; background: radial-gradient(50% 50% at 50% 50%, #272a2e99 0%, #272a2ef0 85%, #272a2e 100%), var(--glow); }
|
.detail-image { flex: none; width: 440px; height: 260px; display: flex; align-items: center; justify-content: center; border-radius: 5px; background: radial-gradient(50% 50% at 50% 50%, #272a2e99 0%, #272a2ef0 85%, #272a2e 100%), var(--glow); }
|
||||||
.detail-image img { max-width: 92%; max-height: 92%; object-fit: contain; }
|
.detail-image img { width: 92%; height: 92%; object-fit: contain; }
|
||||||
.tags { display: flex; flex-wrap: wrap; gap: 6px; }
|
.tags { display: flex; flex-wrap: wrap; gap: 6px; }
|
||||||
.tag { padding: 4px 10px; border-radius: 2px; color: #000; font-size: 12px; font-weight: 600; }
|
.tag { padding: 4px 10px; border-radius: 2px; color: #000; font-size: 12px; font-weight: 600; }
|
||||||
.tag.game { background: #12151a9e; color: #fff; }
|
.tag.game { background: #12151a9e; color: #fff; }
|
||||||
|
|||||||
@@ -44,6 +44,7 @@ import { StoreService } from './store/store-service.ts';
|
|||||||
import { TrafficLog } from './traffic-log/traffic-log.ts';
|
import { TrafficLog } from './traffic-log/traffic-log.ts';
|
||||||
import { loadTuning, type Tuning } from './tuning/tuning.ts';
|
import { loadTuning, type Tuning } from './tuning/tuning.ts';
|
||||||
import { UnlockShop } from './unlocks/unlock-purchase.ts';
|
import { UnlockShop } from './unlocks/unlock-purchase.ts';
|
||||||
|
import { GameArtwork } from './web-ui/game-artwork.ts';
|
||||||
import { WebUiService } from './web-ui/web-ui-service.ts';
|
import { WebUiService } from './web-ui/web-ui-service.ts';
|
||||||
|
|
||||||
export interface LocalServiceOptions {
|
export interface LocalServiceOptions {
|
||||||
@@ -77,7 +78,13 @@ export async function startLocalService(options: LocalServiceOptions): Promise<R
|
|||||||
const labels = datasets.load(uiLabels);
|
const labels = datasets.load(uiLabels);
|
||||||
const { profiles, research, equipment } = setUpProfiles(options.dataFolder, gameFiles, datasets, tuning, { accounts, clans }, vehicles);
|
const { profiles, research, equipment } = setUpProfiles(options.dataFolder, gameFiles, datasets, tuning, { accounts, clans }, vehicles);
|
||||||
const { clanEconomy: squadronEconomy, ...catalogues } = loadDomainCatalogues(datasets, tuning, vehicles, labels);
|
const { clanEconomy: squadronEconomy, ...catalogues } = loadDomainCatalogues(datasets, tuning, vehicles, labels);
|
||||||
const webUi = new WebUiService(datasets.load(webIcons), labels, options.dataFolder);
|
const storeProducts = catalogues.store.allProducts();
|
||||||
|
const artwork = new GameArtwork(options.gameFolder, {
|
||||||
|
vehicles: storeProducts.flatMap((product) => product.vehicles?.map((vehicle) => vehicle.name) ?? []),
|
||||||
|
groups: storeProducts.flatMap((product) => product.artworkGroup ? [product.artworkGroup] : []),
|
||||||
|
listings: catalogues.inventory.marketplaceListings(),
|
||||||
|
}, report);
|
||||||
|
const webUi = new WebUiService(datasets.load(webIcons), labels, options.dataFolder, artwork);
|
||||||
gameFiles.releasePacks();
|
gameFiles.releasePacks();
|
||||||
|
|
||||||
let matching: MatchingService | undefined;
|
let matching: MatchingService | undefined;
|
||||||
|
|||||||
@@ -37,6 +37,8 @@ export interface StoreProduct {
|
|||||||
readonly premiumDays?: number;
|
readonly premiumDays?: number;
|
||||||
/** Vehicles granted on purchase (1 for single packs, 2-3 for starter/bundle packs), with any split-vehicle parts. */
|
/** Vehicles granted on purchase (1 for single packs, 2-3 for starter/bundle packs), with any split-vehicle parts. */
|
||||||
readonly vehicles?: readonly CatalogueVehicle[];
|
readonly vehicles?: readonly CatalogueVehicle[];
|
||||||
|
/** Stock group artwork resource name for a multi-vehicle pack. */
|
||||||
|
readonly artworkGroup?: string;
|
||||||
/** Localized names of `vehicles` in the same order. */
|
/** Localized names of `vehicles` in the same order. */
|
||||||
readonly vehicleTitles?: readonly LocalizedText[];
|
readonly vehicleTitles?: readonly LocalizedText[];
|
||||||
}
|
}
|
||||||
@@ -153,6 +155,7 @@ function buildVehiclePackProducts(
|
|||||||
kind: 'vehicle-pack',
|
kind: 'vehicle-pack',
|
||||||
chapter: 'bonuses',
|
chapter: 'bonuses',
|
||||||
title: resolveMultiPackTitle(pack.id, pack.naming, packVehicles[0]!, names, labels),
|
title: resolveMultiPackTitle(pack.id, pack.naming, packVehicles[0]!, names, labels),
|
||||||
|
...(pack.naming.kind === 'group' ? { artworkGroup: pack.naming.groupKey.slice('shop/group/'.length) } : {}),
|
||||||
gjnCostCents: pack.gjnCents,
|
gjnCostCents: pack.gjnCents,
|
||||||
...(pack.goldenEagles ? { goldIncome: pack.goldenEagles } : {}),
|
...(pack.goldenEagles ? { goldIncome: pack.goldenEagles } : {}),
|
||||||
...(pack.silverLions ? { silverIncome: pack.silverLions } : {}),
|
...(pack.silverLions ? { silverIncome: pack.silverLions } : {}),
|
||||||
|
|||||||
@@ -124,6 +124,7 @@ function webProduct(product: StoreProduct, owned: boolean): Record<string, unkno
|
|||||||
return {
|
return {
|
||||||
id: product.id,
|
id: product.id,
|
||||||
...(product.guid ? { guid: product.guid } : {}),
|
...(product.guid ? { guid: product.guid } : {}),
|
||||||
|
...(product.artworkGroup ? { artworkGroup: product.artworkGroup } : {}),
|
||||||
kind: product.kind,
|
kind: product.kind,
|
||||||
title: product.title,
|
title: product.title,
|
||||||
gjnCostCents: product.gjnCostCents,
|
gjnCostCents: product.gjnCostCents,
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ const T = {
|
|||||||
buy: '购买', freeBuy: '老福爷付过了', owned: '已拥有', pickAccount: '请先在右上角选择账号', redeem: '兑换', codePlaceholder: '输入兑换码',
|
buy: '购买', freeBuy: '老福爷付过了', owned: '已拥有', pickAccount: '请先在右上角选择账号', redeem: '兑换', codePlaceholder: '输入兑换码',
|
||||||
empty: '没有符合条件的商品', includes: '本特惠包包含', back: '‹ 返回目录', bonusTitle: 'Premium bonuses', bonusText: '高级载具获得的银狮与研发点有加成,并可直接使用。',
|
empty: '没有符合条件的商品', includes: '本特惠包包含', back: '‹ 返回目录', bonusTitle: 'Premium bonuses', bonusText: '高级载具获得的银狮与研发点有加成,并可直接使用。',
|
||||||
footer: 'WTOffline 本地商店 · 买完关闭本窗口,机库会自动刷新', badgeOwned: '已拥有', badgeHot: '人气商品',
|
footer: 'WTOffline 本地商店 · 买完关闭本窗口,机库会自动刷新', badgeOwned: '已拥有', badgeHot: '人气商品',
|
||||||
|
cover: '封面', screenshot: '截图 {index}', video: '演示视频', videoNumber: '演示视频 {index}', videoUnavailable: '暂时无法播放官方视频。',
|
||||||
},
|
},
|
||||||
en: {
|
en: {
|
||||||
store: 'Store', toMarket: 'Market', eagles: 'Golden Eagles', lions: 'Silver Lions', premium: 'Premium', premiumOff: 'inactive', premiumLeft: '{days} days left',
|
store: 'Store', toMarket: 'Market', eagles: 'Golden Eagles', lions: 'Silver Lions', premium: 'Premium', premiumOff: 'inactive', premiumLeft: '{days} days left',
|
||||||
@@ -22,6 +23,7 @@ const T = {
|
|||||||
buy: 'Buy', freeBuy: '老福爷付过了', owned: 'Owned', pickAccount: 'Pick an account at the top right', redeem: 'Redeem', codePlaceholder: 'Enter a code',
|
buy: 'Buy', freeBuy: '老福爷付过了', owned: 'Owned', pickAccount: 'Pick an account at the top right', redeem: 'Redeem', codePlaceholder: 'Enter a code',
|
||||||
empty: 'Nothing matches the filters', includes: 'This pack includes', back: '‹ Back to catalog', bonusTitle: 'Premium bonuses', bonusText: 'Premium vehicles earn more Silver Lions and research points and are ready to use.',
|
empty: 'Nothing matches the filters', includes: 'This pack includes', back: '‹ Back to catalog', bonusTitle: 'Premium bonuses', bonusText: 'Premium vehicles earn more Silver Lions and research points and are ready to use.',
|
||||||
footer: 'WTOffline local store · close this window after buying to refresh the hangar', badgeOwned: 'Owned', badgeHot: 'Best seller',
|
footer: 'WTOffline local store · close this window after buying to refresh the hangar', badgeOwned: 'Owned', badgeHot: 'Best seller',
|
||||||
|
cover: 'Cover', screenshot: 'Screenshot {index}', video: 'Demo video', videoNumber: 'Demo video {index}', videoUnavailable: 'The official video is unavailable.',
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
const ROMAN = ['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X'];
|
const ROMAN = ['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X'];
|
||||||
@@ -82,6 +84,7 @@ function matches(product) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function render() {
|
function render() {
|
||||||
|
stopProductVideo($('detail').querySelector('video'));
|
||||||
for (const tab of document.querySelectorAll('.snav-item')) tab.classList.toggle('active', tab.dataset.tab === currentTab);
|
for (const tab of document.querySelectorAll('.snav-item')) tab.classList.toggle('active', tab.dataset.tab === currentTab);
|
||||||
const product = detailId && state.products.find((p) => p.id === detailId);
|
const product = detailId && state.products.find((p) => p.id === detailId);
|
||||||
$('redeemPanel').hidden = currentTab !== 'redeem';
|
$('redeemPanel').hidden = currentTab !== 'redeem';
|
||||||
@@ -100,9 +103,92 @@ function render() {
|
|||||||
for (const item of items) grid.appendChild(productCard(item));
|
for (const item of items) grid.appendChild(productCard(item));
|
||||||
}
|
}
|
||||||
|
|
||||||
function productImage(product, className) {
|
function productArtwork(product) {
|
||||||
if (product.unitName) return WtoUi.vehicleImg(product.unitName, className);
|
const group = product.artworkGroup ? [WtoUi.artworkUrl('group', product.artworkGroup)] : [];
|
||||||
return WtoUi.storeImg(product.guid, '', className ? className + ' cover' : 'cover');
|
const image = product.unitName ? WtoUi.artworkUrl('vehicle', product.unitName) : WtoUi.artworkUrl('product', product.kind);
|
||||||
|
return [...group, image];
|
||||||
|
}
|
||||||
|
|
||||||
|
function productImage(product) {
|
||||||
|
const { cover } = WtoUi.storeMedia(product.id);
|
||||||
|
const urls = product.unitName ? [cover, ...WtoUi.vehicleUrls(product.unitName)] : [cover];
|
||||||
|
return WtoUi.tieredImg(urls, productArtwork(product), '');
|
||||||
|
}
|
||||||
|
|
||||||
|
function stopProductVideo(video) {
|
||||||
|
if (!video) return;
|
||||||
|
video.onerror = null;
|
||||||
|
video.pause();
|
||||||
|
video.remove();
|
||||||
|
video.removeAttribute('src');
|
||||||
|
video.load();
|
||||||
|
}
|
||||||
|
|
||||||
|
function showPackVideo(media, status, product, urls) {
|
||||||
|
const player = document.createElement('video');
|
||||||
|
player.controls = true;
|
||||||
|
player.playsInline = true;
|
||||||
|
player.preload = 'metadata';
|
||||||
|
const sources = urls.filter((url) => player.canPlayType(url.endsWith('.webm') ? 'video/webm' : 'video/mp4'));
|
||||||
|
let timer;
|
||||||
|
|
||||||
|
function next() {
|
||||||
|
clearTimeout(timer);
|
||||||
|
if (player.parentNode !== media) return;
|
||||||
|
const url = sources.shift();
|
||||||
|
if (!url) {
|
||||||
|
stopProductVideo(player);
|
||||||
|
media.replaceChildren(productImage(product));
|
||||||
|
status.textContent = t('videoUnavailable');
|
||||||
|
status.hidden = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
player.src = url;
|
||||||
|
timer = setTimeout(next, 4500);
|
||||||
|
void player.play().catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
player.onerror = next;
|
||||||
|
player.onloadedmetadata = () => clearTimeout(timer);
|
||||||
|
media.replaceChildren(player);
|
||||||
|
next();
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderProductMedia(detail, product) {
|
||||||
|
const media = detail.querySelector('.media');
|
||||||
|
const status = detail.querySelector('.media-status');
|
||||||
|
const toolbar = detail.querySelector('.thumbs');
|
||||||
|
const { screenshots, videos } = WtoUi.storeMedia(product.id);
|
||||||
|
let selected;
|
||||||
|
|
||||||
|
function addChoice(label, show) {
|
||||||
|
const button = Object.assign(document.createElement('button'), { type: 'button', textContent: label });
|
||||||
|
button.setAttribute('aria-pressed', 'false');
|
||||||
|
button.onclick = () => {
|
||||||
|
stopProductVideo(media.querySelector('video'));
|
||||||
|
selected?.setAttribute('aria-pressed', 'false');
|
||||||
|
selected = button;
|
||||||
|
button.setAttribute('aria-pressed', 'true');
|
||||||
|
status.hidden = true;
|
||||||
|
show();
|
||||||
|
};
|
||||||
|
toolbar.appendChild(button);
|
||||||
|
return button;
|
||||||
|
}
|
||||||
|
|
||||||
|
const cover = addChoice(t('cover'), () => media.replaceChildren(productImage(product)));
|
||||||
|
screenshots.forEach((url, index) => {
|
||||||
|
addChoice(t('screenshot', { index: index + 1 }), () => media.replaceChildren(WtoUi.tieredImg([url], productArtwork(product), '')));
|
||||||
|
});
|
||||||
|
for (const vehicle of product.vehicles || []) {
|
||||||
|
addChoice(WtoUi.text(vehicle.title), () => media.replaceChildren(WtoUi.vehicleImg(vehicle.unitName, '')));
|
||||||
|
}
|
||||||
|
videos.forEach((sources, index) => {
|
||||||
|
const label = videos.length === 1 ? t('video') : t('videoNumber', { index: index + 1 });
|
||||||
|
addChoice(label, () => showPackVideo(media, status, product, sources));
|
||||||
|
});
|
||||||
|
toolbar.hidden = toolbar.childElementCount <= 1;
|
||||||
|
cover.click();
|
||||||
}
|
}
|
||||||
|
|
||||||
function contentsOf(product) {
|
function contentsOf(product) {
|
||||||
@@ -127,7 +213,7 @@ function productCard(product) {
|
|||||||
const card = document.createElement('div');
|
const card = document.createElement('div');
|
||||||
card.className = 'pw';
|
card.className = 'pw';
|
||||||
card.innerHTML = '<div class="pw-poster"></div><div class="pw-desc"><div class="pw-game">War Thunder</div><div class="pw-title"></div><div class="pw-comment"></div><ul class="pw-contents"></ul></div><div class="pw-price"></div><div class="pw-buy"></div>';
|
card.innerHTML = '<div class="pw-poster"></div><div class="pw-desc"><div class="pw-game">War Thunder</div><div class="pw-title"></div><div class="pw-comment"></div><ul class="pw-contents"></ul></div><div class="pw-price"></div><div class="pw-buy"></div>';
|
||||||
card.querySelector('.pw-poster').appendChild(productImage(product, ''));
|
card.querySelector('.pw-poster').appendChild(productImage(product));
|
||||||
if (product.owned) card.querySelector('.pw-poster').appendChild(Object.assign(document.createElement('div'), { className: 'badge owned', textContent: t('badgeOwned') }));
|
if (product.owned) card.querySelector('.pw-poster').appendChild(Object.assign(document.createElement('div'), { className: 'badge owned', textContent: t('badgeOwned') }));
|
||||||
card.querySelector('.pw-title').textContent = WtoUi.text(product.title);
|
card.querySelector('.pw-title').textContent = WtoUi.text(product.title);
|
||||||
if (product.country) {
|
if (product.country) {
|
||||||
@@ -145,20 +231,13 @@ function productCard(product) {
|
|||||||
|
|
||||||
function renderDetail(product) {
|
function renderDetail(product) {
|
||||||
const detail = $('detail');
|
const detail = $('detail');
|
||||||
detail.innerHTML = '<span class="back"></span><h1></h1><div class="detail-cols"><div class="detail-left"><div class="media"></div><div class="thumbs"></div>'
|
detail.innerHTML = '<span class="back"></span><h1></h1><div class="detail-cols"><div class="detail-left"><div class="media"></div><div class="thumbs"></div><p class="media-status" role="status" hidden></p>'
|
||||||
+ '<h2></h2><div class="bonus"><h3></h3><div></div></div></div><div class="detail-right"><div class="buy-panel"><div class="price"></div><div class="btns"></div>'
|
+ '<h2></h2><div class="bonus"><h3></h3><div></div></div></div><div class="detail-right"><div class="buy-panel"><div class="price"></div><div class="btns"></div>'
|
||||||
+ '<div class="includes"><h4></h4><ul></ul></div></div></div></div>';
|
+ '<div class="includes"><h4></h4><ul></ul></div></div></div></div>';
|
||||||
detail.querySelector('.back').textContent = t('back');
|
detail.querySelector('.back').textContent = t('back');
|
||||||
detail.querySelector('.back').onclick = () => { detailId = ''; render(); };
|
detail.querySelector('.back').onclick = () => { detailId = ''; render(); };
|
||||||
detail.querySelector('h1').textContent = WtoUi.text(product.title);
|
detail.querySelector('h1').textContent = WtoUi.text(product.title);
|
||||||
const media = detail.querySelector('.media');
|
renderProductMedia(detail, product);
|
||||||
media.appendChild(productImage(product, ''));
|
|
||||||
const thumbs = detail.querySelector('.thumbs');
|
|
||||||
for (const v of product.vehicles || []) {
|
|
||||||
const thumb = WtoUi.vehicleImg(v.unitName, v.unitName === product.unitName ? 'active' : '');
|
|
||||||
thumb.onclick = () => { media.innerHTML = ''; media.appendChild(WtoUi.vehicleImg(v.unitName, '')); };
|
|
||||||
thumbs.appendChild(thumb);
|
|
||||||
}
|
|
||||||
detail.querySelector('.detail-left h2').textContent = product.vehicles ? product.vehicles.map((v) => WtoUi.text(v.title)).join(' / ') : WtoUi.text(product.title);
|
detail.querySelector('.detail-left h2').textContent = product.vehicles ? product.vehicles.map((v) => WtoUi.text(v.title)).join(' / ') : WtoUi.text(product.title);
|
||||||
detail.querySelector('.bonus h3').textContent = t('bonusTitle');
|
detail.querySelector('.bonus h3').textContent = t('bonusTitle');
|
||||||
detail.querySelector('.bonus div').textContent = t('bonusText');
|
detail.querySelector('.bonus div').textContent = t('bonusText');
|
||||||
@@ -210,4 +289,4 @@ $('tabs').onclick = (event) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
applyStaticTexts();
|
applyStaticTexts();
|
||||||
Promise.all([WtoUi.loadLabels(), WtoUi.loadImageSources()]).then(() => loadState(WtoUi.savedAccount()));
|
Promise.all([WtoUi.loadLabels(), WtoUi.loadImageSources(true)]).then(() => loadState(WtoUi.savedAccount()));
|
||||||
@@ -2,6 +2,7 @@
|
|||||||
<html>
|
<html>
|
||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8" />
|
<meta charset="utf-8" />
|
||||||
|
<meta name="referrer" content="no-referrer" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
<title>Gaijin.Net Store · WTOffline</title>
|
<title>Gaijin.Net Store · WTOffline</title>
|
||||||
<link rel="stylesheet" href="/store/styles.css" />
|
<link rel="stylesheet" href="/store/styles.css" />
|
||||||
|
|||||||
@@ -36,8 +36,7 @@ body { background: var(--navy-40) linear-gradient(180deg, #1b2530 0%, #27323f 42
|
|||||||
.pw { position: relative; display: flex; flex-direction: column; height: 344px; background: var(--navy-60); overflow: hidden; cursor: pointer; transition: transform 0.3s; }
|
.pw { position: relative; display: flex; flex-direction: column; height: 344px; background: var(--navy-60); overflow: hidden; cursor: pointer; transition: transform 0.3s; }
|
||||||
.pw:hover { transform: translateY(-3px); }
|
.pw:hover { transform: translateY(-3px); }
|
||||||
.pw-poster { position: relative; height: 162px; display: flex; align-items: center; justify-content: center; background: linear-gradient(180deg, #33475a, var(--navy-60)); }
|
.pw-poster { position: relative; height: 162px; display: flex; align-items: center; justify-content: center; background: linear-gradient(180deg, #33475a, var(--navy-60)); }
|
||||||
.pw-poster img { max-width: 92%; max-height: 92%; object-fit: contain; }
|
.pw-poster img { width: 92%; height: 92%; object-fit: contain; }
|
||||||
.pw-poster img.cover { width: 100%; height: 100%; max-width: none; max-height: none; object-fit: cover; }
|
|
||||||
.badge { position: absolute; left: 0; right: 0; top: 0; height: 30px; padding: 0 12px; display: flex; align-items: center; justify-content: space-between; color: #fff; font-size: 14px; text-transform: uppercase; background: linear-gradient(90deg, #0050e0, #1a8cff); }
|
.badge { position: absolute; left: 0; right: 0; top: 0; height: 30px; padding: 0 12px; display: flex; align-items: center; justify-content: space-between; color: #fff; font-size: 14px; text-transform: uppercase; background: linear-gradient(90deg, #0050e0, #1a8cff); }
|
||||||
.badge.owned { background: linear-gradient(90deg, #3a8a2a, #6cc04a); }
|
.badge.owned { background: linear-gradient(90deg, #3a8a2a, #6cc04a); }
|
||||||
.pw-desc { flex: 1; padding: 10px 14px 0; min-height: 0; overflow: hidden; }
|
.pw-desc { flex: 1; padding: 10px 14px 0; min-height: 0; overflow: hidden; }
|
||||||
@@ -60,11 +59,12 @@ body { background: var(--navy-40) linear-gradient(180deg, #1b2530 0%, #27323f 42
|
|||||||
.detail-cols { display: flex; gap: 24px; align-items: flex-start; }
|
.detail-cols { display: flex; gap: 24px; align-items: flex-start; }
|
||||||
.detail-left { flex: 1; min-width: 0; }
|
.detail-left { flex: 1; min-width: 0; }
|
||||||
.media { height: 452px; display: flex; align-items: center; justify-content: center; background: radial-gradient(circle at 50% 40%, #3a4d60, #1b2633 75%); }
|
.media { height: 452px; display: flex; align-items: center; justify-content: center; background: radial-gradient(circle at 50% 40%, #3a4d60, #1b2633 75%); }
|
||||||
.media img { max-width: 90%; max-height: 90%; object-fit: contain; }
|
.media img, .media video { width: 100%; height: 100%; object-fit: contain; }
|
||||||
.media img.cover { width: 100%; height: 100%; max-width: none; max-height: none; object-fit: cover; }
|
.thumbs { display: flex; flex-wrap: wrap; gap: 8px; padding: 8px 0; }
|
||||||
.thumbs { display: flex; gap: 8px; padding: 8px 0; }
|
.thumbs[hidden] { display: none; }
|
||||||
.thumbs img { width: 132px; height: 85px; object-fit: contain; background: #1b2633; border: 2px solid transparent; cursor: pointer; }
|
.thumbs button { padding: 6px 12px; background: #1b2633; color: var(--text); border: 1px solid #425367; cursor: pointer; }
|
||||||
.thumbs img.active { border-color: #f9ae3d; }
|
.thumbs button[aria-pressed='true'] { border-color: #f9ae3d; }
|
||||||
|
.media-status { margin: 0; color: var(--muted); }
|
||||||
.detail-left h2 { color: #fff; font-size: 32px; font-weight: 300; margin: 24px 0 8px; }
|
.detail-left h2 { color: #fff; font-size: 32px; font-weight: 300; margin: 24px 0 8px; }
|
||||||
.bonus { margin-top: 24px; padding: 28px 32px; background: linear-gradient(90deg, #5c5030, #e8d08a); color: #3a2a10; }
|
.bonus { margin-top: 24px; padding: 28px 32px; background: linear-gradient(90deg, #5c5030, #e8d08a); color: #3a2a10; }
|
||||||
.bonus h3 { margin: 0 0 8px; font-size: 32px; text-transform: uppercase; }
|
.bonus h3 { margin: 0 0 8px; font-size: 32px; text-transform: uppercase; }
|
||||||
|
|||||||
@@ -0,0 +1,116 @@
|
|||||||
|
/**
|
||||||
|
* Browser-ready pictures from the player's own UI archives. Copy only the art
|
||||||
|
* used by the commerce catalogues, then release the archive's backing buffer.
|
||||||
|
*/
|
||||||
|
import { readFileSync } from 'node:fs';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { readArchive } from '@wto/vromfs';
|
||||||
|
|
||||||
|
const VEHICLES = 'ui/tex.vromfs.bin';
|
||||||
|
const PICTURES = 'ui/images.vromfs.bin';
|
||||||
|
const ATLAS = 'ui/atlases.vromfs.bin';
|
||||||
|
const VEHICLE_FOLDERS = ['tanks', 'aircrafts', 'ships'] as const;
|
||||||
|
|
||||||
|
const PRODUCT_ART = {
|
||||||
|
eagles: 'images/ingame_currency_shop/eagles/item_icon_5.avif',
|
||||||
|
warpoints: 'images/ingame_currency_shop/lions/item_icon_5.avif',
|
||||||
|
'premium-gold': 'images/premium/premium_account_image.avif',
|
||||||
|
'premium-gjn': 'images/premium/premium_account_image.avif',
|
||||||
|
};
|
||||||
|
|
||||||
|
const COUPON_ART = {
|
||||||
|
vehicle: 'gameuiskin/item_type_blueprints.svg',
|
||||||
|
skin: 'gameuiskin/item_type_skin.svg',
|
||||||
|
decal: 'gameuiskin/item_type_decal.svg',
|
||||||
|
attachable: 'gameuiskin/item_attachable.avif',
|
||||||
|
unlock: 'gameuiskin/item_type_unlock.svg',
|
||||||
|
};
|
||||||
|
|
||||||
|
export interface GamePicture {
|
||||||
|
readonly filename: string;
|
||||||
|
readonly bytes: Uint8Array;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface PictureLocation {
|
||||||
|
readonly pack: string;
|
||||||
|
readonly paths: readonly string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ArtworkSelection {
|
||||||
|
readonly vehicles: readonly string[];
|
||||||
|
readonly groups: readonly string[];
|
||||||
|
readonly listings: ReadonlyArray<{ readonly category: string; readonly targetKey: string }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class GameArtwork {
|
||||||
|
readonly #gameFolder: string;
|
||||||
|
readonly #report: (message: string) => void;
|
||||||
|
readonly #locations = new Map<string, PictureLocation>();
|
||||||
|
readonly #wanted = new Map<string, Set<string>>();
|
||||||
|
readonly #loaded = new Map<string, Map<string, GamePicture>>();
|
||||||
|
|
||||||
|
constructor(gameFolder: string, selection: ArtworkSelection, report: (message: string) => void) {
|
||||||
|
this.#gameFolder = gameFolder;
|
||||||
|
this.#report = report;
|
||||||
|
for (const name of selection.vehicles) this.#register('vehicle', name, VEHICLES, vehiclePaths(name));
|
||||||
|
for (const name of selection.groups) this.#register('group', name, VEHICLES, ['groups/' + name.toLowerCase() + '.avif']);
|
||||||
|
for (const { category, targetKey } of selection.listings) {
|
||||||
|
this.#registerListing(category, targetKey);
|
||||||
|
}
|
||||||
|
for (const [kind, path] of Object.entries(PRODUCT_ART)) this.#register('product', kind, PICTURES, [path]);
|
||||||
|
for (const [kind, path] of Object.entries(COUPON_ART)) this.#register('coupon', kind, ATLAS, [path]);
|
||||||
|
}
|
||||||
|
|
||||||
|
image(kind: string, key: string): GamePicture | undefined {
|
||||||
|
return this.#lookup(kind, key) ?? this.#lookup('coupon', kind);
|
||||||
|
}
|
||||||
|
|
||||||
|
#registerListing(category: string, key: string): void {
|
||||||
|
const lower = key.toLowerCase();
|
||||||
|
if (category === 'vehicle') this.#register(category, key, VEHICLES, vehiclePaths(lower));
|
||||||
|
if (category === 'skin') {
|
||||||
|
const [vehicle] = lower.split('/', 1);
|
||||||
|
if (vehicle) this.#register(category, key, VEHICLES, vehiclePaths(vehicle));
|
||||||
|
}
|
||||||
|
if (category === 'attachable') this.#register(category, key, PICTURES, ['images/attachables/' + lower + '.avif']);
|
||||||
|
if (category === 'unlock') this.#register(category, key, PICTURES, ['images/avatars/' + lower + '.avif']);
|
||||||
|
}
|
||||||
|
|
||||||
|
#register(kind: string, key: string, pack: string, paths: readonly string[]): void {
|
||||||
|
this.#locations.set(kind + '/' + key.toLowerCase(), { pack, paths });
|
||||||
|
const wanted = this.#wanted.get(pack) ?? new Set();
|
||||||
|
for (const path of paths) wanted.add(path);
|
||||||
|
this.#wanted.set(pack, wanted);
|
||||||
|
}
|
||||||
|
|
||||||
|
#lookup(kind: string, key: string): GamePicture | undefined {
|
||||||
|
const location = this.#locations.get(kind + '/' + key.toLowerCase());
|
||||||
|
if (!location) return undefined;
|
||||||
|
const pictures = this.#loaded.get(location.pack) ?? this.#load(location.pack);
|
||||||
|
for (const path of location.paths) {
|
||||||
|
const picture = pictures.get(path);
|
||||||
|
if (picture) return picture;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#load(pack: string): Map<string, GamePicture> {
|
||||||
|
const pictures = new Map<string, GamePicture>();
|
||||||
|
this.#loaded.set(pack, pictures);
|
||||||
|
try {
|
||||||
|
const archive = readArchive(readFileSync(join(this.#gameFolder, pack)));
|
||||||
|
const storedPaths = new Map([...archive.files.keys()].map((path) => [path.toLowerCase(), path]));
|
||||||
|
for (const path of this.#wanted.get(pack) ?? []) {
|
||||||
|
const storedPath = storedPaths.get(path);
|
||||||
|
const bytes = storedPath ? archive.files.get(storedPath) : undefined;
|
||||||
|
if (bytes) pictures.set(path, { filename: path, bytes: Buffer.from(bytes) });
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
this.#report('web artwork ' + pack + ': ' + (error instanceof Error ? error.message : String(error)));
|
||||||
|
}
|
||||||
|
return pictures;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function vehiclePaths(name: string): string[] {
|
||||||
|
return VEHICLE_FOLDERS.map((folder) => folder + '/' + name.toLowerCase() + '.avif');
|
||||||
|
}
|
||||||
@@ -14,6 +14,7 @@ const CONTENT_TYPES: Readonly<Record<string, string>> = {
|
|||||||
'.css': 'text/css; charset=utf-8',
|
'.css': 'text/css; charset=utf-8',
|
||||||
'.js': 'text/javascript; charset=utf-8',
|
'.js': 'text/javascript; charset=utf-8',
|
||||||
'.svg': 'image/svg+xml',
|
'.svg': 'image/svg+xml',
|
||||||
|
'.avif': 'image/avif',
|
||||||
'.json': 'application/json; charset=utf-8',
|
'.json': 'application/json; charset=utf-8',
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -7,21 +7,25 @@
|
|||||||
* labels.json the game's country and vehicle type names (ui-labels dataset)
|
* labels.json the game's country and vehicle type names (ui-labels dataset)
|
||||||
* vehicle/<vehicle>.svg the game's silhouette icon of a vehicle (web-icons dataset)
|
* vehicle/<vehicle>.svg the game's silhouette icon of a vehicle (web-icons dataset)
|
||||||
* flag/<country>.svg the game's country flag (web-icons dataset)
|
* flag/<country>.svg the game's country flag (web-icons dataset)
|
||||||
|
* official-store-media.json public store cover, screenshot and video paths by product
|
||||||
|
* art/<kind>/<key> game artwork for vehicles, products and coupons
|
||||||
* asset-pack/<path> the player's own optional copy of official images, made by
|
* asset-pack/<path> the player's own optional copy of official images, made by
|
||||||
* asset-pack-cli.ts into <data folder>/asset-pack/
|
* asset-pack-cli.ts into <data folder>/asset-pack/
|
||||||
* Icons and names come from the player's game files at start-up; nothing of Gaijin's is shipped.
|
* Icons and names come from the player's game files at start-up; nothing of Gaijin's is shipped.
|
||||||
* Image order on the pages: asset pack → official site (when reachable) → game files.
|
* Image order on the pages: asset pack → official site (when reachable) → game files.
|
||||||
*/
|
*/
|
||||||
import { existsSync, readFileSync } from 'node:fs';
|
import { existsSync, readFileSync } from 'node:fs';
|
||||||
import { join, normalize, sep } from 'node:path';
|
import { resolve, sep } from 'node:path';
|
||||||
import type { WebIcons } from '../game-data/datasets/web-icons.ts';
|
import type { WebIcons } from '../game-data/datasets/web-icons.ts';
|
||||||
import type { UiLabels } from '../game-data/datasets/ui-labels.ts';
|
import type { UiLabels } from '../game-data/datasets/ui-labels.ts';
|
||||||
import type { Service, ServiceRequest, ServiceResponse } from '../server/exchange.ts';
|
import type { Service, ServiceRequest, ServiceResponse } from '../server/exchange.ts';
|
||||||
|
import type { GameArtwork } from './game-artwork.ts';
|
||||||
import { contentResponse, createStaticWebSite, notFound } from './web-helpers.ts';
|
import { contentResponse, createStaticWebSite, notFound } from './web-helpers.ts';
|
||||||
|
|
||||||
const PREFIX = '/_wto/ui/';
|
const PREFIX = '/_wto/ui/';
|
||||||
const SHARED_FILES = createStaticWebSite(new URL('./web/', import.meta.url), ['common.css', 'common.js', 'official-images.json']);
|
const SHARED_FILES = createStaticWebSite(new URL('./web/', import.meta.url), ['common.css', 'common.js', 'official-images.json', 'official-store-media.json']);
|
||||||
const ICON_PATH = /^(vehicle|flag)\/([^/]+)\.svg$/;
|
const ICON_PATH = /^(vehicle|flag)\/([^/]+)\.svg$/;
|
||||||
|
const ART_PATH = /^art\/(vehicle|group|product|skin|decal|attachable|unlock)\/([^/]+)$/;
|
||||||
const PACK_PREFIX = 'asset-pack/';
|
const PACK_PREFIX = 'asset-pack/';
|
||||||
const PACK_TYPES: Readonly<Record<string, string>> = { '.png': 'image/png', '.jpg': 'image/jpeg', '.webp': 'image/webp', '.json': 'application/json; charset=utf-8' };
|
const PACK_TYPES: Readonly<Record<string, string>> = { '.png': 'image/png', '.jpg': 'image/jpeg', '.webp': 'image/webp', '.json': 'application/json; charset=utf-8' };
|
||||||
|
|
||||||
@@ -30,11 +34,13 @@ export class WebUiService implements Service {
|
|||||||
readonly #icons: WebIcons;
|
readonly #icons: WebIcons;
|
||||||
readonly #labels: string;
|
readonly #labels: string;
|
||||||
readonly #packDir: string;
|
readonly #packDir: string;
|
||||||
|
readonly #artwork: GameArtwork;
|
||||||
|
|
||||||
constructor(icons: WebIcons, labels: UiLabels, dataFolder: string) {
|
constructor(icons: WebIcons, labels: UiLabels, dataFolder: string, artwork: GameArtwork) {
|
||||||
this.#icons = icons;
|
this.#icons = icons;
|
||||||
this.#labels = JSON.stringify(labels);
|
this.#labels = JSON.stringify(labels);
|
||||||
this.#packDir = join(dataFolder, 'asset-pack');
|
this.#packDir = resolve(dataFolder, 'asset-pack');
|
||||||
|
this.#artwork = artwork;
|
||||||
}
|
}
|
||||||
|
|
||||||
accepts(request: ServiceRequest): boolean {
|
accepts(request: ServiceRequest): boolean {
|
||||||
@@ -45,6 +51,8 @@ export class WebUiService implements Service {
|
|||||||
const subPath = request.path.slice(PREFIX.length);
|
const subPath = request.path.slice(PREFIX.length);
|
||||||
if (subPath === 'labels.json') return contentResponse(subPath, this.#labels, 'web ui: labels');
|
if (subPath === 'labels.json') return contentResponse(subPath, this.#labels, 'web ui: labels');
|
||||||
if (subPath.startsWith(PACK_PREFIX)) return this.#packFile(subPath.slice(PACK_PREFIX.length));
|
if (subPath.startsWith(PACK_PREFIX)) return this.#packFile(subPath.slice(PACK_PREFIX.length));
|
||||||
|
const art = ART_PATH.exec(subPath);
|
||||||
|
if (art) return this.#gamePicture(art[1]!, art[2]!);
|
||||||
const icon = ICON_PATH.exec(subPath);
|
const icon = ICON_PATH.exec(subPath);
|
||||||
if (icon) {
|
if (icon) {
|
||||||
const [, kind, name] = icon;
|
const [, kind, name] = icon;
|
||||||
@@ -55,10 +63,22 @@ export class WebUiService implements Service {
|
|||||||
return SHARED_FILES.serve(subPath, 'web ui') ?? notFound(`web ui 404: ${subPath}`);
|
return SHARED_FILES.serve(subPath, 'web ui') ?? notFound(`web ui 404: ${subPath}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#gamePicture(kind: string, encodedKey: string): ServiceResponse {
|
||||||
|
let key: string;
|
||||||
|
try {
|
||||||
|
key = decodeURIComponent(encodedKey);
|
||||||
|
} catch {
|
||||||
|
return notFound('web ui: invalid artwork key');
|
||||||
|
}
|
||||||
|
const picture = this.#artwork.image(kind, key);
|
||||||
|
return picture ? contentResponse(picture.filename, picture.bytes, 'web ui: game ' + kind + ' artwork')
|
||||||
|
: notFound('web ui: no game artwork for ' + kind + '/' + key);
|
||||||
|
}
|
||||||
|
|
||||||
/** A file of the player's asset pack; only image/json files inside the pack folder. */
|
/** A file of the player's asset pack; only image/json files inside the pack folder. */
|
||||||
#packFile(relative: string): ServiceResponse {
|
#packFile(relative: string): ServiceResponse {
|
||||||
const decoded = decodeURIComponent(relative);
|
const decoded = decodeURIComponent(relative);
|
||||||
const full = normalize(join(this.#packDir, decoded));
|
const full = resolve(this.#packDir, decoded);
|
||||||
const type = PACK_TYPES[decoded.slice(decoded.lastIndexOf('.')).toLowerCase()];
|
const type = PACK_TYPES[decoded.slice(decoded.lastIndexOf('.')).toLowerCase()];
|
||||||
if (!type || !full.startsWith(this.#packDir + sep) || !existsSync(full)) return notFound(`asset pack: no ${decoded}`);
|
if (!type || !full.startsWith(this.#packDir + sep) || !existsSync(full)) return notFound(`asset pack: no ${decoded}`);
|
||||||
return { status: 200, headers: { 'content-type': type, 'cache-control': 'max-age=86400' }, body: readFileSync(full), logNotes: { summary: `asset pack: ${decoded}` } };
|
return { status: 200, headers: { 'content-type': type, 'cache-control': 'max-age=86400' }, body: readFileSync(full), logNotes: { summary: `asset pack: ${decoded}` } };
|
||||||
|
|||||||
@@ -102,74 +102,135 @@ const WtoUi = (() => {
|
|||||||
element.className = 'notice ' + (ok ? 'ok' : 'err');
|
element.className = 'notice ' + (ok ? 'ok' : 'err');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Resolve images from the player's asset pack, reachable public URLs, or local game data.
|
const ASSET_PACK = '/_wto/ui/asset-pack/';
|
||||||
const ONLINE_PROBE = 'https://static-ggc.gaijin.net/units/ussr_object_292.png';
|
let officialImages = { base: '', byKey: {} };
|
||||||
let officialImages = { base: 'https://static-ggc.gaijin.net/', byKey: {} };
|
let officialStore = { base: '', byProduct: {} };
|
||||||
let packIndex = new Set();
|
let packIndex = new Set();
|
||||||
let online = false;
|
|
||||||
|
|
||||||
/** Load the official image table, the asset pack index and probe the official site (2.5 s at most). */
|
async function mediaJson(url, fallback) {
|
||||||
async function loadImageSources() {
|
try {
|
||||||
const table = fetch('/_wto/ui/official-images.json').then((r) => r.json()).then((j) => { officialImages = j; }).catch(() => {});
|
const response = await fetch(url);
|
||||||
const pack = fetch('/_wto/ui/asset-pack/index.json').then((r) => (r.ok ? r.json() : [])).then((list) => { packIndex = new Set(list); }).catch(() => {});
|
return response.ok ? await response.json() : fallback;
|
||||||
const probe = new Promise((resolve) => {
|
} catch (error) {
|
||||||
const img = new Image();
|
return fallback;
|
||||||
const timer = setTimeout(() => resolve(false), 2500);
|
|
||||||
img.onload = () => { clearTimeout(timer); resolve(true); };
|
|
||||||
img.onerror = () => { clearTimeout(timer); resolve(false); };
|
|
||||||
img.src = ONLINE_PROBE + '?t=' + Date.now();
|
|
||||||
}).then((ok) => { online = ok; });
|
|
||||||
await Promise.all([table, pack, probe]);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Candidate image sources for official URLs: asset-pack copies first, then (if online) the URLs. */
|
|
||||||
function sourcesFor(urls) {
|
|
||||||
const out = [];
|
|
||||||
for (const url of urls) {
|
|
||||||
const key = url.replace(/^https?:\/\//, '');
|
|
||||||
if (packIndex.has(key)) out.push('/_wto/ui/asset-pack/' + key);
|
|
||||||
}
|
}
|
||||||
if (online) out.push(...urls);
|
|
||||||
return out;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** An <img> that walks through `sources` and ends at `fallback` (a local URL) or hides itself. */
|
/** Page startup depends only on metadata served by the local service. */
|
||||||
function tieredImg(sources, fallback, className) {
|
async function loadImageSources(withStore = false) {
|
||||||
|
const [images, index, store] = await Promise.all([
|
||||||
|
mediaJson('/_wto/ui/official-images.json', officialImages),
|
||||||
|
mediaJson(ASSET_PACK + 'index.json', []),
|
||||||
|
withStore ? mediaJson('/_wto/ui/official-store-media.json', officialStore) : officialStore,
|
||||||
|
]);
|
||||||
|
officialImages = images;
|
||||||
|
officialStore = store;
|
||||||
|
packIndex = new Set(Array.isArray(index) ? index : []);
|
||||||
|
}
|
||||||
|
|
||||||
|
function publicImageAvailable(url) {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
const probe = new Image();
|
||||||
|
const finish = (available) => {
|
||||||
|
clearTimeout(timer);
|
||||||
|
probe.onload = probe.onerror = null;
|
||||||
|
if (!available) probe.removeAttribute('src');
|
||||||
|
resolve(available);
|
||||||
|
};
|
||||||
|
const timer = setTimeout(() => finish(false), 2500);
|
||||||
|
probe.crossOrigin = 'anonymous';
|
||||||
|
probe.referrerPolicy = 'no-referrer';
|
||||||
|
probe.onload = () => finish(true);
|
||||||
|
probe.onerror = () => finish(false);
|
||||||
|
probe.src = url;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function preferPublicImage(img, urls) {
|
||||||
|
for (const url of urls) {
|
||||||
|
if (!img.isConnected) return;
|
||||||
|
const ready = await publicImageAvailable(url);
|
||||||
|
if (ready && img.isConnected) {
|
||||||
|
const previous = img.getAttribute('src');
|
||||||
|
img.onload = null;
|
||||||
|
img.onerror = () => {
|
||||||
|
img.onerror = null;
|
||||||
|
if (previous) img.src = previous;
|
||||||
|
else img.style.visibility = 'hidden';
|
||||||
|
};
|
||||||
|
img.style.visibility = '';
|
||||||
|
img.src = url;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Use downloaded art first and show game art while attempting the public URL. */
|
||||||
|
function tieredImg(urls, fallbacks, className) {
|
||||||
const img = document.createElement('img');
|
const img = document.createElement('img');
|
||||||
img.className = className;
|
img.className = className;
|
||||||
img.alt = '';
|
img.alt = '';
|
||||||
const queue = [...sources, ...(fallback ? [fallback] : [])];
|
img.loading = 'lazy';
|
||||||
const next = () => {
|
img.crossOrigin = 'anonymous';
|
||||||
const src = queue.shift();
|
img.referrerPolicy = 'no-referrer';
|
||||||
if (src) img.src = src; else img.style.visibility = 'hidden';
|
const official = [...new Set(urls.filter(Boolean))];
|
||||||
};
|
const packed = official.map((url) => url.replace(/^https:\/\//, ''))
|
||||||
img.onerror = next;
|
.filter((key) => packIndex.has(key))
|
||||||
next();
|
.map((key) => ASSET_PACK + key);
|
||||||
|
const local = [...packed, ...fallbacks];
|
||||||
|
const upgrade = () => queueMicrotask(() => { void preferPublicImage(img, official); });
|
||||||
|
|
||||||
|
function nextLocal() {
|
||||||
|
const url = local.shift();
|
||||||
|
if (!url) {
|
||||||
|
img.style.visibility = 'hidden';
|
||||||
|
upgrade();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
img.onload = url.startsWith(ASSET_PACK) ? null : upgrade;
|
||||||
|
img.src = url;
|
||||||
|
}
|
||||||
|
|
||||||
|
img.onerror = nextLocal;
|
||||||
|
nextLocal();
|
||||||
return img;
|
return img;
|
||||||
}
|
}
|
||||||
|
|
||||||
const officialUrl = (key) => (officialImages.byKey[key] ? officialImages.base + officialImages.byKey[key] : '');
|
const officialUrl = (key) => {
|
||||||
|
const path = officialImages.byKey[key] || officialImages.byKey[key.toLowerCase()];
|
||||||
|
return path ? officialImages.base + path : '';
|
||||||
|
};
|
||||||
|
|
||||||
|
const artworkUrl = (kind, key) => '/_wto/ui/art/' + kind + '/' + encodeURIComponent(key);
|
||||||
|
|
||||||
|
function vehicleUrls(unitName) {
|
||||||
|
return [officialUrl(unitName), 'https://static.encyclopedia.warthunder.com/images/' + unitName.toLowerCase() + '.png'];
|
||||||
|
}
|
||||||
|
|
||||||
/** A vehicle picture: market render, encyclopedia render, then the game's silhouette. */
|
|
||||||
function vehicleImg(unitName, className) {
|
function vehicleImg(unitName, className) {
|
||||||
const urls = [officialUrl(unitName), 'https://static.encyclopedia.warthunder.com/images/' + unitName.toLowerCase() + '.png'].filter(Boolean);
|
return tieredImg(vehicleUrls(unitName), [artworkUrl('vehicle', unitName)], className);
|
||||||
return tieredImg(sourcesFor(urls), '/_wto/ui/vehicle/' + encodeURIComponent(unitName) + '.svg', className);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** An item picture by its resource key (decal, attachable, avatar), with an optional local fallback. */
|
function itemImg(kind, key, className) {
|
||||||
function itemImg(key, fallback, className) {
|
return tieredImg([officialUrl(key)], [artworkUrl(kind, key)], className);
|
||||||
const url = officialUrl(key);
|
|
||||||
return tieredImg(sourcesFor(url ? [url] : []), fallback, className);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A store product picture by its official store GUID, then a fallback. */
|
function storeMedia(productId) {
|
||||||
function storeImg(guid, fallback, className) {
|
const entry = officialStore.byProduct[productId];
|
||||||
const urls = guid ? ['https://static-store.gaijin.net/img/items/' + guid + '.jpg'] : [];
|
if (!entry) return { cover: '', screenshots: [], videos: [] };
|
||||||
return tieredImg(sourcesFor(urls), fallback, className);
|
const url = (path) => officialStore.base + path;
|
||||||
|
const clips = new Map();
|
||||||
|
for (const path of entry.videos || []) {
|
||||||
|
const name = path.replace(/\.(webm|mp4)$/i, '');
|
||||||
|
const sources = clips.get(name) || [];
|
||||||
|
sources.push(url(path));
|
||||||
|
clips.set(name, sources);
|
||||||
|
}
|
||||||
|
return { cover: url(entry.cover), screenshots: (entry.screenshots || []).map(url), videos: [...clips.values()] };
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
lang, query, text, tr, num, gjn, escapeHtml, label, getJson, postJson, loadLabels, iconImg, savedAccount, saveAccount,
|
lang, query, text, tr, num, gjn, escapeHtml, label, getJson, postJson, loadLabels, iconImg, savedAccount, saveAccount,
|
||||||
clearSavedAccount, fillAccountSelect, pageLink, showNotice, loadImageSources, vehicleImg, itemImg, storeImg, tieredImg,
|
clearSavedAccount, fillAccountSelect, pageLink, showNotice, loadImageSources, artworkUrl, vehicleUrls, vehicleImg, itemImg, storeMedia, tieredImg,
|
||||||
};
|
};
|
||||||
})();
|
})();
|
||||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user