Merge pull request #28 from kanomahoro1224/feat/media-audio-route
音频改走无扩展名的 /media 路由:下载管理器不再弹「下载文件信息」
This commit is contained in:
7 files changed
+362
-14
No files matched your search
+23
-1
@@ -31,6 +31,7 @@
|
||||
// which follows the store).
|
||||
|
||||
import { PHASE } from '../../shared/constants.js';
|
||||
import { mediaUrl } from './media.js';
|
||||
|
||||
const MAX_VOICES = 8;
|
||||
const UNIT_COOLDOWN_MS = 160;
|
||||
@@ -215,6 +216,20 @@ export class SfxLimiter {
|
||||
|
||||
// ---- manager -----------------------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Could Web Audio decode this response? A host without the `/media/` route answers 404; some static hosts answer a
|
||||
* missing path with 200 + the SPA's index.html instead, and fetching *that* would fail to decode as silently as a
|
||||
* 404 would — so the fallback looks at the declared type too.
|
||||
*
|
||||
* A response that declares no type at all is not treated as wrong: absence of a header is not evidence of an HTML
|
||||
* page, and fetch stubs / minimal hosts legitimately omit it.
|
||||
* @param {{ ok?: boolean, headers?: { get?: (n: string) => string | null } }} res
|
||||
*/
|
||||
function isAudioResponse(res) {
|
||||
if (!res || !res.ok) return false;
|
||||
const type = res.headers?.get?.('content-type');
|
||||
return !type || /^\s*audio\//i.test(type);
|
||||
}
|
||||
export class AudioManager {
|
||||
/**
|
||||
* @param {{ getManifest?: () => any, win?: any }} [opts]
|
||||
@@ -383,7 +398,14 @@ export class AudioManager {
|
||||
}
|
||||
const p = (async () => {
|
||||
try {
|
||||
const res = await fetch(url);
|
||||
// Extension-less URL first so download managers leave the BGM alone; a host without /media/ still works.
|
||||
const media = mediaUrl(url);
|
||||
let res = await fetch(media);
|
||||
if (media !== url && !isAudioResponse(res)) {
|
||||
// Drop the unusable response (404, or a 200 that is really index.html) before trying the original URL.
|
||||
try { await res.body?.cancel?.(); } catch { /* the fallback request matters more than draining this one */ }
|
||||
res = await fetch(url);
|
||||
}
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
const ab = await res.arrayBuffer();
|
||||
return await new Promise((resolve) => {
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
// audio URL rewriting for download managers (IDM / 迅雷 / FDM …) — see shared/media.js for the why.
|
||||
//
|
||||
// The game plays audio with fetch() + Web Audio (`audio.js`): it never uses <audio src>, <a download> or a
|
||||
// navigation. Download managers do not care — their browser integration hooks XHR/fetch whose URL ends in a
|
||||
// media extension and (usually above ~1 MB) pops up "下载文件信息" for every BGM track. That dialog has nothing
|
||||
// to do with the game, but players see it and blame the game.
|
||||
//
|
||||
// So audio is fetched through a same-origin, extension-less path instead:
|
||||
//
|
||||
// /assets/audio/bgm/act1.mp3 → /media/bgm/act1
|
||||
//
|
||||
// `server/index.js` resolves /media/… back to the real file under public/assets/audio and still answers with
|
||||
// `Content-Type: audio/mpeg` + range support; Web Audio sniffs the container, so the URL is all the same to it.
|
||||
// A host that does not implement /media/ keeps working: `audio.js` falls back to the original URL whenever the
|
||||
// /media/ response is unusable (a 404, or a 200 that is not audio at all — some static hosts answer a missing
|
||||
// path with the SPA's index.html).
|
||||
import { MEDIA_PREFIX, AUDIO_EXTS } from '../../shared/media.js';
|
||||
|
||||
const AUDIO_PATH = /^\/assets\/audio\/(.+)$/i;
|
||||
|
||||
/**
|
||||
* Rewrite an audio URL to its extension-less `/media/…` form.
|
||||
*
|
||||
* Returns the input unchanged when the URL is not one of our audio assets, points at another origin (a CDN
|
||||
* serves media itself, so the download-manager problem is not ours to solve there), or would produce a path the
|
||||
* server refuses (empty / dot segments).
|
||||
* @param {string} url
|
||||
* @param {string} [origin] origin of the page; defaults to `location.origin`
|
||||
* @returns {string} a URL safe to pass to fetch()
|
||||
*/
|
||||
export function mediaUrl(url, origin = globalThis.location?.origin) {
|
||||
if (typeof url !== 'string' || !url) return url;
|
||||
let u;
|
||||
// No origin known (Node / tests): parse relative URLs against a placeholder, absolute ones are rejected below.
|
||||
try { u = new URL(url, origin || 'http://localhost'); } catch { return url; }
|
||||
// Cross-origin (or absolute while the page origin is unknown) stays untouched: that host serves its own media.
|
||||
const absolute = /^[a-z][a-z0-9+.-]*:/i.test(url) || url.startsWith('//');
|
||||
if (origin ? u.origin !== origin : absolute) return url;
|
||||
const m = AUDIO_PATH.exec(u.pathname);
|
||||
if (!m) return url;
|
||||
let rest = m[1];
|
||||
const ext = AUDIO_EXTS.find((e) => rest.toLowerCase().endsWith(e));
|
||||
if (!ext) return url; // not a file we serve as audio (e.g. "x.mp3.bak") — leave it alone
|
||||
rest = rest.slice(0, -ext.length);
|
||||
const segments = rest.split('/');
|
||||
if (!rest || segments.some((s) => !s || s === '.' || s === '..' || s.startsWith('.'))) return url;
|
||||
return `${MEDIA_PREFIX}${rest}${u.search}`;
|
||||
}
|
||||
@@ -8,6 +8,9 @@
|
||||
// /data.js → a generated browser stand-in of server/data.js (the sim's content modules
|
||||
// import `../../../data.js`; in the browser it serves the data injected with
|
||||
// /sim/simdata.js setSimData). No other server file is ever served.
|
||||
// /media/bgm/act1 → public/assets/audio/bgm/act1.mp3 — the same audio files, addressed
|
||||
// **without** an extension so download managers (IDM / 迅雷 …) stop popping a
|
||||
// "下载文件信息" dialog for every BGM track (shared/media.js, public/js/media.js)
|
||||
// MIME types incl. .mjs/.js text/javascript, .skel application/octet-stream, .atlas text/plain;
|
||||
// gzip for text-like types, .skel and uncompressed fonts when the client accepts it (small files are
|
||||
// compressed once and cached in memory); strong ETag + Last-Modified with 304s; Cache-Control
|
||||
@@ -39,6 +42,7 @@ import { Network, SessionRegistry, NET_DEFAULTS } from './net.js';
|
||||
import { Lobby } from './lobby.js';
|
||||
import { getData, loadData } from './data.js';
|
||||
import { PROTOCOL_VERSION, APP_VERSION } from '../shared/constants.js';
|
||||
import { MEDIA_PREFIX, AUDIO_EXTS } from '../shared/media.js';
|
||||
|
||||
/** Repository root. */
|
||||
export const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
@@ -311,6 +315,11 @@ export function createStaticHandler({ publicDir, dataDir, sharedDir, simDir = pa
|
||||
res.end(req.method === 'HEAD' ? undefined : shimBody);
|
||||
return;
|
||||
}
|
||||
// Extension-less audio (download-manager avoidance): /media/bgm/act1 → /assets/audio/bgm/act1.mp3
|
||||
if (decoded.startsWith(MEDIA_PREFIX)) {
|
||||
await serveMedia(req, res, decoded.slice(MEDIA_PREFIX.length), query, publicDir, gzipCache, log);
|
||||
return;
|
||||
}
|
||||
// Bare mount paths (e.g. "/data") → treat as the mount directory.
|
||||
const mount = mounts.find((m) => decoded.startsWith(m.prefix) || decoded === m.prefix.slice(0, -1)) || mounts[mounts.length - 1];
|
||||
const rest = decoded.length > mount.prefix.length ? decoded.slice(mount.prefix.length) : '';
|
||||
@@ -372,6 +381,51 @@ export function createStaticHandler({ publicDir, dataDir, sharedDir, simDir = pa
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Extension-less audio route: `/media/bgm/act1` → `public/assets/audio/bgm/act1.mp3`.
|
||||
*
|
||||
* Clients ask for audio through this path because download managers (IDM, 迅雷, FDM …) hijack XHR/fetch whose
|
||||
* URL ends in a media extension and pop a "下载文件信息" dialog for every BGM track — see `public/js/media.js`.
|
||||
* Requests for the direct `/assets/audio/…` URLs keep working (they are the fallback for plain static hosts).
|
||||
* `MEDIA_PREFIX` / `AUDIO_EXTS` live in `shared/media.js`: the browser decides which URLs to rewrite with the
|
||||
* same two values, and they must not drift apart.
|
||||
*/
|
||||
async function serveMedia(req, res, rest, query, publicDir, gzipCache, log) {
|
||||
const root = path.join(path.resolve(publicDir), 'assets', 'audio');
|
||||
const segments = String(rest || '').split('/').filter((s) => s.length > 0);
|
||||
if (!segments.length || rest.endsWith('/')) { sendError(req, res, 404, '页面不存在 · Not found'); return; }
|
||||
if (segments.some((s) => s === '..' || s === '.')) { sendError(req, res, 403, '禁止访问 · Forbidden'); return; }
|
||||
// A leading or trailing dot would address something else (dotfiles, "x..mp3") — and the client never asks for it.
|
||||
if (segments.some((s) => s.startsWith('.') || s.endsWith('.'))) { sendError(req, res, 404, '页面不存在 · Not found'); return; }
|
||||
|
||||
const last = segments[segments.length - 1];
|
||||
const given = path.extname(last).toLowerCase();
|
||||
const wanted = AUDIO_EXTS.includes(given) ? given : '';
|
||||
const stem = wanted ? last.slice(0, -wanted.length) : last;
|
||||
if (!stem || stem.startsWith('.')) { sendError(req, res, 404, '页面不存在 · Not found'); return; }
|
||||
const dir = path.join(root, ...segments.slice(0, -1));
|
||||
if (dir !== root && !dir.startsWith(root + path.sep)) { sendError(req, res, 403, '禁止访问 · Forbidden'); return; }
|
||||
|
||||
// An explicit extension wins (`/media/bgm.ogg` → bgm.ogg), otherwise the usual order decides.
|
||||
const order = wanted ? [wanted, ...AUDIO_EXTS.filter((e) => e !== wanted)] : AUDIO_EXTS;
|
||||
for (const ext of order) {
|
||||
const absPath = path.join(dir, stem + ext);
|
||||
if (!absPath.startsWith(root + path.sep)) continue;
|
||||
let stat;
|
||||
try {
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
stat = await fsp.stat(absPath);
|
||||
} catch { continue; }
|
||||
if (!stat.isFile()) continue;
|
||||
// serveFile decides Content-Type from the resolved name (`.mp3` → audio/mpeg) — Range/ETag handling is shared.
|
||||
// Cache policy is that of the public path the client would otherwise have asked for (`/assets/audio/…`, 1 day).
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
await serveFile(req, res, absPath, stat, 'public', ['assets', 'audio', ...segments], query, gzipCache, log);
|
||||
return;
|
||||
}
|
||||
sendError(req, res, 404, '页面不存在 · Not found');
|
||||
}
|
||||
|
||||
async function serveFile(req, res, absPath, stat, mountName, segments, query, gzipCache, log) {
|
||||
const ext = path.extname(absPath).toLowerCase();
|
||||
const type = MIME[ext] || 'application/octet-stream';
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
// Extension-less audio route (/media/…) — the one place that defines it.
|
||||
//
|
||||
// The game plays audio with fetch() + Web Audio, never <audio src> / <a download>. Download managers (IDM / 迅雷 /
|
||||
// FDM …) do not care: their browser integration hooks XHR/fetch whose URL ends in a media extension and pops up
|
||||
// "下载文件信息" for every BGM track. So the browser asks for audio through a same-origin, extension-less path —
|
||||
//
|
||||
// /assets/audio/bgm/act1.mp3 → /media/bgm/act1
|
||||
//
|
||||
// — and `server/index.js` resolves it back to the real file under public/assets/audio, still answering with
|
||||
// `Content-Type: audio/mpeg`, Range support and the ETag of the file it resolved.
|
||||
//
|
||||
// Both sides import this module: the browser to decide which URLs to rewrite (`public/js/media.js`), the server to
|
||||
// decide which extensions a `/media/…` request may resolve to. A second copy of the list on one side would let them
|
||||
// drift apart silently — the client would rewrite to a path the server no longer accepts.
|
||||
|
||||
/** Prefix of the extension-less audio route served by `server/index.js`. */
|
||||
export const MEDIA_PREFIX = '/media/';
|
||||
|
||||
/** Extensions a `/media/…` request may resolve to, in the order the server tries them. */
|
||||
export const AUDIO_EXTS = Object.freeze(['.mp3', '.m4a', '.aac', '.ogg', '.oga', '.opus', '.wav']);
|
||||
@@ -281,6 +281,44 @@ describe('static http server', () => {
|
||||
assert.equal(textRange.body.toString(), js.slice(0, 2));
|
||||
});
|
||||
|
||||
test('extension-less /media audio route (download managers sniff .mp3 URLs)', async () => {
|
||||
const direct = await httpReq(srv.port, '/assets/audio/bgm.mp3');
|
||||
const media = await httpReq(srv.port, '/media/bgm');
|
||||
assert.equal(media.status, 200);
|
||||
assert.equal(media.headers['content-type'], 'audio/mpeg', 'resolved from the real .mp3 on disk');
|
||||
assert.equal(media.headers['accept-ranges'], 'bytes');
|
||||
assert.deepEqual(media.body, mp3, 'same bytes as the direct URL');
|
||||
assert.equal(media.headers['cache-control'], direct.headers['cache-control'], 'same 1-day policy as /assets/…');
|
||||
assert.equal(media.headers.etag, direct.headers.etag, 'ETag is the file validator, not the URL');
|
||||
|
||||
const range = await httpReq(srv.port, '/media/bgm', { headers: { range: 'bytes=0-9' } });
|
||||
assert.equal(range.status, 206);
|
||||
assert.equal(range.headers['content-range'], `bytes 0-9/${mp3.length}`);
|
||||
assert.deepEqual(range.body, mp3.subarray(0, 10));
|
||||
const head = await httpReq(srv.port, '/media/bgm', { method: 'HEAD' });
|
||||
assert.equal(head.status, 200);
|
||||
assert.equal(head.body.length, 0);
|
||||
|
||||
// The extension may still be given, and the other audio extension resolves too.
|
||||
assert.equal((await httpReq(srv.port, '/media/bgm.mp3')).status, 200);
|
||||
const ogg = await httpReq(srv.port, '/media/bgm.ogg');
|
||||
assert.equal(ogg.status, 200);
|
||||
assert.equal(ogg.headers['content-type'], 'audio/ogg');
|
||||
assert.equal(ogg.body.length, 64);
|
||||
|
||||
// …and it only ever reaches public/assets/audio.
|
||||
for (const p of ['/media/nope', '/media/bgm/', '/media/', '/media/.hidden', '/media/bgm.mp3/nope', '/media/js/app']) {
|
||||
const r = await httpReq(srv.port, p);
|
||||
assert.equal(r.status, 404, `${p} → 404`);
|
||||
assert.doesNotMatch(r.body.toString(), /TOP-SECRET-CONTENT/, `${p} must not leak files outside public/assets/audio`);
|
||||
}
|
||||
for (const p of ['/media/..%2f..%2fsecret.txt', '/media/bgm/../..%2f..%2fsecret.txt']) {
|
||||
const r = await httpReq(srv.port, p);
|
||||
assert.equal(r.status, 403, `${p} → 403 (same as the rest of the server)`);
|
||||
assert.doesNotMatch(r.body.toString(), /TOP-SECRET-CONTENT/);
|
||||
}
|
||||
});
|
||||
|
||||
test('path traversal and dotfiles are blocked', async () => {
|
||||
const attempts = [
|
||||
'/../secret.txt', '/%2e%2e/secret.txt', '/..%2fsecret.txt', '/%2e%2e%2fsecret.txt', '/data/../../secret.txt',
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
// mediaUrl(): audio is fetched through an extension-less /media/… path so download managers (IDM / 迅雷 / FDM)
|
||||
// stop hijacking BGM playback with a "下载文件信息" dialog. See public/js/media.js for the full rationale.
|
||||
import { test, describe } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mediaUrl } from '../public/js/media.js';
|
||||
// 前缀与扩展名列表只有一份(客户端和服务端都从这里取),所以断言也直接盯住这一份。
|
||||
import { MEDIA_PREFIX, AUDIO_EXTS } from '../shared/media.js';
|
||||
|
||||
const ORIGIN = 'http://127.0.0.1:3000';
|
||||
|
||||
describe('mediaUrl: 音频地址去掉扩展名(躲开下载器嗅探)', () => {
|
||||
test('把 /assets/audio/**.mp3 改写成 /media/**', () => {
|
||||
assert.equal(mediaUrl('/assets/audio/bgm/m_sys_act1autochess_loop.mp3', ORIGIN), '/media/bgm/m_sys_act1autochess_loop');
|
||||
assert.equal(mediaUrl('/assets/audio/sfx/player/p_imp/hit.mp3', ORIGIN), '/media/sfx/player/p_imp/hit');
|
||||
// 绝对同源地址同样改写
|
||||
assert.equal(mediaUrl(`${ORIGIN}/assets/audio/bgm/a.mp3`, ORIGIN), '/media/bgm/a');
|
||||
// 查询串保留(?v=… 会拿到 immutable 缓存)
|
||||
assert.equal(mediaUrl('/assets/audio/bgm/a.mp3?v=2', ORIGIN), '/media/bgm/a?v=2');
|
||||
// 各音频扩展名
|
||||
for (const ext of AUDIO_EXTS) {
|
||||
assert.equal(mediaUrl(`/assets/audio/x/a${ext}`, ORIGIN), '/media/x/a', ext);
|
||||
}
|
||||
assert.equal(mediaUrl('/assets/audio/x/A.MP3', ORIGIN), '/media/x/A', '大小写不敏感');
|
||||
});
|
||||
|
||||
test('改写后的地址里不再有任何媒体扩展名(下载器就是按这个嗅探的)', () => {
|
||||
const out = mediaUrl('/assets/audio/bgm/m_bat_vtlionk_loop.mp3', ORIGIN);
|
||||
assert.equal(out.startsWith(MEDIA_PREFIX), true);
|
||||
assert.doesNotMatch(out, /\.(mp3|m4a|aac|ogg|oga|opus|wav)(\?|$)/i);
|
||||
});
|
||||
|
||||
test('不是我们的音频、或不是同源时不改写', () => {
|
||||
assert.equal(mediaUrl('/assets/img/a.png', ORIGIN), '/assets/img/a.png');
|
||||
assert.equal(mediaUrl('/assets/audio/bgm.m4a.bak', ORIGIN), '/assets/audio/bgm.m4a.bak', '扩展名不认识就原样返回');
|
||||
assert.equal(mediaUrl('https://cdn.example.com/assets/audio/a.mp3', ORIGIN), 'https://cdn.example.com/assets/audio/a.mp3', '别的源自己负责');
|
||||
assert.equal(mediaUrl('/data/assets.json', ORIGIN), '/data/assets.json');
|
||||
assert.equal(mediaUrl('', ORIGIN), '');
|
||||
assert.equal(mediaUrl(null, ORIGIN), null);
|
||||
assert.equal(mediaUrl(undefined, ORIGIN), undefined);
|
||||
assert.equal(mediaUrl('/assets/audio/', ORIGIN), '/assets/audio/', '空路径不改写(服务端只会 404)');
|
||||
});
|
||||
|
||||
test('会产生非法路径的输入不碰(点目录 / 空段)', () => {
|
||||
assert.equal(mediaUrl('/assets/audio/.hidden.mp3', ORIGIN), '/assets/audio/.hidden.mp3');
|
||||
// URL 解析本来就会把 .. 归一化,改写跟着归一化后的路径走(服务端仍是同一道校验)
|
||||
assert.equal(mediaUrl('/assets/audio/bgm/../x.mp3', ORIGIN), '/media/x');
|
||||
});
|
||||
|
||||
test('没有 location 时(测试环境)用传入的 origin 判断同源', () => {
|
||||
assert.equal(mediaUrl('/assets/audio/bgm/a.mp3'), '/media/bgm/a', '相对地址本来就同源');
|
||||
assert.equal(mediaUrl('https://other.example/assets/audio/a.mp3'), 'https://other.example/assets/audio/a.mp3');
|
||||
});
|
||||
});
|
||||
+126
-13
@@ -7,11 +7,20 @@ import { readFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { bgmKeyFor, resolveBgm, SfxLimiter, AudioManager, normalAttackSfx } from '../../public/js/audio.js';
|
||||
import { mediaUrl } from '../../public/js/media.js';
|
||||
import { PHASE } from '../../shared/constants.js';
|
||||
|
||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
|
||||
const manifest = JSON.parse(readFileSync(path.join(ROOT, 'data', 'assets.json'), 'utf8'));
|
||||
|
||||
// audio.js 取音频时**先请求无扩展名的 /media/…**(正是为了躲开下载管理器对 .mp3 后缀的嗅探),
|
||||
// 只有那样 404 了才回退到 manifest 里的原始地址。所以「某个音效响了没有」不能拿原始地址去比对——
|
||||
// 那样断言的是一个客户端永远不会请求的 URL。下面两个助手把比对放到同一条换算上。
|
||||
/** 这个 manifest 地址被请求过吗(/media/ 形式或 404 后的原始形式)。 */
|
||||
const asked = (urls, raw) => urls.includes(mediaUrl(raw)) || urls.includes(raw);
|
||||
/** 这个 manifest 地址被请求了几次。 */
|
||||
const askedCount = (urls, raw) => urls.filter((u) => u === mediaUrl(raw) || u === raw).length;
|
||||
|
||||
describe('bgm selection', () => {
|
||||
test('route and phase → key', () => {
|
||||
assert.equal(bgmKeyFor('title', null), 'lobby');
|
||||
@@ -129,11 +138,11 @@ describe('AudioManager', () => {
|
||||
fw.fire('pointerdown');
|
||||
assert.equal(a.unlocked, true);
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
assert.ok(urls.includes(manifest.audio.bgm.prep.loop), 'BGM fetched after unlock');
|
||||
assert.ok(asked(urls, manifest.audio.bgm.prep.loop), 'BGM fetched after unlock');
|
||||
a.sfx('buy');
|
||||
a.sfx('nonexistent');
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
assert.ok(urls.includes(manifest.audio.sfx.ui.buy));
|
||||
assert.ok(asked(urls, manifest.audio.sfx.ui.buy));
|
||||
// same loop URL ⇒ no restart
|
||||
const before = fw.made.started;
|
||||
a.playBgm('combat');
|
||||
@@ -144,8 +153,8 @@ describe('AudioManager', () => {
|
||||
a.setFieldUnits([{ id: 1, side: 'ally', spine: charId }, { id: 2, side: 'enemy', spine: 'enemy_nope' }]);
|
||||
a.handleBattleEvents([['atk', 1, 2, 'arrow'], ['dmg', 2, 100, 'phys'], ['die', 2], ['spawn', { id: 3, side: 'enemy', spine: 'x' }], ['bounty', 'p', 1]]);
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
assert.ok(urls.includes(manifest.audio.sfx.units[charId].attack));
|
||||
assert.ok(urls.includes(manifest.audio.sfx.battle.enemyDie), 'fallback death sound');
|
||||
assert.ok(asked(urls, manifest.audio.sfx.units[charId].attack));
|
||||
assert.ok(asked(urls, manifest.audio.sfx.battle.enemyDie), 'fallback death sound');
|
||||
assert.ok(a.limiter.active <= a.limiter.maxVoices);
|
||||
a.setVolumes({ muted: true });
|
||||
const n = urls.length;
|
||||
@@ -176,6 +185,107 @@ describe('AudioManager', () => {
|
||||
console.warn = origWarn;
|
||||
}
|
||||
});
|
||||
test('音频先走无扩展名的 /media/ 路由;只有它 404 才回退到带扩展名的原地址', async () => {
|
||||
const raw = manifest.audio.bgm.prep.loop;
|
||||
const media = mediaUrl(raw);
|
||||
assert.notEqual(media, raw, '前提:manifest 地址确实会被换算成 /media/ 路径');
|
||||
|
||||
// 第一发 404:必须看到 /media/ 在前、原地址在后,两者都请求过
|
||||
{
|
||||
const fw = fakeWindow();
|
||||
const urls = [];
|
||||
const origFetch = globalThis.fetch;
|
||||
globalThis.fetch = async (u) => {
|
||||
urls.push(u);
|
||||
return u === media ? { ok: false, status: 404 } : { ok: true, arrayBuffer: async () => new ArrayBuffer(8) };
|
||||
};
|
||||
try {
|
||||
const a = new AudioManager({ win: fw.win, getManifest: () => manifest });
|
||||
a.install();
|
||||
fw.fire('pointerdown');
|
||||
a.playBgm('prep');
|
||||
await new Promise((r) => setTimeout(r, 25));
|
||||
const first = urls.indexOf(media);
|
||||
const fallback = urls.indexOf(raw);
|
||||
assert.ok(first !== -1, '先试无扩展名路径');
|
||||
assert.ok(fallback !== -1, '404 后回退到原地址');
|
||||
assert.ok(first < fallback, '顺序必须是先 /media/ 再原地址');
|
||||
} finally { globalThis.fetch = origFetch; }
|
||||
}
|
||||
|
||||
// 第一发 200:不该再去碰带扩展名的地址(否则白白多一次请求,也正是 IDM 会拦的那个 URL)
|
||||
{
|
||||
const fw = fakeWindow();
|
||||
const urls = [];
|
||||
const origFetch = globalThis.fetch;
|
||||
globalThis.fetch = async (u) => { urls.push(u); return { ok: true, arrayBuffer: async () => new ArrayBuffer(8) }; };
|
||||
try {
|
||||
const a = new AudioManager({ win: fw.win, getManifest: () => manifest });
|
||||
a.install();
|
||||
fw.fire('pointerdown');
|
||||
a.playBgm('prep');
|
||||
await new Promise((r) => setTimeout(r, 25));
|
||||
assert.ok(urls.includes(media), '走了 /media/');
|
||||
assert.ok(!urls.includes(raw), '/media/ 成功就不该再请求 .mp3 地址');
|
||||
} finally { globalThis.fetch = origFetch; }
|
||||
}
|
||||
|
||||
// 第一发 200 但内容不是音频:有些静态托管对不存在的路径回 200 + index.html,解码会静默失败,也要回退。
|
||||
{
|
||||
const fw = fakeWindow();
|
||||
const urls = [];
|
||||
let cancelled = 0;
|
||||
const origFetch = globalThis.fetch;
|
||||
globalThis.fetch = async (u) => {
|
||||
urls.push(u);
|
||||
if (u !== media) return { ok: true, arrayBuffer: async () => new ArrayBuffer(8) };
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
headers: { get: (n) => (n.toLowerCase() === 'content-type' ? 'text/html; charset=utf-8' : null) },
|
||||
body: { cancel: async () => { cancelled += 1; } },
|
||||
arrayBuffer: async () => new ArrayBuffer(8),
|
||||
};
|
||||
};
|
||||
try {
|
||||
const a = new AudioManager({ win: fw.win, getManifest: () => manifest });
|
||||
a.install();
|
||||
fw.fire('pointerdown');
|
||||
a.playBgm('prep');
|
||||
await new Promise((r) => setTimeout(r, 25));
|
||||
assert.ok(urls.includes(raw), '内容不是音频时回退到原地址');
|
||||
assert.equal(cancelled, 1, '丢掉那个用不上的响应,别把连接挂着');
|
||||
} finally { globalThis.fetch = origFetch; }
|
||||
}
|
||||
|
||||
// /media/ 直接给出 audio/*(服务端真实行为):不回退,也不去 cancel 一个能用的响应
|
||||
{
|
||||
const fw = fakeWindow();
|
||||
const urls = [];
|
||||
let cancelled = 0;
|
||||
const origFetch = globalThis.fetch;
|
||||
globalThis.fetch = async (u) => {
|
||||
urls.push(u);
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
headers: { get: (n) => (n.toLowerCase() === 'content-type' ? 'audio/mpeg' : null) },
|
||||
body: { cancel: async () => { cancelled += 1; } },
|
||||
arrayBuffer: async () => new ArrayBuffer(8),
|
||||
};
|
||||
};
|
||||
try {
|
||||
const a = new AudioManager({ win: fw.win, getManifest: () => manifest });
|
||||
a.install();
|
||||
fw.fire('pointerdown');
|
||||
a.playBgm('prep');
|
||||
await new Promise((r) => setTimeout(r, 25));
|
||||
assert.ok(urls.includes(media));
|
||||
assert.ok(!urls.includes(raw), 'audio/* 就是成功,不该再回退');
|
||||
assert.equal(cancelled, 0);
|
||||
} finally { globalThis.fetch = origFetch; }
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// user playtest #4 item 6: 纯烬艾雅法拉's skill sound rang outside her skill — her manifest `hit` is her S3 impact
|
||||
@@ -218,23 +328,26 @@ describe('impact sounds (user playtest #4 item 6)', () => {
|
||||
{ id: 3, side: 'enemy', kind: 'enemy', spine: enemyId },
|
||||
]);
|
||||
try {
|
||||
const own = new Set(Object.values(manifest.audio.sfx.units[AGOAT2]).filter((x) => typeof x === 'string'));
|
||||
// 她的技能形态(_s)文件:这条断言要盯住它们一个都没响,所以先确认音效表里真的有 _s ——
|
||||
// 否则集合为空,断言会永远成立、形同虚设。
|
||||
const ownSkill = Object.values(manifest.audio.sfx.units[AGOAT2]).filter((x) => typeof x === 'string' && /_s\.mp3$/.test(x));
|
||||
assert.ok(ownSkill.length > 0, '前提:她的音效表里确实有 _s(技能形态)文件');
|
||||
a.handleBattleEvents([['atk', 1, 2, 'orb'], ['heal', 2, 300], ['dmg', 2, 120, 'phys'], ['dmg', 2, 80, 'arts']]);
|
||||
await settle();
|
||||
assert.ok(urls.includes(manifest.audio.sfx.units[AGOAT2].attack), 'her cast sound');
|
||||
assert.ok(!urls.some((x) => x === manifest.audio.sfx.units[AGOAT2].hit), 'no impact sound of hers on the ally');
|
||||
assert.ok(!urls.some((x) => own.has(x) && /_s\.mp3$/.test(x)), 'nothing of her S3');
|
||||
assert.ok(asked(urls, manifest.audio.sfx.units[AGOAT2].attack), 'her cast sound');
|
||||
assert.ok(!asked(urls, manifest.audio.sfx.units[AGOAT2].hit), 'no impact sound of hers on the ally');
|
||||
assert.ok(!ownSkill.some((p) => asked(urls, p)), 'nothing of her S3');
|
||||
// a hostile attack still authors its impact — once, and only for a real hit (not an element gauge fill)
|
||||
a.handleBattleEvents([['atk', 3, 2, 'none'], ['dmg', 2, 900, 'burn']]);
|
||||
await settle();
|
||||
assert.ok(!urls.includes(manifest.audio.sfx.units[enemyId].hit), 'a gauge fill is no impact');
|
||||
assert.ok(!asked(urls, manifest.audio.sfx.units[enemyId].hit), 'a gauge fill is no impact');
|
||||
a.handleBattleEvents([['dmg', 2, 200, 'phys']]);
|
||||
await settle();
|
||||
assert.equal(urls.filter((x) => x === manifest.audio.sfx.units[enemyId].hit).length, 1, 'the impact');
|
||||
assert.equal(askedCount(urls, manifest.audio.sfx.units[enemyId].hit), 1, 'the impact');
|
||||
a.limiter.lastByUnit.clear(); a.limiter.lastByUrl.clear();
|
||||
a.handleBattleEvents([['dmg', 2, 50, 'phys']]);
|
||||
await settle();
|
||||
assert.equal(urls.filter((x) => x === manifest.audio.sfx.units[enemyId].hit).length, 1, 'a later tick is not the same attack\'s impact');
|
||||
assert.equal(askedCount(urls, manifest.audio.sfx.units[enemyId].hit), 1, 'a later tick is not the same attack\'s impact');
|
||||
} finally { restore(); }
|
||||
});
|
||||
|
||||
@@ -251,12 +364,12 @@ describe('impact sounds (user playtest #4 item 6)', () => {
|
||||
try {
|
||||
a.handleBattleEvents([['atk', 5, 6, 'chain']]);
|
||||
await settle();
|
||||
assert.ok(!urls.includes(manifest.audio.sfx.units[enemyId].attack), 'the bounce is not an enemy attack');
|
||||
assert.ok(!asked(urls, manifest.audio.sfx.units[enemyId].attack), 'the bounce is not an enemy attack');
|
||||
a.handleBattleEvents([['atk', 1, 5, 'arrow']]);
|
||||
fakeNow += 4000;
|
||||
a.handleBattleEvents([['dmg', 5, 100, 'phys']]);
|
||||
await settle();
|
||||
assert.ok(!urls.includes(manifest.audio.sfx.units[charId].hit), '4 s later: not that attack\'s impact');
|
||||
assert.ok(!asked(urls, manifest.audio.sfx.units[charId].hit), '4 s later: not that attack\'s impact');
|
||||
} finally { globalThis.performance = perf; restore(); }
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user