// 用户设置:默认值、合并、读取与保存
import { db } from './db.js';
export const DEFAULT_SETTINGS = {
// 外观
appearance: {
language: 'zh', // zh | en
theme: 'system', // light | dark | system
accent: 'blue',
density: 'comfortable', // comfortable | compact
fontFamily: 'sans', // sans | serif
fontSize: 15,
lineHeight: 1.6,
contentWidth: 'standard', // narrow | standard | wide | full
},
// 同步
sync: {
rangeDays: 30,
folderLimit: 300,
autoEnabled: true,
intervalMinutes: 15,
},
// 编辑器
editor: {
signature: '',
fontFamily: 'sans',
fontSize: 15,
lineHeight: 1.7,
defaultAccountId: null,
},
// 备份
backup: {
webdavUrl: '',
webdavUsername: '',
webdavPasswordEnc: '', // 加密后的密码,仅服务端使用
remotePath: 'xmail',
autoEnabled: false,
intervalHours: 24,
includeBodies: false,
includeAttachments: false,
days: 90,
accountIds: [],
lastBackupAt: null,
},
// 通知
notifications: {
enabled: false,
botTokenEnc: '', // 加密后的 Bot Token,仅服务端使用
chatIdEnc: '', // 加密后的 Chat ID,仅服务端使用
},
};
function isPlainObject(v) {
return v !== null && typeof v === 'object' && !Array.isArray(v);
}
/** 深合并(用于兼容旧版本设置) */
export function deepMerge(base, extra) {
const out = Array.isArray(base) ? [...base] : { ...base };
if (!isPlainObject(extra)) return out;
for (const [key, value] of Object.entries(extra)) {
if (isPlainObject(value) && isPlainObject(out[key])) {
out[key] = deepMerge(out[key], value);
} else if (value !== undefined) {
out[key] = value;
}
}
return out;
}
/** 读取包含加密字段的原始设置 */
export function getRawSettings(userId) {
const row = db.prepare('SELECT json FROM settings WHERE user_id = ?').get(userId);
let saved = {};
if (row) {
try {
saved = JSON.parse(row.json);
} catch {
saved = {};
}
}
return deepMerge(DEFAULT_SETTINGS, saved);
}
/** 保存设置(整体覆盖) */
export function saveSettings(userId, settings) {
const json = JSON.stringify(settings);
db.prepare(
`INSERT INTO settings (user_id, json, updated_at) VALUES (?, ?, ?)
ON CONFLICT(user_id) DO UPDATE SET json = excluded.json, updated_at = excluded.updated_at`
).run(userId, json, Date.now());
}
/** 返回给前端的设置(隐去敏感字段) */
export function getClientSettings(userId) {
const s = getRawSettings(userId);
const { webdavPasswordEnc, ...backup } = s.backup;
const { botTokenEnc, chatIdEnc, ...notifications } = s.notifications;
return {
...s,
backup: { ...backup, hasWebdavPassword: Boolean(webdavPasswordEnc) },
notifications: {
...notifications,
hasBotToken: Boolean(botTokenEnc),
hasChatId: Boolean(chatIdEnc),
},
};
}