// Calls to the API of Febe. In the demo the scene (scena) and the imitated shell (veste) chosen in the address are // carried on every call and on every internal link, so that the whole interface stays in the chosen scene. import { t } from './text.js'; /** Query parameters that travel with every page and call (demo and screenshots). */ export const CARRIED = ['scena', 'veste', 'tema']; const carried = {}; /** Reads the carried parameters from the address (and from the previous pages of this tab). */ export function initCarried() { const query = new URLSearchParams(location.search); for (const key of CARRIED) { let value = query.get(key); try { if (value) sessionStorage.setItem(`febe.${key}`, value); else value = sessionStorage.getItem(`febe.${key}`); } catch { // no session storage: the address is the only source } if (value) carried[key] = value; } } export function carriedValue(key) { return carried[key]; } /** Adds the carried parameters to an internal address. */ export function withCarried(url) { const u = new URL(url, location.origin); for (const [key, value] of Object.entries(carried)) { if (!u.searchParams.has(key)) u.searchParams.set(key, value); } return u.pathname + u.search + u.hash; } /** An API error with the Italian message given by the server. */ export class ApiError extends Error { constructor(status, message) { super(message); this.status = status; } } function headers(extra) { const h = { Accept: 'application/json', ...extra }; if (carried.scena) h['X-Febe-Scena'] = carried.scena; if (carried.veste) h['X-Febe-Veste'] = carried.veste; return h; } /** * Calls the API and returns the JSON answer. Errors become ApiError with the message to show. * options: method, body (object → JSON), signal, raw (returns the Response), keepalive (the request outlives the * page: closing or reloading the tab). A keepalive fetch, unlike a beacon, keeps the Origin of the interface that the * server checks on every command (spec §13.1; with «Referrer-Policy: no-referrer» a beacon would say «null»). */ export async function api(path, options = {}) { const { method = 'GET', body, signal, raw = false, keepalive = false } = options; let response; try { response = await fetch(path, { method, signal, keepalive, credentials: 'same-origin', headers: headers(body !== undefined ? { 'Content-Type': 'application/json' } : {}), body: body !== undefined ? JSON.stringify(body) : undefined, }); } catch (error) { if (error.name === 'AbortError') throw error; throw new ApiError(0, t('comune.errore')); } if (response.status === 401 && access === 'password') { // Password mode: the session ended; go back to the login page. location.href = `/accesso?torna=${encodeURIComponent(location.pathname)}`; } if (!response.ok) { let message = t('comune.errore'); try { const data = await response.json(); if (data && data.message) message = data.message; } catch { // not JSON } throw new ApiError(response.status, message); } if (raw) return response; if (response.status === 204) return null; return response.json(); } let access; /** Remembers the access mode from the capabilities (password, token, none). */ export function setAccess(mode) { access = mode; } /** The address of the event stream, with the carried parameters (EventSource cannot send headers). */ export function eventsUrl() { return withCarried('/api/eventi'); } /** * Downloads an answer as a file: a POST with the body (CSV export), or a GET when the body is null (diagnostic report). * Through api(), so the carried scene and shell travel with it. */ export async function download(path, body, fallbackName) { const response = await api(path, body === null ? { raw: true } : { method: 'POST', body, raw: true }); const blob = await response.blob(); const disposition = response.headers.get('Content-Disposition') || ''; const match = /filename="?([^";]+)"?/.exec(disposition); const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = match ? match[1] : fallbackName; document.body.append(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(a.href), 10000); }