okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-027-gh-app: GitHub app and Terminal items for 0.2.73cabb9e3f

main
3.8 KiB77 linesraw
1/**
2 * The desktop shell's own choices, kept in <Strata data folder>/shell-prefs.json (#3402, #3477): the shell reads the file when it starts
3 * (the port it asks for, whether closing the window keeps Strata in the tray, the language of the tray menu), before any page exists.
4 * The page changes them through the host (POST /api/shell/prefs); a change of the port or the tray applies the next time Strata starts.
5 *
6 *   { "port": 0 | 1024..65535, "tray": false, "language": "en" }
7 *
8 * Port 0 is the default: the shell asks for 47831 and takes a free port when that one is busy.
9 */
10import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
11import { dirname, join } from 'node:path';
12import { componentsDirectory } from './control-runtime.mjs';
13
14export const DEFAULT_PORT = 47831;
15export const LANGUAGES = ['en', 'zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko'];
16export const DEFAULTS = Object.freeze({ port: 0, tray: false, language: 'en' });
17
18export const validPort = value => Number.isInteger(value) && value >= 1024 && value <= 65535;
19
20export function shellPrefsFile({ env = process.env } = {}) {
21  return join(dirname(componentsDirectory({ env })), 'shell-prefs.json');
22}
23
24/** The file's content with every field checked; anything missing or wrong is the default. */
25export function cleanPrefs(raw) {
26  const value = raw && typeof raw === 'object' ? raw : {};
27  return {
28    port: validPort(value.port) ? value.port : 0,
29    tray: value.tray === true,
30    language: LANGUAGES.includes(value.language) ? value.language : 'en',
31  };
32}
33
34export function readShellPrefs(file = shellPrefsFile()) {
35  try { return cleanPrefs(JSON.parse(readFileSync(file, 'utf8').replace(/^/, ''))); } catch { return { ...DEFAULTS }; }
36}
37
38/** Merge a change into the file. Throws a plain sentence for a port that cannot be used. */
39export function writeShellPrefs(patch, file = shellPrefsFile()) {
40  const next = readShellPrefs(file);
41  if (patch && 'port' in patch) {
42    const wanted = patch.port === null || patch.port === '' || patch.port === 0 ? 0 : Number(patch.port);
43    if (wanted !== 0 && !validPort(wanted)) throw new Error('Choose a port between 1024 and 65535, or leave it empty to let Strata choose.');
44    next.port = wanted;
45  }
46  if (patch && 'tray' in patch) next.tray = patch.tray === true;
47  if (patch && 'language' in patch && LANGUAGES.includes(patch.language)) next.language = patch.language;
48  mkdirSync(dirname(file), { recursive: true });
49  const temporary = `${file}.${process.pid}.tmp`;
50  writeFileSync(temporary, JSON.stringify(next, null, 2) + '\n');
51  renameSync(temporary, file);
52  return next;
53}
54
55/**
56 * What the shell tells the host about this start: STRATA_PORT_NOTICE is "busy:<wanted>:<used>" when the port it wanted was taken
57 * (set by the shell, never by the person). The page turns it into a sentence in the person's language.
58 */
59export function parsePortNotice(value) {
60  const m = /^busy:(\d{1,5}):(\d{1,5})$/.exec(String(value ?? ''));
61  return m ? { wanted: Number(m[1]), used: Number(m[2]) } : null;
62}
63
64/** The notification route of the shell's bridge (loopback, token). Null outside the desktop app. */
65export function createShellNotifier({ env = process.env, fetcher = fetch } = {}) {
66  const base = env.STRATA_SHELL_BRIDGE, token = env.STRATA_SHELL_TOKEN;
67  if (!base || !token || !/^http:\/\/127\.0\.0\.1:\d+$/.test(base)) return null;
68  return {
69    async notify({ title, body }) {
70      const query = `title=${encodeURIComponent(String(title ?? '').slice(0, 120))}&body=${encodeURIComponent(String(body ?? '').slice(0, 300))}`;
71      const response = await fetcher(`${base}/shell/notify?${query}`, { method: 'POST', headers: { authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(5000) });
72      let reply = null;
73      try { reply = await response.json(); } catch { /* no body */ }
74      return { shown: response.ok && reply?.shown === true };
75    },
76  };
77}