72 lines
2.7 KiB
JavaScript
72 lines
2.7 KiB
JavaScript
const express = require('express');
|
|
const router = express.Router();
|
|
const path = require('path');
|
|
const fs = require('fs');
|
|
const multer = require('multer');
|
|
const crypto = require('crypto');
|
|
|
|
// Configure multer storage to create unique filenames
|
|
const storage = multer.diskStorage({
|
|
destination: 'public/upload',
|
|
filename: (req, file, cb) => {
|
|
const originalName = path.parse(file.originalname);
|
|
const uniqueSuffix = Date.now() + '-' + crypto.randomBytes(4).toString('hex'); // Generate a unique suffix
|
|
const newFilename = `${originalName.name}-${uniqueSuffix}${originalName.ext}`; // Create new filename
|
|
cb(null, newFilename); // Save the file with the new name
|
|
}
|
|
});
|
|
|
|
const upload = multer({ storage }); // Use the custom storage configuration
|
|
const messagesFilePath = path.join(__dirname, '../messages.json');
|
|
|
|
// Function to load the appropriate language file
|
|
function getLanguageFile(language) {
|
|
const filePath = path.join(__dirname, `../locales/guestbook/${language}.json`);
|
|
return JSON.parse(fs.readFileSync(filePath, 'utf8'));
|
|
}
|
|
|
|
// Load previous messages from a JSON file
|
|
let messages = [];
|
|
if (fs.existsSync(messagesFilePath)) {
|
|
messages = JSON.parse(fs.readFileSync(messagesFilePath, 'utf8'));
|
|
}
|
|
|
|
// Route for the guestbook, with language support
|
|
router.get('/:lang', (req, res) => {
|
|
const lang = req.params.lang || 'en'; // Default to English
|
|
let languageData;
|
|
|
|
// Try to load the correct language file, fall back to English
|
|
try {
|
|
languageData = getLanguageFile(lang);
|
|
} catch (err) {
|
|
languageData = getLanguageFile('en');
|
|
}
|
|
|
|
// Render the guestbook with messages
|
|
res.render('guestbook', { langData: languageData, messages });
|
|
});
|
|
|
|
// Endpoint to handle guestbook form submission
|
|
router.post('/new_comment', upload.single('file'), (req, res) => {
|
|
const lang = req.params.lang || 'en'; // Get the language from the URL
|
|
const comment = req.body.comment;
|
|
const name = req.body.name;
|
|
const imagePath = req.file ? path.join('/upload', req.file.filename) : null;
|
|
const originalFilename = req.file ? req.file.originalname : null; // Get the original filename
|
|
|
|
// Add the new message to the messages array
|
|
messages.push({ name, comment, imagePath, originalFilename });
|
|
|
|
// Save messages to a JSON file
|
|
try {
|
|
fs.writeFileSync(messagesFilePath, JSON.stringify(messages, null, 2)); // Indent for readability
|
|
} catch (error) {
|
|
console.error('Error writing to messages.json:', error);
|
|
}
|
|
|
|
res.redirect(`/guestbook/${lang}`); // Redirect to the guestbook page with language
|
|
});
|
|
|
|
module.exports = router;
|