76 lines
1.8 KiB
JavaScript
76 lines
1.8 KiB
JavaScript
const fs = require('fs');
|
|
const path = require('path');
|
|
|
|
const PREF_DIR = path.join(__dirname, '..', 'config');
|
|
|
|
const DEFAULT_PREFERENCES = {
|
|
location: null
|
|
};
|
|
|
|
function ensureDir() {
|
|
if (!fs.existsSync(PREF_DIR)) {
|
|
fs.mkdirSync(PREF_DIR, { recursive: true });
|
|
}
|
|
}
|
|
|
|
function getPreferencesPath(profileId = 'shared') {
|
|
return path.join(PREF_DIR, `${profileId}-preferences.json`);
|
|
}
|
|
|
|
function sanitizeLocation(location) {
|
|
if (!location) {
|
|
return null;
|
|
}
|
|
const lat = Number(location.lat);
|
|
const lon = Number(location.lon);
|
|
if (!Number.isFinite(lat) || !Number.isFinite(lon)) {
|
|
return null;
|
|
}
|
|
if (lat < -90 || lat > 90 || lon < -180 || lon > 180) {
|
|
return null;
|
|
}
|
|
return {
|
|
lat,
|
|
lon,
|
|
updatedAt: Date.now()
|
|
};
|
|
}
|
|
|
|
function readPreferences(profileId) {
|
|
ensureDir();
|
|
const filePath = getPreferencesPath(profileId);
|
|
if (!fs.existsSync(filePath)) {
|
|
fs.writeFileSync(filePath, JSON.stringify(DEFAULT_PREFERENCES, null, 2));
|
|
return { ...DEFAULT_PREFERENCES };
|
|
}
|
|
try {
|
|
const raw = fs.readFileSync(filePath, 'utf8');
|
|
const parsed = JSON.parse(raw);
|
|
return {
|
|
location: sanitizeLocation(parsed.location) || null
|
|
};
|
|
} catch (error) {
|
|
console.error(`[PREFERENCES] Konnte Datei ${filePath} nicht lesen:`, error.message);
|
|
return { ...DEFAULT_PREFERENCES };
|
|
}
|
|
}
|
|
|
|
function writePreferences(profileId, patch = {}) {
|
|
const current = readPreferences(profileId);
|
|
const next = {
|
|
location:
|
|
patch.location === undefined
|
|
? current.location
|
|
: sanitizeLocation(patch.location)
|
|
};
|
|
ensureDir();
|
|
const filePath = getPreferencesPath(profileId);
|
|
fs.writeFileSync(filePath, JSON.stringify(next, null, 2));
|
|
return next;
|
|
}
|
|
|
|
module.exports = {
|
|
readPreferences,
|
|
writePreferences
|
|
};
|