testing stuf
This commit is contained in:
1 parent
da39fd4fd0
commit
be4cc0bf1c
6 files changed
+495
-90
No files matched your search
+61
@@ -0,0 +1,61 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
||||
<title>FEDL Offline</title>
|
||||
<link rel="stylesheet" href="styles.css">
|
||||
</head>
|
||||
<body>
|
||||
<header>
|
||||
<h1>FEDL Maintenance</h1>
|
||||
<nav>
|
||||
<a href="lists.html">Lists</a>
|
||||
<a href="players.html">Players</a>
|
||||
<a href="run.html">Submit Run</a>
|
||||
<a href="rules.html">Rules</a>
|
||||
<a href="roulette.html">Roulette</a>
|
||||
</nav>
|
||||
</header>
|
||||
<main>
|
||||
<section class="panel">
|
||||
<p class="hero-kicker">Server Offline</p>
|
||||
<h2>The FEDL backend is currently down</h2>
|
||||
<p class="hero-text">The site is being worked on or the server is offline. This static fallback page is available while the live API is unavailable.</p>
|
||||
<div class="hero-actions">
|
||||
<a class="btn" href="lists.html">Browse static list</a>
|
||||
<a class="btn ghost-btn" href="players.html">View players</a>
|
||||
<a class="btn ghost-btn" href="rules.html">Read rules</a>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="layout">
|
||||
<article class="panel info-panel">
|
||||
<p class="status-label">Maintenance Mode</p>
|
||||
<h3>Live data is not available</h3>
|
||||
<p class="muted">The server-side list and run services are currently offline. Please check back once the maintenance is complete.</p>
|
||||
</article>
|
||||
|
||||
<article class="panel info-panel">
|
||||
<p class="status-label">Static access only</p>
|
||||
<h3>Local pages still work</h3>
|
||||
<p class="muted">This page is designed to display even when the backend cannot respond.</p>
|
||||
</article>
|
||||
|
||||
<article class="panel info-panel">
|
||||
<p class="status-label">Try again soon</p>
|
||||
<h3>We'll be back shortly</h3>
|
||||
<p class="muted">Refresh this page after a few minutes to see if the FEDL server is back online.</p>
|
||||
</article>
|
||||
</section>
|
||||
|
||||
<section class="panel spotlight-panel">
|
||||
<div class="spotlight-copy">
|
||||
<p class="status-label">What changed</p>
|
||||
<h2>One index page for maintenance</h2>
|
||||
<p class="spotlight-text">This version of `1index.html` is meant for server downtime and repair work. It keeps the same visual style but avoids live data loading.</p>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
@@ -109,6 +109,20 @@
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="panel admin-panel">
|
||||
<div class="admin-toolbar">
|
||||
<div>
|
||||
<p class="hero-kicker">Import external runs</p>
|
||||
<h2>Pointercrate / AREDL</h2>
|
||||
<p id="import-status" class="muted">Import runs from external demonlists. AREDL import requires a server-side API key or access token. Imports run one page at a time to avoid rate limiting.</p>
|
||||
</div>
|
||||
<div class="admin-actions">
|
||||
<button id="import-pointercrate" type="button" class="btn ghost-btn">Import Pointercrate</button>
|
||||
<button id="import-aredl" type="button" class="btn ghost-btn">Import AREDL</button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</section>
|
||||
</main>
|
||||
<script src="app.js"></script>
|
||||
|
||||
@@ -528,18 +528,149 @@
|
||||
|
||||
// Players page
|
||||
if(page==='players'){
|
||||
const form = qs('player-form'); const nameIn = qs('player-name'); const list = qs('players');
|
||||
if(!form || !nameIn || !list) return;
|
||||
let players = read('gd_players',[]);
|
||||
function render(){list.innerHTML=''; players.forEach((p,idx)=>{
|
||||
const li=document.createElement('li'); li.innerHTML=`<span><span class="name">${escapeHtml(p.name)}</span> <span class="muted">(${p.id})</span></span>`;
|
||||
const actions=document.createElement('div'); actions.className='actions';
|
||||
const edit=document.createElement('button'); edit.textContent='Edit'; edit.onclick=()=>{const nv=prompt('Edit name',p.name); if(nv){players[idx].name=nv; write('gd_players',players); render()}};
|
||||
const del=document.createElement('button'); del.textContent='Delete'; del.onclick=()=>{if(confirm('Delete player?')){players.splice(idx,1); write('gd_players',players); render()}};
|
||||
actions.appendChild(edit); actions.appendChild(del); li.appendChild(actions); list.appendChild(li);
|
||||
})}
|
||||
form.addEventListener('submit',e=>{e.preventDefault(); const name=nameIn.value.trim(); if(!name) return; players.push({id:Date.now().toString(36),name}); write('gd_players',players); nameIn.value=''; render()});
|
||||
render();
|
||||
const playersArea = qs('players-area');
|
||||
const searchEl = qs('search');
|
||||
const filterSelect = qs('group-filter');
|
||||
const groupsEl = qs('player-groups');
|
||||
if(!playersArea || !searchEl || !filterSelect || !groupsEl) return;
|
||||
|
||||
let players = [];
|
||||
|
||||
function getGroupKey(name){
|
||||
const first = String(name || '').trim().charAt(0).toUpperCase();
|
||||
return first.match(/[A-Z0-9]/) ? first : '#';
|
||||
}
|
||||
|
||||
function computeGroups(items){
|
||||
const set = new Set();
|
||||
items.forEach(item => set.add(getGroupKey(item.name)));
|
||||
return Array.from(set).sort((a,b)=> a === '#' ? 1 : b === '#' ? -1 : a.localeCompare(b));
|
||||
}
|
||||
|
||||
function setupGroups(items){
|
||||
const groups = computeGroups(items);
|
||||
groupsEl.innerHTML = '';
|
||||
filterSelect.innerHTML = '<option value="all">All players</option>';
|
||||
groups.forEach(group => {
|
||||
const li = document.createElement('li');
|
||||
const btn = document.createElement('button');
|
||||
btn.type = 'button';
|
||||
btn.textContent = group;
|
||||
btn.className = 'level-link';
|
||||
btn.addEventListener('click', () => {
|
||||
filterSelect.value = group;
|
||||
renderTable();
|
||||
groupsEl.querySelectorAll('.level-link').forEach(el=>el.classList.remove('active'));
|
||||
btn.classList.add('active');
|
||||
});
|
||||
li.appendChild(btn);
|
||||
groupsEl.appendChild(li);
|
||||
|
||||
const opt = document.createElement('option');
|
||||
opt.value = group;
|
||||
opt.textContent = group;
|
||||
filterSelect.appendChild(opt);
|
||||
});
|
||||
}
|
||||
|
||||
function buildPlayers(runs, listItems){
|
||||
const lookup = new Map(listItems.map(item => [String(item.title || '').toLowerCase(), Number(item.position) || 9999]));
|
||||
const map = new Map();
|
||||
runs.filter(run => String(run.status || '').toLowerCase() === 'approved').forEach(run => {
|
||||
const playerName = String(run.playerName || '').trim();
|
||||
if(!playerName) return;
|
||||
const key = playerName.toLowerCase();
|
||||
let entry = map.get(key);
|
||||
if(!entry){
|
||||
entry = {name: playerName, runs: 0, bestRank: 9999, topLevels: new Set()};
|
||||
map.set(key, entry);
|
||||
}
|
||||
entry.runs += 1;
|
||||
const rank = lookup.get(String(run.levelTitle || '').toLowerCase()) || 9999;
|
||||
if(rank > 0 && rank < entry.bestRank) entry.bestRank = rank;
|
||||
if(run.levelTitle) entry.topLevels.add(String(run.levelTitle).trim());
|
||||
});
|
||||
return Array.from(map.values()).map(entry => ({
|
||||
name: entry.name,
|
||||
runs: entry.runs,
|
||||
bestRank: entry.bestRank === 9999 ? '—' : `#${entry.bestRank}`,
|
||||
topLevels: Array.from(entry.topLevels).slice(0, 3).join(', ')
|
||||
})).sort((a,b) => {
|
||||
if(b.runs !== a.runs) return b.runs - a.runs;
|
||||
const aRank = typeof a.bestRank === 'string' ? Number(a.bestRank.slice(1)) || 9999 : a.bestRank;
|
||||
const bRank = typeof b.bestRank === 'string' ? Number(b.bestRank.slice(1)) || 9999 : b.bestRank;
|
||||
if(aRank !== bRank) return aRank - bRank;
|
||||
return a.name.localeCompare(b.name);
|
||||
});
|
||||
}
|
||||
|
||||
function renderTable(){
|
||||
const query = String(searchEl.value || '').toLowerCase().trim();
|
||||
const filterValue = filterSelect.value || 'all';
|
||||
const filtered = players.filter(item => {
|
||||
if(filterValue !== 'all' && getGroupKey(item.name) !== filterValue) return false;
|
||||
if(!query) return true;
|
||||
return item.name.toLowerCase().includes(query);
|
||||
});
|
||||
|
||||
playersArea.innerHTML = '';
|
||||
if(!filtered.length){
|
||||
playersArea.innerHTML = '<tr><td colspan="4" class="muted">No server players found.</td></tr>';
|
||||
return;
|
||||
}
|
||||
|
||||
filtered.forEach(item => {
|
||||
const tr = document.createElement('tr');
|
||||
const tdName = document.createElement('td'); tdName.textContent = item.name;
|
||||
const tdRuns = document.createElement('td'); tdRuns.textContent = String(item.runs);
|
||||
const tdRank = document.createElement('td'); tdRank.textContent = item.bestRank;
|
||||
const tdLevels = document.createElement('td'); tdLevels.textContent = item.topLevels;
|
||||
tr.appendChild(tdName);
|
||||
tr.appendChild(tdRuns);
|
||||
tr.appendChild(tdRank);
|
||||
tr.appendChild(tdLevels);
|
||||
playersArea.appendChild(tr);
|
||||
});
|
||||
}
|
||||
|
||||
function showLoading(){
|
||||
playersArea.innerHTML = '<tr><td colspan="4" class="muted">Loading player stats from server...</td></tr>';
|
||||
}
|
||||
|
||||
function syncView(newPlayers){
|
||||
players = newPlayers;
|
||||
setupGroups(players);
|
||||
renderTable();
|
||||
}
|
||||
|
||||
function loadPlayerStats(){
|
||||
showLoading();
|
||||
return Promise.all([loadRuns(), loadItems()])
|
||||
.then(([runs, items]) => {
|
||||
const computed = buildPlayers(runs, items);
|
||||
syncView(computed);
|
||||
})
|
||||
.catch(err => {
|
||||
console.error(err);
|
||||
playersArea.innerHTML = '<tr><td colspan="4" class="muted">Could not load server player stats.</td></tr>';
|
||||
});
|
||||
}
|
||||
|
||||
searchEl.addEventListener('input', renderTable);
|
||||
filterSelect.addEventListener('change', () => {
|
||||
const activeBtn = Array.from(groupsEl.querySelectorAll('.level-link')).find(btn => btn.textContent === filterSelect.value);
|
||||
groupsEl.querySelectorAll('.level-link').forEach(btn => btn.classList.toggle('active', btn === activeBtn));
|
||||
renderTable();
|
||||
});
|
||||
|
||||
loadPlayerStats();
|
||||
bindLiveUpdates();
|
||||
onRunsUpdate(() => {
|
||||
loadPlayerStats();
|
||||
});
|
||||
onLiveUpdate(() => {
|
||||
loadPlayerStats();
|
||||
});
|
||||
}
|
||||
|
||||
function initListPage(){
|
||||
@@ -668,6 +799,9 @@
|
||||
const runsStatusEl = qs('runs-admin-status');
|
||||
const runsTbody = qs('run-admin-body');
|
||||
const runSearchEl = qs('run-search');
|
||||
const importStatusEl = qs('import-status');
|
||||
const importPointercrateBtn = qs('import-pointercrate');
|
||||
const importAredlBtn = qs('import-aredl');
|
||||
let items = [];
|
||||
let runs = [];
|
||||
const adminPasswordKey = 'fedl_admin_password';
|
||||
@@ -1093,6 +1227,54 @@
|
||||
if(adminPasswordEl){
|
||||
setAdminPassword(getAdminPassword());
|
||||
}
|
||||
|
||||
function setImportStatus(message, isError){
|
||||
if(!importStatusEl) return;
|
||||
importStatusEl.textContent = message;
|
||||
importStatusEl.classList.toggle('error-text', !!isError);
|
||||
}
|
||||
|
||||
function toggleImportButtons(enabled){
|
||||
[importPointercrateBtn, importAredlBtn].forEach(btn=>{ if(btn) btn.disabled = !enabled; });
|
||||
}
|
||||
|
||||
function runImport(path, label){
|
||||
setImportStatus(`Importing ${label} runs...`);
|
||||
toggleImportButtons(false);
|
||||
return fetch(path, {
|
||||
method: 'POST',
|
||||
headers: authHeaders({'Content-Type':'application/json'})
|
||||
}).then(async response => {
|
||||
const payload = await response.json().catch(()=>({}));
|
||||
if(response.status === 401){
|
||||
throw new Error('Admin auth failed');
|
||||
}
|
||||
if(!response.ok){
|
||||
throw new Error(payload.error || `Import failed with status ${response.status}`);
|
||||
}
|
||||
return payload;
|
||||
}).then(payload => {
|
||||
setImportStatus(`${label} import complete. Added ${payload.added || 0} runs, skipped ${payload.skipped || 0}.`);
|
||||
refreshRuns().catch(()=>{});
|
||||
}).catch(error => {
|
||||
console.error(error);
|
||||
if(error.message === 'Admin auth failed'){
|
||||
handleAdminAuthFailure('Wrong admin password. Enter it above, then try again.', setImportStatus);
|
||||
return;
|
||||
}
|
||||
setImportStatus(error.message || 'Import failed.', true);
|
||||
}).finally(()=>{
|
||||
toggleImportButtons(true);
|
||||
});
|
||||
}
|
||||
|
||||
if(importPointercrateBtn){
|
||||
importPointercrateBtn.addEventListener('click', ()=> runImport('/api/import/pointercrate', 'Pointercrate'));
|
||||
}
|
||||
if(importAredlBtn){
|
||||
importAredlBtn.addEventListener('click', ()=> runImport('/api/import/aredl', 'AREDL'));
|
||||
}
|
||||
|
||||
if(loginFormEl){
|
||||
loginFormEl.addEventListener('submit', function(event){
|
||||
event.preventDefault();
|
||||
|
||||
@@ -1,62 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
||||
<title>GD fedl</title>
|
||||
<link rel="stylesheet" href="styles.css">
|
||||
</head>
|
||||
<body data-page="index">
|
||||
<header>
|
||||
<h1>GD fedl</h1>
|
||||
<nav>
|
||||
<a href="players.html">Players</a>
|
||||
<a href="lists.html">Lists</a>
|
||||
<a href="rules.html">Rules</a>
|
||||
<a href="roulette.html">Roulette</a>
|
||||
</nav>
|
||||
</header>
|
||||
<main>
|
||||
<section class="panel">
|
||||
<h2>Welcome</h2>
|
||||
<p class="small muted">Use the top navigation to view players or fedls. This UI follows a compact table-first layout for quick browsing.</p>
|
||||
</section>
|
||||
<section class="layout">
|
||||
<div class="panel" style="flex:1">
|
||||
<h3>Quick Links</h3>
|
||||
<a class="btn" href="lists.html">View Lists</a>
|
||||
<a class="btn" href="players.html" style="margin-left:8px">Players</a>
|
||||
<a class="btn" href="rules.html" style="margin-left:8px">Rules</a>
|
||||
<a class="btn" href="roulette.html" style="margin-left:8px">Roulette</a>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="panel discord-panel">
|
||||
<div class="discord-copy">
|
||||
<div class="discord-badge">
|
||||
<span class="discord-logo" aria-hidden="true">
|
||||
<img src="https://cdn.prod.website-files.com/6257adef93867e50d84d30e2/66e3d7f4ef6498ac018f2c55_Symbol.svg" alt="Discord logo" />
|
||||
</span>
|
||||
<div>
|
||||
<p class="discord-label">Community</p>
|
||||
<h2>Join Our Discord</h2>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p class="discord-text">Join the FEDL Discord to ask questions about rules, talk about levels, share progress, report issues, and get help from moderators and other players.</p>
|
||||
|
||||
<div class="discord-highlights">
|
||||
<span>Rule help</span>
|
||||
<span>Level discussion</span>
|
||||
<span>Moderator support</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="discord-actions">
|
||||
<a class="btn discord-btn" href="https://discord.gg/vA8GcdCG" target="_blank" rel="noopener noreferrer">Join Now</a>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
<script src="app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
+50
-16
@@ -19,26 +19,60 @@
|
||||
<a href="admelist.html">Admin</a>
|
||||
</nav>
|
||||
</header>
|
||||
<main>
|
||||
<section class="coming-shell">
|
||||
<div class="coming-orb orb-one" aria-hidden="true"></div>
|
||||
<div class="coming-orb orb-two" aria-hidden="true"></div>
|
||||
<main class="layout">
|
||||
<aside class="sidebar">
|
||||
<div class="panel list-sidebar-panel">
|
||||
<p class="sidebar-kicker">Quick jump</p>
|
||||
<h2>Player groups</h2>
|
||||
<p class="muted">Jump to players by first letter.</p>
|
||||
<ul id="player-groups"></ul>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<article class="panel coming-panel">
|
||||
<p class="hero-kicker">Players Page</p>
|
||||
<h2>Coming soon</h2>
|
||||
<p class="coming-text">We’re still cooking this page. The roster will show up here once it is done being dramatically overdesigned.</p>
|
||||
<section class="content list-page-shell">
|
||||
<section class="panel list-hero-panel">
|
||||
<div class="list-hero-copy">
|
||||
<p class="hero-kicker">Player tracker</p>
|
||||
<h2 id="list-title">Local player roster</h2>
|
||||
<p class="muted list-hero-text">Manage your player list in browser storage with the same searchable table experience as the FEDL demonlist UI.</p>
|
||||
</div>
|
||||
<div class="list-hero-badge">
|
||||
<strong>Local only</strong>
|
||||
<span>Player names are stored in this browser only.</span>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div class="coming-loader" aria-hidden="true">
|
||||
<span></span>
|
||||
<span></span>
|
||||
<span></span>
|
||||
<section class="panel list-controls-panel">
|
||||
<div class="search-row">
|
||||
<label class="control-block" for="search">
|
||||
<span>Search</span>
|
||||
<input id="search" type="text" placeholder="Search player names..." />
|
||||
</label>
|
||||
<label class="control-block control-select" for="group-filter">
|
||||
<span>Filter</span>
|
||||
<select id="group-filter"><option value="all">All players</option></select>
|
||||
</label>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="panel list-table-panel">
|
||||
<div class="table-header">
|
||||
<div>
|
||||
<p class="status-label">Player table</p>
|
||||
<h3>Saved players</h3>
|
||||
</div>
|
||||
<p class="muted table-hint">Use the search box or letter filter to locate players quickly.</p>
|
||||
</div>
|
||||
|
||||
<p class="dad-joke">I was going to make a Geometry Dash joke... but I kept missing the timing.</p>
|
||||
|
||||
<a class="btn" href="index.html">Back Home</a>
|
||||
</article>
|
||||
<div class="table-wrap">
|
||||
<table class="levels-table">
|
||||
<thead>
|
||||
<tr><th>Name</th><th style="width:120px">Runs</th><th style="width:120px">Best rank</th><th style="width:180px">Top levels</th></tr>
|
||||
</thead>
|
||||
<tbody id="players-area"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
</section>
|
||||
</main>
|
||||
<script src="app.js"></script>
|
||||
|
||||
@@ -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);
|
||||
|
||||
Reference in new issue
Block a user