mirror of
https://github.com/nfonteyne/octane-website.git
synced 2026-09-03 23:24:48 +02:00
update: add calendar to app
This commit is contained in:
parent
b17715eaff
commit
08717c24bc
29 changed files with 1478 additions and 313 deletions
96
src/routes/calendar.js
Normal file
96
src/routes/calendar.js
Normal file
|
|
@ -0,0 +1,96 @@
|
|||
const express = require('express');
|
||||
const calendarRepo = require('../repositories/calendarRepo');
|
||||
const workflowState = require('../lib/calendarWorkflowState');
|
||||
const config = require('../config');
|
||||
const asyncHandler = require('../lib/asyncHandler');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
router.get(
|
||||
'/people',
|
||||
asyncHandler(async (req, res) => {
|
||||
res.json(await calendarRepo.getPeople());
|
||||
})
|
||||
);
|
||||
|
||||
router.get(
|
||||
'/slots',
|
||||
asyncHandler(async (req, res) => {
|
||||
const minPeople = req.query.min_people !== undefined ? parseInt(req.query.min_people, 10) : 1;
|
||||
const weeks = req.query.weeks !== undefined ? parseInt(req.query.weeks, 10) : 3;
|
||||
const personIds = req.query.person_ids
|
||||
? req.query.person_ids.split(',').map(Number).filter((n) => !Number.isNaN(n))
|
||||
: null;
|
||||
|
||||
const slots = await calendarRepo.getSlots({ minPeople, personIds, weeks });
|
||||
res.json(slots);
|
||||
})
|
||||
);
|
||||
|
||||
router.get(
|
||||
'/last-checked',
|
||||
asyncHandler(async (req, res) => {
|
||||
res.json({ last_checked: await calendarRepo.getLastChecked() });
|
||||
})
|
||||
);
|
||||
|
||||
router.get('/workflow-status', (req, res) => {
|
||||
res.json(workflowState.getState());
|
||||
});
|
||||
|
||||
function webhookHeaders() {
|
||||
const headers = { 'Content-Type': 'application/json' };
|
||||
if (config.n8nWebhookUser && config.n8nWebhookPass) {
|
||||
const token = Buffer.from(`${config.n8nWebhookUser}:${config.n8nWebhookPass}`).toString('base64');
|
||||
headers.Authorization = `Basic ${token}`;
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
|
||||
router.post('/refresh', (req, res) => {
|
||||
if (!config.n8nWebhookUrl) {
|
||||
return res.status(400).json({ error: 'n8n_not_configured' });
|
||||
}
|
||||
if (workflowState.getState().status === 'running') {
|
||||
return res.status(409).json({ ok: false, error: 'A refresh is already in progress' });
|
||||
}
|
||||
|
||||
workflowState.setRunning();
|
||||
res.json({ ok: true });
|
||||
|
||||
// Fire-and-forget: the browser polls GET /workflow-status for the result.
|
||||
(async () => {
|
||||
const controller = new AbortController();
|
||||
const watchdog = setTimeout(() => controller.abort(), 5 * 60 * 1000);
|
||||
try {
|
||||
const response = await fetch(config.n8nWebhookUrl, {
|
||||
method: 'GET',
|
||||
headers: webhookHeaders(),
|
||||
signal: controller.signal,
|
||||
});
|
||||
clearTimeout(watchdog);
|
||||
|
||||
if (!response.ok) {
|
||||
const text = await response.text();
|
||||
workflowState.setError(`n8n returned ${response.status}: ${text}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
if (!Array.isArray(data.slots)) {
|
||||
workflowState.setError('Unexpected response format from n8n');
|
||||
return;
|
||||
}
|
||||
|
||||
await calendarRepo.ingestSlots(data.slots);
|
||||
workflowState.setSuccess();
|
||||
} catch (err) {
|
||||
clearTimeout(watchdog);
|
||||
const message = err.name === 'AbortError' ? 'n8n did not respond within 5 minutes' : err.message;
|
||||
console.error('[calendar] n8n refresh failed:', message);
|
||||
workflowState.setError(message);
|
||||
}
|
||||
})();
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
42
src/routes/calendarWebhooks.js
Normal file
42
src/routes/calendarWebhooks.js
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
const express = require('express');
|
||||
const calendarRepo = require('../repositories/calendarRepo');
|
||||
const workflowState = require('../lib/calendarWorkflowState');
|
||||
const calendarWebhookAuth = require('../lib/calendarWebhookAuth');
|
||||
const asyncHandler = require('../lib/asyncHandler');
|
||||
|
||||
// Mounted directly in app.js, before the session-gated /api router — these
|
||||
// two routes are called by n8n itself (server-to-server), so they cannot
|
||||
// rely on a browser session cookie. The secret check is applied per-route
|
||||
// here rather than as middleware on the whole /api/calendar mount, so that
|
||||
// unmatched paths (e.g. GET /api/calendar/people) fall through untouched to
|
||||
// the normal session-gated router mounted afterwards.
|
||||
const router = express.Router();
|
||||
|
||||
router.post(
|
||||
'/ingest',
|
||||
calendarWebhookAuth,
|
||||
asyncHandler(async (req, res) => {
|
||||
const slots = Array.isArray(req.body) ? req.body : req.body?.slots;
|
||||
if (!Array.isArray(slots)) {
|
||||
return res.status(400).json({ error: 'expected_array_of_slots' });
|
||||
}
|
||||
try {
|
||||
await calendarRepo.ingestSlots(slots);
|
||||
workflowState.setSuccess();
|
||||
res.json({ ok: true, count: slots.length });
|
||||
} catch (err) {
|
||||
workflowState.setError(err.message);
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
router.post('/workflow-error', calendarWebhookAuth, (req, res) => {
|
||||
const message = req.body?.message || req.body?.error || 'Workflow failed';
|
||||
const node = req.body?.node || null;
|
||||
console.error('[calendar] n8n workflow error:', message, node ? `(node: ${node})` : '');
|
||||
workflowState.setError(message, node);
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
|
|
@ -5,6 +5,7 @@ const songsRoutes = require('./songs');
|
|||
const suggestionsRoutes = require('./suggestions');
|
||||
const setlistsRoutes = require('./setlists');
|
||||
const musicSearchRoutes = require('./musicSearch');
|
||||
const calendarRoutes = require('./calendar');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
|
|
@ -14,5 +15,6 @@ router.use('/songs', songsRoutes);
|
|||
router.use('/suggestions', suggestionsRoutes);
|
||||
router.use('/setlists', setlistsRoutes);
|
||||
router.use('/music-search', musicSearchRoutes);
|
||||
router.use('/calendar', calendarRoutes);
|
||||
|
||||
module.exports = router;
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ const express = require('express');
|
|||
const suggestionsRepo = require('../repositories/suggestionsRepo');
|
||||
const { requireAdmin } = require('../auth/middleware');
|
||||
const { isValidYoutubeUrl } = require('../lib/youtube');
|
||||
const { isValidSpotifyUrl } = require('../lib/spotify');
|
||||
const asyncHandler = require('../lib/asyncHandler');
|
||||
|
||||
const router = express.Router();
|
||||
|
|
@ -26,17 +27,21 @@ router.get(
|
|||
router.post(
|
||||
'/',
|
||||
asyncHandler(async (req, res) => {
|
||||
const { title, artist, youtubeUrl, description } = req.body || {};
|
||||
const { title, artist, youtubeUrl, spotifyUrl, description } = req.body || {};
|
||||
if (!title || !title.trim() || !youtubeUrl || !youtubeUrl.trim()) {
|
||||
return res.status(400).json({ error: 'title_and_youtube_url_required' });
|
||||
}
|
||||
if (!isValidYoutubeUrl(youtubeUrl.trim())) {
|
||||
return res.status(400).json({ error: 'invalid_youtube_url' });
|
||||
}
|
||||
if (spotifyUrl && !isValidSpotifyUrl(spotifyUrl.trim())) {
|
||||
return res.status(400).json({ error: 'invalid_spotify_url' });
|
||||
}
|
||||
const suggestion = await suggestionsRepo.create({
|
||||
title: title.trim(),
|
||||
artist: artist ? artist.trim() : null,
|
||||
youtubeUrl: youtubeUrl.trim(),
|
||||
spotifyUrl: spotifyUrl ? spotifyUrl.trim() : null,
|
||||
description: description ? description.trim() : null,
|
||||
suggestedBy: req.user.id,
|
||||
});
|
||||
|
|
@ -91,7 +96,6 @@ router.delete(
|
|||
|
||||
router.post(
|
||||
'/:id/promote',
|
||||
requireAdmin,
|
||||
asyncHandler(async (req, res) => {
|
||||
const song = await suggestionsRepo.promoteToSong(req.params.id, req.user.id);
|
||||
if (!song) return res.status(404).json({ error: 'not_found' });
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue