Files

142 lines
7.0 KiB
TypeScript

import fs from 'node:fs';
import path from 'node:path';
import zlib from 'node:zlib';
import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
/**
* 발로란트 맵 3D 모양 (tools/map-extract 가 Riot CDN 에서 뽑아 tools/map-extract/scripts/update.sh 가 올린다).
* 게임 파일에서 나온 것이라 로그인한 사람(봇과 같은 서버 멤버)에게만 준다.
*
* <dataDir>/maps3d/index.json {version, dir, updatedAt, maps:{<맵 경로>:{code,file,bytes,triangles}}}
* <dataDir>/maps3d/<dir>/<code>.glb.gz meshopt 압축 glb 를 gzip 한 것. 위치는 UE 월드 좌표(cm)
* <dataDir>/maps3d/<dir>/abilities.json.gz · m_*.glb.gz · t_*.png.gz 스킬 목록 · 모델 · 텍스처 (모두 gzip)
*
* GET /site/maps3d → index.json (없으면 {maps:{}})
* GET /site/maps3d/:dir/:f → glb · json · png · jpg (content-encoding gzip). 폴더 이름이 패치마다 바뀌므로 오래 캐시한다
*
* 무기 스킨 (본 것만 뽑는다, tools/map-extract/scripts/skins-update.sh 가 몇 분마다 요청을 가져가 뽑아 올린다):
* <dataDir>/maps3d/skins/index.json {skins:{"스킨|단계|색상":{weapon, sig}}, looks:{서명:{w3p, points, w1p, points1p, gunClips}}, failed:{열쇠:이유}}
* <dataDir>/maps3d/skins/skin3p_<서명>.glb.gz · skin1p_<서명>.glb.gz (파일 이름이 모습마다 달라 오래 캐시한다)
* <dataDir>/maps3d/skins/want.json 사이트가 받은 요청 (아직 없는 열쇠, 시간 순 · 최대 MAX_WANT)
* GET /site/maps3d/skins → skins/index.json (없으면 빈 목록)
* POST /site/maps3d/skins/want {keys:[열쇠]} → 없는 것만 want.json 에 더한다
*/
export interface Maps3dIndex {
version: string;
dir: string;
updatedAt: string;
maps: Record<string, { code: string; file: string; bytes: number; triangles: number }>;
}
/** 보내는 파일 종류: 3D (맵 · 요원 · 무기 · 스킬 모델 · 공용 애니메이션) · 스킬 목록 · 스킬 텍스처 */
const TYPES: Record<string, string> = { '.glb': 'model/gltf-binary', '.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg' };
/** 스킨 요청 열쇠 "스킨|단계|색상" (게임 데이터 에셋 경로, 단계 · 색상은 비어도 된다). 추출기 Skins.ValidKey 와 같다 */
const SKIN_KEY = /^\/Game\/Equippables\/[A-Za-z0-9_/-]+\|(\/Game\/Equippables\/[A-Za-z0-9_/-]+)?\|(\/Game\/Equippables\/[A-Za-z0-9_/-]+)?$/;
export const isSkinKey = (k: unknown): k is string => typeof k === 'string' && k.length < 600 && SKIN_KEY.test(k);
const MAX_WANT = 2000;
const MAX_WANT_PER_REQUEST = 100;
/** JSON 파일을 mtime 이 바뀔 때만 다시 읽는다 (없거나 깨졌으면 null) */
function jsonFile<T>(file: string): () => T | null {
let cache: { mtime: number; data: T | null } = { mtime: -1, data: null };
return () => {
let st: fs.Stats;
try {
st = fs.statSync(file);
} catch {
return null;
}
if (st.mtimeMs !== cache.mtime) {
try {
cache = { mtime: st.mtimeMs, data: JSON.parse(fs.readFileSync(file, 'utf8')) as T };
} catch {
cache = { mtime: st.mtimeMs, data: null };
}
}
return cache.data;
};
}
export interface SkinsIndex {
skins: Record<string, { weapon: string; sig: string }>;
looks: Record<string, { w3p?: string; points?: Record<string, number[]>; w1p?: string; points1p?: Record<string, number[]>; gunClips?: string[] }>;
failed?: Record<string, string>;
}
export function registerMaps3d(app: FastifyInstance, dataDir: string, requireSession: (req: FastifyRequest, reply: FastifyReply) => Promise<unknown>, publicUrl?: string) {
const root = path.join(dataDir, 'maps3d');
let cache: { mtime: number; data: Maps3dIndex | null } = { mtime: -1, data: null };
const index = (): Maps3dIndex | null => {
const f = path.join(root, 'index.json');
let st: fs.Stats;
try {
st = fs.statSync(f);
} catch {
return null;
}
if (st.mtimeMs !== cache.mtime) {
try {
cache = { mtime: st.mtimeMs, data: JSON.parse(fs.readFileSync(f, 'utf8')) as Maps3dIndex };
} catch {
cache = { mtime: st.mtimeMs, data: null };
}
}
return cache.data;
};
app.get('/site/maps3d', async (req, reply) => {
if (!(await requireSession(req, reply))) return;
reply.header('cache-control', 'private, no-cache');
return index() ?? { version: null, dir: null, maps: {} };
});
const skinsDir = path.join(root, 'skins');
const skins = jsonFile<SkinsIndex>(path.join(skinsDir, 'index.json'));
app.get('/site/maps3d/skins', async (req, reply) => {
if (!(await requireSession(req, reply))) return;
reply.header('cache-control', 'private, no-cache');
return skins() ?? { skins: {}, looks: {} };
});
app.post<{ Body: { keys?: unknown } }>('/site/maps3d/skins/want', async (req, reply) => {
if (!(await requireSession(req, reply))) return;
const origin = String(req.headers.origin || '');
if (origin && publicUrl && origin !== publicUrl) return reply.code(403).send({ error: 'bad_origin' });
const keys = Array.isArray(req.body?.keys) ? req.body.keys.slice(0, MAX_WANT_PER_REQUEST).filter(isSkinKey) : [];
const idx = skins();
const file = path.join(skinsDir, 'want.json');
let want: string[] = [];
try {
const w = JSON.parse(fs.readFileSync(file, 'utf8')) as unknown;
if (Array.isArray(w)) want = w.filter(isSkinKey);
} catch {
/* 처음이거나 깨졌으면 새로 */
}
const have = new Set(want);
const add = [...new Set(keys)].filter((k) => !have.has(k) && !idx?.skins?.[k] && !idx?.failed?.[k]);
if (add.length === 0) return { queued: 0 };
// 다 뽑은 것은 뺀다 (뽑는 쪽은 이 파일을 읽기만 한다)
want = [...want.filter((k) => !idx?.skins?.[k] && !idx?.failed?.[k]), ...add].slice(-MAX_WANT);
fs.mkdirSync(skinsDir, { recursive: true });
fs.writeFileSync(file + '.tmp', JSON.stringify(want));
fs.renameSync(file + '.tmp', file);
req.log.info({ area: 'skins', add: add.length, total: want.length }, '무기 스킨 요청');
return { queued: add.length };
});
app.get<{ Params: { dir: string; file: string } }>('/site/maps3d/:dir/:file', async (req, reply) => {
if (!(await requireSession(req, reply))) return;
const { dir, file } = req.params;
const type = TYPES[path.extname(file).toLowerCase()];
if (!/^[\w.-]+$/.test(dir) || !/^[\w.-]+$/.test(file) || !type || dir.includes('..')) return reply.code(404).send({ error: 'not_found' });
const gz = path.join(root, dir, file + '.gz');
if (!fs.existsSync(gz)) return reply.code(404).send({ error: 'not_found' });
reply.header('cache-control', 'private, max-age=31536000, immutable').type(type);
if (/\bgzip\b/.test(String(req.headers['accept-encoding'] ?? ''))) {
reply.header('content-encoding', 'gzip').header('content-length', fs.statSync(gz).size);
return reply.send(fs.createReadStream(gz));
}
return reply.send(fs.createReadStream(gz).pipe(zlib.createGunzip()));
});
}