Herden/Gang-System + Online-Praesenz

- V11-Tabellen genutzt: Gruppen gruenden/beitreten/verlassen (group_create/join/leave)
- Praesenz: last_seen + current_room werden bei state-Polls gesetzt, heartbeat fuer Landing
- groups_my liefert Mitglieder mit Online-Status und aktueller Lobby
- index.html: 'Deine Herde'-Sektion (nur eingeloggt) mit Live-Uebersicht + 20s-Polling

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
danny 2026-06-15 06:39:27 +02:00
parent 6b21658a70
commit f22007003a
2 changed files with 175 additions and 1 deletions

80
api.php
View file

@ -459,6 +459,11 @@ try {
$code = slugCode((string) ($_GET['code'] ?? ''));
// Update activity timestamp so room stays alive while anyone polls
$pdo->prepare('UPDATE gtl_rooms SET updated_at=? WHERE code=?')->execute([$now, $code]);
// Präsenz für die Herden-Übersicht: dieser User ist gerade in diesem Raum
if ($authUserId) {
$pdo->prepare('UPDATE gtl_users SET last_seen=?, current_room=? WHERE id=?')
->execute([$now, $code, $authUserId]);
}
// Lazy cleanup: delete rooms inactive for 12+ hours
$pdo->exec('DELETE FROM gtl_rooms WHERE updated_at < ' . ($now - 43200));
// Admin spectators keep seeing imposters while polling (flag set via admin_spectate)
@ -943,6 +948,81 @@ try {
respond(['ok' => true]);
break;
// ── Präsenz-Heartbeat (Landing): online, aber in keinem Raum ──
case 'heartbeat':
if ($authUserId) {
$pdo->prepare('UPDATE gtl_users SET last_seen=?, current_room=NULL WHERE id=?')
->execute([$now, $authUserId]);
}
respond(['ok' => true]);
break;
// ── Herden / Gang-System ──────────────────────────────────────
case 'group_create':
if (!$authUserId) respond(['error' => 'Bitte erst einloggen.'], 401);
$body = input();
$gname = substr(trim((string) ($body['name'] ?? '')), 0, 60);
if ($gname === '') respond(['error' => 'Gruppenname erforderlich.'], 400);
$pdo->prepare('INSERT INTO gtl_groups (group_name, created_by, created_at) VALUES (?,?,?)')
->execute([$gname, $authUserId, $now]);
$gid = (int) $pdo->lastInsertId();
$pdo->prepare('INSERT IGNORE INTO gtl_group_members (group_id, user_id, joined_at) VALUES (?,?,?)')
->execute([$gid, $authUserId, $now]);
respond(['ok' => true, 'id' => $gid]);
break;
case 'group_join':
if (!$authUserId) respond(['error' => 'Bitte erst einloggen.'], 401);
$body = input();
$gname = substr(trim((string) ($body['name'] ?? '')), 0, 60);
$gs = $pdo->prepare('SELECT id FROM gtl_groups WHERE group_name = ? ORDER BY id ASC LIMIT 1');
$gs->execute([$gname]);
$gid = (int) ($gs->fetchColumn() ?: 0);
if (!$gid) respond(['error' => 'Herde nicht gefunden.'], 404);
$pdo->prepare('INSERT IGNORE INTO gtl_group_members (group_id, user_id, joined_at) VALUES (?,?,?)')
->execute([$gid, $authUserId, $now]);
respond(['ok' => true, 'id' => $gid]);
break;
case 'group_leave':
if (!$authUserId) respond(['error' => 'Bitte erst einloggen.'], 401);
$body = input();
$gid = (int) ($body['id'] ?? 0);
$pdo->prepare('DELETE FROM gtl_group_members WHERE group_id=? AND user_id=?')
->execute([$gid, $authUserId]);
respond(['ok' => true]);
break;
case 'groups_my':
if (!$authUserId) respond(['ok' => true, 'groups' => []]);
$gq = $pdo->prepare(
'SELECT g.id, g.group_name FROM gtl_groups g
JOIN gtl_group_members m ON m.group_id = g.id
WHERE m.user_id = ? ORDER BY g.group_name ASC'
);
$gq->execute([$authUserId]);
$groups = $gq->fetchAll();
$mq = $pdo->prepare(
'SELECT u.username, u.last_seen, u.current_room, u.color
FROM gtl_group_members gm JOIN gtl_users u ON u.id = gm.user_id
WHERE gm.group_id = ? ORDER BY u.username ASC'
);
$online = $now - 40;
foreach ($groups as &$g) {
$mq->execute([(int) $g['id']]);
$g['members'] = array_map(function ($m) use ($online) {
return [
'username' => $m['username'],
'color' => $m['color'],
'online' => ((int) ($m['last_seen'] ?? 0)) >= $online,
'room' => $m['current_room'],
];
}, $mq->fetchAll());
}
unset($g);
respond(['ok' => true, 'groups' => $groups]);
break;
default:
respond(['error' => 'Unbekannte Aktion.'], 400);
}

View file

@ -149,6 +149,25 @@
.cookie .btn{font-size:14px;padding:11px 18px}
.hidden{display:none!important}
/* Deine Herde */
.herd-actions{display:flex;gap:10px;max-width:520px;margin:0 auto 26px;flex-wrap:wrap}
.herd-actions input{flex:1;min-width:180px;background:#fff;border:1.5px solid var(--line);
border-radius:999px;padding:12px 18px;font-size:15px;font-family:inherit;outline:none;color:var(--text)}
.herd-actions input:focus{border-color:var(--accent-deep)}
.herd-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:16px}
.herd-card{background:#fff;border:1px solid var(--line);border-radius:var(--radius);padding:20px;box-shadow:var(--shadow)}
.herd-card-head{display:flex;align-items:center;justify-content:space-between;margin-bottom:12px}
.herd-card-head h3{font-size:18px;color:var(--navy)}
.herd-leave{background:transparent;border:none;color:var(--muted);font-size:12px;font-weight:600;cursor:pointer}
.herd-leave:hover{color:#c0392b}
.herd-member{display:flex;align-items:center;gap:10px;padding:7px 0;border-top:1px solid var(--line);font-size:14px}
.herd-member:first-of-type{border-top:none}
.herd-dot{width:9px;height:9px;border-radius:50%;flex-shrink:0;background:#c2cad8}
.herd-dot.on{background:var(--accent);box-shadow:0 0 0 3px rgba(62,204,92,.2)}
.herd-name{font-weight:700}
.herd-status{margin-left:auto;font-size:12.5px;color:var(--muted)}
.herd-status.playing{color:var(--accent-deep);font-weight:700}
/* Icons (Lucide) */
svg.lucide{width:18px;height:18px;stroke-width:2;vertical-align:-3px;flex-shrink:0}
.hero-meta .lucide{width:16px;height:16px}
@ -264,6 +283,23 @@
</div>
</section> -->
<!-- DEINE HERDE (nur eingeloggt) -->
<section id="herdSection" class="sec-soft hidden">
<div class="wrap">
<div class="sec-head">
<div class="sec-tag">Deine Herde</div>
<h2>Wer aus deiner Crew ist gerade da?</h2>
<p>Gründe eine Herde oder tritt einer bei – seht in Echtzeit, wer online ist und in welcher Lobby zockt.</p>
</div>
<div class="herd-actions">
<input id="herdName" placeholder="Herden-Name…" maxlength="60" autocomplete="off">
<button class="btn btn-primary" onclick="Herd.create()">Gründen</button>
<button class="btn btn-ghost" onclick="Herd.join()">Beitreten</button>
</div>
<div id="herdList"><p style="text-align:center;color:var(--muted);font-size:14px">Lade…</p></div>
</div>
</section>
<!-- CTA -->
<section>
<div class="wrap">
@ -314,7 +350,7 @@
function bsbGalleryFail(img){ const f=img.closest('figure'); if(f){ f.classList.add('empty'); f.innerHTML='<i data-lucide="image"></i><span>Bild hier ablegen</span>'; renderIcons(); } }
renderIcons();
// Auth-aware nav (Login bleibt Pflicht zum Spielen)
// Auth-aware nav (Login bleibt Pflicht zum Spielen) + Herde
(async () => {
try {
const r = await fetch('auth.php?action=me');
@ -322,10 +358,68 @@
if (d && d.user) {
document.getElementById('navProfile').classList.remove('hidden');
document.getElementById('navLogin').classList.add('hidden');
document.getElementById('herdSection').classList.remove('hidden');
Herd.init();
}
} catch (e) {}
})();
// ── Deine Herde (Gruppen + Online-Präsenz) ──
const Herd = (() => {
const $ = id => document.getElementById(id);
const esc = s => (s||'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
async function api(action, body){
const opt = body ? {method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)} : {};
const r = await fetch('api.php?action='+action, opt);
return r.json();
}
function render(groups){
const wrap = $('herdList');
if(!groups || !groups.length){
wrap.innerHTML = '<p style="text-align:center;color:var(--muted);font-size:14px">Noch keine Herde – gründe oder tritt einer bei. 🐑</p>';
return;
}
wrap.innerHTML = '<div class="herd-grid">'+groups.map(g => `
<div class="herd-card">
<div class="herd-card-head">
<h3>${esc(g.group_name)}</h3>
<button class="herd-leave" onclick="Herd.leave(${parseInt(g.id)})">verlassen</button>
</div>
${(g.members||[]).map(m => {
const status = m.online ? (m.room ? `in Lobby ${esc(m.room)}` : 'online') : 'offline';
return `<div class="herd-member">
<span class="herd-dot ${m.online?'on':''}"></span>
<span class="herd-name" style="color:${m.color||'var(--navy)'}">${esc(m.username)}</span>
<span class="herd-status ${m.online&&m.room?'playing':''}">${status}</span>
</div>`;
}).join('')}
</div>`).join('')+'</div>';
}
async function load(){
try{ const d = await api('groups_my'); render(d.groups||[]); }catch(e){}
}
async function create(){
const name = $('herdName').value.trim();
if(!name) return;
try{ const d = await api('group_create',{name}); if(d.error){alert(d.error);return;} $('herdName').value=''; load(); }catch(e){}
}
async function join(){
const name = $('herdName').value.trim();
if(!name) return;
try{ const d = await api('group_join',{name}); if(d.error){alert(d.error);return;} $('herdName').value=''; load(); }catch(e){}
}
async function leave(id){
try{ await api('group_leave',{id}); load(); }catch(e){}
}
function init(){
load();
// Heartbeat: hält den eigenen Online-Status auf der Landing aktuell
fetch('api.php?action=heartbeat');
setInterval(()=>{ fetch('api.php?action=heartbeat'); load(); }, 20000);
}
return { init, create, join, leave };
})();
// Cookie banner
const Cookie = (() => {
const KEY = 'bsb_cookie_consent';