diff --git a/1index.html b/1index.html new file mode 100644 index 0000000..2030826 --- /dev/null +++ b/1index.html @@ -0,0 +1,61 @@ + + + + + + FEDL Offline + + + +
+

FEDL Maintenance

+ +
+
+
+

Server Offline

+

The FEDL backend is currently down

+

The site is being worked on or the server is offline. This static fallback page is available while the live API is unavailable.

+ +
+ +
+
+

Maintenance Mode

+

Live data is not available

+

The server-side list and run services are currently offline. Please check back once the maintenance is complete.

+
+ +
+

Static access only

+

Local pages still work

+

This page is designed to display even when the backend cannot respond.

+
+ +
+

Try again soon

+

We'll be back shortly

+

Refresh this page after a few minutes to see if the FEDL server is back online.

+
+
+ +
+
+

What changed

+

One index page for maintenance

+

This version of `1index.html` is meant for server downtime and repair work. It keeps the same visual style but avoids live data loading.

+
+
+
+ + diff --git a/admelist.html b/admelist.html index 99a4f32..87b1b57 100644 --- a/admelist.html +++ b/admelist.html @@ -109,6 +109,20 @@ + +
+
+
+

Import external runs

+

Pointercrate / AREDL

+

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.

+
+
+ + +
+
+
diff --git a/app.js b/app.js index b2786de..3063de2 100644 --- a/app.js +++ b/app.js @@ -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=`${escapeHtml(p.name)} (${p.id})`; - 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 = ''; + 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 = 'No server players found.'; + 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 = 'Loading player stats from server...'; + } + + 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 = 'Could not load server player stats.'; + }); + } + + 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(); diff --git a/oldindex.html b/oldindex.html deleted file mode 100644 index b060c2b..0000000 --- a/oldindex.html +++ /dev/null @@ -1,62 +0,0 @@ - - - - - - GD fedl - - - -
-

GD fedl

- -
-
-
-

Welcome

-

Use the top navigation to view players or fedls. This UI follows a compact table-first layout for quick browsing.

-
-
-
-

Quick Links

- View Lists - Players - Rules - Roulette -
-
- -
-
-
- -
-

Community

-

Join Our Discord

-
-
- -

Join the FEDL Discord to ask questions about rules, talk about levels, share progress, report issues, and get help from moderators and other players.

- -
- Rule help - Level discussion - Moderator support -
-
- -
- Join Now -
-
-
- - - diff --git a/players.html b/players.html index 2168fa7..31c3958 100644 --- a/players.html +++ b/players.html @@ -19,26 +19,60 @@ Admin -
-
- - +
+ -
-

Players Page

-

Coming soon

-

We’re still cooking this page. The roster will show up here once it is done being dramatically overdesigned.

+
+
+
+

Player tracker

+

Local player roster

+

Manage your player list in browser storage with the same searchable table experience as the FEDL demonlist UI.

+
+
+ Local only + Player names are stored in this browser only. +
+
-
+
+ + + + + +
NameRunsBest rankTop levels
+
+
diff --git a/server/server.js b/server/server.js index 66eea49..4f306f9 100644 --- a/server/server.js +++ b/server/server.js @@ -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);