feat: sync GridSmart agendas and use event-relative demo time
Support script and URL sources, automatic Sessionize polling, staff-linked service sessions, chronological agenda blocks, and inline Placeholders. Fix demo mode to use the active event date and document deployed behavior with regression coverage. Co-authored-by: Stephan Charles <[email protected]> Co-authored-by: Amelia Hernandez <[email protected]> Co-authored-by: Markus Franz <[email protected]> Co-authored-by: Sabrina Hota <[email protected]> Co-authored-by: Nilüfer Doğan <[email protected]>
This commit is contained in:
1 parent
f32289f583
commit
84691de6ee
27 files changed
+1215
-60
No files matched your search
+25
-15
@@ -42,6 +42,8 @@
|
||||
const http = require('http');
|
||||
const XLSX = require('xlsx');
|
||||
const { transformExcel } = require('./transform-excel');
|
||||
const { readSessionizeSource } = require('./sessionize-source');
|
||||
const { createSessionizePoller } = require('./sessionize-poller');
|
||||
const PDFDocument = require('pdfkit');
|
||||
|
||||
const SUPABASE_URL = (process.env.SUPABASE_URL || 'http://supabase_kong_Convivo:8000').replace(/\/$/, '');
|
||||
@@ -52,6 +54,9 @@ const SESSIONIZE_API_KEY = process.env.SESSIONIZE_API_KEY || '';
|
||||
const PRETIX_API_KEY = process.env.PRETIX_API_KEY || '';
|
||||
const PRETIX_BASE = (process.env.PRETIX_BASE || 'https://pretix.eu/api/v1').replace(/\/$/, '');
|
||||
const PRETIX_SYNC_INTERVAL_MS = parseInt(process.env.PRETIX_SYNC_INTERVAL_MS || '60000', 10);
|
||||
const configuredSessionizeInterval = Number(process.env.SESSIONIZE_SYNC_INTERVAL_MS || 900000);
|
||||
const SESSIONIZE_SYNC_INTERVAL_MS = configuredSessionizeInterval === 0 ? 0
|
||||
: Number.isFinite(configuredSessionizeInterval) ? Math.max(60000, configuredSessionizeInterval) : 900000;
|
||||
const PORT = parseInt(process.env.PORT || '3002', 10);
|
||||
|
||||
// In-memory last-run state (the sidecar is otherwise stateless).
|
||||
@@ -305,21 +310,11 @@ async function runSync(eventId) {
|
||||
throw new Error(`event "${event.name}" has no sessionize_endpoint set`);
|
||||
}
|
||||
|
||||
// 2. Fetch the Sessionize data. The public /view/ endpoint needs no key;
|
||||
// if a key is configured we send it (required for /api/ endpoints).
|
||||
const szUrl = event.sessionize_endpoint.trim();
|
||||
log('run: fetching Sessionize', { szUrl, hasKey: Boolean(SESSIONIZE_API_KEY) });
|
||||
const szHeaders = {};
|
||||
if (SESSIONIZE_API_KEY) szHeaders['X-Sessionize-API-Key'] = SESSIONIZE_API_KEY;
|
||||
const szRes = await fetch(szUrl, { headers: szHeaders });
|
||||
if (!szRes.ok) {
|
||||
const t = await szRes.text();
|
||||
throw new Error(`Sessionize ${szRes.status}: ${t.slice(0, 200)}`);
|
||||
}
|
||||
const szData = await szRes.json();
|
||||
|
||||
// 3. Transform.
|
||||
const { payload, skippedSpeakers } = transform(szData);
|
||||
const source = await readSessionizeSource(event.sessionize_endpoint, { apiKey: SESSIONIZE_API_KEY });
|
||||
const { payload, skippedSpeakers } = source.payload
|
||||
? { payload: source.payload, skippedSpeakers: [] }
|
||||
: transform(source.data);
|
||||
if (!payload.sessions.length) throw new Error('Sessionize contains no scheduled sessions; existing agenda retained');
|
||||
log('run: transformed', {
|
||||
speakers: payload.speakers.length,
|
||||
sessions: payload.sessions.length,
|
||||
@@ -331,6 +326,7 @@ async function runSync(eventId) {
|
||||
method: 'POST',
|
||||
body: { p_event_id: event.id, p_payload: payload },
|
||||
});
|
||||
if (summary.errors?.length) throw new Error(`Sessionize import reported ${summary.errors.length} error(s)`);
|
||||
|
||||
const finishedAt = new Date().toISOString();
|
||||
const result = {
|
||||
@@ -339,6 +335,7 @@ async function runSync(eventId) {
|
||||
started_at: startedAt,
|
||||
finished_at: finishedAt,
|
||||
status: 'success',
|
||||
source_format: source.format,
|
||||
summary,
|
||||
skipped_speakers: skippedSpeakers,
|
||||
};
|
||||
@@ -810,6 +807,13 @@ async function handleExport(body) {
|
||||
};
|
||||
}
|
||||
|
||||
const pollSessionize = createSessionizePoller({
|
||||
listEvents: () => supabaseFetch('/rest/v1/events?is_active=eq.true&sessionize_endpoint=not.is.null&select=id'),
|
||||
syncEvent: runSync,
|
||||
isBusy: () => running,
|
||||
onError: (error, eventId) => log('sessionize poll error', { eventId, error: error.message }),
|
||||
});
|
||||
|
||||
const server = http.createServer(async (req, res) => {
|
||||
const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`);
|
||||
const path = url.pathname;
|
||||
@@ -822,6 +826,7 @@ const server = http.createServer(async (req, res) => {
|
||||
ok: true,
|
||||
running,
|
||||
lastRun,
|
||||
sessionizeIntervalMs: SESSIONIZE_SYNC_INTERVAL_MS,
|
||||
pretixRunning,
|
||||
lastPretixRun,
|
||||
pretixIntervalMs: PRETIX_SYNC_INTERVAL_MS,
|
||||
@@ -870,6 +875,11 @@ const server = http.createServer(async (req, res) => {
|
||||
});
|
||||
|
||||
server.listen(PORT, () => {
|
||||
if (SESSIONIZE_SYNC_INTERVAL_MS > 0) {
|
||||
log('sessionize auto-sync scheduled', { intervalMs: SESSIONIZE_SYNC_INTERVAL_MS });
|
||||
setInterval(pollSessionize, SESSIONIZE_SYNC_INTERVAL_MS);
|
||||
void pollSessionize();
|
||||
}
|
||||
log('sidecar listening', {
|
||||
port: PORT,
|
||||
supabase: SUPABASE_URL,
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
function createSessionizePoller({ listEvents, syncEvent, isBusy, onError }) {
|
||||
let polling = false;
|
||||
return async function pollSessionize() {
|
||||
if (polling || isBusy()) return;
|
||||
polling = true;
|
||||
try {
|
||||
const events = await listEvents();
|
||||
for (const event of events) {
|
||||
if (isBusy()) break;
|
||||
try { await syncEvent(event.id); }
|
||||
catch (error) { onError(error, event.id); }
|
||||
}
|
||||
} catch (error) {
|
||||
onError(error);
|
||||
} finally {
|
||||
polling = false;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { createSessionizePoller };
|
||||
@@ -0,0 +1,85 @@
|
||||
const { load } = require('cheerio');
|
||||
|
||||
function normalizeSessionizeSource(value) {
|
||||
let source = String(value || '').trim();
|
||||
if (source.startsWith('<')) {
|
||||
const document = load(source);
|
||||
const scripts = document('script[src]');
|
||||
if (scripts.length !== 1) throw new Error('Paste one Sessionize script tag or URL');
|
||||
source = scripts.attr('src');
|
||||
}
|
||||
let url;
|
||||
try { url = new URL(source); } catch { throw new Error('Enter a valid Sessionize URL or script tag'); }
|
||||
if (url.protocol !== 'https:' || url.hostname !== 'sessionize.com' || url.port
|
||||
|| url.username || url.password || !/^\/api\/v2\/[a-z0-9]+\/view\/(All|GridSmart)$/i.test(url.pathname)) {
|
||||
throw new Error('Use a Sessionize HTTPS All or GridSmart endpoint');
|
||||
}
|
||||
url.search = '';
|
||||
url.hash = '';
|
||||
return url.href;
|
||||
}
|
||||
|
||||
function parseGridSmart(html, offsetMinutes) {
|
||||
if (!Number.isInteger(offsetMinutes) || offsetMinutes < -720 || offsetMinutes > 840) {
|
||||
throw new Error('Sessionize event timezone is missing or invalid');
|
||||
}
|
||||
const document = load(html);
|
||||
const sessions = new Map();
|
||||
document('.sz-session[data-sessionid]').each((index, element) => {
|
||||
const card = document(element);
|
||||
const id = card.attr('data-sessionid');
|
||||
const title = card.find('.sz-session__title').text().trim();
|
||||
const timing = card.find('.sz-session__time[data-sztz]').attr('data-sztz')?.split('|');
|
||||
const start = new Date(timing?.[2]);
|
||||
const end = new Date(timing?.[3]);
|
||||
if (!id || !title || !Number.isFinite(start.getTime()) || !Number.isFinite(end.getTime()) || end <= start) {
|
||||
throw new Error('GridSmart contains a session with incomplete identity or timing');
|
||||
}
|
||||
const localStart = new Date(start.getTime() + offsetMinutes * 60000).toISOString();
|
||||
const localEnd = new Date(end.getTime() + offsetMinutes * 60000).toISOString();
|
||||
if (localStart.slice(0, 10) !== localEnd.slice(0, 10)) throw new Error('Overnight sessions are not supported');
|
||||
const session = {
|
||||
external_id: id, title, description: null,
|
||||
room: card.find('.sz-session__room').text().trim() || null,
|
||||
date: localStart.slice(0, 10), start_time: localStart.slice(11, 19), end_time: localEnd.slice(11, 19),
|
||||
is_service_session: card.hasClass('sz-session--service') || card.hasClass('sz-session--plenum'),
|
||||
speakers: [], level: null, area: null,
|
||||
};
|
||||
if (sessions.has(id) && JSON.stringify(sessions.get(id)) !== JSON.stringify(session)) {
|
||||
throw new Error('GridSmart contains conflicting copies of a session');
|
||||
}
|
||||
sessions.set(id, session);
|
||||
});
|
||||
if (!sessions.size) throw new Error('GridSmart contains no scheduled sessions');
|
||||
return { speakers: [], sessions: [...sessions.values()] };
|
||||
}
|
||||
|
||||
async function readSessionizeSource(value, { fetchImpl = fetch, apiKey = '' } = {}) {
|
||||
const source = normalizeSessionizeSource(value);
|
||||
const headers = apiKey ? { 'X-Sessionize-API-Key': apiKey } : {};
|
||||
async function request(url) {
|
||||
const response = await fetchImpl(url, { headers, redirect: 'error', signal: AbortSignal.timeout(30000) });
|
||||
if (!response.ok) throw new Error(`Sessionize HTTP ${response.status}`);
|
||||
const text = await response.text();
|
||||
if (text.length > 5_000_000) throw new Error('Sessionize response exceeds size limit');
|
||||
return text;
|
||||
}
|
||||
const body = await request(source);
|
||||
try {
|
||||
const data = JSON.parse(body);
|
||||
if (!Array.isArray(data.sessions)) throw new Error('Sessionize JSON must contain sessions');
|
||||
return { format: 'json', data };
|
||||
} catch (error) {
|
||||
if (!(error instanceof SyntaxError)) throw error;
|
||||
}
|
||||
const grid = new URL(source);
|
||||
grid.pathname = grid.pathname.replace(/\/(All|GridSmart)$/i, '/GridSmart');
|
||||
const loader = /\/GridSmart$/i.test(new URL(source).pathname) ? body : await request(grid.href);
|
||||
const zone = loader.match(/sessionize\.eventTimezone\s*=\s*['"]UTC([+-])(\d{2})(?::?(\d{2}))?['"]/);
|
||||
if (!zone) throw new Error('Sessionize embed does not expose an event timezone');
|
||||
const offset = (Number(zone[2]) * 60 + Number(zone[3] || 0)) * (zone[1] === '-' ? -1 : 1);
|
||||
grid.searchParams.set('under', 'True');
|
||||
return { format: 'gridsmart', payload: parseGridSmart(await request(grid.href), offset) };
|
||||
}
|
||||
|
||||
module.exports = { normalizeSessionizeSource, parseGridSmart, readSessionizeSource };
|
||||
Reference in new issue
Block a user