const express = require("express"); const bodyParser = require('body-parser'); const mysql = require("mysql"); const fs = require("fs"); const yaml = require("js-yaml"); const multer = require("multer"); const path = require("path"); const os = require("os"); const app = express(); const port = 3000; // Read database configuration from config.yaml const config = yaml.load(fs.readFileSync("config.yaml", "utf8")); const db = mysql.createConnection(config.database); db.connect((err) => { if (err) { console.error("Database connection failed: " + err.stack); return; } console.log("Connected to the database"); }); // Middleware for authentication const authenticate = (req, res, next) => { const providedPassword = req.headers.authorization; if (providedPassword === config.app.password) { next(); } else { res.status(401).json({ error: 'Unauthorized' }); } }; // Set up multer for file uploads const storage = multer.diskStorage({ destination: (req, file, cb) => { const gameId = req.params.id; const homeDir = os.homedir(); const dir = path.join(homeDir, 'game-images', gameId); if (!fs.existsSync(dir)){ fs.mkdirSync(dir, { recursive: true }); } cb(null, dir); }, filename: (req, file, cb) => { const gameId = req.params.id; cb(null, gameId); // Save the file with the ID as its name, without extension } }); const upload = multer({ storage }); // Serve static files (HTML, CSS, JavaScript) app.use(express.static("public")); // JSON data parser app.use(bodyParser.json()); // Define a route to retrieve game data app.get("/games", (req, res) => { const sql = "SELECT * FROM games"; db.query(sql, (err, results) => { if (err) { console.error("Error fetching game data: " + err); res.status(500).send("Internal Server Error"); return; } res.setHeader("Content-Type", "application/json"); res.json(results); }); }); // Endpoint to add a game app.post('/add-game', authenticate, (req, res) => { const { name, publishedLink, year, state, education, level, place, name1, name2 } = req.body; // SQL query to insert data into the games table const sql = ` INSERT INTO games (name, publishedLink, year, state, education, level, place, name1, name2) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) `; // Array of values to be inserted into the query const values = [name, publishedLink, year, state, education, level, place, name1, name2]; // Execute the SQL query db.query(sql, values, (error, results) => { if (error) { console.error('Error executing SQL query:', error); res.status(500).json({ error: 'Internal Server Error' }); } else { console.log('Data inserted into the games table:', results); res.json({ message: 'Game added successfully!', gameId: results.insertId }); } }); }); // Endpoint to upload an image for a game app.post('/upload-image/:id', authenticate, upload.single('gameImage'), (req, res) => { res.json({ message: 'Image uploaded successfully!' }); }); app.listen(port, () => { console.log(`Server is running on port ${port}`); });