181 lines
11 KiB
JavaScript
181 lines
11 KiB
JavaScript
'use strict';
|
|
|
|
const fs = require('node:fs');
|
|
const path = require('node:path');
|
|
const { USER_STYLE_PREF } = require('./themes');
|
|
const { VOICE_SCHEMA, migrateVoicePrefs } = require('./voice-prefs');
|
|
const { PRIVACY_SCHEMA, migratePrivacyPrefs } = require('./privacy-prefs');
|
|
const { CHAT_SCHEMA } = require('./chat-prefs');
|
|
const { CONTACT_SCHEMA } = require('./contacts-prefs');
|
|
const bookmarks = require('../renderer/shared/bookmarks.js');
|
|
const LAYOUT_VERSION = 2;
|
|
|
|
/**
|
|
* UI preferences owned by main (identity/nickname live in the core data dir, never here).
|
|
* Every key has a validator; unknown keys and wrong types are rejected.
|
|
*/
|
|
const SCHEMA = {
|
|
lastAddress: { default: '', check: (v) => typeof v === 'string' && v.length <= 255 && !/[\u0000-\u001f]/.test(v) },
|
|
...VOICE_SCHEMA,
|
|
...PRIVACY_SCHEMA,
|
|
pttCode: { default: 'F8', check: (v) => typeof v === 'string' && /^[A-Za-z0-9]{1,32}$/.test(v) },
|
|
inputDeviceId: { default: '', check: (v) => typeof v === 'string' && v.length <= 512 },
|
|
outputDeviceId: { default: '', check: (v) => typeof v === 'string' && v.length <= 512 },
|
|
hardwareVideoDecode: { default: true, check: (v) => typeof v === 'boolean' },
|
|
streamVolume: { default: 100, check: (v) => Number.isInteger(v) && v >= 0 && v <= 100 },
|
|
streamStageRatio: { default: 0.55, check: (v) => typeof v === 'number' && Number.isFinite(v) && v >= 0.15 && v <= 0.8 },
|
|
streamStageCollapsed: { default: false, check: (v) => typeof v === 'boolean' },
|
|
// Zero retains the responsive default; the renderer clamps saved pixels to the current window.
|
|
sidebarWidth: { default: 0, check: (v) => Number.isInteger(v) && v >= 0 && v <= 1600 },
|
|
// Server pane width in px (official main slot); zero keeps the official default 500 px.
|
|
serverPaneWidth: { default: 0, check: (v) => Number.isInteger(v) && v >= 0 && v <= 1600 },
|
|
collapsedChannels: { default: [], check: validCollapsedChannels },
|
|
savedServersCollapsed: { default: false, check: (v) => typeof v === 'boolean' },
|
|
// Dark by default for new profiles regardless of the OS (owner's request); a stored valid choice —
|
|
// including 'system' or 'light' — is always kept.
|
|
theme: { default: 'dark', check: (v) => v === 'system' || v === 'dark' || v === 'light' },
|
|
displaySize: { default: 'medium', check: (v) => ['small', 'medium', 'large'].includes(v) },
|
|
treeStyle: { default: 'detailed', check: (v) => ['compact', 'detailed'].includes(v) },
|
|
chatStyle: { default: 'detailed', check: (v) => ['compact', 'detailed'].includes(v) },
|
|
sidebarIconMode: { default: 'adaptive', check: (v) => ['adaptive', 'small', 'large'].includes(v) },
|
|
showCountryFlags: { default: false, check: (v) => typeof v === 'boolean' },
|
|
showChannelBanners: { default: true, check: (v) => typeof v === 'boolean' },
|
|
showChannelBackground: { default: true, check: (v) => typeof v === 'boolean' },
|
|
showClientsBeforeChannels: { default: true, check: (v) => typeof v === 'boolean' },
|
|
channelCommanderAsLamp: { default: true, check: (v) => typeof v === 'boolean' },
|
|
// Updater: 'preview' accepts prereleases (all TeamsPeach releases so far), 'stable' only full releases.
|
|
updateChannel: { default: 'preview', check: (v) => v === 'preview' || v === 'stable' },
|
|
// Interface language: English for new profiles (owner's request); a stored valid choice is kept.
|
|
language: { default: 'en', check: (v) => v === 'en' || v === 'ru' },
|
|
// Quick-access servers may select a local identity UID and a containing folder; passwords are never stored.
|
|
savedServers: { default: [], check: validServers },
|
|
// Local bookmark folders (official Bookmarks "New Folder") and the shared display order of folders and
|
|
// bookmarks. Cross-field rules (references, cycles, depth, order permutation) live in shared/bookmarks.js.
|
|
bookmarkFolders: { default: [], check: bookmarks.validFolders },
|
|
bookmarkOrder: { default: [], check: bookmarks.validOrder },
|
|
// Chat (official settings.chat.*): formatting toolbar visibility, diagram auto-load and images.
|
|
...CHAT_SCHEMA,
|
|
...CONTACT_SCHEMA,
|
|
// Official workflowSettings.autoEnableMicrophone (default off): focusing a server tab moves the microphone there.
|
|
autoEnableMicrophone: { default: false, check: (v) => typeof v === 'boolean' },
|
|
// Official workflowSettings.autoReactivateMicOnPreviousTarget (default on): when the microphone's connection
|
|
// ends, the microphone returns to the connection that had it before.
|
|
autoReactivateMicOnPreviousTarget: { default: true, check: (v) => typeof v === 'boolean' },
|
|
// Third-party theme extension selection '<identifier>//<variant name>' (official appearance.user_style); null = stock theme.
|
|
userStyle: USER_STYLE_PREF,
|
|
// Main-only (main.js rejects renderer writes): set by the recording folder dialog (recording-main.js).
|
|
recordingFolder: { default: null, check: (v) => v === null || (typeof v === 'string' && v.length >= 1 && v.length <= 1024 && path.isAbsolute(v) && !/[\u0000-\u001f\u007f]/.test(v)) },
|
|
// Official recording.mode: 1 Multitrack, 2 Master, 3 Multitrack + Master (default).
|
|
recordingMode: { default: 3, check: (v) => v === 1 || v === 2 || v === 3 },
|
|
// Per event: 0 off, 1 sound, 2 important (also while muted/away); logs are independent.
|
|
notificationStates: { default: {}, check: (v) => v !== null && typeof v === 'object' && !Array.isArray(v) && Object.keys(v).length <= 128 && Object.entries(v).every(([k, s]) => /^[a-z_]{1,96}$/.test(k) && (s === 0 || s === 1 || s === 2)) },
|
|
systemNotifyServerPrivate: { default: false, check: (v) => typeof v === 'boolean' },
|
|
systemNotifyChannelChat: { default: false, check: (v) => typeof v === 'boolean' },
|
|
// OS integration (official settings.os.*).
|
|
osFlashOnMessage: { default: false, check: (v) => typeof v === 'boolean' },
|
|
osFlashOnPoke: { default: false, check: (v) => typeof v === 'boolean' },
|
|
osHideInTaskbar: { default: 'never', check: (v) => ['never', 'minimize', 'close', 'both'].includes(v) },
|
|
osMuteWhenLocked: { default: false, check: (v) => typeof v === 'boolean' },
|
|
};
|
|
|
|
const CONTROL = /[\u0000-\u001f\u007f]/;
|
|
|
|
const BOOKMARK_KEYS = ['savedServers', 'bookmarkFolders', 'bookmarkOrder'];
|
|
|
|
function validServers(list) {
|
|
if (!Array.isArray(list) || list.length > bookmarks.MAX_BOOKMARKS) return false;
|
|
const ids = new Set();
|
|
for (const s of list) {
|
|
if (!s || typeof s !== 'object' || Array.isArray(s)) return false;
|
|
const keys = Object.keys(s);
|
|
if (!keys.includes('id') || !keys.includes('name') || !keys.includes('address') || keys.some((key) => !['id', 'name', 'address', 'identity_id', 'folder'].includes(key))) return false;
|
|
if (typeof s.id !== 'string' || !bookmarks.ID.test(s.id) || ids.has(s.id)) return false;
|
|
if (typeof s.name !== 'string' || s.name.trim().length < 1 || s.name.length > 64 || CONTROL.test(s.name)) return false;
|
|
if (typeof s.address !== 'string' || s.address.trim().length < 1 || s.address.length > 255 || CONTROL.test(s.address)) return false;
|
|
if (s.identity_id !== undefined && (typeof s.identity_id !== 'string' || !/^[A-Za-z0-9+/]{27}=$/.test(s.identity_id))) return false;
|
|
if (s.folder !== undefined && (typeof s.folder !== 'string' || !bookmarks.ID.test(s.folder))) return false;
|
|
ids.add(s.id);
|
|
}
|
|
return true;
|
|
}
|
|
|
|
function validCollapsedChannels(list) {
|
|
if (!Array.isArray(list) || list.length > 32) return false;
|
|
const servers = new Set();
|
|
for (const entry of list) {
|
|
if (!entry || typeof entry !== 'object' || Array.isArray(entry)) return false;
|
|
const keys = Object.keys(entry);
|
|
if (keys.length !== 2 || !keys.includes('server') || !keys.includes('channels')) return false;
|
|
if (typeof entry.server !== 'string' || !entry.server.trim() || entry.server.length > 255 || CONTROL.test(entry.server) || servers.has(entry.server)) return false;
|
|
if (!Array.isArray(entry.channels) || entry.channels.length > 512) return false;
|
|
const channels = new Set();
|
|
for (const id of entry.channels) {
|
|
if (!Number.isSafeInteger(id) || id <= 0 || channels.has(id)) return false;
|
|
channels.add(id);
|
|
}
|
|
servers.add(entry.server);
|
|
}
|
|
return true;
|
|
}
|
|
|
|
class Prefs {
|
|
constructor(file) {
|
|
this.file = file;
|
|
this.values = defaults();
|
|
try {
|
|
const raw = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
if (raw && typeof raw === 'object') {
|
|
for (const [key, spec] of Object.entries(SCHEMA)) {
|
|
if (Object.prototype.hasOwnProperty.call(raw, key) && spec.check(raw[key])) this.values[key] = raw[key];
|
|
}
|
|
migrateVoicePrefs(raw, this.values);
|
|
migratePrivacyPrefs(raw, this.values);
|
|
// Two-pane files predate serverPaneWidth. Three-pane saves always include that key,
|
|
// so preserve those even before the explicit version marker was introduced.
|
|
if (!Object.hasOwn(raw, 'layoutVersion') && !Object.hasOwn(raw, 'serverPaneWidth') && Object.hasOwn(raw, 'sidebarWidth') && SCHEMA.sidebarWidth.check(raw.sidebarWidth)) {
|
|
this.values.serverPaneWidth = raw.sidebarWidth;
|
|
this.values.sidebarWidth = SCHEMA.sidebarWidth.default;
|
|
}
|
|
}
|
|
} catch {
|
|
// first run or unreadable file: defaults
|
|
}
|
|
// Each bookmark list was validated alone; references and order are repaired together without losing bookmarks.
|
|
Object.assign(this.values, bookmarks.normalize(this.values));
|
|
}
|
|
|
|
get() {
|
|
return { ...this.values };
|
|
}
|
|
|
|
/** Applies a validated partial update; returns the full prefs or throws. */
|
|
set(partial) {
|
|
if (!partial || typeof partial !== 'object' || Array.isArray(partial)) throw new Error('prefs: expected an object');
|
|
const next = { ...this.values };
|
|
for (const [key, value] of Object.entries(partial)) {
|
|
const spec = SCHEMA[key];
|
|
if (!spec) throw new Error(`prefs: unknown key ${key}`);
|
|
if (!spec.check(value)) throw new Error(`prefs: invalid value for ${key}`);
|
|
next[key] = value;
|
|
}
|
|
if (BOOKMARK_KEYS.some((key) => Object.hasOwn(partial, key))) {
|
|
// A write without an explicit order keeps the stored sequence: removed ids drop out, new ones go last.
|
|
if (!Object.hasOwn(partial, 'bookmarkOrder')) next.bookmarkOrder = bookmarks.completeOrder(next);
|
|
if (!bookmarks.consistent(next)) throw new Error('prefs: inconsistent bookmarks and folders');
|
|
}
|
|
// Persist first: if writing fails, neither the file nor the in-memory values change.
|
|
fs.mkdirSync(path.dirname(this.file), { recursive: true });
|
|
const tmp = `${this.file}.tmp`;
|
|
fs.writeFileSync(tmp, JSON.stringify({ ...next, layoutVersion: LAYOUT_VERSION }, null, 2));
|
|
fs.renameSync(tmp, this.file);
|
|
this.values = next;
|
|
return this.get();
|
|
}
|
|
}
|
|
|
|
function defaults() {
|
|
return Object.fromEntries(Object.entries(SCHEMA).map(([key, spec]) => [key, structuredClone(spec.default)]));
|
|
}
|
|
|
|
module.exports = { Prefs };
|