84 lines
2.0 KiB
JavaScript
84 lines
2.0 KiB
JavaScript
const fs = require('fs');
|
|
const path = require('path');
|
|
|
|
const CONFIG_DIR = path.join(__dirname, '..', 'config');
|
|
const IMAGE_ROOT = path.join(CONFIG_DIR, 'journal-images');
|
|
|
|
function ensureDir(dirPath) {
|
|
if (!fs.existsSync(dirPath)) {
|
|
fs.mkdirSync(dirPath, { recursive: true });
|
|
}
|
|
}
|
|
|
|
function ensureBaseDirs() {
|
|
ensureDir(CONFIG_DIR);
|
|
ensureDir(IMAGE_ROOT);
|
|
}
|
|
|
|
function getJournalPath(profileId = 'shared') {
|
|
return path.join(CONFIG_DIR, `${profileId}-pickup-journal.json`);
|
|
}
|
|
|
|
function getProfileImageDir(profileId = 'shared') {
|
|
return path.join(IMAGE_ROOT, String(profileId));
|
|
}
|
|
|
|
function hydrateJournalFile(profileId) {
|
|
ensureBaseDirs();
|
|
const filePath = getJournalPath(profileId);
|
|
if (!fs.existsSync(filePath)) {
|
|
fs.writeFileSync(filePath, JSON.stringify([], null, 2));
|
|
}
|
|
return filePath;
|
|
}
|
|
|
|
function readJournal(profileId) {
|
|
const filePath = hydrateJournalFile(profileId);
|
|
try {
|
|
const raw = fs.readFileSync(filePath, 'utf8');
|
|
const parsed = JSON.parse(raw);
|
|
return Array.isArray(parsed) ? parsed : [];
|
|
} catch (error) {
|
|
console.error(`[JOURNAL] Konnte Journal für ${profileId} nicht lesen:`, error.message);
|
|
return [];
|
|
}
|
|
}
|
|
|
|
function writeJournal(profileId, entries = []) {
|
|
const filePath = hydrateJournalFile(profileId);
|
|
fs.writeFileSync(filePath, JSON.stringify(entries, null, 2));
|
|
return filePath;
|
|
}
|
|
|
|
function saveJournalImage(profileId, { id, filename, buffer }) {
|
|
ensureBaseDirs();
|
|
const profileDir = getProfileImageDir(profileId);
|
|
ensureDir(profileDir);
|
|
const safeName = filename.replace(/[^a-zA-Z0-9_.-]/g, '_');
|
|
const filePath = path.join(profileDir, safeName);
|
|
fs.writeFileSync(filePath, buffer);
|
|
return {
|
|
id,
|
|
filename: safeName,
|
|
filePath
|
|
};
|
|
}
|
|
|
|
function deleteJournalImage(profileId, filename) {
|
|
if (!filename) {
|
|
return;
|
|
}
|
|
const filePath = path.join(getProfileImageDir(profileId), filename);
|
|
if (fs.existsSync(filePath)) {
|
|
fs.unlinkSync(filePath);
|
|
}
|
|
}
|
|
|
|
module.exports = {
|
|
readJournal,
|
|
writeJournal,
|
|
saveJournalImage,
|
|
deleteJournalImage,
|
|
getProfileImageDir
|
|
};
|