testing stuf

This commit is contained in:
miles committed 2026-04-01 20:06:06 -05:00
1 parent da39fd4fd0
commit be4cc0bf1c
6 files changed
+495 -90

No files matched your search

+176
View File
@@ -107,6 +107,164 @@ function writeRuns(runs) {
fs.writeFileSync(runsPath, `${JSON.stringify(runs, null, 2)}\n`, 'utf8');
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function fetchWithRetry(url, options, retries = 3) {
let attempt = 0;
while (true) {
const res = await fetch(url, options);
if (res.ok) return res;
if (attempt >= retries || ![429, 503].includes(res.status)) return res;
const retryAfter = Number(res.headers.get('retry-after'));
const delayMs = Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter * 1000 : 2000 * (attempt + 1);
await sleep(delayMs);
attempt += 1;
}
}
function parseLinkHeader(header) {
const links = {};
if (!header) return links;
header.split(',').forEach(part => {
const match = part.match(/<([^>]+)>\s*;\s*rel=?"?([^";]+)"?/);
if (match) {
links[match[2]] = match[1];
}
});
return links;
}
function getAredlAuthHeaders() {
const headers = {};
const accessToken = String(process.env.AREDL_ACCESS_TOKEN || '').trim();
const apiKey = String(process.env.AREDL_API_KEY || '').trim();
if (accessToken) {
headers.Authorization = `Bearer ${accessToken}`;
} else if (apiKey) {
headers['api-key'] = apiKey;
}
return headers;
}
function normalizeImportedRun(payload, source) {
return normalizeRun({
playerName: String(payload.playerName || '').trim(),
levelTitle: String(payload.levelTitle || '').trim(),
videoUrl: String(payload.videoUrl || '').trim(),
percent: String(payload.percent || '100').trim() || '100',
rawFootageUrl: String(payload.rawFootageUrl || '').trim(),
notes: String(payload.notes || `Imported from ${source}`).trim(),
status: 'approved',
reviewedBy: `${source} import`,
reviewNotes: String(payload.reviewNotes || `Imported from ${source}`).trim()
});
}
function appendImportedRuns(importedRuns, source) {
const currentRuns = readRuns();
const seen = new Set(currentRuns.map(run => String(run.videoUrl || '').trim().toLowerCase()).filter(Boolean));
const newRuns = [];
importedRuns.forEach(run => {
const videoUrl = String(run.videoUrl || '').trim();
if (!videoUrl) return;
const normalizedUrl = videoUrl.toLowerCase();
if (seen.has(normalizedUrl)) return;
seen.add(normalizedUrl);
newRuns.push(normalizeImportedRun(run, source));
});
if (newRuns.length) {
writeRuns(newRuns.concat(currentRuns));
sendEvent('runs-update', { updatedAt: new Date().toISOString() });
}
return {
added: newRuns.length,
skipped: importedRuns.length - newRuns.length,
total: importedRuns.length
};
}
async function fetchPointercrateRecords(maxPages = 20, perPage = 100) {
const results = [];
let nextUrl = `https://pointercrate.com/api/v1/records/?limit=${perPage}&status=approved`;
for (let page = 0; page < maxPages && nextUrl; page += 1) {
const res = await fetchWithRetry(nextUrl, {
headers: {
Accept: 'application/json',
'User-Agent': 'FEDL Importer'
}
});
if (!res.ok) {
throw new Error(`Pointercrate API responded with ${res.status}`);
}
const items = await res.json();
if (!Array.isArray(items)) {
throw new Error('Unexpected pointercrate API response');
}
results.push(...items);
const linkHeader = res.headers.get('link') || res.headers.get('Link');
const links = parseLinkHeader(linkHeader);
if (links.next) {
await sleep(1000);
nextUrl = new URL(links.next, 'https://pointercrate.com').toString();
continue;
}
break;
}
return results;
}
async function fetchAredlRecords(maxPages = 20, perPage = 100) {
const authHeaders = getAredlAuthHeaders();
if (!Object.keys(authHeaders).length) {
throw new Error('AREDL authentication is not configured on the server. Set AREDL_API_KEY or AREDL_ACCESS_TOKEN.');
}
const results = [];
let page = 1;
while (page <= maxPages) {
const url = `https://api.aredl.net/v2/api/aredl/records?page=${page}&per_page=${perPage}`;
const res = await fetchWithRetry(url, {
headers: Object.assign({ Accept: 'application/json', 'User-Agent': 'FEDL Importer' }, authHeaders)
});
if (!res.ok) {
const text = await res.text();
throw new Error(`AREDL API responded with ${res.status}: ${text}`);
}
const body = await res.json();
const items = Array.isArray(body.data) ? body.data : [];
results.push(...items);
if (!body.pages || page >= body.pages || items.length < perPage) break;
await sleep(1000);
page += 1;
}
return results;
}
function mapPointercrateRecord(record) {
return {
playerName: String(record.player?.name || record.player?.global_name || '').trim(),
levelTitle: String(record.demon?.name || record.demon?.title || '').trim(),
videoUrl: String(record.video || '').trim(),
percent: String(record.progress != null ? record.progress : 100).trim(),
rawFootageUrl: '',
notes: `Imported from Pointercrate record ${record.id}`,
reviewNotes: `Imported from Pointercrate record ${record.id}`
};
}
function mapAredlRecord(record) {
return {
playerName: String(record.submitted_by?.global_name || record.submitted_by?.username || '').trim(),
levelTitle: String(record.level?.name || '').trim(),
videoUrl: String(record.video_url || '').trim(),
percent: String(record.progress != null ? record.progress : 100).trim(),
rawFootageUrl: '',
notes: `Imported from AREDL record ${record.id}`,
reviewNotes: `Imported from AREDL record ${record.id}`
};
}
function normalizeRun(payload, existingRun) {
return {
id: existingRun && existingRun.id ? existingRun.id : `run_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`,
@@ -249,6 +407,24 @@ const server = http.createServer((req, res) => {
return;
}
if (req.method === 'POST' && pathname === '/api/import/pointercrate') {
if (!requireAdmin(req, res)) return;
fetchPointercrateRecords()
.then(records => appendImportedRuns(records.map(mapPointercrateRecord), 'Pointercrate'))
.then(summary => sendJson(res, 200, Object.assign({ ok: true, source: 'pointercrate' }, summary)))
.catch(error => sendJson(res, 500, { error: String(error.message || error) }));
return;
}
if (req.method === 'POST' && pathname === '/api/import/aredl') {
if (!requireAdmin(req, res)) return;
fetchAredlRecords()
.then(records => appendImportedRuns(records.map(mapAredlRecord), 'AREDL'))
.then(summary => sendJson(res, 200, Object.assign({ ok: true, source: 'aredl' }, summary)))
.catch(error => sendJson(res, 500, { error: String(error.message || error) }));
return;
}
if ((req.method === 'PUT' || req.method === 'DELETE') && pathname.startsWith('/api/runs/')) {
if (!requireAdmin(req, res)) return;
const runId = pathname.slice('/api/runs/'.length);