173 lines
8.3 KiB
JavaScript
173 lines
8.3 KiB
JavaScript
// House of RC (api.houseofrc.com) connection. The API key is a club secret: it lives only in
|
|
// data/houseofrc.json (mode 600) or the HOUSEOFRC_API_KEY env var, never in app_state, so it
|
|
// can't leak through GET /api/state, a JSON export or a backup. The browser only ever sees
|
|
// whether a key is set and its last four characters.
|
|
const fs = require("fs");
|
|
const path = require("path");
|
|
|
|
const DEFAULT_BASE_URL = "https://api.houseofrc.com";
|
|
const TIMEOUT_MS = 10000;
|
|
|
|
function createHouseOfRc({ dataDir, env = process.env, fetchImpl = globalThis.fetch }) {
|
|
const configPath = path.join(dataDir, "houseofrc.json");
|
|
const baseUrl = String(env.HOUSEOFRC_BASE_URL || DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
|
|
const readStoredKey = () => {
|
|
try {
|
|
return String(JSON.parse(fs.readFileSync(configPath, "utf8")).apiKey || "");
|
|
} catch {
|
|
return "";
|
|
}
|
|
};
|
|
const getKey = () => String(env.HOUSEOFRC_API_KEY || "").trim() || readStoredKey();
|
|
|
|
function status() {
|
|
const key = getKey();
|
|
return {
|
|
configured: Boolean(key),
|
|
source: env.HOUSEOFRC_API_KEY ? "env" : key ? "file" : "none",
|
|
keyHint: key ? `…${key.slice(-4)}` : "",
|
|
};
|
|
}
|
|
|
|
function setKey(value) {
|
|
account = null;
|
|
const key = String(value || "").trim();
|
|
if (!key) {
|
|
fs.rmSync(configPath, { force: true });
|
|
return status();
|
|
}
|
|
if (key.length < 16 || key.length > 200 || /\s/.test(key)) throw new Error("invalid_key");
|
|
fs.mkdirSync(dataDir, { recursive: true });
|
|
fs.writeFileSync(configPath, JSON.stringify({ apiKey: key, savedAt: new Date().toISOString() }), { mode: 0o600 });
|
|
fs.chmodSync(configPath, 0o600);
|
|
return status();
|
|
}
|
|
|
|
// GET against the API with the club key. Returns { ok, status, data, error, retryAfter }.
|
|
async function get(apiPath, query = {}) {
|
|
const key = getKey();
|
|
if (!key) return { ok: false, status: 0, error: "not_configured" };
|
|
const url = new URL(baseUrl + apiPath);
|
|
Object.entries(query).forEach(([name, value]) => {
|
|
if (value !== undefined && value !== null && value !== "") url.searchParams.set(name, String(value));
|
|
});
|
|
try {
|
|
const response = await fetchImpl(url, {
|
|
headers: { Authorization: `Bearer ${key}`, Accept: "application/json" },
|
|
signal: AbortSignal.timeout(TIMEOUT_MS),
|
|
});
|
|
const data = await response.json().catch(() => null);
|
|
if (response.ok) return { ok: true, status: response.status, data };
|
|
const error = response.status === 401 || response.status === 403 ? "unauthorized"
|
|
: response.status === 429 ? "rate_limited" : "http_error";
|
|
return { ok: false, status: response.status, error, retryAfter: Number(response.headers.get("retry-after")) || 0 };
|
|
} catch (error) {
|
|
return { ok: false, status: 0, error: error?.name === "TimeoutError" ? "timeout" : "unreachable" };
|
|
}
|
|
}
|
|
|
|
// A member's key answers with `user`, a club's (timing) key with `organization`. The
|
|
// organization is what lists the club's events and opens their entries.
|
|
let account = null;
|
|
async function testConnection() {
|
|
const result = await get("/v1/me");
|
|
if (!result.ok) return result;
|
|
const body = result.data?.data || {};
|
|
account = { user: body.user || null, organization: body.organization || null };
|
|
return { ok: true, status: result.status, ...account, rateLimit: body.rate_limit ?? null };
|
|
}
|
|
async function getOrganizationId() {
|
|
if (!account) await testConnection();
|
|
return account?.organization?.id ?? null;
|
|
}
|
|
|
|
// Members owning these transponders (/timing/users, max 200 per call). The newest owner of a
|
|
// transponder comes first, so the first hit per number wins.
|
|
async function lookupTransponders(list) {
|
|
const numbers = [...new Set((Array.isArray(list) ? list : []).map((value) => String(value || "").trim()).filter((value) => /^[A-Za-z0-9]{1,20}$/.test(value)))];
|
|
const members = {};
|
|
for (let index = 0; index < numbers.length; index += 200) {
|
|
const result = await get("/timing/users", { transponders: numbers.slice(index, index + 200).join(",") });
|
|
if (!result.ok) return result;
|
|
(Array.isArray(result.data) ? result.data : []).forEach((user) => {
|
|
const transponder = String(user?.transponder || "").trim();
|
|
if (!transponder || members[transponder]) return;
|
|
members[transponder] = {
|
|
id: user.id ?? null,
|
|
name: String(user.name || "").trim(),
|
|
model: String(user.model?.name || "").trim(),
|
|
// Often only the model name carries the make ("Xray XB4 2025"), with no brand object.
|
|
brand: String(user.model?.brand?.name || "").trim(),
|
|
};
|
|
});
|
|
}
|
|
return { ok: true, status: 200, asked: numbers.length, members };
|
|
}
|
|
|
|
const pickEvent = (event) => ({
|
|
id: event.id, name: String(event.name || ""), type: event.type || "", status: event.status || null,
|
|
start: event.start || null, end: event.end || null, city: event.city || "", country: event.country || "",
|
|
organizerId: event.organizer_id ?? null, seriesId: event.series_id ?? null, url: event.web_url || "",
|
|
});
|
|
|
|
// Events in a date range: the club's own (hosted or organized) when the key is an
|
|
// organization's, otherwise every public event filtered by country. At most 5 pages of 100.
|
|
async function listEvents({ from, to, country = "" } = {}) {
|
|
const organizationId = await getOrganizationId();
|
|
const query = organizationId
|
|
? { parent_id: organizationId, from, to }
|
|
: { start_from: from, start_to: to, country: String(country || "").toUpperCase() || undefined };
|
|
const events = [];
|
|
for (let page = 1; page <= 5; page += 1) {
|
|
const result = await get("/v1/events", { ...query, sort: "start", per_page: 100, page });
|
|
if (!result.ok) return result;
|
|
const rows = Array.isArray(result.data?.data) ? result.data.data : [];
|
|
events.push(...rows.map(pickEvent));
|
|
if (!result.data?.links?.next || rows.length < 100) break;
|
|
}
|
|
return { ok: true, status: 200, organizationId, events: events.filter((event) => event.type !== "series") };
|
|
}
|
|
|
|
// One event with its racing classes and entries (/v1/timing/events/{id}/entries, needs the
|
|
// hosting or organizing club's key). The answer also holds the drivers' email, phone,
|
|
// emergency contact and age: those are dropped here and never reach the browser.
|
|
const NOT_RACING = new Set(["entrycancelled", "waitinglist"]);
|
|
async function getEventEntries(eventId) {
|
|
const text = String(eventId || "").trim();
|
|
const id = Number(text.match(/events\/(\d+)/)?.[1] || text.match(/^\d+$/)?.[0]);
|
|
if (!Number.isInteger(id) || id < 1) return { ok: false, status: 400, error: "invalid_event" };
|
|
const result = await get(`/v1/timing/events/${id}/entries`);
|
|
if (!result.ok) {
|
|
if (result.status === 403) return { ...result, error: "not_your_event" };
|
|
if (result.status === 404) return { ...result, error: "event_not_found" };
|
|
return result;
|
|
}
|
|
const data = result.data?.data || {};
|
|
const users = new Map((data.users || []).map((user) => [user.id, user]));
|
|
const classes = (data.classes || []).map((item) => ({ id: item.id, name: String(item.name || "").trim(), order: item.order ?? null }));
|
|
const entries = (data.entries || []).filter((entry) => !NOT_RACING.has(entry.status)).map((entry) => {
|
|
const user = users.get(entry.user_id) || {};
|
|
const brand = String(entry.brands?.[0]?.name || "").trim();
|
|
const model = String(entry.car?.name || "").trim();
|
|
return {
|
|
entryId: entry.id,
|
|
classId: entry.class_id,
|
|
houseOfRcId: entry.user_id,
|
|
name: String(user.name || [user.firstname, user.lastname].filter(Boolean).join(" ")).trim(),
|
|
country: user.represents_country || user.country || "",
|
|
number: entry.driver_number ?? null,
|
|
transponders: (entry.transponders || []).map((value) => String(value).trim()).filter(Boolean),
|
|
club: String(entry.club?.name || "").trim(),
|
|
car: brand && !model.toLowerCase().startsWith(brand.toLowerCase()) ? `${brand} ${model}`.trim() : model || brand,
|
|
status: entry.status || "",
|
|
};
|
|
}).filter((entry) => entry.name);
|
|
return { ok: true, status: 200, event: pickEvent(data.event || { id }), classes, entries };
|
|
}
|
|
|
|
return { status, setKey, get, testConnection, lookupTransponders, listEvents, getEventEntries };
|
|
}
|
|
|
|
module.exports = { createHouseOfRc, DEFAULT_BASE_URL };
|