Add targeted import and bulk approval features with modals and API integration
This commit is contained in:
1 parent
09fced106d
commit
453e6662e0
4 files changed
+602
-19
No files matched your search
+60
-4
@@ -113,16 +113,72 @@
|
||||
<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>
|
||||
<p class="hero-kicker">Import tool</p>
|
||||
<h2>External lists & bulk approve</h2>
|
||||
<p id="import-status" class="muted">Pull records from Pointercrate or AREDL (AREDL needs a server API key or token). Targeted import loads victories from the API by player or level, adds them as approved runs with notes set to “Valid run”. Bulk approve approves pending FEDL submissions only. Full imports run one page at a time to limit rate usage.</p>
|
||||
</div>
|
||||
<div class="admin-actions">
|
||||
<div class="admin-actions admin-import-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>
|
||||
<button id="import-targeted-open" type="button" class="btn ghost-btn">Import by player or level…</button>
|
||||
<button id="bulk-approve-open" type="button" class="btn ghost-btn">Bulk-approve by player…</button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div id="import-targeted-modal" class="video-modal bulk-approve-modal" hidden>
|
||||
<div class="inner bulk-approve-modal-card" role="dialog" aria-modal="true" aria-labelledby="import-targeted-title">
|
||||
<p class="hero-kicker">Import tool</p>
|
||||
<h2 id="import-targeted-title">Import victories from API</h2>
|
||||
<p class="muted">Choose a list, match by player or level, then import. New runs are <strong>approved</strong> with submission and review notes <strong>Valid run</strong>. Duplicates (same video URL) are skipped.</p>
|
||||
<form id="import-targeted-form" class="admin-login-form bulk-approve-form">
|
||||
<label class="admin-password-field" for="import-targeted-source">
|
||||
<span>List API</span>
|
||||
<select id="import-targeted-source" required>
|
||||
<option value="pointercrate">Pointercrate</option>
|
||||
<option value="aredl">AREDL</option>
|
||||
</select>
|
||||
</label>
|
||||
<div class="import-targeted-mode">
|
||||
<span class="import-targeted-mode-label">Match</span>
|
||||
<label class="import-targeted-radio"><input type="radio" name="import-targeted-filter" value="player" checked /> Player</label>
|
||||
<label class="import-targeted-radio"><input type="radio" name="import-targeted-filter" value="level" /> Level</label>
|
||||
</div>
|
||||
<label class="admin-password-field" for="import-targeted-query">
|
||||
<span id="import-targeted-query-label">Player name</span>
|
||||
<input id="import-targeted-query" type="text" placeholder="Name as on the list" autocomplete="off" required />
|
||||
</label>
|
||||
<p class="muted small import-targeted-hint">Pointercrate: use the <strong>exact</strong> player or demon name from the list, or a numeric id (player id / demon id). The old API filters were unreliable; names are resolved correctly now. AREDL prefers an exact name match, then substring, across scanned pages.</p>
|
||||
<div class="admin-login-actions bulk-approve-actions">
|
||||
<button type="submit" class="btn" id="import-targeted-submit">Import as valid runs</button>
|
||||
<button type="button" class="btn ghost-btn" id="import-targeted-cancel">Cancel</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="bulk-approve-modal" class="video-modal bulk-approve-modal" hidden>
|
||||
<div class="inner bulk-approve-modal-card" role="dialog" aria-modal="true" aria-labelledby="bulk-approve-title">
|
||||
<p class="hero-kicker">Import tool</p>
|
||||
<h2 id="bulk-approve-title">Bulk-approve by player</h2>
|
||||
<p class="muted">Only submissions still marked <strong>pending</strong> are updated. Approved and rejected runs are left unchanged.</p>
|
||||
<form id="bulk-approve-form" class="admin-login-form bulk-approve-form">
|
||||
<label class="admin-password-field" for="bulk-approve-player">
|
||||
<span>Player name</span>
|
||||
<input id="bulk-approve-player" type="text" placeholder="Exact name from the run queue" autocomplete="off" required />
|
||||
</label>
|
||||
<p id="bulk-approve-preview" class="muted" aria-live="polite"></p>
|
||||
<label class="admin-password-field" for="bulk-approve-notes">
|
||||
<span>Review notes (optional)</span>
|
||||
<input id="bulk-approve-notes" type="text" placeholder="Shown on each approved run" autocomplete="off" />
|
||||
</label>
|
||||
<div class="admin-login-actions bulk-approve-actions">
|
||||
<button type="submit" class="btn" id="bulk-approve-submit">Approve all pending</button>
|
||||
<button type="button" class="btn ghost-btn" id="bulk-approve-cancel">Cancel</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
<script src="app.js"></script>
|
||||
|
||||
@@ -10,6 +10,11 @@
|
||||
const liveRunsUrl = `${liveServerBase}/api/runs`;
|
||||
const liveEventsUrl = `${liveServerBase}/events`;
|
||||
const liveDataFileUrl = `${liveServerBase}/server/data.txt`;
|
||||
/** Use for POST /api/import/* and any path under the same base as list/runs (not root-relative /api/...). */
|
||||
function liveApiPath(path){
|
||||
const p = String(path || '').startsWith('/') ? path : `/${path}`;
|
||||
return `${liveServerBase}${p}`;
|
||||
}
|
||||
const offlinePage = 'offlineindex.html';
|
||||
|
||||
function redirectToOffline(){
|
||||
@@ -830,6 +835,22 @@
|
||||
const importStatusEl = qs('import-status');
|
||||
const importPointercrateBtn = qs('import-pointercrate');
|
||||
const importAredlBtn = qs('import-aredl');
|
||||
const importTargetedOpenBtn = qs('import-targeted-open');
|
||||
const importTargetedModal = qs('import-targeted-modal');
|
||||
const importTargetedForm = qs('import-targeted-form');
|
||||
const importTargetedSourceEl = qs('import-targeted-source');
|
||||
const importTargetedQueryEl = qs('import-targeted-query');
|
||||
const importTargetedQueryLabelEl = qs('import-targeted-query-label');
|
||||
const importTargetedSubmitBtn = qs('import-targeted-submit');
|
||||
const importTargetedCancelBtn = qs('import-targeted-cancel');
|
||||
const bulkApproveOpenBtn = qs('bulk-approve-open');
|
||||
const bulkApproveModal = qs('bulk-approve-modal');
|
||||
const bulkApproveForm = qs('bulk-approve-form');
|
||||
const bulkApprovePlayerInput = qs('bulk-approve-player');
|
||||
const bulkApproveNotesInput = qs('bulk-approve-notes');
|
||||
const bulkApprovePreviewEl = qs('bulk-approve-preview');
|
||||
const bulkApproveCancelBtn = qs('bulk-approve-cancel');
|
||||
const bulkApproveSubmitBtn = qs('bulk-approve-submit');
|
||||
let items = [];
|
||||
let runs = [];
|
||||
const adminPasswordKey = 'fedl_admin_password';
|
||||
@@ -1263,13 +1284,160 @@
|
||||
}
|
||||
|
||||
function toggleImportButtons(enabled){
|
||||
[importPointercrateBtn, importAredlBtn].forEach(btn=>{ if(btn) btn.disabled = !enabled; });
|
||||
[importPointercrateBtn, importAredlBtn, importTargetedOpenBtn, bulkApproveOpenBtn].forEach(btn=>{ if(btn) btn.disabled = !enabled; });
|
||||
}
|
||||
|
||||
function updateImportTargetedQueryLabel(){
|
||||
if(!importTargetedQueryLabelEl) return;
|
||||
const levelRadio = document.querySelector('input[name="import-targeted-filter"][value="level"]');
|
||||
const isLevel = levelRadio && levelRadio.checked;
|
||||
importTargetedQueryLabelEl.textContent = isLevel ? 'Level name or id' : 'Player name';
|
||||
if(importTargetedQueryEl){
|
||||
importTargetedQueryEl.placeholder = isLevel ? 'e.g. Acheron or demon id' : 'Name as on the list';
|
||||
}
|
||||
}
|
||||
function openImportTargetedModal(){
|
||||
if(!importTargetedModal) return;
|
||||
importTargetedModal.hidden = false;
|
||||
if(importTargetedForm) importTargetedForm.reset();
|
||||
const playerRadio = document.querySelector('input[name="import-targeted-filter"][value="player"]');
|
||||
if(playerRadio) playerRadio.checked = true;
|
||||
updateImportTargetedQueryLabel();
|
||||
if(importTargetedQueryEl) importTargetedQueryEl.focus();
|
||||
}
|
||||
function closeImportTargetedModal(){
|
||||
if(importTargetedModal) importTargetedModal.hidden = true;
|
||||
}
|
||||
function submitImportTargeted(event){
|
||||
event.preventDefault();
|
||||
if(!canUseLiveServer){
|
||||
setImportStatus('Start the Node server to use the import tool.', true);
|
||||
return;
|
||||
}
|
||||
const source = importTargetedSourceEl && String(importTargetedSourceEl.value || '').trim();
|
||||
const filterRadio = document.querySelector('input[name="import-targeted-filter"]:checked');
|
||||
const filter = filterRadio && String(filterRadio.value || '').trim();
|
||||
const query = importTargetedQueryEl && String(importTargetedQueryEl.value || '').trim();
|
||||
if(!source || !filter || !query) return;
|
||||
if(importTargetedSubmitBtn) importTargetedSubmitBtn.disabled = true;
|
||||
setImportStatus(`Fetching ${source} records…`);
|
||||
toggleImportButtons(false);
|
||||
fetch(liveApiPath('/api/import/targeted'), {
|
||||
method: 'POST',
|
||||
headers: authHeaders({'Content-Type':'application/json'}),
|
||||
body: JSON.stringify({ source, filter, query })
|
||||
}).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 (${response.status})`);
|
||||
return payload;
|
||||
}).then(payload=>{
|
||||
clearRunsCache();
|
||||
const matched = Number(payload.matched) || 0;
|
||||
const added = Number(payload.added) || 0;
|
||||
const skipped = Number(payload.skipped) || 0;
|
||||
setImportStatus(
|
||||
`Targeted import: ${matched} API record${matched === 1 ? '' : 's'} matched, ${added} added, ${skipped} skipped (duplicates or missing video). Notes set to “Valid run”.`
|
||||
);
|
||||
closeImportTargetedModal();
|
||||
return refreshRuns();
|
||||
}).catch(err=>{
|
||||
console.error(err);
|
||||
if(String(err && err.message || '') === 'Admin auth failed'){
|
||||
handleAdminAuthFailure('Wrong admin password. Enter it above, then try again.', setImportStatus);
|
||||
closeImportTargetedModal();
|
||||
return;
|
||||
}
|
||||
setImportStatus(err.message || 'Targeted import failed.', true);
|
||||
}).finally(()=>{
|
||||
if(importTargetedSubmitBtn) importTargetedSubmitBtn.disabled = false;
|
||||
toggleImportButtons(true);
|
||||
});
|
||||
}
|
||||
|
||||
let bulkApprovePreviewTimer = null;
|
||||
function countPendingRunsForPlayer(name){
|
||||
const q = String(name || '').trim().toLowerCase();
|
||||
if(!q) return 0;
|
||||
return runs.filter(run=>{
|
||||
const st = String(run.status || 'pending').toLowerCase();
|
||||
const pn = String(run.playerName || '').trim().toLowerCase();
|
||||
return st === 'pending' && pn === q;
|
||||
}).length;
|
||||
}
|
||||
function updateBulkApprovePreview(){
|
||||
if(!bulkApprovePreviewEl || !bulkApprovePlayerInput) return;
|
||||
const n = countPendingRunsForPlayer(bulkApprovePlayerInput.value);
|
||||
const label = String(bulkApprovePlayerInput.value || '').trim();
|
||||
if(!label){
|
||||
bulkApprovePreviewEl.textContent = '';
|
||||
return;
|
||||
}
|
||||
bulkApprovePreviewEl.textContent = n
|
||||
? `${n} pending run${n === 1 ? '' : 's'} match this name in the current queue.`
|
||||
: 'No pending runs match this name in the current queue.';
|
||||
}
|
||||
function openBulkApproveModal(){
|
||||
if(!bulkApproveModal) return;
|
||||
bulkApproveModal.hidden = false;
|
||||
if(bulkApproveForm) bulkApproveForm.reset();
|
||||
updateBulkApprovePreview();
|
||||
if(bulkApprovePlayerInput){
|
||||
bulkApprovePlayerInput.focus();
|
||||
}
|
||||
}
|
||||
function closeBulkApproveModal(){
|
||||
if(bulkApproveModal) bulkApproveModal.hidden = true;
|
||||
if(bulkApprovePreviewTimer){
|
||||
clearTimeout(bulkApprovePreviewTimer);
|
||||
bulkApprovePreviewTimer = null;
|
||||
}
|
||||
}
|
||||
function submitBulkApprove(event){
|
||||
event.preventDefault();
|
||||
if(!canUseLiveServer){
|
||||
setImportStatus('Start the Node server to use the import tool.', true);
|
||||
return;
|
||||
}
|
||||
const playerName = bulkApprovePlayerInput && String(bulkApprovePlayerInput.value || '').trim();
|
||||
if(!playerName) return;
|
||||
const reviewNotesRaw = bulkApproveNotesInput && String(bulkApproveNotesInput.value || '').trim();
|
||||
const body = { playerName };
|
||||
if(reviewNotesRaw) body.reviewNotes = reviewNotesRaw;
|
||||
if(bulkApproveSubmitBtn) bulkApproveSubmitBtn.disabled = true;
|
||||
setImportStatus('Bulk-approving pending runs for that player...');
|
||||
fetch(`${liveRunsUrl}/bulk-approve`, {
|
||||
method: 'POST',
|
||||
headers: authHeaders({'Content-Type':'application/json'}),
|
||||
body: JSON.stringify(body)
|
||||
}).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 || `Bulk approve failed (${response.status})`);
|
||||
return payload;
|
||||
}).then(payload=>{
|
||||
clearRunsCache();
|
||||
const n = Number(payload.approved) || 0;
|
||||
setImportStatus(n ? `Bulk approve done: ${n} pending run${n === 1 ? '' : 's'} approved for ${playerName}.` : `No pending runs to approve for ${playerName}.`);
|
||||
closeBulkApproveModal();
|
||||
return refreshRuns();
|
||||
}).catch(err=>{
|
||||
console.error(err);
|
||||
if(String(err && err.message || '') === 'Admin auth failed'){
|
||||
handleAdminAuthFailure('Wrong admin password. Enter it above, then try again.', setImportStatus);
|
||||
closeBulkApproveModal();
|
||||
return;
|
||||
}
|
||||
setImportStatus(err.message || 'Bulk approve failed.', true);
|
||||
}).finally(()=>{
|
||||
if(bulkApproveSubmitBtn) bulkApproveSubmitBtn.disabled = false;
|
||||
});
|
||||
}
|
||||
|
||||
function runImport(path, label){
|
||||
setImportStatus(`Importing ${label} runs...`);
|
||||
toggleImportButtons(false);
|
||||
return fetch(path, {
|
||||
return fetch(liveApiPath(path), {
|
||||
method: 'POST',
|
||||
headers: authHeaders({'Content-Type':'application/json'})
|
||||
}).then(async response => {
|
||||
@@ -1303,6 +1471,53 @@
|
||||
importAredlBtn.addEventListener('click', ()=> runImport('/api/import/aredl', 'AREDL'));
|
||||
}
|
||||
|
||||
if(importTargetedOpenBtn){
|
||||
importTargetedOpenBtn.addEventListener('click', ()=> openImportTargetedModal());
|
||||
}
|
||||
if(importTargetedCancelBtn){
|
||||
importTargetedCancelBtn.addEventListener('click', ()=> closeImportTargetedModal());
|
||||
}
|
||||
if(importTargetedModal){
|
||||
importTargetedModal.addEventListener('click', event=>{
|
||||
if(event.target === importTargetedModal) closeImportTargetedModal();
|
||||
});
|
||||
}
|
||||
if(importTargetedForm){
|
||||
importTargetedForm.addEventListener('submit', submitImportTargeted);
|
||||
importTargetedForm.querySelectorAll('input[name="import-targeted-filter"]').forEach(radio=>{
|
||||
radio.addEventListener('change', updateImportTargetedQueryLabel);
|
||||
});
|
||||
}
|
||||
|
||||
if(bulkApproveOpenBtn){
|
||||
bulkApproveOpenBtn.addEventListener('click', ()=> openBulkApproveModal());
|
||||
}
|
||||
if(bulkApproveCancelBtn){
|
||||
bulkApproveCancelBtn.addEventListener('click', ()=> closeBulkApproveModal());
|
||||
}
|
||||
if(bulkApproveModal){
|
||||
bulkApproveModal.addEventListener('click', event=>{
|
||||
if(event.target === bulkApproveModal) closeBulkApproveModal();
|
||||
});
|
||||
}
|
||||
if(bulkApproveForm){
|
||||
bulkApproveForm.addEventListener('submit', submitBulkApprove);
|
||||
}
|
||||
if(bulkApprovePlayerInput){
|
||||
bulkApprovePlayerInput.addEventListener('input', ()=>{
|
||||
if(bulkApprovePreviewTimer) clearTimeout(bulkApprovePreviewTimer);
|
||||
bulkApprovePreviewTimer = setTimeout(updateBulkApprovePreview, 200);
|
||||
});
|
||||
}
|
||||
document.addEventListener('keydown', event=>{
|
||||
if(event.key !== 'Escape') return;
|
||||
if(importTargetedModal && !importTargetedModal.hidden){
|
||||
closeImportTargetedModal();
|
||||
return;
|
||||
}
|
||||
if(bulkApproveModal && !bulkApproveModal.hidden) closeBulkApproveModal();
|
||||
});
|
||||
|
||||
if(loginFormEl){
|
||||
loginFormEl.addEventListener('submit', function(event){
|
||||
event.preventDefault();
|
||||
|
||||
+314
-13
@@ -162,7 +162,8 @@ function normalizeImportedRun(payload, source) {
|
||||
});
|
||||
}
|
||||
|
||||
function appendImportedRuns(importedRuns, source) {
|
||||
function appendImportedRuns(importedRuns, source, options) {
|
||||
const validRunNote = options && String(options.validRunNote || '').trim();
|
||||
const currentRuns = readRuns();
|
||||
const seen = new Set(currentRuns.map(run => String(run.videoUrl || '').trim().toLowerCase()).filter(Boolean));
|
||||
const newRuns = [];
|
||||
@@ -172,7 +173,8 @@ function appendImportedRuns(importedRuns, source) {
|
||||
const normalizedUrl = videoUrl.toLowerCase();
|
||||
if (seen.has(normalizedUrl)) return;
|
||||
seen.add(normalizedUrl);
|
||||
newRuns.push(normalizeImportedRun(run, source));
|
||||
const payload = validRunNote ? Object.assign({}, run, { notes: validRunNote, reviewNotes: validRunNote }) : run;
|
||||
newRuns.push(normalizeImportedRun(payload, source));
|
||||
});
|
||||
if (newRuns.length) {
|
||||
writeRuns(newRuns.concat(currentRuns));
|
||||
@@ -185,10 +187,17 @@ function appendImportedRuns(importedRuns, source) {
|
||||
};
|
||||
}
|
||||
|
||||
async function fetchPointercrateRecords(maxPages = 20, perPage = 100) {
|
||||
function getLinkHeader(res) {
|
||||
return res.headers.get('link') || res.headers.get('Link') || res.headers.get('links') || '';
|
||||
}
|
||||
|
||||
async function fetchPointercrateRecordsStartingAt(startUrl, maxPages = 25) {
|
||||
const results = [];
|
||||
let nextUrl = `https://pointercrate.com/api/v1/records/?limit=${perPage}&status=approved`;
|
||||
let nextUrl = startUrl;
|
||||
for (let page = 0; page < maxPages && nextUrl; page += 1) {
|
||||
if (page > 0) {
|
||||
await sleep(1000);
|
||||
}
|
||||
const res = await fetchWithRetry(nextUrl, {
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
@@ -196,25 +205,211 @@ async function fetchPointercrateRecords(maxPages = 20, perPage = 100) {
|
||||
}
|
||||
});
|
||||
if (!res.ok) {
|
||||
throw new Error(`Pointercrate API responded with ${res.status}`);
|
||||
const text = await res.text();
|
||||
throw new Error(`Pointercrate API responded with ${res.status}: ${text.slice(0, 280)}`);
|
||||
}
|
||||
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;
|
||||
const links = parseLinkHeader(getLinkHeader(res));
|
||||
nextUrl = links.next ? new URL(links.next, 'https://pointercrate.com').toString() : null;
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
async function fetchPointercrateRecords(maxPages = 20, perPage = 100) {
|
||||
const qs = new URLSearchParams({ limit: String(perPage), status: 'approved' }).toString();
|
||||
return fetchPointercrateRecordsStartingAt(`https://pointercrate.com/api/v1/records/?${qs}`, maxPages);
|
||||
}
|
||||
|
||||
/** Records API `player=` expects numeric id, not display name. Resolve name → id via /players/. */
|
||||
async function resolvePointercratePlayerIds(rawQuery) {
|
||||
const q = String(rawQuery || '').trim();
|
||||
if (!q) {
|
||||
return [];
|
||||
}
|
||||
if (/^\d+$/.test(q)) {
|
||||
return [q];
|
||||
}
|
||||
const ql = q.toLowerCase();
|
||||
const headers = { Accept: 'application/json', 'User-Agent': 'FEDL Importer' };
|
||||
const exactParams = new URLSearchParams({ limit: '100', name: q });
|
||||
let players = await fetchPointercrateRecordsStartingAt(`https://pointercrate.com/api/v1/players/?${exactParams}`, 20);
|
||||
let ids = players
|
||||
.filter(p => p && p.name && String(p.name).trim().toLowerCase() === ql)
|
||||
.map(p => String(p.id));
|
||||
if (ids.length) {
|
||||
return [...new Set(ids)];
|
||||
}
|
||||
const containsParams = new URLSearchParams({ limit: '100', name_contains: q });
|
||||
players = await fetchPointercrateRecordsStartingAt(`https://pointercrate.com/api/v1/players/?${containsParams}`, 30);
|
||||
ids = players
|
||||
.filter(p => p && p.name && String(p.name).trim().toLowerCase() === ql)
|
||||
.map(p => String(p.id));
|
||||
if (ids.length) {
|
||||
return [...new Set(ids)];
|
||||
}
|
||||
const loose = players.filter(
|
||||
p => p && p.name && String(p.name).toLowerCase().includes(ql)
|
||||
);
|
||||
if (loose.length === 1) {
|
||||
return [String(loose[0].id)];
|
||||
}
|
||||
if (loose.length > 1) {
|
||||
throw new Error(
|
||||
`Multiple Pointercrate players match "${q}". Use the exact list name or open the player on pointercrate.com and use their numeric id.`
|
||||
);
|
||||
}
|
||||
throw new Error(
|
||||
`No Pointercrate player matched "${q}". Check spelling or paste the numeric player id from the list profile.`
|
||||
);
|
||||
}
|
||||
|
||||
async function fetchPointercrateRecordsForPlayerIds(playerIds) {
|
||||
const seen = new Set();
|
||||
const out = [];
|
||||
for (let i = 0; i < playerIds.length; i += 1) {
|
||||
const id = playerIds[i];
|
||||
const qs = new URLSearchParams({ limit: '100', status: 'approved', player: id });
|
||||
const url = `https://pointercrate.com/api/v1/records/?${qs}`;
|
||||
const chunk = await fetchPointercrateRecordsStartingAt(url, 30);
|
||||
for (const r of chunk) {
|
||||
const rid = r && r.id != null ? r.id : null;
|
||||
if (rid != null && !seen.has(rid)) {
|
||||
seen.add(rid);
|
||||
out.push(r);
|
||||
}
|
||||
}
|
||||
if (i < playerIds.length - 1) {
|
||||
await sleep(600);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function filterPointercrateRecordsByQuery(records, filter, rawQuery) {
|
||||
const trimmed = String(rawQuery || '').trim();
|
||||
if (!trimmed) {
|
||||
return [];
|
||||
}
|
||||
const ql = trimmed.toLowerCase();
|
||||
if (filter === 'player') {
|
||||
if (/^\d+$/.test(trimmed)) {
|
||||
return records.filter(r => String(r.player && r.player.id != null ? r.player.id : '') === trimmed);
|
||||
}
|
||||
return records.filter(r => {
|
||||
const name = String(r.player && r.player.name ? r.player.name : '')
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
return name === ql;
|
||||
});
|
||||
}
|
||||
if (filter === 'level') {
|
||||
if (/^\d+$/.test(trimmed)) {
|
||||
return records.filter(r => String(r.demon && r.demon.id != null ? r.demon.id : '') === trimmed);
|
||||
}
|
||||
return records.filter(r => {
|
||||
const dname = String(r.demon && r.demon.name ? r.demon.name : r.demon && r.demon.title ? r.demon.title : '')
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
return dname === ql;
|
||||
});
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Pointercrate: `demon_contains` / `player_contains` on records do not match display names reliably.
|
||||
* Player: resolve id via /players/ then records ?player=id. Level: exact demon name or demon_id only.
|
||||
*/
|
||||
async function fetchPointercrateFiltered(filter, rawQuery) {
|
||||
const query = String(rawQuery || '').trim();
|
||||
if (!query) {
|
||||
throw new Error('Query is required');
|
||||
}
|
||||
if (filter === 'player') {
|
||||
const ids = await resolvePointercratePlayerIds(query);
|
||||
const records = await fetchPointercrateRecordsForPlayerIds(ids);
|
||||
return filterPointercrateRecordsByQuery(records, 'player', query);
|
||||
}
|
||||
if (filter === 'level') {
|
||||
if (/^\d+$/.test(query)) {
|
||||
const qs = new URLSearchParams({ limit: '100', status: 'approved', demon_id: query });
|
||||
const url = `https://pointercrate.com/api/v1/records/?${qs}`;
|
||||
const records = await fetchPointercrateRecordsStartingAt(url, 30);
|
||||
return filterPointercrateRecordsByQuery(records, 'level', query);
|
||||
}
|
||||
const qs = new URLSearchParams({ limit: '100', status: 'approved', demon: query });
|
||||
const url = `https://pointercrate.com/api/v1/records/?${qs}`;
|
||||
const records = await fetchPointercrateRecordsStartingAt(url, 30);
|
||||
const narrowed = filterPointercrateRecordsByQuery(records, 'level', query);
|
||||
if (narrowed.length || !records.length) {
|
||||
return narrowed;
|
||||
}
|
||||
throw new Error(
|
||||
`No approved Pointercrate records for demon "${query}". Use the exact demon name as shown on the list, or the numeric demon id.`
|
||||
);
|
||||
}
|
||||
throw new Error('filter must be player or level');
|
||||
}
|
||||
|
||||
function filterAredlRecordsByQuery(records, filter, rawQuery) {
|
||||
const trimmed = String(rawQuery || '').trim();
|
||||
if (!trimmed) {
|
||||
return [];
|
||||
}
|
||||
const query = trimmed.toLowerCase();
|
||||
if (filter === 'player') {
|
||||
const exact = records.filter(record => {
|
||||
const a = String(record.submitted_by && record.submitted_by.global_name ? record.submitted_by.global_name : '')
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
const b = String(record.submitted_by && record.submitted_by.username ? record.submitted_by.username : '')
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
return a === query || b === query;
|
||||
});
|
||||
if (exact.length) {
|
||||
return exact;
|
||||
}
|
||||
return records.filter(record => {
|
||||
const a = String(record.submitted_by && record.submitted_by.global_name ? record.submitted_by.global_name : '')
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
const b = String(record.submitted_by && record.submitted_by.username ? record.submitted_by.username : '')
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
return (a && a.includes(query)) || (b && b.includes(query));
|
||||
});
|
||||
}
|
||||
if (filter === 'level') {
|
||||
if (/^\d+$/.test(trimmed)) {
|
||||
return records.filter(record => {
|
||||
const id = String(record.level && record.level.id != null ? record.level.id : '').trim();
|
||||
return id === trimmed;
|
||||
});
|
||||
}
|
||||
const exact = records.filter(record => {
|
||||
const level = String(record.level && record.level.name ? record.level.name : '')
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
return level === query;
|
||||
});
|
||||
if (exact.length) {
|
||||
return exact;
|
||||
}
|
||||
return records.filter(record => {
|
||||
const level = String(record.level && record.level.name ? record.level.name : '')
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
return level && level.includes(query);
|
||||
});
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
async function fetchAredlRecords(maxPages = 20, perPage = 100) {
|
||||
const authHeaders = getAredlAuthHeaders();
|
||||
if (!Object.keys(authHeaders).length) {
|
||||
@@ -407,6 +602,112 @@ const server = http.createServer((req, res) => {
|
||||
return;
|
||||
}
|
||||
|
||||
if (req.method === 'POST' && pathname === '/api/runs/bulk-approve') {
|
||||
if (!requireAdmin(req, res)) return;
|
||||
let body = '';
|
||||
req.on('data', chunk => {
|
||||
body += chunk;
|
||||
if (body.length > 65536) req.destroy();
|
||||
});
|
||||
req.on('end', () => {
|
||||
try {
|
||||
const payload = JSON.parse(body || '{}');
|
||||
const playerQuery = String(payload.playerName || '').trim();
|
||||
if (!playerQuery) {
|
||||
sendJson(res, 400, { error: 'playerName is required' });
|
||||
return;
|
||||
}
|
||||
const normalizedQuery = playerQuery.toLowerCase();
|
||||
const reviewNotes = String(
|
||||
payload.reviewNotes != null && String(payload.reviewNotes).trim()
|
||||
? payload.reviewNotes
|
||||
: 'Bulk approved (player profile tool)'
|
||||
).trim();
|
||||
const runs = readRuns();
|
||||
let approved = 0;
|
||||
let updatedAt = new Date().toISOString();
|
||||
runs.forEach((run, index) => {
|
||||
const name = String(run.playerName || '').trim().toLowerCase();
|
||||
const status = String(run.status || 'pending').toLowerCase();
|
||||
if (name === normalizedQuery && status === 'pending') {
|
||||
runs[index] = normalizeRun(
|
||||
{
|
||||
...run,
|
||||
status: 'approved',
|
||||
reviewNotes,
|
||||
reviewedBy: 'FEDL Admin'
|
||||
},
|
||||
run
|
||||
);
|
||||
updatedAt = runs[index].updatedAt;
|
||||
approved += 1;
|
||||
}
|
||||
});
|
||||
if (approved) {
|
||||
writeRuns(runs);
|
||||
sendEvent('runs-update', { updatedAt });
|
||||
}
|
||||
sendJson(res, 200, { ok: true, approved, playerName: playerQuery });
|
||||
} catch (error) {
|
||||
sendJson(res, 400, { error: 'Invalid bulk-approve payload' });
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (req.method === 'POST' && pathname === '/api/import/targeted') {
|
||||
if (!requireAdmin(req, res)) return;
|
||||
let body = '';
|
||||
req.on('data', chunk => {
|
||||
body += chunk;
|
||||
if (body.length > 65536) req.destroy();
|
||||
});
|
||||
req.on('end', () => {
|
||||
(async () => {
|
||||
try {
|
||||
const payload = JSON.parse(body || '{}');
|
||||
const source = String(payload.source || '').toLowerCase();
|
||||
const filter = String(payload.filter || '').toLowerCase();
|
||||
const query = String(payload.query || '').trim();
|
||||
if (!['pointercrate', 'aredl'].includes(source)) {
|
||||
sendJson(res, 400, { error: 'source must be pointercrate or aredl' });
|
||||
return;
|
||||
}
|
||||
if (!['player', 'level'].includes(filter)) {
|
||||
sendJson(res, 400, { error: 'filter must be player or level' });
|
||||
return;
|
||||
}
|
||||
if (!query) {
|
||||
sendJson(res, 400, { error: 'query is required' });
|
||||
return;
|
||||
}
|
||||
const validRunNote = 'Valid run';
|
||||
let records = [];
|
||||
if (source === 'pointercrate') {
|
||||
records = await fetchPointercrateFiltered(filter, query);
|
||||
} else {
|
||||
const pool = await fetchAredlRecords(40, 100);
|
||||
records = filterAredlRecordsByQuery(pool, filter, query);
|
||||
}
|
||||
const label = source === 'pointercrate' ? 'Pointercrate' : 'AREDL';
|
||||
const mapped = records.map(r => (source === 'pointercrate' ? mapPointercrateRecord(r) : mapAredlRecord(r)));
|
||||
const summary = appendImportedRuns(mapped, label, { validRunNote: validRunNote });
|
||||
sendJson(
|
||||
res,
|
||||
200,
|
||||
Object.assign(
|
||||
{ ok: true, source, filter, query, matched: records.length, note: validRunNote },
|
||||
summary
|
||||
)
|
||||
);
|
||||
} catch (error) {
|
||||
sendJson(res, 500, { error: String(error.message || error) });
|
||||
}
|
||||
})();
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (req.method === 'POST' && pathname === '/api/import/pointercrate') {
|
||||
if (!requireAdmin(req, res)) return;
|
||||
fetchPointercrateRecords()
|
||||
|
||||
+11
@@ -55,6 +55,17 @@ linear-gradient(180deg,rgba(6,16,33,0.98),rgba(7,20,38,0.99))}
|
||||
.admin-password-field input,.admin-actions input[type=text],.admin-actions input[type=password]{min-width:220px;padding:10px 12px;border-radius:10px;border:1px solid rgba(255,255,255,0.08);background:rgba(255,255,255,0.03);color:var(--text)}
|
||||
.admin-toolbar{display:flex;justify-content:space-between;gap:18px;align-items:flex-end;margin-bottom:18px}
|
||||
.admin-toolbar h2{margin:0 0 8px 0}
|
||||
.admin-import-actions{flex-wrap:wrap;justify-content:flex-end}
|
||||
.bulk-approve-modal[hidden]{display:none !important}
|
||||
.bulk-approve-modal-card{max-width:480px}
|
||||
.bulk-approve-modal-card h2{margin:0 0 8px 0;font-size:clamp(1.35rem,3vw,1.75rem)}
|
||||
.bulk-approve-form{margin-top:8px}
|
||||
.bulk-approve-actions{grid-template-columns:repeat(auto-fit,minmax(140px,1fr))}
|
||||
.import-targeted-mode{display:flex;flex-wrap:wrap;align-items:center;gap:12px 18px;margin:4px 0 8px}
|
||||
.import-targeted-mode-label{font-size:0.88rem;font-weight:700;color:var(--muted)}
|
||||
.import-targeted-radio{display:inline-flex;align-items:center;gap:8px;cursor:pointer;font-size:0.95rem}
|
||||
.import-targeted-radio input{accent-color:var(--accent)}
|
||||
.import-targeted-hint{margin:0 0 4px;line-height:1.45}
|
||||
.admin-actions{display:flex;flex-wrap:wrap;gap:10px;align-items:center}
|
||||
.admin-table td:last-child{text-align:center}
|
||||
.run-admin-cell{display:grid;gap:6px}
|
||||
|
||||
Reference in new issue
Block a user