@zenux/dsh-theme-endfield 0.0.0-stage → 1.2.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/audio.js ADDED
@@ -0,0 +1,600 @@
1
+ 'use strict';
2
+ /**
3
+ * Audio notification engine for the installed (bundle) HOST half.
4
+ *
5
+ * Why the sound is played by the HOST and not in the browser: the moments worth
6
+ * marking are exactly the moments the user is NOT looking at the page. A
7
+ * browser `AudioContext` is suspended until a user gesture and dies with the
8
+ * tab, so a task that finishes while the window is minimized would stay silent.
9
+ * The host owns a real process boundary instead and hands the file to the
10
+ * platform player.
11
+ *
12
+ * Consequences handled here:
13
+ * - `subprocess` is an optional seam. Without it the whole feature degrades to
14
+ * a no-op (and says so once) rather than throwing during boot.
15
+ * - The player is a child process per play. Playback is therefore
16
+ * "fire and forget", latest-wins per slot, with a hard grace timeout.
17
+ * - Volume is applied by rescaling PCM samples into a cache file, never by
18
+ * touching the system volume.
19
+ */
20
+
21
+ const fs = require('fs');
22
+ const os = require('os');
23
+ const path = require('path');
24
+ const { scaleWavVolume, parseWav } = require('./tone.js');
25
+ const { SLOT_IDS, PLAY_SLOT_IDS } = require('./slots.js');
26
+
27
+ const LOG_TAG = '[theme-endfield/audio]';
28
+ const BUNDLED_SOUNDS = path.join(__dirname, '..', 'sounds');
29
+ const CACHE_DIR = path.join(os.tmpdir(), 'dsh-theme-endfield');
30
+ /** Longest sound a slot accepts, in seconds. The per-slot debounce window is
31
+ * 2.5s (audioDebounceMs), so a longer file would still be speaking when the
32
+ * next announcement is due; the cap keeps "replace the tone" from turning
33
+ * into "play a jingle over the next one". */
34
+ const MAX_UPLOAD_SECONDS = 2.5;
35
+
36
+ /** Preference keys owned by this feature (all strings, per the namespace convention). */
37
+ const PREF = {
38
+ enabled: 'audioEnabled',
39
+ volume: 'audioVolume',
40
+ boot: 'audioBoot',
41
+ start: 'audioTurnStart',
42
+ done: 'audioTurnDone',
43
+ attention: 'audioAttention',
44
+ fail: 'audioTurnFail',
45
+ debounceMs: 'audioDebounceMs',
46
+ soundDir: 'audioSoundDir',
47
+ humanOnly: 'audioHumanOnly',
48
+ diag: 'audioDiag',
49
+ /* 开机音频 lives in the 动画 section, not in the notification block, and is
50
+ deliberately independent of the notification master switch (see play()). */
51
+ bootAudio: 'bootAudio',
52
+ /* 开机音频 has its own volume: the login voice is a one-shot speech clip and
53
+ must be able to sit above the looping background music without dragging the
54
+ notification volume with it. */
55
+ bootVolume: 'bootVolume',
56
+ };
57
+
58
+ /** Defaults mirroring FIELD_DEFAULTS in index.js — the master switch ships OFF
59
+ * (sound is opt-in); the per-slot switches ship ON, so turning the master on is
60
+ * what starts the sound. */
61
+ const FALLBACK = {
62
+ [PREF.enabled]: '0',
63
+ [PREF.volume]: '100',
64
+ [PREF.boot]: '1',
65
+ [PREF.start]: '1',
66
+ [PREF.done]: '1',
67
+ [PREF.attention]: '1',
68
+ [PREF.fail]: '1',
69
+ [PREF.debounceMs]: '2500',
70
+ [PREF.soundDir]: '',
71
+ [PREF.humanOnly]: '1',
72
+ [PREF.diag]: '0',
73
+ /* Opt-in, like the master: an install that upgrades into the feature must not
74
+ start talking at boot without being asked to. */
75
+ [PREF.bootAudio]: '0',
76
+ [PREF.bootVolume]: '100',
77
+ };
78
+
79
+ /** The user's Desktop, probed lazily: a convenient drop-in place for own sounds. */
80
+ function desktopDir() {
81
+ const home = typeof os.homedir === 'function' ? os.homedir() : '';
82
+ if (home === '') return undefined;
83
+ for (const candidate of [path.join(home, 'Desktop'), path.join(home, '桌面')]) {
84
+ try {
85
+ if (fs.existsSync(candidate)) return candidate;
86
+ } catch (error) { /* ignore */ }
87
+ }
88
+ return undefined;
89
+ }
90
+
91
+ /**
92
+ * The directory this plugin OWNS for uploaded slot sounds.
93
+ *
94
+ * Uploads are written here instead of into the user's configured directory or
95
+ * the Desktop for one reason: "恢复内置" has to be a safe operation. Deleting a
96
+ * file this plugin created is reversible (the user's own copy is not touched
97
+ * and the bundled tone is always there); deleting `turn-start.wav` out of a
98
+ * directory the user pointed us at would not be.
99
+ *
100
+ * `<dshHome>` follows the same order as the host's own resolver (DSH_HOME, then
101
+ * `~/.dsh`): the fallback here only matters for a runtime constructed outside a
102
+ * host that supplies one explicitly.
103
+ *
104
+ * @returns the absolute directory, or undefined when no home can be resolved.
105
+ */
106
+ function uploadDirFor() {
107
+ let home = '';
108
+ try {
109
+ if (process.env && typeof process.env.DSH_HOME === 'string') home = process.env.DSH_HOME;
110
+ } catch (error) { /* no env */ }
111
+ if (home === '') {
112
+ try {
113
+ home = typeof os.homedir === 'function' ? path.join(os.homedir(), '.dsh') : '';
114
+ } catch (error) { /* no home dir */ }
115
+ }
116
+ if (home === '') return undefined;
117
+ return path.join(home, 'theme-endfield', 'sounds');
118
+ }
119
+
120
+ /** Short stable hash of a path for cache-file naming: FNV-1a, hex. */
121
+ function pathHash(value) {
122
+ let h = 0x811c9dc5;
123
+ for (let i = 0; i < value.length; i++) {
124
+ h ^= value.charCodeAt(i);
125
+ h = Math.imul(h, 0x01000193) >>> 0;
126
+ }
127
+ return h.toString(16);
128
+ }
129
+
130
+ /** Short stable hash of file CONTENT for the cache-file name: the same FNV-1a
131
+ * over the bytes. Content, not just size, has to be in the key — a replaced
132
+ * sound with an identical duration (e.g. a re-rendered bundled wav) is
133
+ * byte-length-identical, and a name-only key would serve the previous file's
134
+ * scaled copy forever. The wavs are a few hundred KB, so this is microseconds. */
135
+ function bytesHash(bytes) {
136
+ let h = 0x811c9dc5;
137
+ for (let i = 0; i < bytes.length; i++) {
138
+ h ^= bytes[i];
139
+ h = Math.imul(h, 0x01000193) >>> 0;
140
+ }
141
+ return h.toString(16);
142
+ }
143
+
144
+ /**
145
+ * The audio runtime: preference view, sound resolution, volume cache, playback
146
+ * and the diagnostic ring the settings page reads.
147
+ */
148
+ class AudioRuntime {
149
+ /**
150
+ * @param ctx - the host Cordis context the feature is mounted on.
151
+ * @param [options] - `{ uploadDir }` overrides the managed upload directory.
152
+ * The shipped host does not pass one (both sides derive the same
153
+ * `DSH_HOME` / `~/.dsh` path); the override exists so a test, or a host
154
+ * with a different home layout, can point uploads somewhere else.
155
+ */
156
+ constructor(ctx, options) {
157
+ this.ctx = ctx;
158
+ this.values = Object.assign({}, FALLBACK);
159
+ this.scope = undefined;
160
+ /** Where "上传 wav" stores its files, or undefined on a host with no home. */
161
+ this.uploadDir = options !== undefined && options !== null && typeof options.uploadDir === 'string'
162
+ ? options.uploadDir
163
+ : uploadDirFor();
164
+ /** Last play timestamp per slot, for the per-slot debounce window. */
165
+ this.lastPlayed = Object.create(null);
166
+ /** Per slot: the instant its previous announcement finishes speaking. */
167
+ this.playUntil = Object.create(null);
168
+ /** Sound-file duration in ms, memoised per path (read once per file). */
169
+ this.durationCache = new Map();
170
+ /** Slots whose child process has not settled yet — no overlapping play. */
171
+ this.playing = new Set();
172
+ /** Bounded diagnostic ring: what the plugin saw and what it did about it. */
173
+ this.diag = [];
174
+ this.warnedNoSubprocess = false;
175
+ /** One-shot guard so an unwritable volume cache says so once, not per play. */
176
+ this.warnedCacheDir = false;
177
+ }
178
+
179
+ /** Record one diagnostic line and echo it to the host console. */
180
+ note(kind, detail) {
181
+ const entry = { at: Date.now(), kind, detail: detail === undefined ? '' : String(detail) };
182
+ this.diag.push(entry);
183
+ if (this.diag.length > 60) this.diag.shift();
184
+ console.log(`${LOG_TAG} ${kind}${entry.detail === '' ? '' : ' — ' + entry.detail}`);
185
+ }
186
+
187
+ /** Whether verbose diagnostics are on (the settings page can switch them on). */
188
+ get diagnosing() {
189
+ return this.values[PREF.diag] !== '0';
190
+ }
191
+
192
+ /** Adopt the durable preference snapshot. */
193
+ setValues(values) {
194
+ this.values = Object.assign({}, FALLBACK, values === undefined ? {} : values);
195
+ }
196
+
197
+ /** One preference as a string, falling back to the shipped default. */
198
+ value(key) {
199
+ const raw = this.values[key];
200
+ return raw === undefined || raw === null ? FALLBACK[key] : String(raw);
201
+ }
202
+
203
+ /** One preference as an integer with bounds. */
204
+ number(key, min, max) {
205
+ const parsed = Number.parseInt(this.value(key), 10);
206
+ if (!Number.isFinite(parsed)) return Number.parseInt(FALLBACK[key], 10);
207
+ return Math.min(max, Math.max(min, parsed));
208
+ }
209
+
210
+ /** Whether one switch preference is on (stored `'1'`, read with `!== '0'`). */
211
+ enabled(key) {
212
+ return this.value(key) !== '0';
213
+ }
214
+
215
+ /** Candidate directories for own sound files, most specific first. */
216
+ soundDirs() {
217
+ const dirs = [];
218
+ /* Uploads first, and per FILE rather than as a directory switch: a slot the
219
+ user just uploaded must be the one that sounds, even when a configured
220
+ directory or the Desktop already holds a same-named file — otherwise the
221
+ upload succeeds and is silently shadowed, which reads as a broken button.
222
+ Slots without an upload simply fall through to the rest of the chain. */
223
+ if (typeof this.uploadDir === 'string' && this.uploadDir !== '') dirs.push(this.uploadDir);
224
+ const configured = this.value(PREF.soundDir);
225
+ if (configured !== '') dirs.push(configured);
226
+ try {
227
+ const workspace = this.ctx.get('workspace');
228
+ const root = workspace === undefined || typeof workspace.root !== 'function' ? undefined : workspace.root();
229
+ if (typeof root === 'string' && root !== '') dirs.push(root);
230
+ } catch (error) { /* workspace service absent — fine */ }
231
+ const desktop = desktopDir();
232
+ if (desktop !== undefined) dirs.push(desktop);
233
+ dirs.push(BUNDLED_SOUNDS);
234
+ return dirs;
235
+ }
236
+
237
+ /**
238
+ * Resolve one slot to a playable file: uploaded overrides, the configured
239
+ * dirs, the workspace, the Desktop drop-in, then the bundled synthesized tone.
240
+ *
241
+ * @param slot - slot id from `lib/slots.js`.
242
+ * @returns `{ file, origin, uploaded }` or undefined when nothing exists.
243
+ */
244
+ resolve(slot) {
245
+ const name = `${slot}.wav`;
246
+ const dirs = this.soundDirs();
247
+ for (const dir of dirs) {
248
+ const candidate = path.join(dir, name);
249
+ try {
250
+ if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) {
251
+ return {
252
+ file: candidate,
253
+ origin: dir === BUNDLED_SOUNDS ? 'bundled' : candidate,
254
+ uploaded: this.uploadDir !== undefined && dir === this.uploadDir,
255
+ };
256
+ }
257
+ } catch (error) { /* unreadable candidate — try the next */ }
258
+ }
259
+ return undefined;
260
+ }
261
+
262
+ /**
263
+ * Store one uploaded wav as a slot's own sound.
264
+ *
265
+ * The file is validated as a PCM wav before anything is written, so a renamed
266
+ * MP3 (the common mistake) is refused with a reason instead of being played
267
+ * as silence by the platform player, and a longer-than-cap clip is refused
268
+ * rather than overlapping the next announcement.
269
+ *
270
+ * @param slot - slot id from `lib/slots.js`.
271
+ * @param bytes - the request body as a Buffer.
272
+ * @returns `{ ok, why?, file?, dir?, seconds? }`.
273
+ */
274
+ saveUpload(slot, bytes) {
275
+ if (typeof slot !== 'string' || SLOT_IDS.indexOf(slot) < 0) {
276
+ return { ok: false, why: `unknown slot "${String(slot)}"` };
277
+ }
278
+ if (this.uploadDir === undefined) return { ok: false, why: 'no upload directory is available on this host' };
279
+ if (!Buffer.isBuffer(bytes) || bytes.length === 0) return { ok: false, why: 'empty request body' };
280
+ const parsed = parseWav(bytes);
281
+ if (parsed === undefined) return { ok: false, why: 'not a PCM wav file' };
282
+ const frameBytes = (parsed.bitsPerSample / 8) * parsed.channels;
283
+ const seconds = frameBytes > 0 ? parsed.dataSize / (parsed.sampleRate * frameBytes) : 0;
284
+ if (!(seconds > 0)) return { ok: false, why: 'the wav carries no audio data' };
285
+ if (seconds > MAX_UPLOAD_SECONDS) {
286
+ return { ok: false, why: `too long: ${seconds.toFixed(1)}s (limit ${MAX_UPLOAD_SECONDS}s)` };
287
+ }
288
+ const target = path.join(this.uploadDir, `${slot}.wav`);
289
+ /* Stage next to the target and rename: the resolver may be asked for this
290
+ slot between the write and its end (a notification can fire mid-upload),
291
+ and a half-written wav would be handed to the player. rename() is atomic
292
+ on every platform we ship to and replaces an existing file. */
293
+ const staging = `${target}.upload`;
294
+ try {
295
+ fs.mkdirSync(this.uploadDir, { recursive: true });
296
+ fs.writeFileSync(staging, bytes);
297
+ fs.renameSync(staging, target);
298
+ } catch (error) {
299
+ try { fs.unlinkSync(staging); } catch (cleanup) { /* nothing staged */ }
300
+ return { ok: false, why: `cannot write ${target}: ${error && error.message ? error.message : error}` };
301
+ }
302
+ // A replaced file can share its path with the previous upload.
303
+ this.durationCache.delete(target);
304
+ this.note('upload', `${slot} ← ${bytes.length} bytes (${seconds.toFixed(2)}s)`);
305
+ return { ok: true, slot, file: target, dir: this.uploadDir, seconds: Number(seconds.toFixed(2)) };
306
+ }
307
+
308
+ /**
309
+ * Drop a slot's uploaded sound, so the slot falls back to the configured
310
+ * directory / workspace / Desktop / bundled chain again.
311
+ *
312
+ * Only files inside {@link AudioRuntime#uploadDir} are ever removed — this is
313
+ * the safety half of the ownership rule that keeps "恢复内置" harmless.
314
+ *
315
+ * @param slot - slot id from `lib/slots.js`.
316
+ * @returns `{ ok, removed, file?, why? }`.
317
+ */
318
+ removeUpload(slot) {
319
+ if (typeof slot !== 'string' || SLOT_IDS.indexOf(slot) < 0) {
320
+ return { ok: false, why: `unknown slot "${String(slot)}"` };
321
+ }
322
+ if (this.uploadDir === undefined) return { ok: false, why: 'no upload directory is available on this host' };
323
+ const target = path.join(this.uploadDir, `${slot}.wav`);
324
+ try {
325
+ if (!fs.existsSync(target)) return { ok: true, removed: false, slot, file: target };
326
+ fs.unlinkSync(target);
327
+ } catch (error) {
328
+ return { ok: false, why: `cannot remove ${target}: ${error && error.message ? error.message : error}` };
329
+ }
330
+ this.durationCache.delete(target);
331
+ this.note('upload', `${slot} restored to the fallback chain`);
332
+ return { ok: true, removed: true, slot, file: target };
333
+ }
334
+
335
+ /**
336
+ * Whether one slot's OWN switch is on.
337
+ *
338
+ * Callers that fire on an event already test this before calling `play()`; it
339
+ * exists as a method so the preview route can honour the same switch and report
340
+ * it, instead of playing a sound the user has switched off. `play()` itself
341
+ * deliberately does NOT consult it: `force` means "ignore the debounce", and
342
+ * folding a second meaning into it would make the switch and the preview fight
343
+ * each other.
344
+ *
345
+ * @param slot - slot id from `lib/slots.js`.
346
+ * @returns true when the slot may sound.
347
+ */
348
+ slotEnabled(slot) {
349
+ const key = PREF[slotSwitchKey(slot)];
350
+ if (key === undefined) return false;
351
+ return this.enabled(key);
352
+ }
353
+
354
+ /**
355
+ * How long one sound file runs, in milliseconds.
356
+ *
357
+ * Used to derive the per-slot "still speaking" gate. The formula is the WAV
358
+ * one — data bytes / (rate * channels * bytes-per-sample) — and a file that
359
+ * cannot be parsed contributes 0, which degrades to the fixed debounce alone
360
+ * rather than to silence.
361
+ *
362
+ * @param file - sound file path.
363
+ * @returns duration in ms (0 when unknown).
364
+ */
365
+ soundDurationMs(file) {
366
+ const cached = this.durationCache.get(file);
367
+ if (cached !== undefined) return cached;
368
+ let ms = 0;
369
+ try {
370
+ const parsed = parseWav(fs.readFileSync(file));
371
+ if (parsed !== undefined && parsed.sampleRate > 0 && parsed.channels > 0 && parsed.bitsPerSample > 0) {
372
+ ms = Math.round((parsed.dataSize / (parsed.sampleRate * parsed.channels * (parsed.bitsPerSample / 8))) * 1000);
373
+ }
374
+ } catch (error) {
375
+ ms = 0;
376
+ }
377
+ this.durationCache.set(file, ms);
378
+ return ms;
379
+ }
380
+
381
+ /**
382
+ * Apply the volume to a sound file by rescaling its PCM into the cache, so the
383
+ * system volume is never touched.
384
+ *
385
+ * @param file - source wav path.
386
+ * @param volume - 0..100.
387
+ * @returns the file to play (the source itself when scaling is a no-op).
388
+ */
389
+ applyVolume(file, volume) {
390
+ if (volume >= 100) return file;
391
+ let bytes;
392
+ try {
393
+ bytes = fs.readFileSync(file);
394
+ } catch (error) {
395
+ return file;
396
+ }
397
+ let scaled;
398
+ try {
399
+ scaled = scaleWavVolume(bytes, volume);
400
+ } catch (error) {
401
+ // A malformed user file must degrade to "play it as-is", never escape:
402
+ // play() runs inside the approval / user-questions waterfall callbacks,
403
+ // where a throw would skip next() and break the whole chain (see the
404
+ // tools/execute note in index.js).
405
+ return file;
406
+ }
407
+ if (scaled === bytes) return file; // non-rescalable format: original level
408
+ try {
409
+ fs.mkdirSync(CACHE_DIR, { recursive: true });
410
+ /* The cache key covers the SOURCE DIRECTORY (basename + size alone would
411
+ let a turn-done.wav from the custom dir collide with an unrelated
412
+ same-named, same-length file from the desktop) AND the source content
413
+ (a replaced file with an identical duration is byte-length-identical,
414
+ and only the content distinguishes its scaled copy from the old one). */
415
+ const target = path.join(CACHE_DIR,
416
+ `${path.basename(file, path.extname(file))}-v${volume}-${bytes.length}-${bytesHash(bytes)}-${pathHash(file)}.wav`);
417
+ if (!fs.existsSync(target)) fs.writeFileSync(target, scaled);
418
+ return target;
419
+ } catch (error) {
420
+ /* An unwritable cache dir (shared/stale tmp on POSIX) must not disable
421
+ volume scaling SILENTLY — say so once, then keep degrading to the
422
+ unscaled file like every other failure here. */
423
+ if (!this.warnedCacheDir) {
424
+ this.warnedCacheDir = true;
425
+ this.note('volume-cache-unwritable', `serving sounds unscaled; cache dir issue: ${error && error.message ? error.message : error}`);
426
+ }
427
+ return file;
428
+ }
429
+ }
430
+
431
+ /** The platform command matrix: try each entry until one runs. */
432
+ playerCommands(file) {
433
+ if (process.platform === 'win32') {
434
+ // PowerShell's Media.SoundPlayer takes a literal path, so quote-escape it
435
+ // and hand the whole script over as -EncodedCommand (no shell quoting
436
+ // games, no console window when run detached).
437
+ const escaped = file.replace(/'/g, "''");
438
+ const script = `$p = New-Object Media.SoundPlayer '${escaped}'; $p.PlaySync()`;
439
+ const encoded = Buffer.from(script, 'utf16le').toString('base64');
440
+ const args = ['-NoProfile', '-NonInteractive', '-EncodedCommand', encoded];
441
+ return [
442
+ [path.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'), ...args],
443
+ ['pwsh.exe', ...args],
444
+ ];
445
+ }
446
+ if (process.platform === 'darwin') return [['/usr/bin/afplay', file]];
447
+ return [['paplay', file], ['aplay', file]];
448
+ }
449
+
450
+ /**
451
+ * Play one slot.
452
+ *
453
+ * @param slot - slot id.
454
+ * @param options - `force` skips the debounce (used by the settings preview),
455
+ * `reason` is recorded in diagnostics.
456
+ * @returns the outcome, for the preview route to report.
457
+ */
458
+ play(slot, options) {
459
+ const force = options !== undefined && options.force === true;
460
+ const reason = options === undefined || options.reason === undefined ? '' : options.reason;
461
+ if (!PLAY_SLOT_IDS.includes(slot)) return { played: false, why: `unknown slot "${slot}"` };
462
+ /* 开机音频 has its OWN switch and is intentionally not gated by the
463
+ notification master: it is listed under 动画, and a user who only wants the
464
+ login voice should not have to enable task notifications to get it. */
465
+ const ignoreMaster = options !== undefined && options.ignoreMaster === true;
466
+ if (!ignoreMaster && !this.enabled(PREF.enabled)) return { played: false, why: 'audio disabled' };
467
+ /* The boot voice is the one slot with its OWN volume: it is a one-shot
468
+ speech clip that has to be heard over whatever else is playing, and the
469
+ notification volume governs task chimes instead. */
470
+ const volume = this.number(slot === 'login' ? PREF.bootVolume : PREF.volume, 0, 100);
471
+ if (volume <= 0) return { played: false, why: 'volume is 0' };
472
+ const resolved = this.resolve(slot);
473
+ if (resolved === undefined) return { played: false, why: 'no sound file found' };
474
+ const debounce = this.number(PREF.debounceMs, 0, 60000);
475
+ const now = Date.now();
476
+ if (!force && now - (this.lastPlayed[slot] || 0) < debounce) {
477
+ return { played: false, why: `debounced (${debounce} ms window)`, file: resolved.file };
478
+ }
479
+ /* Second, independent gate: never start a slot while its own previous
480
+ announcement is still speaking.
481
+
482
+ The fixed window above is a floor for rapid repeats, but a real voice line
483
+ is not a chime: the generated Endfield lines run 3-5 seconds (measured), so
484
+ a 2.5 s window would let one line start on top of another. Deriving a
485
+ per-slot window from the file's own duration means a long announcement is
486
+ never clipped and a short chime is not held back — no per-slot setting to
487
+ keep in sync with whatever audio the user drops in. */
488
+ const playingUntil = this.playUntil[slot] || 0;
489
+ if (!force && now < playingUntil) {
490
+ const remaining = playingUntil - now;
491
+ return { played: false, why: `previous ${slot} still speaking (${remaining} ms left)`, file: resolved.file };
492
+ }
493
+ const subprocess = (() => {
494
+ try { return this.ctx.get('subprocess'); } catch (error) { return undefined; }
495
+ })();
496
+ if (subprocess === undefined || typeof subprocess.spawn !== 'function') {
497
+ if (!this.warnedNoSubprocess) {
498
+ this.warnedNoSubprocess = true;
499
+ this.note('unavailable', 'the subprocess service is absent; audio notifications stay silent');
500
+ }
501
+ return { played: false, why: 'subprocess service unavailable' };
502
+ }
503
+ /* `force` (the settings preview) bypasses this too: a preview whose whole job
504
+ is "let me hear it now" must not be refused because the previous
505
+ announcement has not finished, and the child process is fire-and-forget, so
506
+ overlapping one preview with a notification is harmless. */
507
+ if (!force && this.playing.has(slot)) return { played: false, why: 'previous play still running', file: resolved.file };
508
+
509
+ const file = this.applyVolume(resolved.file, volume);
510
+ const attempts = this.playerCommands(file);
511
+ this.lastPlayed[slot] = now;
512
+ /* Record when this announcement finishes so a second trigger cannot start on
513
+ top of it. Measured from the ORIGINAL file (the cache copy has identical
514
+ duration), plus a small margin for player start-up and process teardown. */
515
+ this.playUntil[slot] = now + this.soundDurationMs(resolved.file) + 250;
516
+ this.playing.add(slot);
517
+ const runtime = this;
518
+ let index = 0;
519
+ const tryNext = () => {
520
+ if (index >= attempts.length) {
521
+ runtime.playing.delete(slot);
522
+ /* Nothing sounded, so the not-speaking window recorded in play() must be
523
+ returned too — otherwise real notifications stay gated for the file's
524
+ whole duration after a total player failure. */
525
+ delete runtime.playUntil[slot];
526
+ runtime.note('failed', `${slot}: no player command succeeded`);
527
+ return;
528
+ }
529
+ const argv = attempts[index++];
530
+ let handle;
531
+ try {
532
+ handle = subprocess.spawn({
533
+ argv,
534
+ cwd: process.platform === 'win32' ? (process.env.SystemRoot || 'C:\\Windows') : '/',
535
+ stdio: { stdin: 'ignore', stdout: 'ignore', stderr: 'ignore' },
536
+ graceMs: 8000,
537
+ });
538
+ } catch (error) {
539
+ tryNext();
540
+ return;
541
+ }
542
+ Promise.resolve(handle.done).then(
543
+ () => { runtime.playing.delete(slot); },
544
+ (error) => {
545
+ runtime.note('player-failed', `${slot}: ${argv[0]}`);
546
+ tryNext();
547
+ },
548
+ );
549
+ };
550
+ tryNext();
551
+ if (this.diagnosing) {
552
+ this.note('played', `${slot} (${force ? 'preview' : reason || 'event'}) <- ${resolved.origin} volume=${volume}`);
553
+ }
554
+ return { played: true, file: resolved.file, origin: resolved.origin, volume };
555
+ }
556
+
557
+ /** Diagnostic snapshot for the settings page. */
558
+ snapshot() {
559
+ return {
560
+ enabled: this.enabled(PREF.enabled),
561
+ volume: this.number(PREF.volume, 0, 100),
562
+ debounceMs: this.number(PREF.debounceMs, 0, 60000),
563
+ humanOnly: this.enabled(PREF.humanOnly),
564
+ slots: SLOT_IDS.map((slot) => {
565
+ const resolved = this.resolve(slot);
566
+ return {
567
+ id: slot,
568
+ switchOn: this.enabled(PREF[slotSwitchKey(slot)]),
569
+ file: resolved === undefined ? null : resolved.file,
570
+ origin: resolved === undefined ? null : resolved.origin,
571
+ bundled: resolved !== undefined && resolved.origin === 'bundled',
572
+ /* True when the file above came from THIS plugin's upload dir. The
573
+ panel keys the 「恢复内置」 button on it: only a file we wrote may be
574
+ deleted, and only then does "restore" have anything to do. */
575
+ uploaded: resolved !== undefined && resolved.uploaded === true,
576
+ };
577
+ }),
578
+ soundDirs: this.soundDirs(),
579
+ uploadDir: this.uploadDir === undefined ? null : this.uploadDir,
580
+ desktop: desktopDir() === undefined ? null : desktopDir(),
581
+ subprocess: (() => {
582
+ try { return typeof this.ctx.get('subprocess')?.spawn === 'function'; } catch (error) { return false; }
583
+ })(),
584
+ diagnosing: this.diagnosing,
585
+ log: this.diag.slice(-40),
586
+ };
587
+ }
588
+ }
589
+
590
+ /** Preference key holding one slot's own switch. */
591
+ function slotSwitchKey(slot) {
592
+ if (slot === 'login') return 'bootAudio';
593
+ if (slot === 'boot') return 'boot';
594
+ if (slot === 'turn-start') return 'start';
595
+ if (slot === 'turn-done') return 'done';
596
+ if (slot === 'attention') return 'attention';
597
+ return 'fail';
598
+ }
599
+
600
+ module.exports = { AudioRuntime, PREF, FALLBACK, LOG_TAG, desktopDir, BUNDLED_SOUNDS, CACHE_DIR };