version 0.8.0
This commit is contained in:
parent
f22007003a
commit
e5ca9ef194
95 changed files with 5601 additions and 4042 deletions
252
public/assets/js/admin.js
Normal file
252
public/assets/js/admin.js
Normal file
|
|
@ -0,0 +1,252 @@
|
|||
/* Black Sheep Bluff – admin.php – ausgelagertes JS */
|
||||
const Admin = (() => {
|
||||
const $ = id => document.getElementById(id);
|
||||
const COLORS = ['#3ECC5C','#4A5BE8','#5DCAA5','#ffcf6e','#65DC7A','#85B7EB','#D4537E','#97C459'];
|
||||
const colorFor = s => { let h=0; for(const c of (s||''))h=(h*31+c.charCodeAt(0))>>>0; return COLORS[h%COLORS.length]; };
|
||||
const initials = s => (s||'?').trim().split(/\s+/).map(w=>w[0]).join('').slice(0,2).toUpperCase();
|
||||
const esc = s => (s||'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
||||
|
||||
function err(msg) { const e=$('errBox'); e.textContent=msg; e.classList.remove('hidden'); setTimeout(()=>e.classList.add('hidden'),4500); }
|
||||
function ok(msg) { const e=$('okBox'); e.textContent=msg; e.classList.remove('hidden'); setTimeout(()=>e.classList.add('hidden'),3000); }
|
||||
|
||||
async function init() {
|
||||
const res = await fetch('/api/auth/me');
|
||||
const data = await res.json();
|
||||
if (!data.user || data.user.role !== 'admin') {
|
||||
window.location.href = '/login';
|
||||
return;
|
||||
}
|
||||
await loadUsers();
|
||||
await loadAds();
|
||||
await loadAssets();
|
||||
}
|
||||
|
||||
function fileToBase64(file){ return new Promise((res,rej)=>{ const r=new FileReader(); r.onload=()=>res(r.result); r.onerror=rej; r.readAsDataURL(file); }); }
|
||||
|
||||
async function loadAssets(){
|
||||
try{
|
||||
const res=await fetch('/api/assets'); const d=await res.json();
|
||||
if(!d||!d.ok) return;
|
||||
const sw=$('soundListWrap');
|
||||
if(sw) sw.innerHTML=(d.sounds&&d.sounds.length)? d.sounds.map(s=>`
|
||||
<div class="asset-row">
|
||||
<span class="asset-main">🔊 ${esc(s.label)}</span>
|
||||
<audio src="${esc(s.file)}" controls preload="none" style="height:30px;max-width:160px"></audio>
|
||||
<button class="danger sm" onclick="Admin.deleteSound(${parseInt(s.id)})">✕</button>
|
||||
</div>`).join('') : '<p class="empty">Keine Sounds.</p>';
|
||||
const rw=$('reactionListWrap');
|
||||
if(rw) rw.innerHTML=(d.reactions&&d.reactions.length)? d.reactions.map(x=>`
|
||||
<div class="asset-row">
|
||||
<span class="asset-main">${x.emoji?`<span style="font-size:24px">${esc(x.emoji)}</span>`:`<img src="${esc(x.image)}" style="width:34px;height:34px;object-fit:contain">`}</span>
|
||||
<button class="danger sm" onclick="Admin.deleteReaction(${parseInt(x.id)})">✕</button>
|
||||
</div>`).join('') : '<p class="empty">Keine Reaktionen.</p>';
|
||||
const stw=$('stickerListWrap');
|
||||
if(stw) stw.innerHTML=(d.stickers&&d.stickers.length)? d.stickers.map(s=>`
|
||||
<div class="asset-row">
|
||||
<img src="${esc(s.file)}" style="width:42px;height:42px;object-fit:contain">
|
||||
<span class="asset-main">${esc(s.label)}</span>
|
||||
<button class="danger sm" onclick="Admin.deleteSticker(${parseInt(s.id)})">✕</button>
|
||||
</div>`).join('') : '<p class="empty">Keine Sticker.</p>';
|
||||
}catch(e){}
|
||||
}
|
||||
|
||||
async function createSound(){
|
||||
const label=$('soundLabel').value.trim(); const f=$('soundFile').files[0];
|
||||
if(!label){ err('Bezeichnung eingeben.'); return; }
|
||||
if(!f){ err('Audio-Datei wählen.'); return; }
|
||||
try{
|
||||
const fileBase64=await fileToBase64(f);
|
||||
const res=await fetch('/api/sound_create',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({label,fileBase64})});
|
||||
const d=await res.json(); if(!res.ok||d.error){ err(d.error||'Fehler'); return; }
|
||||
$('soundLabel').value=''; $('soundFile').value=''; ok('Sound hinzugefügt.'); await loadAssets();
|
||||
}catch(e){ err('Fehler.'); }
|
||||
}
|
||||
async function deleteSound(id){ if(!confirm('Sound löschen?'))return; try{ await fetch('/api/sound_delete',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({id})}); await loadAssets(); }catch(e){} }
|
||||
|
||||
async function createReaction(){
|
||||
const emoji=$('reactionEmoji').value.trim(); const f=$('reactionImage').files[0];
|
||||
if(!emoji && !f){ err('Emoji oder Bild angeben.'); return; }
|
||||
try{
|
||||
const payload = emoji ? {emoji} : {imageBase64:await fileToBase64(f)};
|
||||
const res=await fetch('/api/reaction_create',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});
|
||||
const d=await res.json(); if(!res.ok||d.error){ err(d.error||'Fehler'); return; }
|
||||
$('reactionEmoji').value=''; $('reactionImage').value=''; ok('Reaktion hinzugefügt.'); await loadAssets();
|
||||
}catch(e){ err('Fehler.'); }
|
||||
}
|
||||
async function deleteReaction(id){ if(!confirm('Reaktion löschen?'))return; try{ await fetch('/api/reaction_delete',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({id})}); await loadAssets(); }catch(e){} }
|
||||
|
||||
async function createSticker(){
|
||||
const label=$('stickerLabel').value.trim(); const f=$('stickerImage').files[0];
|
||||
if(!label){ err('Bezeichnung eingeben.'); return; }
|
||||
if(!f){ err('Bild wählen.'); return; }
|
||||
try{
|
||||
const imageBase64=await fileToBase64(f);
|
||||
const res=await fetch('/api/sticker_create',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({label,imageBase64})});
|
||||
const d=await res.json(); if(!res.ok||d.error){ err(d.error||'Fehler'); return; }
|
||||
$('stickerLabel').value=''; $('stickerImage').value=''; ok('Sticker hinzugefügt.'); await loadAssets();
|
||||
}catch(e){ err('Fehler.'); }
|
||||
}
|
||||
async function deleteSticker(id){ if(!confirm('Sticker löschen?'))return; try{ await fetch('/api/sticker_delete',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({id})}); await loadAssets(); }catch(e){} }
|
||||
|
||||
async function loadAds() {
|
||||
try {
|
||||
const res = await fetch('/api/fake_ads_all');
|
||||
const data = await res.json();
|
||||
const wrap = $('adListWrap');
|
||||
if (!data.ads || !data.ads.length) { wrap.innerHTML = '<p class="empty">Noch keine Fake-Anzeigen.</p>'; return; }
|
||||
wrap.innerHTML = data.ads.map(a => `
|
||||
<div style="display:flex;align-items:center;gap:12px;padding:10px;border:1px solid var(--line);border-radius:12px;margin-bottom:8px">
|
||||
<img src="${esc(a.image_url)}" alt="" style="width:54px;height:54px;object-fit:cover;border-radius:8px;background:var(--bg2)" onerror="this.style.opacity=.3">
|
||||
<div style="flex:1;min-width:0">
|
||||
<div style="font-size:12px;color:var(--muted);word-break:break-all">${esc(a.image_url)}</div>
|
||||
<div style="font-size:11px;color:var(--muted)">${a.target_url?('→ '+esc(a.target_url)):'kein Ziel'} · ${parseInt(a.is_active)?'<span style="color:var(--accent2)">aktiv</span>':'inaktiv'}</div>
|
||||
</div>
|
||||
<button class="ghost sm" onclick="Admin.toggleAd(${parseInt(a.id)})">${parseInt(a.is_active)?'Aus':'An'}</button>
|
||||
<button class="danger sm" onclick="Admin.deleteAd(${parseInt(a.id)})">✕</button>
|
||||
</div>`).join('');
|
||||
} catch(e) { $('adListWrap').innerHTML = '<p class="empty">Ladefehler.</p>'; }
|
||||
}
|
||||
|
||||
async function createAd() {
|
||||
const image_url = $('adImage').value.trim();
|
||||
const target_url = $('adTarget').value.trim();
|
||||
if (!image_url) { err('Bild-URL erforderlich.'); return; }
|
||||
try {
|
||||
const res = await fetch('/api/fake_ad_create', {
|
||||
method:'POST', headers:{'Content-Type':'application/json'},
|
||||
body: JSON.stringify({image_url, target_url})
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok || data.error) { err(data.error||'Fehler'); return; }
|
||||
$('adImage').value=''; $('adTarget').value='';
|
||||
ok('Fake-Anzeige angelegt.'); await loadAds();
|
||||
} catch(e) { err('Fehler.'); }
|
||||
}
|
||||
async function toggleAd(id) {
|
||||
try { await fetch('/api/fake_ad_toggle', {method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({id})}); await loadAds(); }
|
||||
catch(e) { err('Fehler.'); }
|
||||
}
|
||||
async function deleteAd(id) {
|
||||
if (!confirm('Fake-Anzeige löschen?')) return;
|
||||
try { await fetch('/api/fake_ad_delete', {method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({id})}); await loadAds(); }
|
||||
catch(e) { err('Fehler.'); }
|
||||
}
|
||||
|
||||
async function loadUsers() {
|
||||
const res = await fetch('/api/auth/get_users');
|
||||
const data = await res.json();
|
||||
if (!data.users) { err('Ladefehler.'); return; }
|
||||
|
||||
const users = data.users;
|
||||
const noPIN = users.filter(u => parseInt(u.needs_pin_setup) && u.role !== 'admin').length;
|
||||
$('sumUsers').textContent = users.filter(u => u.role !== 'admin').length;
|
||||
$('sumNoPIN').textContent = noPIN;
|
||||
|
||||
const totalGames = users.reduce((s,u)=>s+(parseInt(u.games_played)||0),0);
|
||||
$('sumRounds').textContent = totalGames;
|
||||
|
||||
if (!users.length) {
|
||||
$('userTableWrap').innerHTML = '<p class="empty">Keine User.</p>';
|
||||
return;
|
||||
}
|
||||
|
||||
$('userTableWrap').innerHTML = `<table class="user-table">
|
||||
<thead><tr>
|
||||
<th>User</th><th>Rolle</th><th>Status</th><th>Gespielt</th><th>Gewonnen</th><th>Letzter Login</th><th>Aktionen</th>
|
||||
</tr></thead>
|
||||
<tbody>${users.map(u => {
|
||||
const col = colorFor(u.username);
|
||||
const pin = parseInt(u.needs_pin_setup);
|
||||
const ts = u.last_login ? new Date(u.last_login*1000).toLocaleDateString('de-DE') : '–';
|
||||
const sinc = new Date(u.created_at*1000).toLocaleDateString('de-DE');
|
||||
return `<tr>
|
||||
<td style="display:flex;align-items:center">
|
||||
<div class="av-mini" style="background:${col}">${initials(u.username)}</div>
|
||||
<div>
|
||||
<div class="uname">${esc(u.username)}</div>
|
||||
<div class="meta">Seit ${sinc}</div>
|
||||
</div>
|
||||
</td>
|
||||
<td><span class="badge ${u.role}">${u.role}</span></td>
|
||||
<td>${pin ? '<span class="badge no-pin">PIN fehlt</span>' : '<span class="badge user">Aktiv</span>'}</td>
|
||||
<td>${u.games_played||0}</td>
|
||||
<td>${u.games_won||0}</td>
|
||||
<td style="color:var(--muted);font-size:12px">${ts}</td>
|
||||
<td>
|
||||
<div class="actions">
|
||||
<button class="ghost sm" onclick="Admin.loginAs(${u.id},'${esc(u.username)}')">Anmelden</button>
|
||||
${u.role !== 'admin' && pin===0 ? `<button class="ghost sm" onclick="Admin.resetPIN(${u.id},'${esc(u.username)}')">PIN reset</button>` : ''}
|
||||
${u.role !== 'admin' ? `<button class="danger sm" onclick="Admin.deleteUser(${u.id},'${esc(u.username)}')">Löschen</button>` : ''}
|
||||
</div>
|
||||
</td>
|
||||
</tr>`;
|
||||
}).join('')}</tbody>
|
||||
</table>`;
|
||||
}
|
||||
|
||||
async function createUser() {
|
||||
const username = $('newUsername').value.trim();
|
||||
if (!username) { err('Username eingeben.'); return; }
|
||||
try {
|
||||
const res = await fetch('/api/auth/create_user', {
|
||||
method: 'POST', headers: {'Content-Type':'application/json'},
|
||||
body: JSON.stringify({username})
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok || data.error) { err(data.error || 'Fehler'); return; }
|
||||
ok('User „' + username + '" angelegt! Sie legen beim ersten Login ihren PIN fest.');
|
||||
$('newUsername').value = '';
|
||||
await loadUsers();
|
||||
} catch(e) { err('Fehler.'); }
|
||||
}
|
||||
|
||||
async function resetPIN(uid, uname) {
|
||||
if (!confirm('PIN von „' + uname + '" zurücksetzen? Der User muss beim nächsten Login einen neuen PIN festlegen.')) return;
|
||||
try {
|
||||
const res = await fetch('/api/auth/reset_pin', {
|
||||
method: 'POST', headers: {'Content-Type':'application/json'},
|
||||
body: JSON.stringify({user_id: uid})
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok || data.error) { err(data.error || 'Fehler'); return; }
|
||||
ok('PIN von „' + uname + '" zurückgesetzt.');
|
||||
await loadUsers();
|
||||
} catch(e) { err('Fehler.'); }
|
||||
}
|
||||
|
||||
async function deleteUser(uid, uname) {
|
||||
if (!confirm('User „' + uname + '" wirklich löschen? Alle Statistiken werden gelöscht.')) return;
|
||||
try {
|
||||
const res = await fetch('/api/auth/delete_user', {
|
||||
method: 'POST', headers: {'Content-Type':'application/json'},
|
||||
body: JSON.stringify({user_id: uid})
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok || data.error) { err(data.error || 'Fehler'); return; }
|
||||
ok('User „' + uname + '" gelöscht.');
|
||||
await loadUsers();
|
||||
} catch(e) { err('Fehler.'); }
|
||||
}
|
||||
|
||||
async function loginAs(uid, uname) {
|
||||
if (!confirm('Als „' + uname + '" anmelden? Du wechselst zu diesem Konto. Zurück zum Admin: ausloggen und wieder als Admin anmelden.')) return;
|
||||
try {
|
||||
const res = await fetch('/api/auth/impersonate', {
|
||||
method: 'POST', headers: {'Content-Type':'application/json'},
|
||||
body: JSON.stringify({ user_id: uid })
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok || data.error) { err(data.error || 'Fehler'); return; }
|
||||
window.location.href = '/profile';
|
||||
} catch(e) { err('Fehler.'); }
|
||||
}
|
||||
|
||||
async function logout() {
|
||||
await fetch('/api/auth/logout', {method:'POST'});
|
||||
window.location.href = '/login';
|
||||
}
|
||||
|
||||
init();
|
||||
return { loadUsers, createUser, resetPIN, deleteUser, loginAs, logout, loadAds, createAd, toggleAd, deleteAd,
|
||||
loadAssets, createSound, deleteSound, createReaction, deleteReaction, createSticker, deleteSticker };
|
||||
})();
|
||||
85
public/assets/js/home.js
Normal file
85
public/assets/js/home.js
Normal file
|
|
@ -0,0 +1,85 @@
|
|||
/* ============================================================
|
||||
Startseite – „Deine Herde" (Gruppen + Online-Präsenz)
|
||||
Wird nur für eingeloggte User aktiviert (BSB.onUser).
|
||||
============================================================ */
|
||||
const Herd = (() => {
|
||||
const $ = id => document.getElementById(id);
|
||||
const esc = s => (s || '').replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||
|
||||
const BSB_FONTS = { inter:"Inter", sora:"Sora", pacifico:"Pacifico", lobster:"Lobster", bungee:"Bungee", bangers:"Bangers", orbitron:"Orbitron", pressstart:"'Press Start 2P'" };
|
||||
function nameStyle(u){
|
||||
u = u || {};
|
||||
const c1 = u.color || 'var(--navy)';
|
||||
const st = u.nameStyle || u.name_style || 'solid';
|
||||
const font = BSB_FONTS[u.nameFont || u.name_font] || '';
|
||||
let style = '', cls = '';
|
||||
if (st === 'rainbow') { cls = 'name-rainbow'; }
|
||||
else if (st === 'gradient' && u.color2) { style = `background:linear-gradient(90deg,${c1},${u.color2});-webkit-background-clip:text;background-clip:text;-webkit-text-fill-color:transparent;color:transparent`; }
|
||||
else { style = `color:${c1}`; }
|
||||
if (font) style += `;font-family:${font}`;
|
||||
return { style, cls };
|
||||
}
|
||||
|
||||
async function api(action, body) {
|
||||
const opt = body ? { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) } : {};
|
||||
const r = await fetch('/api/' + 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';
|
||||
const ns = nameStyle(m);
|
||||
return `<div class="herd-member">
|
||||
<span class="herd-dot ${m.online ? 'on' : ''}"></span>
|
||||
<span class="herd-name ${ns.cls}" style="${ns.style}">${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/heartbeat');
|
||||
setInterval(() => { fetch('/api/heartbeat'); load(); }, 20000);
|
||||
}
|
||||
return { init, create, join, leave };
|
||||
})();
|
||||
|
||||
// Herde-Sektion nur für eingeloggte User einblenden
|
||||
BSB.onUser(u => {
|
||||
if (u) {
|
||||
const sec = document.getElementById('herdSection');
|
||||
if (sec) sec.classList.remove('hidden');
|
||||
Herd.init();
|
||||
}
|
||||
});
|
||||
100
public/assets/js/login.js
Normal file
100
public/assets/js/login.js
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
/* Black Sheep Bluff – login.php – ausgelagertes JS */
|
||||
const Login = (() => {
|
||||
let currentUser = '';
|
||||
let isAdmin = false;
|
||||
|
||||
const $ = id => document.getElementById(id);
|
||||
const show = (...ids) => ids.forEach(id => $(id).classList.remove('hidden'));
|
||||
const hide = (...ids) => ids.forEach(id => $(id).classList.add('hidden'));
|
||||
const err = msg => { const e=$('errBox'); e.textContent=msg; e.classList.remove('hidden'); };
|
||||
const clearErr = () => $('errBox').classList.add('hidden');
|
||||
|
||||
function updateDots(inputId, dotsId) {
|
||||
const val = $(inputId).value;
|
||||
const wrap = $(dotsId);
|
||||
if (!wrap.children.length) {
|
||||
for (let i = 0; i < 8; i++) {
|
||||
const d = document.createElement('div');
|
||||
d.className = 'pin-dot';
|
||||
wrap.appendChild(d);
|
||||
}
|
||||
}
|
||||
[...wrap.children].forEach((d, i) => d.classList.toggle('filled', i < val.length));
|
||||
}
|
||||
|
||||
async function checkUser() {
|
||||
clearErr();
|
||||
const username = $('usernameInput').value.trim();
|
||||
if (!username) { err('Bitte Username eingeben.'); return; }
|
||||
try {
|
||||
const res = await fetch('/api/auth/check_username?username=' + encodeURIComponent(username));
|
||||
const data = await res.json();
|
||||
if (!res.ok || data.error) { err(data.error || 'Fehler'); return; }
|
||||
currentUser = username;
|
||||
isAdmin = data.is_admin;
|
||||
hide('step1');
|
||||
if (data.needs_pin_setup) {
|
||||
show('step2setup');
|
||||
$('newPinInput').focus();
|
||||
} else if (data.is_admin) {
|
||||
show('step2pass');
|
||||
$('passInput').focus();
|
||||
} else {
|
||||
show('step2pin');
|
||||
$('pinInput').focus();
|
||||
}
|
||||
} catch (e) { err('Verbindungsfehler.'); }
|
||||
}
|
||||
|
||||
async function login() {
|
||||
clearErr();
|
||||
const credential = isAdmin ? $('passInput').value : $('pinInput').value;
|
||||
if (!credential) { err('Bitte Credential eingeben.'); return; }
|
||||
try {
|
||||
const res = await fetch('/api/auth/login', {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({username: currentUser, credential})
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok || data.error) { err(data.error || 'Fehler'); return; }
|
||||
window.location.href = '/play';
|
||||
} catch (e) { err('Verbindungsfehler.'); }
|
||||
}
|
||||
|
||||
async function setPin() {
|
||||
clearErr();
|
||||
const pin = $('newPinInput').value;
|
||||
const confirmPin = $('confirmPinInput').value;
|
||||
if (!/^\d{4,8}$/.test(pin)) { err('PIN muss 4–8 Ziffern sein.'); return; }
|
||||
if (pin !== confirmPin) { err('PINs stimmen nicht überein.'); return; }
|
||||
try {
|
||||
const res = await fetch('/api/auth/set_pin', {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({username: currentUser, pin, confirmPin})
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok || data.error) { err(data.error || 'Fehler'); return; }
|
||||
window.location.href = '/play';
|
||||
} catch (e) { err('Verbindungsfehler.'); }
|
||||
}
|
||||
|
||||
function back() {
|
||||
clearErr();
|
||||
hide('step2pin','step2pass','step2setup');
|
||||
show('step1');
|
||||
$('usernameInput').focus();
|
||||
}
|
||||
|
||||
// Check if already logged in
|
||||
(async () => {
|
||||
try {
|
||||
const res = await fetch('/api/auth/me');
|
||||
const data = await res.json();
|
||||
if (data.user) window.location.href = '/play';
|
||||
} catch(e) {}
|
||||
})();
|
||||
|
||||
return { checkUser, login, setPin, back, updateDots };
|
||||
})();
|
||||
1235
public/assets/js/play.js
Normal file
1235
public/assets/js/play.js
Normal file
File diff suppressed because it is too large
Load diff
301
public/assets/js/profile.js
Normal file
301
public/assets/js/profile.js
Normal file
|
|
@ -0,0 +1,301 @@
|
|||
/* Black Sheep Bluff – profile.php – ausgelagertes JS */
|
||||
const Profile = (() => {
|
||||
const $ = id => document.getElementById(id);
|
||||
let _page=1, _total=0, _isAdmin=false;
|
||||
const COLORS=['#3ECC5C','#4A5BE8','#5DCAA5','#ffcf6e','#65DC7A','#85B7EB','#D4537E','#97C459'];
|
||||
const colorFor=s=>{let h=0;for(const c of(s||''))h=(h*31+c.charCodeAt(0))>>>0;return COLORS[h%COLORS.length];};
|
||||
const initials=s=>(s||'?').trim().split(/\s+/).map(w=>w[0]).join('').slice(0,2).toUpperCase();
|
||||
const esc=s=>(s||'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
||||
const pct=(n,d)=>d?Math.round((n/d)*100):0;
|
||||
|
||||
function msg(type,text){
|
||||
const el=$(type==='err'?'errBox':'okBox');
|
||||
el.textContent=text; el.classList.remove('hidden');
|
||||
setTimeout(()=>el.classList.add('hidden'),type==='err'?4500:3000);
|
||||
}
|
||||
|
||||
function animCount(el,to){
|
||||
const dur=600,start=Date.now(),from=0;
|
||||
const step=()=>{
|
||||
const t=Math.min(1,(Date.now()-start)/dur);
|
||||
const ease=1-Math.pow(1-t,3);
|
||||
el.textContent=Math.round(from+(to-from)*ease);
|
||||
if(t<1)requestAnimationFrame(step);
|
||||
};
|
||||
requestAnimationFrame(step);
|
||||
}
|
||||
|
||||
function setAvatar(username, avatarFile){
|
||||
const el=$('heroAv');
|
||||
if(avatarFile){
|
||||
el.style='';
|
||||
el.innerHTML=`<img src="/uploads/avatars/${encodeURIComponent(avatarFile)}?v=${Date.now()}" style="width:100%;height:100%;object-fit:cover;border-radius:inherit" alt="${esc(username)}">`;
|
||||
} else {
|
||||
el.style.background=colorFor(username);
|
||||
el.textContent=initials(username);
|
||||
}
|
||||
}
|
||||
|
||||
function bsbImpBar(on){
|
||||
if(!on || document.getElementById('imp-bar')) return;
|
||||
const b=document.createElement('div'); b.id='imp-bar';
|
||||
b.style.cssText='position:fixed;top:0;left:0;right:0;z-index:5000;background:#a86f00;color:#fff;font:600 13px/1.4 Inter,system-ui,sans-serif;padding:8px 14px;display:flex;align-items:center;justify-content:center;gap:12px;flex-wrap:wrap';
|
||||
b.innerHTML='👁 Admin-Modus – du bist als anderer User angemeldet <button type="button" style="background:#fff;color:#a86f00;border:none;border-radius:6px;padding:5px 12px;font-weight:700;cursor:pointer">Zurück zum Admin</button>';
|
||||
b.querySelector('button').onclick=async()=>{ try{ await fetch('/api/auth/stop_impersonating',{method:'POST'}); }catch(e){} location.href='/admin'; };
|
||||
document.body.appendChild(b); document.body.style.paddingTop=(b.offsetHeight||38)+'px';
|
||||
}
|
||||
|
||||
const BSB_FONTS={inter:"Inter",sora:"Sora",pacifico:"Pacifico",lobster:"Lobster",bungee:"Bungee",bangers:"Bangers",orbitron:"Orbitron",pressstart:"'Press Start 2P'"};
|
||||
function nameStyleObj(u){
|
||||
u=u||{};
|
||||
const c1=u.color||'var(--navy)';
|
||||
const st=u.name_style||u.nameStyle||'solid';
|
||||
const font=BSB_FONTS[u.name_font||u.nameFont]||'';
|
||||
let style='',cls='';
|
||||
if(st==='rainbow'){ cls='name-rainbow'; }
|
||||
else if(st==='gradient'&&u.color2){ style=`background:linear-gradient(90deg,${c1},${u.color2});-webkit-background-clip:text;background-clip:text;-webkit-text-fill-color:transparent;color:transparent`; }
|
||||
else { style=`color:${c1}`; }
|
||||
if(font) style+=`;font-family:${font}`;
|
||||
return {style,cls};
|
||||
}
|
||||
function applyName(el, baseCls, baseStyle, u, text){
|
||||
if(!el) return;
|
||||
const ns=nameStyleObj(u);
|
||||
el.className=(baseCls+(ns.cls?' '+ns.cls:'')).trim();
|
||||
el.setAttribute('style', baseStyle+ns.style);
|
||||
if(text!=null) el.textContent=text;
|
||||
}
|
||||
function currentStyle(){ return { color:$('colorPicker').value, color2:$('colorPicker2').value, name_style:$('nameStyleSel').value, name_font:$('nameFontSel').value }; }
|
||||
function updatePreview(){
|
||||
const grad=$('nameStyleSel').value==='gradient';
|
||||
const c2=$('color2Wrap'); if(c2) c2.style.display=grad?'':'none';
|
||||
applyName($('colorPreviewName'),'','font-weight:800;font-size:24px;',currentStyle());
|
||||
}
|
||||
async function saveNameStyle(){
|
||||
try{
|
||||
const res=await fetch('/api/auth/save_name_style',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(currentStyle())});
|
||||
const d=await res.json();
|
||||
if(!res.ok||d.error){ msg('err',d.error||'Fehler.'); return; }
|
||||
msg('ok','Name-Stil gespeichert!'); await loadProfile();
|
||||
}catch(e){ msg('err','Fehler.'); }
|
||||
}
|
||||
|
||||
async function init(){
|
||||
try{
|
||||
const res=await fetch('/api/auth/me');
|
||||
const data=await res.json();
|
||||
if(!data.user){window.location.href='/login';return;}
|
||||
_isAdmin=data.user.role==='admin';
|
||||
bsbImpBar(data && data.impersonating);
|
||||
if(_isAdmin){
|
||||
$('adminLink').classList.remove('hidden');
|
||||
$('oldCred').removeAttribute('inputmode');
|
||||
$('newCred').removeAttribute('inputmode');
|
||||
$('newCred').maxLength=255;
|
||||
$('oldCredLabel').textContent='Aktuelles Passwort';
|
||||
$('newCredLabel').textContent='Neues Passwort (min. 8 Zeichen)';
|
||||
$('pinCardTitle').textContent='Passwort ändern';
|
||||
$('newCred').placeholder='••••••••';
|
||||
}
|
||||
await loadProfile();
|
||||
['nameStyleSel','colorPicker','colorPicker2','nameFontSel'].forEach(id=>{ const el=$(id); if(el) el.addEventListener('input',updatePreview); });
|
||||
await loadHistory(1);
|
||||
}catch(e){msg('err','Ladefehler.');}
|
||||
}
|
||||
|
||||
async function loadProfile(){
|
||||
const res=await fetch('/api/auth/get_profile');
|
||||
const data=await res.json();
|
||||
if(!data.profile)return;
|
||||
const p=data.profile;
|
||||
|
||||
applyName($('profileName'),'hero-name','',p,p.username);
|
||||
{ const _nn=$('newName'); if(_nn && document.activeElement!==_nn) _nn.value=p.username; }
|
||||
$('profileRole').textContent=p.role;
|
||||
$('profileRole').className='role-badge '+p.role;
|
||||
const since=new Date((p.created_at||0)*1000);
|
||||
$('profileSince').textContent='Dabei seit '+since.toLocaleDateString('de-DE',{year:'numeric',month:'long'});
|
||||
setAvatar(p.username, p.avatar);
|
||||
|
||||
const sp=$('stickerPreview');
|
||||
if(p.sticker){ sp.src='/uploads/sticker/'+encodeURIComponent(p.sticker)+'?v='+Date.now(); sp.classList.remove('hidden'); }
|
||||
else { sp.classList.add('hidden'); }
|
||||
|
||||
const savedColor = p.color || colorFor(p.username);
|
||||
$('colorPicker').value = savedColor;
|
||||
$('colorPicker2').value = p.color2 || savedColor;
|
||||
$('nameStyleSel').value = p.name_style || 'solid';
|
||||
$('nameFontSel').value = p.name_font || '';
|
||||
applyName($('colorPreviewName'),'','font-weight:800;font-size:24px;',p,p.username);
|
||||
updatePreview();
|
||||
|
||||
const s=p;
|
||||
animCount($('sPlayed'),parseInt(s.games_played)||0);
|
||||
animCount($('sWon'),parseInt(s.games_won)||0);
|
||||
animCount($('sLost'),parseInt(s.games_lost)||0);
|
||||
animCount($('sImp'),parseInt(s.times_imposter)||0);
|
||||
animCount($('sImpW'),parseInt(s.imposter_wins)||0);
|
||||
animCount($('sInnoW'),parseInt(s.innocent_wins)||0);
|
||||
|
||||
const totalPct=pct(s.games_won,s.games_played);
|
||||
const impPct=pct(s.imposter_wins,s.times_imposter);
|
||||
const innoPct=pct(s.innocent_wins,(s.games_played||0)-(s.times_imposter||0));
|
||||
setTimeout(()=>{
|
||||
$('wrTotal').style.width=totalPct+'%'; $('wrTotalPct').textContent=totalPct+'%';
|
||||
$('wrImp').style.width=impPct+'%'; $('wrImpPct').textContent=impPct+'%';
|
||||
$('wrInno').style.width=innoPct+'%'; $('wrInnoPct').textContent=innoPct+'%';
|
||||
},100);
|
||||
}
|
||||
|
||||
async function loadHistory(page=1){
|
||||
_page=page;
|
||||
const res=await fetch('/api/auth/get_history?page='+page);
|
||||
const data=await res.json();
|
||||
if(!data.rounds)return;
|
||||
_total=data.total;
|
||||
const wrap=$('historyWrap');
|
||||
|
||||
if(!data.rounds.length){
|
||||
wrap.innerHTML='<p class="empty">Noch keine Spielrunden.</p>';
|
||||
$('pageBtns').classList.add('hidden');
|
||||
return;
|
||||
}
|
||||
|
||||
const icon=r=>{
|
||||
if(!r.outcome)return'<div class="hist-icon open">⏳</div>';
|
||||
const won=(r.was_imposter&&!r.voted_out&&r.outcome==='imposters_win')
|
||||
||(!r.was_imposter&&r.outcome==='innocents_win');
|
||||
return`<div class="hist-icon ${won?'win':'loss'}">${won?'🏆':'💀'}</div>`;
|
||||
};
|
||||
const badge=r=>{
|
||||
if(!r.outcome)return'<span class="outcome-badge open">Offen</span>';
|
||||
const won=(parseInt(r.was_imposter)&&r.outcome==='imposters_win'&&!parseInt(r.voted_out))
|
||||
||(!parseInt(r.was_imposter)&&r.outcome==='innocents_win');
|
||||
return`<span class="outcome-badge ${won?'win':'loss'}">${won?'Gewonnen ✓':'Verloren'}</span>`;
|
||||
};
|
||||
|
||||
wrap.innerHTML='<div class="hist-list">'+data.rounds.map(r=>`
|
||||
<div class="hist-card">
|
||||
${icon(r)}
|
||||
<div class="hist-main">
|
||||
<div class="hist-room">${esc(r.room_code)} <span style="color:var(--muted);font-weight:400;font-size:12px">Runde #${r.round_num}</span></div>
|
||||
<div class="hist-sub">
|
||||
${parseInt(r.was_imposter)?'<span class="imp-tag">Imposter</span>':'<span style="color:var(--muted)">Innocent</span>'}
|
||||
<span>${new Date(r.played_at*1000).toLocaleDateString('de-DE',{day:'2-digit',month:'2-digit',year:'numeric'})}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="hist-right">${badge(r)}</div>
|
||||
</div>`).join('')+'</div>';
|
||||
|
||||
const totalPages=Math.ceil(_total/20);
|
||||
if(totalPages>1){
|
||||
$('pageBtns').classList.remove('hidden');
|
||||
$('pageInfo').textContent='Seite '+page+' / '+totalPages;
|
||||
$('prevBtn').disabled=page<=1;
|
||||
$('nextBtn').disabled=page>=totalPages;
|
||||
} else {
|
||||
$('pageBtns').classList.add('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
async function doUpload(file){
|
||||
if(!file)return;
|
||||
if(file.size>2*1024*1024){msg('err','Bild zu groß (max 2 MB).');return;}
|
||||
const reader=new FileReader();
|
||||
reader.onload=async e=>{
|
||||
try{
|
||||
const res=await fetch('/api/auth/upload_avatar',{
|
||||
method:'POST',headers:{'Content-Type':'application/json'},
|
||||
body:JSON.stringify({imageBase64:e.target.result})
|
||||
});
|
||||
const data=await res.json();
|
||||
if(!res.ok||data.error){msg('err',data.error||'Upload fehlgeschlagen.');return;}
|
||||
msg('ok','Profilbild gespeichert!');
|
||||
$('dropZone').classList.remove('over');
|
||||
await loadProfile();
|
||||
}catch(ex){msg('err','Upload-Fehler.');}
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
}
|
||||
|
||||
function uploadAvatar(input){doUpload(input.files[0]);input.value='';}
|
||||
function handleDrop(e){
|
||||
e.preventDefault();
|
||||
$('dropZone').classList.remove('over');
|
||||
doUpload(e.dataTransfer.files[0]);
|
||||
}
|
||||
|
||||
async function doStickerUpload(file){
|
||||
if(!file)return;
|
||||
if(!/^image\/(png|gif)$/.test(file.type)){msg('err','Nur PNG oder GIF erlaubt.');return;}
|
||||
if(file.size>500*1024){msg('err','Sticker zu groß (max 500 KB).');return;}
|
||||
const reader=new FileReader();
|
||||
reader.onload=async e=>{
|
||||
try{
|
||||
const res=await fetch('/api/auth/upload_sticker',{
|
||||
method:'POST',headers:{'Content-Type':'application/json'},
|
||||
body:JSON.stringify({imageBase64:e.target.result})
|
||||
});
|
||||
const data=await res.json();
|
||||
if(!res.ok||data.error){msg('err',data.error||'Upload fehlgeschlagen.');return;}
|
||||
msg('ok','Sticker gespeichert!');
|
||||
$('stickerDropZone').classList.remove('over');
|
||||
await loadProfile();
|
||||
}catch(ex){msg('err','Upload-Fehler.');}
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
}
|
||||
function uploadSticker(input){doStickerUpload(input.files[0]);input.value='';}
|
||||
function handleStickerDrop(e){
|
||||
e.preventDefault();
|
||||
$('stickerDropZone').classList.remove('over');
|
||||
doStickerUpload(e.dataTransfer.files[0]);
|
||||
}
|
||||
|
||||
async function changeCred(){
|
||||
const old=$('oldCred').value, nw=$('newCred').value;
|
||||
if(!old||!nw){msg('err','Alle Felder ausfüllen.');return;}
|
||||
try{
|
||||
const res=await fetch('/api/auth/change_credential',{
|
||||
method:'POST',headers:{'Content-Type':'application/json'},
|
||||
body:JSON.stringify({old,new:nw})
|
||||
});
|
||||
const data=await res.json();
|
||||
if(!res.ok||data.error){msg('err',data.error||'Fehler');return;}
|
||||
msg('ok',_isAdmin?'Passwort geändert!':'PIN geändert!');
|
||||
$('oldCred').value=$('newCred').value='';
|
||||
}catch(e){msg('err','Fehler.');}
|
||||
}
|
||||
|
||||
async function saveColor(){
|
||||
const color=$('colorPicker').value;
|
||||
try{
|
||||
const res=await fetch('/api/auth/save_color',{
|
||||
method:'POST',headers:{'Content-Type':'application/json'},
|
||||
body:JSON.stringify({color})
|
||||
});
|
||||
const data=await res.json();
|
||||
if(!res.ok||data.error){msg('err',data.error||'Fehler');return;}
|
||||
msg('ok','Farbe gespeichert!');
|
||||
}catch(e){msg('err','Fehler.');}
|
||||
}
|
||||
|
||||
async function logout(){
|
||||
await fetch('/api/auth/logout',{method:'POST'});
|
||||
window.location.href='/login';
|
||||
}
|
||||
|
||||
init();
|
||||
async function changeName(){
|
||||
const v=$('newName').value.trim();
|
||||
if(!v){ msg('err','Gib einen Namen ein.'); return; }
|
||||
try{
|
||||
const res=await fetch('/api/auth/change_username',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({username:v})});
|
||||
const d=await res.json();
|
||||
if(!res.ok||d.error){ msg('err',d.error||'Name konnte nicht geändert werden.'); return; }
|
||||
msg('ok','Name geändert!'); await loadProfile();
|
||||
}catch(e){ msg('err','Fehler.'); }
|
||||
}
|
||||
|
||||
return{loadHistory,uploadAvatar,handleDrop,uploadSticker,handleStickerDrop,changeCred,changeName,saveColor,saveNameStyle,logout,get page(){return _page;}};
|
||||
})();
|
||||
78
public/assets/js/site.js
Normal file
78
public/assets/js/site.js
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
/* ============================================================
|
||||
Black Sheep Bluff – globales Frontend-Script (auf jeder Seite)
|
||||
- Lucide-Icons rendern
|
||||
- Spenden-Link (config-gesteuert)
|
||||
- Bild-Fallbacks
|
||||
- Auth-aware Navigation (Login/Profil)
|
||||
- Cookie-Banner
|
||||
Exponiert window.BSB.{ renderIcons, onUser }.
|
||||
============================================================ */
|
||||
window.BSB = (function () {
|
||||
function renderIcons() { if (window.lucide) lucide.createIcons(); }
|
||||
|
||||
// Bild-Fallbacks: fehlende Bilder durch passende Icons ersetzen
|
||||
window.bsbImgFail = function (img) {
|
||||
const i = document.createElement('i');
|
||||
i.setAttribute('data-lucide', img.dataset.icon || 'image');
|
||||
img.replaceWith(i);
|
||||
renderIcons();
|
||||
};
|
||||
window.bsbGalleryFail = function (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(); }
|
||||
};
|
||||
|
||||
// Spenden-Link (config-gesteuert)
|
||||
(function () {
|
||||
const u = (window.BSB_CONFIG && window.BSB_CONFIG.donationUrl) || '';
|
||||
if (u) { const d = document.getElementById('footDonate'); if (d) { d.href = u; d.classList.remove('hidden'); } }
|
||||
})();
|
||||
|
||||
// Admin-Impersonation: Banner „Zurück zum Admin"
|
||||
function bsbImpBar(on){
|
||||
if(!on || document.getElementById('imp-bar')) return;
|
||||
const b=document.createElement('div'); b.id='imp-bar';
|
||||
b.style.cssText='position:fixed;top:0;left:0;right:0;z-index:5000;background:#a86f00;color:#fff;font:600 13px/1.4 Inter,system-ui,sans-serif;padding:8px 14px;display:flex;align-items:center;justify-content:center;gap:12px;flex-wrap:wrap';
|
||||
b.innerHTML='👁 Admin-Modus – du bist als anderer User angemeldet <button type="button" style="background:#fff;color:#a86f00;border:none;border-radius:6px;padding:5px 12px;font-weight:700;cursor:pointer">Zurück zum Admin</button>';
|
||||
b.querySelector('button').onclick=async()=>{ try{ await fetch('/api/auth/stop_impersonating',{method:'POST'}); }catch(e){} location.href='/admin'; };
|
||||
document.body.appendChild(b); document.body.style.paddingTop=(b.offsetHeight||38)+'px';
|
||||
}
|
||||
|
||||
// ── Auth-aware Navigation + User-Broadcast ──
|
||||
let userResolved = false, currentUser = null;
|
||||
const userCbs = [];
|
||||
function onUser(cb) { if (userResolved) cb(currentUser); else userCbs.push(cb); }
|
||||
(async () => {
|
||||
try {
|
||||
const r = await fetch('/api/auth/me');
|
||||
const d = await r.json();
|
||||
currentUser = (d && d.user) ? d.user : null;
|
||||
bsbImpBar(d && d.impersonating);
|
||||
} catch (e) { currentUser = null; }
|
||||
userResolved = true;
|
||||
if (currentUser) {
|
||||
const p = document.getElementById('navProfile'); if (p) p.classList.remove('hidden');
|
||||
const l = document.getElementById('navLogin'); if (l) l.classList.add('hidden');
|
||||
}
|
||||
userCbs.forEach(cb => cb(currentUser));
|
||||
})();
|
||||
|
||||
// ── Cookie-Banner ──
|
||||
(function () {
|
||||
const KEY = 'bsb_cookie_consent';
|
||||
const banner = document.getElementById('cookieBanner');
|
||||
if (!banner) return;
|
||||
function show() { requestAnimationFrame(() => banner.classList.add('show')); }
|
||||
function hide() { banner.classList.remove('show'); }
|
||||
window.Cookie = {
|
||||
accept(level) {
|
||||
try { localStorage.setItem(KEY, JSON.stringify({ level, ts: Date.now() })); } catch (e) {}
|
||||
hide();
|
||||
}
|
||||
};
|
||||
if (!localStorage.getItem(KEY)) setTimeout(show, 600);
|
||||
})();
|
||||
|
||||
renderIcons();
|
||||
return { renderIcons, onUser };
|
||||
})();
|
||||
Loading…
Add table
Add a link
Reference in a new issue