148 lines
7.1 KiB
JavaScript
148 lines
7.1 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) {
|
|
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" };
|
|
}
|
|
}
|
|
|
|
async function testConnection() {
|
|
const result = await get("/v1/me");
|
|
if (!result.ok) return result;
|
|
const body = result.data?.data || {};
|
|
return { ok: true, status: result.status, user: body.user || null, rateLimit: body.rate_limit ?? 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 || "",
|
|
});
|
|
|
|
// Upcoming events in a date range (the API has no country or text filter, so filter here).
|
|
// At most 5 pages of 100 to stay well inside the rate limit.
|
|
async function listEvents({ from, to, country = "" } = {}) {
|
|
const events = [];
|
|
for (let page = 1; page <= 5; page += 1) {
|
|
const result = await get("/v1/events", { start_from: from, start_to: to, 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;
|
|
}
|
|
const wanted = String(country || "").toUpperCase();
|
|
return { ok: true, status: 200, events: events.filter((event) => !wanted || String(event.country).toUpperCase() === wanted) };
|
|
}
|
|
|
|
// One event and its entered drivers. /results on an event that hasn't been run yet lists the
|
|
// entries (0 points); cancelled and waiting-list entries are already left out.
|
|
async function getEventEntries(eventId, eventclassId) {
|
|
// An id, or a pasted link like https://houseofrc.com/events/2253.
|
|
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 event = await get(`/v1/events/${id}`);
|
|
if (!event.ok) return event.status === 404 ? { ...event, error: "event_not_found" } : event;
|
|
const results = await get("/results", { event_id: id, eventclass_id: eventclassId || undefined });
|
|
if (!results.ok) return results;
|
|
const entries = (Array.isArray(results.data) ? results.data : []).map((row) => ({
|
|
houseOfRcId: row.user_id ?? null,
|
|
name: String(row.name || [row.firstname, row.lastname].filter(Boolean).join(" ")).trim(),
|
|
number: row.number ?? null,
|
|
club: String(row.club || "").trim(),
|
|
country: String(row.country || "").trim(),
|
|
car: [row.brand1 && !String(row.product || "").toLowerCase().startsWith(String(row.brand1).toLowerCase()) ? row.brand1 : "", row.product].filter(Boolean).join(" ").trim(),
|
|
brand: String(row.brand1 || "").trim(),
|
|
points: row.points ?? null,
|
|
})).filter((entry) => entry.name);
|
|
return { ok: true, status: 200, event: pickEvent(event.data?.data || {}), entries };
|
|
}
|
|
|
|
return { status, setKey, get, testConnection, lookupTransponders, listEvents, getEventEntries };
|
|
}
|
|
|
|
module.exports = { createHouseOfRc, DEFAULT_BASE_URL };
|