Files
blitzkit/packages/website-ue/src/core/api/server.ts
T

318 lines
9.4 KiB
TypeScript
Raw Normal View History

2025-11-28 13:51:17 -06:00
import type { MetadataAccessor } from "@blitzkit/closed";
2026-02-03 09:04:36 -06:00
import { assertSecret, sluggify } from "@blitzkit/core";
2026-01-09 13:38:00 -06:00
import type { Strings } from "@blitzkit/i18n";
import locales from "@blitzkit/i18n/locales.json";
2025-11-28 14:13:03 -06:00
import type { RemoteStorageComponent } from "@protos/blitz_static_remote_storage_component";
2026-02-03 09:04:36 -06:00
import type { DeepPartial } from "@protos/blitz_static_reward_currency";
import { existsSync } from "fs";
import { mkdir, readFile, writeFile } from "fs/promises";
import { google } from "googleapis";
2026-01-09 13:38:00 -06:00
import { merge } from "lodash-es";
2025-11-28 14:13:03 -06:00
import { parse } from "yaml";
2026-01-11 13:40:01 -06:00
import type { Avatar } from "../../protos/avatar";
2026-01-11 13:46:54 -06:00
import type { Background } from "../../protos/background";
2025-12-26 14:14:29 -06:00
import type { Tank } from "../../protos/tank";
2026-01-11 13:40:01 -06:00
import type { TankListEntry } from "../../protos/tank_list";
2025-12-26 14:59:09 -06:00
import type { Tanks } from "../../protos/tanks";
2026-02-03 09:04:36 -06:00
import type { PopularTanks } from "../../types/popularTanks";
2025-11-28 13:51:17 -06:00
import { AbstractAPI } from "./abstract";
2025-11-30 20:54:36 -06:00
if (typeof window !== "undefined") {
throw new Error("ServerAPI is being evaluated in the browser");
}
2026-01-09 13:57:28 -06:00
const globbedStrings = import.meta.glob("../../../../i18n/strings/*.json", {
import: "default",
});
2026-02-03 09:04:36 -06:00
const tankSlugPattern = /^(\/\w+)?\/tanks\/([a-z0-9-]+)\/$/;
2026-01-09 13:38:00 -06:00
2025-11-28 14:13:03 -06:00
interface LocalizationConfig {
namespaces: string[];
}
2025-11-28 13:51:17 -06:00
export class ServerAPI extends AbstractAPI {
constructor(private metadata: MetadataAccessor) {
super();
2025-11-28 14:13:03 -06:00
}
2025-11-28 13:51:17 -06:00
2026-01-13 13:18:55 -06:00
protected async _gameStrings(locale: string) {
2025-12-05 21:35:58 -06:00
const group = this.metadata.group("ClientConfigsEntity");
if (group.length !== 1) {
throw new RangeError(
2026-02-03 09:04:36 -06:00
`Don't know how to handle ${group.length} ClientConfigsEntities`,
2025-12-05 21:35:58 -06:00
);
}
const clientConfig = this.metadata.item(group[0].id);
2025-11-28 14:13:03 -06:00
const localizationResources = clientConfig.LocalizationResources();
if (!localizationResources.remote_storage) {
throw new Error("Localization resources not found");
}
let remoteStorage: RemoteStorageComponent | undefined = undefined;
for (const candidateId of localizationResources.remote_storage
.remote_urls) {
const item = this.metadata.item(candidateId);
const candidate = item.RemoteStorage();
if (
remoteStorage === undefined ||
candidate.download_speed_weight > remoteStorage.download_speed_weight
) {
remoteStorage = candidate;
}
}
if (remoteStorage === undefined) {
throw new Error("No suitable production remote storage found");
}
const strings: Record<string, string> = {};
2025-12-13 13:16:42 -06:00
const configPath = `${remoteStorage.url}/${remoteStorage.relative_path}/config.yaml`;
2025-11-28 14:13:03 -06:00
2025-12-13 13:16:42 -06:00
try {
const config = await fetch(configPath)
.then((response) => response.text())
.then((text) => parse(text) as LocalizationConfig);
2025-11-28 14:13:03 -06:00
2025-12-13 13:16:42 -06:00
for (const namespace of config.namespaces) {
Object.assign(
strings,
await fetch(
2026-02-03 09:04:36 -06:00
`${remoteStorage.url}${remoteStorage.relative_path}/${namespace}/${locale}.yaml`,
2025-12-13 13:16:42 -06:00
)
.then((response) => response.text())
.then((text) => {
const strings: Record<string, string> = {};
const parsed = parse(text) as Record<string, string>;
2025-11-28 14:13:03 -06:00
2025-12-13 13:16:42 -06:00
for (const key in parsed) {
strings[key] = parsed[key].replaceAll('\\"', '"');
}
return strings;
2026-02-03 09:04:36 -06:00
}),
2025-12-13 13:16:42 -06:00
);
}
} catch (error) {
console.warn(
`Failed to fetch config from ${configPath}. Returning empty strings. This will throw an error in production. Error:`,
2026-02-03 09:04:36 -06:00
error,
2025-11-28 14:13:03 -06:00
);
}
2026-01-13 13:18:55 -06:00
return strings;
}
2026-01-14 11:48:55 -06:00
protected async _groupedGameStrings(locale: string, group: string) {
2026-01-13 13:18:55 -06:00
const strings = await this.gameStrings(locale);
2026-01-09 13:38:00 -06:00
const filtered: Record<string, string> = {};
for (const key in strings) {
2026-01-13 13:18:55 -06:00
if (key.startsWith(`${group}__`)) {
2026-01-14 11:48:55 -06:00
const trimmed = key.substring(group.length + 2);
filtered[trimmed] = strings[key];
2026-01-09 13:38:00 -06:00
}
}
return filtered;
}
2026-01-11 13:40:01 -06:00
protected async _strings(locale: string) {
2026-01-09 13:38:00 -06:00
const localized = (await globbedStrings[
`../../../../i18n/strings/${locale}.json`
]()) as DeepPartial<Strings>;
const defaults = (await globbedStrings[
`../../../../i18n/strings/${locales.default}.json`
]()) as Strings;
const strings = merge({}, defaults, localized);
2025-11-28 14:13:03 -06:00
return strings;
2025-11-28 13:51:17 -06:00
}
2026-01-11 13:40:01 -06:00
protected async _tankList() {
const group = this.metadata.group("TankEntity");
const list: TankListEntry[] = [];
2026-01-14 11:48:55 -06:00
const strings = await this.groupedGameStrings("en", "TankEntity", true);
2025-11-28 13:51:17 -06:00
2026-01-11 13:40:01 -06:00
for (const item of group) {
const tankCatalog = item.TankCatalog();
2025-11-28 14:21:26 -06:00
2026-01-11 13:40:01 -06:00
if (!tankCatalog.name) continue;
2025-11-28 14:21:26 -06:00
2026-01-11 13:40:01 -06:00
const name = strings[tankCatalog.name.value];
2025-11-28 14:21:26 -06:00
2026-01-11 13:40:01 -06:00
if (!name) continue;
2025-11-28 13:51:17 -06:00
2026-01-11 13:40:01 -06:00
const id = item.name;
const slug = sluggify(name);
2025-11-28 13:51:17 -06:00
2026-01-11 13:40:01 -06:00
list.push({ id, slug });
2025-11-28 13:51:17 -06:00
}
2026-01-11 13:40:01 -06:00
return { list };
2025-12-26 14:59:09 -06:00
}
2026-01-11 13:40:01 -06:00
protected async _tanks() {
2025-12-26 14:59:09 -06:00
const tankList = await this.tankList();
const data: Tanks = { tanks: {} };
for (const { id } of tankList.list) {
2026-01-02 14:26:05 -06:00
data.tanks[id] = await this.tank(id);
2025-12-26 14:59:09 -06:00
}
return data;
2025-11-28 13:51:17 -06:00
}
2025-11-28 14:21:26 -06:00
2026-01-11 13:40:01 -06:00
protected async _tank(id: string) {
2026-01-02 14:26:05 -06:00
const tankList = await this.tankList();
2025-12-26 14:59:09 -06:00
const tankListEntry = tankList.list.find((tank) => tank.id === id);
if (!tankListEntry) {
throw new Error(`Tank with id ${id} not found`);
}
const { slug } = tankListEntry;
2025-11-28 14:21:26 -06:00
const item = this.metadata.item(`TankEntity.${id}`);
2025-12-26 14:14:29 -06:00
const tank = item.TankCatalog();
const compensation = item.Compensation();
2025-11-28 14:21:26 -06:00
2026-02-03 09:04:36 -06:00
return { id, slug, tank, compensation } satisfies Tank;
2025-11-28 14:21:26 -06:00
}
2025-12-26 19:21:14 -06:00
2026-01-11 13:46:54 -06:00
protected async _avatars() {
2026-01-11 13:40:01 -06:00
const avatars: Avatar[] = [];
for (const item of this.metadata.group("ProfileAvatarEntity")) {
avatars.push(await this.avatar(item.name));
}
return { avatars };
2026-01-02 14:20:29 -06:00
}
2026-01-02 20:04:19 -06:00
2026-01-11 13:46:54 -06:00
protected async _avatar(id: string) {
2026-01-11 13:40:01 -06:00
const avatar = this.metadata.item(`ProfileAvatarEntity.${id}`);
const name = avatar.name;
const stuff_ui = avatar.StuffUI("UIComponent");
const profile_avatar = avatar.ProfileAvatar();
const sellable = avatar.components.sellableComponent
? avatar.Sellable()
: undefined;
return { name, stuff_ui, profile_avatar, sellable };
2026-01-02 20:04:19 -06:00
}
2026-01-02 20:17:24 -06:00
2026-01-11 13:46:54 -06:00
protected async _backgrounds() {
const backgrounds: Background[] = [];
for (const item of this.metadata.group("ProfileBackgroundEntity")) {
backgrounds.push(await this.background(item.name));
}
return { backgrounds };
2026-01-02 20:17:24 -06:00
}
2026-01-11 13:46:54 -06:00
protected async _background(id: string) {
const background = this.metadata.item(`ProfileBackgroundEntity.${id}`);
const name = background.name;
const stuff_ui = background.StuffUI("UIComponent");
const profile_background = background.ProfileBackground();
const sellable = background.components.sellableComponent
? background.Sellable()
: undefined;
return { name, stuff_ui, profile_background, sellable };
2026-01-02 20:17:24 -06:00
}
2026-01-13 13:18:55 -06:00
protected async _gameStringGroups() {
const defaultGameStrings = await this.gameStrings(locales.default);
const groups = new Set<string>();
for (const key in defaultGameStrings) {
const [group] = key.split("__");
groups.add(group);
}
return Array.from(groups.values());
}
2026-02-03 09:04:36 -06:00
protected async _popularTanks() {
if (!existsSync("../../temp/popular.json")) {
const { tanks } = await this.tanks();
const tanksArray = Object.values(tanks);
const auth = await google.auth.getClient({
keyFile: assertSecret(import.meta.env.GOOGLE_APPLICATION_CREDENTIALS),
scopes: ["https://www.googleapis.com/auth/analytics.readonly"],
});
const analytics = google.analyticsdata({ version: "v1beta", auth });
const report = await analytics.properties.runReport({
property: `properties/${assertSecret(
import.meta.env.PUBLIC_GOOGLE_ANALYTICS_PROPERTY_ID,
)}`,
requestBody: {
dateRanges: [{ startDate: "7daysAgo", endDate: "today" }],
dimensions: [{ name: "pagePath" }],
metrics: [{ name: "screenPageViews" }],
orderBys: [{ metric: { metricName: "screenPageViews" }, desc: true }],
dimensionFilter: {
filter: {
fieldName: "pagePath",
stringFilter: {
matchType: "BEGINS_WITH",
value: "/tanks/",
},
},
},
},
});
const views: Record<string, number> = {};
if (!report.data.rows) {
throw new Error("No rows in report");
}
for (const row of report.data.rows) {
if (
!row.dimensionValues ||
!row.dimensionValues[0].value ||
!row.metricValues ||
!row.metricValues[0].value
) {
continue;
}
const matches = row.dimensionValues[0].value.match(tankSlugPattern);
if (!matches) continue;
const slug = matches[2];
const tank = tanksArray.find((tank) => tank.slug === slug);
if (!tank) continue;
if (tank.id in views) {
views[tank.id] += Number(row.metricValues[0].value);
} else {
views[tank.id] = Number(row.metricValues[0].value);
}
}
const popularTanks: PopularTanks = Object.entries(views)
.sort(([, a], [, b]) => b - a)
.map(([id, views]) => ({ id, views }));
await mkdir("../../temp", { recursive: true });
await writeFile("../../temp/popular.json", JSON.stringify(popularTanks));
return popularTanks;
}
const data = await readFile("../../temp/popular.json", "utf-8");
return JSON.parse(data) as PopularTanks;
}
2025-11-28 13:51:17 -06:00
}