From 36a45e9812cf6e499b67b4cebde74f17b1b87548 Mon Sep 17 00:00:00 2001 From: ChrisChrome Date: Mon, 27 Oct 2025 18:05:43 -0600 Subject: [PATCH] Finished directory API. --- index.js | 59 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/index.js b/index.js index a074936..76590f8 100644 --- a/index.js +++ b/index.js @@ -796,6 +796,65 @@ app.delete('/api/v1/user/dir/deleteEntry/:number', async (req, res) => { }); }); +// User directory endpoint to mass update entries, with boolean 'replace' field to indicate if existing entries should be replaced with the new list. +app.post('/api/v1/user/dir/massUpdate', async (req, res) => { + const apiKey = req.headers['authorization'] ? req.headers['authorization'].replace('Bearer ', '') : null; + if (!apiKey) { + res.status(401).json({ error: 'API Key is required!' }); + return; + } + const routeData = await pool.query("SELECT * FROM routes WHERE apiKey = ?", [apiKey]); + if (!routeData || routeData.length === 0) { + res.status(401).json({ error: 'Unauthorized' }); + return; + } + + // Validate all entries, make sure we check that each number is within the block range for the current user + + + const route = routeData[0]; + const entries = req.body.entries; + const replace = req.body.replace || false; + if (!Array.isArray(entries)) { + res.status(400).json({ error: 'Bad Request. Not array' }); + return; + } + for (const entry of entries) { + const number = Number(entry.number); + const name = String(entry.name); + if (!number || !name) { + res.status(400).json({ error: 'Bad Request. Number Or Name' }); + return; + } + if (number < route.block_start || number > route.block_start + route.block_length) { + res.status(403).json({ error: 'Forbidden' }); + return; + } + } + if(replace) { + // Delete all existing entries for this route + await pool.query('DELETE FROM directory WHERE route = ?', [route.id]); + } + // Insert or update entries + for (const entry of entries) { + const number = Number(entry.number); + const name = String(entry.name); + // Remove html + const safeName = require("escape-html")(name); + // If number already exists, update, otherwise insert + const existingEntries = await pool.query('SELECT * FROM directory WHERE number = ? AND route = ?', [number, route.id]); + const row = existingEntries[0]; + if (row) { + await pool.query('UPDATE directory SET name = ? WHERE number = ? AND route = ?', + [safeName, number, route.id]); + } else { + await pool.query('INSERT INTO directory (number, name, route) VALUES (?, ?, ?)', + [number, safeName, route.id]); + } + } + res.json({ message: 'Mass update completed' }); +}); + // == END USER ROUTES == // == Directory routes == (unauthenticated)