Gear planner import: follow all pages of an aion2hub list, /database takes weapons, armor and accessories

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Maaxxs 2026-09-22 09:34:55 +02:00
parent 5dabbccbd7
commit 92cd48f478
5 changed files with 218 additions and 71 deletions

View file

@ -64,9 +64,14 @@ include __DIR__ . '/../includes/header.php';
<h2>Übernehmen</h2>
<p class="text-muted">
Gegenstands-ID, Link zu einem Gegenstand (<code>aion2hub.com/database/items/110130060</code>) oder
eine Listen-Seite (z.B. <code>aion2hub.com/database?cat=Armor&amp;grade=Unique</code> - übernimmt
alle Gegenstände dieser Seite, bis zu 60).
eine Liste - dann werden <strong>alle Seiten</strong> der Liste übernommen:
</p>
<ul class="text-muted gear-import-examples">
<li><code>aion2hub.com/database</code> - alle Waffen, Rüstungen und Schmuckstücke (rund 3.600, dauert gut eine Stunde)</li>
<li><code>aion2hub.com/database?grade=Unique</code> - nur eine Seltenheit, in allen drei Kategorien</li>
<li><code>aion2hub.com/database?cat=Armor&amp;grade=Heroic</code> - eine Kategorie mit Seltenheit</li>
</ul>
<p class="text-muted">Tränke, Materialien, Skins usw. werden nicht übernommen, nur Ausrüstung.</p>
<div class="gear-import-row">
<input type="text" id="gear-import-input" placeholder="ID oder aion2hub-Link …" aria-label="ID oder aion2hub-Link">
<label class="checkbox-label"><input type="checkbox" id="gear-import-skip" checked> schon vorhandene überspringen</label>

View file

@ -38,23 +38,28 @@ $politePause = static function (): void {
try {
switch ($action) {
case 'list':
// Listen-Seite von aion2hub (z.B. database?cat=Armor&grade=Unique&page=2) -> enthaltene IDs
$url = trim((string) ($_POST['url'] ?? ''));
$single = gear_source_parse_id($url);
case 'plan':
// Was steckt hinter der Eingabe? Ein einzelner Gegenstand oder Listen je Kategorie.
$input = trim((string) ($_POST['url'] ?? ''));
$single = gear_source_parse_id($input);
if ($single !== null) {
$respond(['ok' => true, 'ids' => [$single]]);
$respond(['ok' => true, 'ids' => [$single], 'known' => gear_item($single) ? [$single] : []]);
}
if (!preg_match('#^https://(www\.)?aion2hub\.com/database(\?|$)#i', $url)) {
$respond(['ok' => false, 'error' => 'Bitte eine Gegenstands-ID, einen Gegenstands-Link oder eine Listen-Seite von aion2hub.com/database eintragen.'], 400);
$respond(['ok' => true, 'lists' => gear_source_list_urls($input)]);
case 'list':
// Eine Seite einer Liste (Adresse aus "plan") -> enthaltene IDs und Seitenzahl
$url = trim((string) ($_POST['url'] ?? ''));
$page = max(1, (int) ($_POST['page'] ?? 1));
if (!in_array($url, gear_source_list_urls($url), true)) {
$respond(['ok' => false, 'error' => 'Ungültige Listen-Adresse.'], 400);
}
$politePause();
$ids = gear_source_list_ids(gear_source_fetch($url));
if (!$ids) {
$respond(['ok' => false, 'error' => 'Auf dieser Seite wurden keine Gegenstände gefunden.'], 404);
}
$known = db()->query('SELECT id FROM gear_items')->fetchAll(PDO::FETCH_COLUMN);
$respond(['ok' => true, 'ids' => $ids, 'known' => array_map('intval', array_values(array_intersect($known, $ids)))]);
$result = gear_source_list_page(gear_source_fetch($url . '&page=' . $page));
$known = $result['ids']
? db()->query('SELECT id FROM gear_items WHERE id IN (' . implode(',', $result['ids']) . ')')->fetchAll(PDO::FETCH_COLUMN)
: [];
$respond(['ok' => true, 'known' => array_map('intval', $known)] + $result);
case 'import':
case 'check':

View file

@ -5418,6 +5418,9 @@ strong.grade-common, strong.grade-rare, strong.grade-epic, strong.grade-unique,
/* Admin: Katalog */
.gear-import { margin-top: 1rem; padding: 1rem 1.1rem; border: 1px solid var(--border); border-radius: 8px; background: rgba(255, 255, 255, 0.025); }
.gear-import h2 { margin: 0 0 0.3rem; font-size: 1.1rem; }
.gear-import p { margin: 0.3rem 0; }
.gear-import-examples { margin: 0.3rem 0; padding-left: 1.2rem; font-size: 0.88rem; }
.gear-import-examples li { margin: 0.15rem 0; }
.gear-import-row { display: flex; flex-wrap: wrap; gap: 0.6rem; align-items: center; margin-top: 0.75rem; }
.gear-import-row input[type="text"] { flex: 1 1 320px; width: auto; min-width: 0; }
.gear-import-progress { margin-top: 1rem; }

View file

@ -67,69 +67,154 @@
stopRequested = false;
}
/** IDs nacheinander abarbeiten; kind = 'import' oder 'check'. */
function run(ids, kind, source) {
var counts = { added: 0, changed: 0, same: 0, failed: 0 };
var apply = kind === 'import' || (applyBox && applyBox.checked);
var index = 0;
var CATEGORY_LABELS = { Weapons: 'Waffen', Armor: 'Rüstungen', Accessories: 'Schmuck' };
/** Zustand eines Durchlaufs; kind = 'import' oder 'check'. */
function newRun(kind, source, total) {
setBusy(true);
progress.hidden = false;
log.innerHTML = '';
function next() {
fill.style.width = (ids.length ? Math.round(index / ids.length * 100) : 100) + '%';
progressText.textContent = index + ' von ' + ids.length + ' · neu ' + counts.added + ' · geändert ' + counts.changed
+ ' · unverändert ' + counts.same + (counts.failed ? ' · Fehler ' + counts.failed : '');
if (index >= ids.length || stopRequested) {
if (stopRequested) addLog('Angehalten.', 'info');
setBusy(false);
if (ids.length > 1 && index > 0) {
post({ action: 'batch_done', kind: kind, 'new': counts.added, changed: counts.changed, same: counts.same, failed: counts.failed, source: source || '' });
}
if (counts.added || (apply && counts.changed)) {
addLog('Fertig - Seite neu laden, um die Liste zu aktualisieren.', 'info');
}
return;
}
var id = ids[index++];
post({ action: kind, id: id, batch: ids.length > 1 ? 1 : '', apply: apply ? 1 : '' }).then(function (result) {
if (!result.ok) {
counts.failed++;
addLog('#' + id + ': ' + result.error, 'error');
} else if (result['new']) {
counts.added++;
addLog(result.name + ' übernommen', 'new');
} else if (result.diffs.length) {
counts.changed++;
addLog(result.name + (result.applied ? ' aktualisiert' : ' hat Änderungen (nicht übernommen)'), 'changed', result.diffs);
} else {
counts.same++;
if (ids.length === 1) addLog(result.name + ' ist aktuell - keine Änderungen.', 'same');
}
next();
});
}
next();
return {
kind: kind,
source: source || '',
apply: kind === 'import' || (applyBox && applyBox.checked),
total: total,
done: 0,
label: '',
counts: { added: 0, changed: 0, same: 0, skipped: 0, failed: 0 }
};
}
startButton.addEventListener('click', function () {
function showProgress(run) {
var c = run.counts;
fill.style.width = (run.total ? Math.min(100, Math.round(run.done / run.total * 100)) : 0) + '%';
progressText.textContent = (run.label ? run.label + ' · ' : '') + run.done + ' von ' + run.total
+ ' · neu ' + c.added + ' · geändert ' + c.changed + ' · unverändert ' + c.same
+ (c.skipped ? ' · übersprungen ' + c.skipped : '') + (c.failed ? ' · Fehler ' + c.failed : '');
}
/** Gegenstaende nacheinander uebernehmen bzw. abgleichen. */
async function processIds(run, ids) {
for (var i = 0; i < ids.length && !stopRequested; i++) {
var id = ids[i];
var result = await post({ action: run.kind, id: id, batch: run.total > 1 ? 1 : '', apply: run.apply ? 1 : '' });
if (!result.ok) {
run.counts.failed++;
addLog('#' + id + ': ' + result.error, 'error');
} else if (result['new']) {
run.counts.added++;
addLog(result.name + ' übernommen', 'new');
} else if (result.diffs.length) {
run.counts.changed++;
addLog(result.name + (result.applied ? ' aktualisiert' : ' hat Änderungen (nicht übernommen)'), 'changed', result.diffs);
} else {
run.counts.same++;
if (run.total === 1) addLog(result.name + ' ist aktuell - keine Änderungen.', 'same');
}
run.done++;
showProgress(run);
}
}
function finishRun(run) {
var c = run.counts;
if (stopRequested) addLog('Angehalten.', 'info');
setBusy(false);
showProgress(run);
if (run.total > 1 && (c.added || c.changed || c.same || c.failed)) {
post({ action: 'batch_done', kind: run.kind, 'new': c.added, changed: c.changed, same: c.same, failed: c.failed, source: run.source });
}
if (c.added || (run.apply && c.changed)) {
addLog('Fertig - Seite neu laden, um die Liste zu aktualisieren.', 'info');
} else if (!c.failed && !stopRequested && c.skipped === run.done && run.done > 0) {
addLog('Alles schon im Katalog - nichts Neues gefunden.', 'same');
}
}
/** Feste Liste von IDs (einzelner Gegenstand, "Alle abgleichen"). */
async function runIds(ids, kind, source) {
var run = newRun(kind, source, ids.length);
showProgress(run);
await processIds(run, ids);
finishRun(run);
}
/**
* Listen von aion2hub Seite fuer Seite: erst die erste Seite jeder Kategorie (Gesamtzahl fuer
* Fortschritt und Rueckfrage), dann jede Seite laden und ihre Gegenstaende gleich uebernehmen.
*/
async function runLists(lists, source) {
var run = newRun('import', source, 0);
progressText.textContent = 'Listen werden gelesen …';
var firsts = [];
for (var i = 0; i < lists.length && !stopRequested; i++) {
var first = await post({ action: 'list', url: lists[i], page: 1 });
if (!first.ok) {
addLog(first.error, 'error');
continue;
}
firsts.push({ url: lists[i], page: first });
run.total += first.total;
}
if (!firsts.length || stopRequested) {
finishRun(run);
return;
}
var pageCount = firsts.reduce(function (sum, f) { return sum + f.page.pages; }, 0);
if (run.total > 100 && !window.confirm(run.total + ' Gegenstände auf ' + pageCount + ' Seiten gefunden'
+ (skipKnown.checked ? ' (schon vorhandene werden übersprungen)' : '') + '.\n\nIn voller Länge dauert das etwa '
+ Math.ceil((run.total + pageCount) * 1.3 / 60) + ' Minuten - die Seite muss so lange offen bleiben (Anhalten geht jederzeit). Starten?')) {
setBusy(false);
progress.hidden = true;
return;
}
for (var f = 0; f < firsts.length && !stopRequested; f++) {
var category = (firsts[f].url.match(/[?&]cat=([^&]+)/) || [])[1] || '';
var result = firsts[f].page;
for (var page = 1; page <= result.pages && !stopRequested; page++) {
if (page > 1) {
result = await post({ action: 'list', url: firsts[f].url, page: page });
if (!result.ok) {
addLog((CATEGORY_LABELS[category] || category) + ', Seite ' + page + ': ' + result.error, 'error');
continue;
}
}
run.label = (CATEGORY_LABELS[category] || category) + ' · Seite ' + page + '/' + result.pages;
var known = result.known || [];
var ids = result.ids;
if (skipKnown.checked) {
ids = ids.filter(function (id) { return known.indexOf(id) === -1; });
run.counts.skipped += result.ids.length - ids.length;
run.done += result.ids.length - ids.length;
}
showProgress(run);
await processIds(run, ids);
}
}
run.label = '';
finishRun(run);
}
startButton.addEventListener('click', async function () {
var value = input.value.trim();
if (!value || running) return;
startButton.disabled = true;
post({ action: 'list', url: value }).then(function (result) {
startButton.disabled = false;
if (!result.ok) {
showMessage(result.error, 'error');
return;
}
var known = result.known || [];
var ids = skipKnown.checked ? result.ids.filter(function (id) { return known.indexOf(id) === -1; }) : result.ids;
if (!ids.length) {
showMessage(result.ids.length === 1 ? 'Dieser Gegenstand ist schon im Katalog - „Abgleichen“ in der Liste prüft ihn.' : 'Alle ' + result.ids.length + ' Gegenstände sind schon im Katalog.', 'same');
return;
}
run(ids, 'import', value);
});
var plan = await post({ action: 'plan', url: value });
startButton.disabled = false;
if (!plan.ok) {
showMessage(plan.error, 'error');
return;
}
if (plan.lists) {
runLists(plan.lists, value);
return;
}
if (skipKnown.checked && plan.known.length) {
showMessage('Dieser Gegenstand ist schon im Katalog - „Abgleichen“ in der Liste prüft ihn.', 'same');
return;
}
runIds(plan.ids, 'import', value);
});
input.addEventListener('keydown', function (event) {
if (event.key === 'Enter') {
@ -144,7 +229,7 @@
if (!ids.length || running) return;
var minutes = Math.ceil(ids.length * 1.3 / 60);
if (ids.length > 30 && !window.confirm(ids.length + ' Gegenstände abgleichen? Das dauert etwa ' + minutes + ' Minuten - die Seite muss so lange offen bleiben.')) return;
run(ids, 'check', 'alle');
runIds(ids, 'check', 'alle');
});
}
stopButton.addEventListener('click', function () { stopRequested = true; });

View file

@ -62,6 +62,9 @@ function gear_source_parse_id(string $input): ?int
return null;
}
// Kategorien der Datenbank, die der Gear-Planer kennt (Listen ohne Kategorie = alle drei)
const GEAR_SOURCE_CATEGORIES = ['Weapons', 'Armor', 'Accessories'];
/** Alle Gegenstands-IDs, die auf einer Listenseite von aion2hub verlinkt sind. */
function gear_source_list_ids(string $html): array
{
@ -69,6 +72,52 @@ function gear_source_list_ids(string $html): array
return array_values(array_unique(array_map('intval', $m[1])));
}
/**
* Listen-Adresse (aion2hub.com/database?...) in die Listen je Kategorie aufteilen. Ohne
* Kategorie werden es Waffen, Ruestungen und Schmuck; weitere Filter (z.B. grade) bleiben.
*
* @return string[] Adressen ohne Seitenzahl
* @throws RuntimeException bei fremden Adressen oder Kategorien ohne Ausruestung
*/
function gear_source_list_urls(string $url): array
{
if (!preg_match('#^https://(www\.)?aion2hub\.com/database/?(\?.*)?$#i', trim($url))) {
throw new RuntimeException('Bitte eine Gegenstands-ID, einen Gegenstands-Link oder eine Listen-Seite von aion2hub.com/database eintragen.');
}
parse_str((string) parse_url(trim($url), PHP_URL_QUERY), $query);
unset($query['page'], $query['view']);
$query = array_filter($query, static fn ($value): bool => is_string($value) && $value !== '');
$categories = isset($query['cat']) ? [(string) $query['cat']] : GEAR_SOURCE_CATEGORIES;
foreach ($categories as $category) {
if (!in_array($category, GEAR_SOURCE_CATEGORIES, true)) {
throw new RuntimeException('Die Kategorie „' . $category . '“ enthält keine Ausrüstung - nur Weapons, Armor und Accessories lassen sich übernehmen.');
}
}
return array_map(
static fn (string $category): string => 'https://' . GEAR_SOURCE_HOST . '/database?' . http_build_query(['cat' => $category] + $query),
$categories
);
}
/**
* Eine Seite einer Liste: enthaltene IDs, Seitenzahl und Gesamtzahl ("1,844 items · page 1 of 31").
*
* @return array{ids: int[], page: int, pages: int, total: int}
*/
function gear_source_list_page(string $html): array
{
$text = implode(' ', gear_source_tokens($html));
preg_match('/page\s+(\d+)\s+of\s+(\d+)/i', $text, $pages);
preg_match('/([\d,]+)\s+items\s+·\s+page/i', $text, $total);
$ids = gear_source_list_ids($html);
return [
'ids' => $ids,
'page' => (int) ($pages[1] ?? 1),
'pages' => max(1, (int) ($pages[2] ?? 1)),
'total' => (int) str_replace(',', '', $total[1] ?? (string) count($ids)),
];
}
/** Seite in Textbausteine zerlegen (jedes HTML-Element wird zur Trennstelle). */
function gear_source_tokens(string $html): array
{