fix: chat scrollback and admin control

This commit is contained in:
jwinterm
2026-02-03 12:02:52 -05:00
parent 10dfd932d8
commit a56063867e
8 changed files with 565 additions and 52 deletions
+172
View File
@@ -284,6 +284,7 @@
<button class="tab-btn" data-tab="payouts">Payouts</button>
<button class="tab-btn" data-tab="games">Games</button>
<button class="tab-btn" data-tab="users">Users</button>
<button class="tab-btn" data-tab="chat">Chat</button>
</div>
<!-- Tab: Overview -->
@@ -406,6 +407,40 @@
<div class="pagination" id="usersPagination"></div>
</div>
</div>
<!-- Tab: Chat -->
<div id="tab-chat" class="tab-content">
<div class="table-container">
<div class="table-header">
<h3>Chat Moderation</h3>
<div style="display: flex; gap: 10px; align-items: center;">
<label style="color:#888; font-size:12px;">
<input type="checkbox" id="showDeletedMessages" onchange="loadChat()"> Show deleted
</label>
<button onclick="loadChat()" style="background:#055; color:#0f0; border:1px solid #0f0; padding:4px 10px; cursor:pointer;">🔄 Refresh</button>
</div>
</div>
<p style="color:#888; margin: 10px 0; font-size:12px;">
Delete offensive messages (they'll be removed from all clients). Ban users from chat if needed.
</p>
<table>
<thead>
<tr>
<th>ID</th>
<th>Time</th>
<th>Player</th>
<th>Message</th>
<th>User ID</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody id="chatTable">
<tr><td colspan="7" class="loading">Loading...</td></tr>
</tbody>
</table>
</div>
</div>
</main>
</div>
@@ -500,6 +535,7 @@
else if (tab === 'payouts') loadPayouts();
else if (tab === 'games') loadGames();
else if (tab === 'users') loadUsers();
else if (tab === 'chat') loadChat();
}
async function loadDashboard() {
@@ -806,6 +842,142 @@
loadUsers(0);
}
// Chat moderation functions
async function loadChat() {
const includeDeleted = document.getElementById('showDeletedMessages')?.checked || false;
try {
const url = `/api/admin/chat?limit=100&includeDeleted=${includeDeleted}`;
const res = await fetch(url, { headers: { 'X-Admin-Key': apiKey } });
const data = await res.json();
const tbody = document.getElementById('chatTable');
if (!data.messages?.length) {
tbody.innerHTML = '<tr><td colspan="7" class="loading">No chat messages</td></tr>';
return;
}
tbody.innerHTML = data.messages.map(m => {
const isDeleted = !!m.deletedAt;
const isBanned = m.chatBanned;
const rowStyle = isDeleted ? 'opacity: 0.5; text-decoration: line-through;' : '';
return `
<tr style="${rowStyle}">
<td>${m.id}</td>
<td>${formatTimeAgo(new Date(m.timestamp))}</td>
<td>${m.playerId || m.username || '-'}</td>
<td style="max-width: 300px; overflow: hidden; text-overflow: ellipsis;" title="${escapeHtml(m.message)}">${escapeHtml(m.message)}</td>
<td>${m.userId || '-'}</td>
<td>
${isDeleted ? '<span class="status-badge status-failed">Deleted</span>' : ''}
${isBanned ? '<span class="status-badge status-failed">Banned</span>' : ''}
${!isDeleted && !isBanned ? '<span class="status-badge status-completed">Active</span>' : ''}
</td>
<td>
${!isDeleted ? `<button class="btn btn-primary" onclick="deleteMessage(${m.id})" style="background:#c33;">Delete</button>` : ''}
${m.userId && !isBanned ? `<button class="btn btn-primary" onclick="banUser(${m.userId})" style="background:#a00; margin-left:4px;">Ban</button>` : ''}
${m.userId && isBanned ? `<button class="btn btn-primary" onclick="unbanUser(${m.userId})" style="background:#060; margin-left:4px;">Unban</button>` : ''}
</td>
</tr>
`;
}).join('');
} catch (e) {
console.error('Failed to load chat:', e);
document.getElementById('chatTable').innerHTML = '<tr><td colspan="7" class="loading">Error loading chat</td></tr>';
}
}
async function deleteMessage(messageId) {
if (!confirm('Delete this message? It will be removed from all clients.')) return;
try {
const res = await fetch(`/api/admin/chat/${messageId}`, {
method: 'DELETE',
headers: {
'X-Admin-Key': apiKey,
'Content-Type': 'application/json'
},
body: JSON.stringify({ reason: 'Admin deleted' })
});
const data = await res.json();
if (data.success) {
loadChat();
} else {
alert('Failed to delete: ' + (data.message || 'Unknown error'));
}
} catch (e) {
console.error('Failed to delete message:', e);
alert('Error deleting message');
}
}
async function banUser(userId) {
const reason = prompt('Ban reason (optional):');
if (reason === null) return; // Cancelled
try {
const res = await fetch(`/api/admin/users/${userId}/chat-ban`, {
method: 'POST',
headers: {
'X-Admin-Key': apiKey,
'Content-Type': 'application/json'
},
body: JSON.stringify({ banned: true, reason: reason || 'Admin banned' })
});
const data = await res.json();
if (data.success) {
loadChat();
} else {
alert('Failed to ban: ' + (data.message || 'Unknown error'));
}
} catch (e) {
console.error('Failed to ban user:', e);
alert('Error banning user');
}
}
async function unbanUser(userId) {
if (!confirm('Unban this user from chat?')) return;
try {
const res = await fetch(`/api/admin/users/${userId}/chat-ban`, {
method: 'POST',
headers: {
'X-Admin-Key': apiKey,
'Content-Type': 'application/json'
},
body: JSON.stringify({ banned: false })
});
const data = await res.json();
if (data.success) {
loadChat();
} else {
alert('Failed to unban: ' + (data.message || 'Unknown error'));
}
} catch (e) {
console.error('Failed to unban user:', e);
alert('Error unbanning user');
}
}
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
function formatTimeAgo(date) {
const seconds = Math.floor((Date.now() - date.getTime()) / 1000);
if (seconds < 60) return 'just now';
if (seconds < 3600) return Math.floor(seconds / 60) + 'm ago';
if (seconds < 86400) return Math.floor(seconds / 3600) + 'h ago';
return Math.floor(seconds / 86400) + 'd ago';
}
// Auto-refresh every 30 seconds
setInterval(() => {
if (apiKey && currentTab === 'overview') {
+2 -1
View File
@@ -205,7 +205,8 @@
<!-- Chat input in its own row -->
<div class="input-container">
<form id="chatForm" action="">
<input id="chatInput" autocomplete="off" placeholder="Type a command..." />
<input id="chatInput" autocomplete="off" placeholder="Type a command..." maxlength="200" />
<span id="charCounter" style="color:#666; font-size:10px; margin-left:5px; min-width:45px;">0/200</span>
<button type="submit">Send</button>
</form>
</div>
+23 -5
View File
@@ -21,22 +21,39 @@ const InputHandler = {
},
setupChatForm: function() {
const MAX_CHAT_LENGTH = 200;
// Character counter update
$('#chatInput').on('input', function() {
const len = $(this).val().length;
const counter = $('#charCounter');
counter.text(len + '/' + MAX_CHAT_LENGTH);
// Change color when approaching limit
if (len >= MAX_CHAT_LENGTH) {
counter.css('color', '#f66');
} else if (len >= MAX_CHAT_LENGTH * 0.8) {
counter.css('color', '#fa0');
} else {
counter.css('color', '#666');
}
});
$('#chatForm').submit(function(e) {
e.preventDefault();
var msg = $('#chatInput').val().trim();
// Don't send empty messages
if (!msg) return false;
// If the message is "enter", always send it to server
// The server will handle queueing logic and timing
if (msg.toLowerCase() === 'enter') {
socket.emit('chat message', msg);
// Don't automatically switch to waiting screen - let the server control screen state
// The server will send appropriate events (payment_created, waiting_status, etc.)
// to control what the user sees
// Add visual feedback that request was sent
$('#messages').append($('<li style="color: #0f0;">').text("🔑 Processing game entry request..."));
UI.scrollChat();
@@ -44,8 +61,9 @@ const InputHandler = {
// Send other chat messages normally
socket.emit('chat message', msg);
}
$('#chatInput').val('');
$('#charCounter').text('0/' + MAX_CHAT_LENGTH).css('color', '#666');
return false;
});
+44 -8
View File
@@ -120,7 +120,9 @@ const SocketHandlers = {
socket.on('status_update', this.onStatusUpdate);
socket.on('chat_broadcast', this.onChatBroadcast);
socket.on('chat_history', this.onChatHistory);
socket.on('chat_deleted', this.onChatDeleted);
socket.on('chat_error', this.onChatError);
// Game state handlers
socket.on('waiting_status', this.onWaitingStatus);
socket.on('queue_joined', this.onQueueJoined);
@@ -298,27 +300,61 @@ const SocketHandlers = {
onChatHistory: function(data) {
if (!data || !data.messages || !Array.isArray(data.messages)) return;
// Add a separator for history messages
if (data.messages.length > 0) {
$('#messages').append($('<li class="chat-history-header" style="color: #666; font-style: italic; border-bottom: 1px solid #333; margin-bottom: 5px; padding-bottom: 5px;">').text('--- Recent Chat History ---'));
}
// Add each historical message
// Add each historical message with data-msg-id for deletion support
data.messages.forEach(function(msg) {
const msgElement = $('<li style="color: #888;">');
const username = msg.username || (msg.socketId ? msg.socketId.substring(0, 6) : 'anon');
msgElement.html('<strong>' + username + ':</strong> ' + msg.message);
if (msg.id) {
msgElement.attr('data-msg-id', msg.id);
}
const username = msg.playerId || msg.username || (msg.socketId ? msg.socketId.substring(0, 6) : 'anon');
const isSystem = msg.type === 'system' || msg.socketId === 'system';
if (isSystem) {
msgElement.addClass('status');
}
// Add timestamp if available
let timeStr = '';
if (msg.timestamp) {
timeStr = '<span style="color:#555;font-size:10px;">[' + SocketHandlers._formatTimeAgo(new Date(msg.timestamp)) + ']</span> ';
}
msgElement.html(timeStr + '<strong>' + username + ':</strong> ' + msg.message);
$('#messages').append(msgElement);
});
if (data.messages.length > 0) {
$('#messages').append($('<li class="chat-history-footer" style="color: #666; font-style: italic; border-top: 1px solid #333; margin-top: 5px; padding-top: 5px;">').text('--- End of History ---'));
}
UI.scrollChat();
},
onChatDeleted: function(data) {
if (!data || !data.messageId) return;
// Remove deleted message from view with fade effect
$('#messages li[data-msg-id="' + data.messageId + '"]').fadeOut(200, function() {
$(this).remove();
});
},
onChatError: function(data) {
if (!data || !data.message) return;
$('#messages').append($('<li class="error" style="color:#f66;">').text(data.message));
UI.scrollChat();
},
_formatTimeAgo: function(date) {
const seconds = Math.floor((Date.now() - date.getTime()) / 1000);
if (seconds < 60) return 'just now';
if (seconds < 3600) return Math.floor(seconds / 60) + 'm ago';
if (seconds < 86400) return Math.floor(seconds / 3600) + 'h ago';
return Math.floor(seconds / 86400) + 'd ago';
},
onWaitingStatus: function(data) {
if (data.status === 'waiting') {
$('#messages').append($('<li style="color:#ff0;">').text(data.message));