Files
Pickup-Config/services/userSettingsStore.js

109 lines
2.9 KiB
JavaScript

const fs = require('fs');
const path = require('path');
const SETTINGS_DIR = path.join(__dirname, '..', 'config');
const DEFAULT_USER_SETTINGS = {
notifications: {
ntfy: {
enabled: false,
topic: '',
serverUrl: ''
},
telegram: {
enabled: false,
chatId: ''
}
}
};
function ensureDir() {
if (!fs.existsSync(SETTINGS_DIR)) {
fs.mkdirSync(SETTINGS_DIR, { recursive: true });
}
}
function getSettingsPath(profileId = 'shared') {
return path.join(SETTINGS_DIR, `${profileId}-notifications.json`);
}
function sanitizeBoolean(value) {
return !!value;
}
function sanitizeString(value) {
if (typeof value !== 'string') {
if (value === null || value === undefined) {
return '';
}
return String(value);
}
return value.trim();
}
function hydrateSettingsFile(profileId) {
ensureDir();
const filePath = getSettingsPath(profileId);
if (!fs.existsSync(filePath)) {
fs.writeFileSync(filePath, JSON.stringify(DEFAULT_USER_SETTINGS, null, 2));
}
return filePath;
}
function readNotificationSettings(profileId) {
const filePath = hydrateSettingsFile(profileId);
try {
const raw = fs.readFileSync(filePath, 'utf8');
const parsed = JSON.parse(raw);
return {
notifications: {
ntfy: {
enabled: sanitizeBoolean(parsed?.notifications?.ntfy?.enabled),
topic: sanitizeString(parsed?.notifications?.ntfy?.topic),
serverUrl: sanitizeString(parsed?.notifications?.ntfy?.serverUrl)
},
telegram: {
enabled: sanitizeBoolean(parsed?.notifications?.telegram?.enabled),
chatId: sanitizeString(parsed?.notifications?.telegram?.chatId)
}
}
};
} catch (error) {
console.error(`[NOTIFICATIONS] Konnte Einstellungen für ${profileId} nicht lesen:`, error.message);
return JSON.parse(JSON.stringify(DEFAULT_USER_SETTINGS));
}
}
function writeNotificationSettings(profileId, patch = {}) {
const current = readNotificationSettings(profileId);
const next = {
notifications: {
ntfy: {
enabled: sanitizeBoolean(patch?.notifications?.ntfy?.enabled ?? current.notifications.ntfy.enabled),
topic: sanitizeString(patch?.notifications?.ntfy?.topic ?? current.notifications.ntfy.topic),
serverUrl: sanitizeString(
patch?.notifications?.ntfy?.serverUrl ?? current.notifications.ntfy.serverUrl
)
},
telegram: {
enabled: sanitizeBoolean(
patch?.notifications?.telegram?.enabled ?? current.notifications.telegram.enabled
),
chatId: sanitizeString(
patch?.notifications?.telegram?.chatId ?? current.notifications.telegram.chatId
)
}
}
};
const filePath = hydrateSettingsFile(profileId);
fs.writeFileSync(filePath, JSON.stringify(next, null, 2));
return next;
}
module.exports = {
DEFAULT_USER_SETTINGS,
readNotificationSettings,
writeNotificationSettings
};