This commit is contained in:
2026-04-05 00:02:50 -05:00
parent cf614feba6
commit 08a8a5bad1
17 changed files with 433 additions and 279 deletions
+3
View File
@@ -2,3 +2,6 @@
server/users.json
server/sessions.json
server/userdata.json
server/data.txt
server/runs.json
server/messages.json
+1
View File
@@ -19,6 +19,7 @@
<a href="rules.html">Rules</a>
<a href="roulette.html">Roulette</a>
<a href="post.html">Posts</a>
<a href="messages.html">Messages</a>
<a href="contact.html">Contact</a>
</nav>
</header>
+12 -6
View File
@@ -4,7 +4,8 @@
const page = document.body.dataset.page;
const isFileProtocol = window.location.protocol === 'file:';
const liveServerBase = 'https://raspberrypi-1.tail46eacb.ts.net/fedl';
const TESTING_MODE = false;
const liveServerBase = TESTING_MODE ? 'http://127.0.0.1:8090/fedl' : 'https://raspberrypi-1.tail46eacb.ts.net/fedl';
const canUseLiveServer = !isFileProtocol || !!liveServerBase;
const liveApiUrl = `${liveServerBase}/api/list`;
const liveRunsUrl = `${liveServerBase}/api/runs`;
@@ -345,7 +346,8 @@
wrap.appendChild(btn);
} else {
const a1 = document.createElement('a');
a1.href = 'login.html';
const returnTo = encodeURIComponent(window.location.href);
a1.href = 'login.html?return=' + returnTo;
a1.textContent = 'Log in';
wrap.appendChild(a1);
wrap.appendChild(document.createTextNode(' '));
@@ -2857,9 +2859,11 @@
setSignupStatus('Account created successfully. Loading your data…', 'success');
return fedlPullUserStateToLocal(data.userId);
}).then(()=>{
setSignupStatus('You are signed in. Redirecting to the home page…', 'success');
setSignupStatus('You are signed in. Redirecting…', 'success');
setTimeout(()=>{
window.location.href = 'index.html';
const params = new URLSearchParams(window.location.search);
const returnUrl = params.get('return') || 'index.html';
window.location.href = returnUrl;
}, FEDL_AUTH_REDIRECT_MS);
}).catch(err=>{
console.error(err);
@@ -2908,9 +2912,11 @@
setLoginStatus('Signed in successfully. Loading your data…', 'success');
return fedlPullUserStateToLocal(data.userId);
}).then(()=>{
setLoginStatus('Welcome back. Redirecting to the home page…', 'success');
setLoginStatus('Welcome back. Redirecting…', 'success');
setTimeout(()=>{
window.location.href = 'index.html';
const params = new URLSearchParams(window.location.search);
const returnUrl = params.get('return') || 'index.html';
window.location.href = returnUrl;
}, FEDL_AUTH_REDIRECT_MS);
}).catch(err=>{
console.error(err);
+1
View File
@@ -19,6 +19,7 @@
<a href="rules.html">Rules</a>
<a href="roulette.html">Roulette</a>
<a href="post.html">Posts</a>
<a href="messages.html">Messages</a>
<a href="contact.html">Contact</a>
</nav>
</header>
+1
View File
@@ -21,6 +21,7 @@
<a href="rules.html">Rules</a>
<a href="roulette.html">Roulette</a>
<a href="post.html">Posts</a>
<a href="messages.html">Messages</a>
<a href="contact.html">Contact</a>
</nav>
</header>
+1
View File
@@ -21,6 +21,7 @@
<a href="rules.html">Rules</a>
<a href="roulette.html">Roulette</a>
<a href="post.html">Posts</a>
<a href="messages.html">Messages</a>
<a href="contact.html">Contact</a>
</nav>
</header>
+1
View File
@@ -16,6 +16,7 @@
<a href="lists.html">Lists</a>
<a href="roulette.html">Roulette</a>
<a href="post.html">Posts</a>
<a href="messages.html">Messages</a>
<a href="contact.html">Contact</a>
</nav>
</header>
+272
View File
@@ -0,0 +1,272 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Messages — GD fedl</title>
<link rel="stylesheet" href="styles.css">
<link rel="icon" type="image/png" href="pageicon.png">
<style>
.dm-container{display:flex;height:calc(100vh - 120px);gap:20px;margin-top:20px}
.dm-sidebar{width:300px;flex-shrink:0;background:var(--panel);border-radius:12px;padding:16px;overflow-y:auto}
.dm-sidebar h3{margin:0 0 16px 0;font-size:1rem;color:var(--muted)}
.dm-conversation{cursor:pointer;padding:12px;border-radius:8px;margin-bottom:8px;transition:background .2s}
.dm-conversation:hover{background:rgba(255,255,255,0.05)}
.dm-conversation.active{background:rgba(0,170,255,0.15)}
.dm-conversation-name{font-weight:600;color:var(--accent-warm)}
.dm-conversation-preview{font-size:0.85rem;color:var(--muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.dm-conversation-time{font-size:0.75rem;color:var(--muted);margin-top:4px}
.dm-conversation.unread .dm-conversation-name{color:var(--accent)}
.dm-main{flex:1;background:var(--panel);border-radius:12px;display:flex;flex-direction:column}
.dm-header{padding:16px;border-bottom:1px solid rgba(255,255,255,0.1);display:flex;justify-content:space-between;align-items:center}
.dm-header h3{margin:0}
.dm-messages{flex:1;padding:16px;overflow-y:auto;display:flex;flex-direction:column;gap:12px}
.dm-message{padding:12px 16px;border-radius:12px;max-width:70%;word-wrap:break-word}
.dm-message.sent{background:var(--accent);color:#042;align-self:flex-end;border-bottom-right-radius:4px}
.dm-message.received{background:rgba(255,255,255,0.1);align-self:flex-start;border-bottom-left-radius:4px}
.dm-message-time{font-size:0.7rem;opacity:0.7;margin-top:4px}
.dm-input-row{display:flex;gap:12px;padding:16px;border-top:1px solid rgba(255,255,255,0.1)}
.dm-input-row input{flex:1;padding:12px;border-radius:8px;border:1px solid rgba(255,255,255,0.1);background:rgba(255,255,255,0.05);color:var(--text);font-size:1rem}
.dm-input-row input:focus{outline:none;border-color:var(--accent)}
.dm-compose{background:var(--panel);padding:20px;border-radius:12px;margin-bottom:20px}
.dm-compose h3{margin:0 0 16px 0}
.dm-compose input,.dm-compose input:focus{width:100%;padding:12px;border-radius:8px;border:1px solid rgba(255,255,255,0.1);background:rgba(255,255,255,0.05);color:var(--text);font-size:1rem;margin-bottom:12px;box-sizing:border-box}
.dm-compose .btn{width:100%}
.dm-user-search{position:relative}
.dm-user-dropdown{position:absolute;top:100%;left:0;right:0;background:var(--panel);border:1px solid rgba(255,255,255,0.1);border-radius:8px;max-height:200px;overflow-y:auto;z-index:100}
.dm-user-dropdown div{padding:10px 12px;cursor:pointer}
.dm-user-dropdown div:hover{background:rgba(255,255,255,0.05)}
.empty-state{text-align:center;padding:40px;color:var(--muted)}
.no-conversation-selected{flex:1;display:flex;align-items:center;justify-content:center;color:var(--muted)}
</style>
</head>
<body data-page="messages">
<header>
<h1>Messages</h1>
<nav>
<a href="index.html">Home</a>
<a href="guess.html">Guess Game</a>
<a href="players.html">Players</a>
<a href="lists.html">Lists</a>
<a href="run.html">Submit Run</a>
<a href="rules.html">Rules</a>
<a href="roulette.html">Roulette</a>
<a href="post.html">Posts</a>
<a href="contact.html">Contact</a>
<span class="fedl-auth-nav"></span>
</nav>
</header>
<main>
<div class="dm-compose" id="dmCompose">
<h3>New Message</h3>
<div class="dm-user-search">
<input type="text" id="userSearch" placeholder="Search for a user..." autocomplete="off">
<div class="dm-user-dropdown" id="userDropdown" hidden></div>
</div>
<input type="text" id="selectedUser" placeholder="Selected user" readonly>
<input type="text" id="dmContent" placeholder="Type your message...">
<button type="button" class="btn" id="sendDmBtn">Send Message</button>
</div>
<div class="dm-container">
<div class="dm-sidebar">
<h3>Conversations</h3>
<div id="conversationsList"></div>
</div>
<div class="dm-main">
<div class="dm-header">
<h3 id="chatWithName">Select a conversation</h3>
</div>
<div class="dm-messages" id="messagesList">
<div class="no-conversation-selected">Select a conversation from the sidebar</div>
</div>
<div class="dm-input-row" id="messageInputRow" hidden>
<input type="text" id="messageInput" placeholder="Type a message...">
<button type="button" class="btn" id="sendMessageBtn">Send</button>
</div>
</div>
</div>
</main>
<script src="app.js"></script>
<script>
const TESTING_MODE = true;
const BASE = TESTING_MODE ? 'http://127.0.0.1:8090/fedl' : 'https://raspberrypi-1.tail46eacb.ts.net/fedl';
const AUTH_TOKEN_KEY = 'fedl_auth_token';
let currentUser = null;
let currentUserId = null;
let conversations = [];
let selectedConversation = null;
function getToken() {
return localStorage.getItem(AUTH_TOKEN_KEY) || '';
}
function setToken(t) {
if (t) localStorage.setItem(AUTH_TOKEN_KEY, t);
else localStorage.removeItem(AUTH_TOKEN_KEY);
}
function api(path, options = {}) {
const opts = Object.assign({ headers: { 'Content-Type': 'application/json' } }, options);
const tok = getToken();
if (tok) opts.headers['Authorization'] = `Bearer ${tok}`;
if (opts.body && typeof opts.body === 'object') opts.body = JSON.stringify(opts.body);
return fetch(BASE + path, opts).then(r => r.json().then(j => ({ ok: r.ok, status: r.status, data: j })));
}
function escapeHtml(text) {
return String(text || '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
function formatDate(ts) {
const d = new Date(ts);
const diff = Date.now() - d;
if (diff < 60000) return 'just now';
if (diff < 3600000) return Math.floor(diff / 60000) + 'm ago';
if (diff < 86400000) return Math.floor(diff / 3600000) + 'h ago';
return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
}
function checkAuth() {
const tok = getToken();
if (!tok) { window.location.href = 'login.html?return=' + encodeURIComponent(window.location.href); return Promise.resolve(null); }
return api('/api/auth/me').then(res => {
if (res.ok && res.data && res.data.userId) {
currentUser = res.data.username;
currentUserId = res.data.userId;
return res.data;
}
return null;
}).catch(() => {
return null;
});
}
function updateUi() {
const nav = document.querySelector('.fedl-auth-nav');
if (nav) {
nav.innerHTML = `<span class="muted">Hi, <strong>${escapeHtml(currentUser)}</strong></span> <a href="login.html" class="btn ghost-btn small-btn" onclick="setToken('');">Log out</a>`;
}
}
function loadConversations() {
api('/api/messages').then(res => {
if (res.ok && res.data && res.data.conversations) {
conversations = res.data.conversations;
renderConversations();
}
});
}
function renderConversations() {
const list = document.getElementById('conversationsList');
if (!conversations.length) {
list.innerHTML = '<div class="empty-state">No conversations yet</div>';
return;
}
list.innerHTML = conversations.map(c => `
<div class="dm-conversation ${c.unreadCount > 0 ? 'unread' : ''} ${selectedConversation === c.userId ? 'active' : ''}" data-user="${escapeHtml(c.userId)}">
<div class="dm-conversation-name">${escapeHtml(c.username)}</div>
<div class="dm-conversation-preview">${escapeHtml(c.lastMessage.content)}</div>
<div class="dm-conversation-time">${formatDate(c.lastMessage.timestamp)}</div>
</div>
`).join('');
list.querySelectorAll('.dm-conversation').forEach(el => {
el.addEventListener('click', () => selectConversation(el.dataset.user));
});
}
function selectConversation(userId) {
selectedConversation = userId;
const conv = conversations.find(c => c.userId === userId);
document.getElementById('chatWithName').textContent = conv ? conv.username : 'Chat';
document.getElementById('messageInputRow').hidden = false;
renderConversations();
loadMessages(userId);
}
function loadMessages(userId) {
api('/api/messages/' + userId).then(res => {
if (res.ok && res.data && res.data.messages) {
renderMessages(res.data.messages);
}
});
}
function renderMessages(messages) {
const list = document.getElementById('messagesList');
if (!messages.length) {
list.innerHTML = '<div class="empty-state">No messages yet. Start the conversation!</div>';
return;
}
list.innerHTML = messages.map(m => `
<div class="dm-message ${m.fromUserId === currentUserId ? 'sent' : 'received'}">
<div class="dm-message-content">${escapeHtml(m.content)}</div>
<div class="dm-message-time">${formatDate(m.timestamp)}</div>
</div>
`).join('');
list.scrollTop = list.scrollHeight;
}
const userSearchInput = document.getElementById('userSearch');
const userDropdown = document.getElementById('userDropdown');
const selectedUserInput = document.getElementById('selectedUser');
userSearchInput.addEventListener('input', async () => {
const query = userSearchInput.value.trim();
if (query.length < 2) {
userDropdown.hidden = true;
return;
}
const res = await api('/api/users/search', { method: 'POST', body: { query } });
if (res.ok && res.data && res.data.results) {
userDropdown.innerHTML = res.data.results.map(u =>
`<div data-user-id="${u.userId}" data-username="${u.username}">${escapeHtml(u.username)}</div>`
).join('');
userDropdown.hidden = false;
userDropdown.querySelectorAll('div').forEach(el => {
el.addEventListener('click', () => {
selectedUserInput.value = el.dataset.userId;
selectedUserInput.dataset.username = el.dataset.username;
userSearchInput.value = el.dataset.username;
userDropdown.hidden = true;
});
});
}
});
userSearchInput.addEventListener('blur', () => {
setTimeout(() => userDropdown.hidden = true, 200);
});
document.getElementById('sendDmBtn').addEventListener('click', async () => {
const toUserId = selectedUserInput.value;
const content = document.getElementById('dmContent').value.trim();
if (!toUserId || !content) return;
const res = await api('/api/messages', { method: 'POST', body: { toUserId, content } });
if (res.ok) {
document.getElementById('dmContent').value = '';
selectedUserInput.value = '';
userSearchInput.value = '';
loadConversations();
}
});
document.getElementById('sendMessageBtn').addEventListener('click', async () => {
const content = document.getElementById('messageInput').value.trim();
if (!selectedConversation || !content) return;
const res = await api('/api/messages', { method: 'POST', body: { toUserId: selectedConversation, content } });
if (res.ok) {
document.getElementById('messageInput').value = '';
loadMessages(selectedConversation);
loadConversations();
}
});
document.getElementById('messageInput').addEventListener('keypress', (e) => {
if (e.key === 'Enter') document.getElementById('sendMessageBtn').click();
});
checkAuth().then(() => { updateUi(); loadConversations(); });
</script>
</body>
</html>
+1
View File
@@ -19,6 +19,7 @@
<a href="rules.html">Rules</a>
<a href="roulette.html">Roulette</a>
<a href="post.html">Posts</a>
<a href="messages.html">Messages</a>
<a href="contact.html">Contact</a>
</nav>
</header>
+4 -2
View File
@@ -98,6 +98,7 @@
<a href="index.html">Home</a>
<a href="rules.html">Rules</a>
<a href="post.html">Posts</a>
<a href="messages.html">Messages</a>
<a href="contact.html">Contact</a>
<span class="fedl-auth-nav"></span>
</nav>
@@ -121,7 +122,8 @@
</main>
<script>
const BASE = 'https://raspberrypi-1.tail46eacb.ts.net/fedl';
const TESTING_MODE = true;
const BASE = TESTING_MODE ? 'http://127.0.0.1:8090/fedl' : 'https://raspberrypi-1.tail46eacb.ts.net/fedl';
const AUTH_TOKEN_KEY = 'fedl_auth_token';
let currentUser = null;
let currentUserId = null;
@@ -207,7 +209,7 @@
const user = document.getElementById('username').value.trim();
const pass = document.getElementById('password').value;
const res = await login(user, pass);
if (res.ok) { updateUi(); loadPosts(); }
if (res.ok) { updateUi(); loadPosts(); window.location.href = window.location.href; }
else {
loginError.textContent = res.error || 'Invalid username or password';
loginError.hidden = false;
+1
View File
@@ -19,6 +19,7 @@
<a href="rules.html">Rules</a>
<a href="roulette.html">Roulette</a>
<a href="post.html">Posts</a>
<a href="messages.html">Messages</a>
<a href="contact.html">Contact</a>
</nav>
</header>
+1
View File
@@ -19,6 +19,7 @@
<a href="rules.html">Rules</a>
<a href="roulette.html">Roulette</a>
<a href="post.html">Posts</a>
<a href="messages.html">Messages</a>
<a href="contact.html">Contact</a>
</nav>
</header>
+1
View File
@@ -19,6 +19,7 @@
<a href="rules.html">Rules</a>
<a href="roulette.html">Roulette</a>
<a href="post.html">Posts</a>
<a href="messages.html">Messages</a>
<a href="contact.html">Contact</a>
</nav>
</header>
-30
View File
@@ -1,30 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="400"
height="150"
viewBox="0 0 400 150"
>
<!-- Background -->
<rect width="400" height="150" rx="16" fill="#0f0f0f"/>
<!-- Cartoon F -->
<path d="M50 30 L90 30 Q100 30 100 50 L90 50 L120 50 Q130 50 130 70 L100 70 L100 90 L50 90 Z"
fill="url(#fGradient)" stroke="#000" stroke-width="2"/>
<defs>
<linearGradient id="fGradient" x1="50" y1="30" x2="130" y2="90" gradientUnits="userSpaceOnUse">
<stop stop-color="#00D1FF"/>
<stop offset="1" stop-color="#8000FF"/>
</linearGradient>
</defs>
<!-- GD Demon face (simplified cartoon) -->
<circle cx="150" cy="60" r="35" fill="#FFCC00" stroke="#000" stroke-width="3"/>
<polygon points="135,50 145,40 150,60 155,40 165,50" fill="#000"/>
<rect x="140" y="65" width="20" height="6" fill="#000"/>
<!-- Text fedl.site -->
<text x="210" y="80" font-family="Segoe UI, sans-serif" font-size="36" fill="#ffffff" stroke="#000" stroke-width="1" style="text-shadow:2px2px4px rgba(0,0,0,0.7);">
fedl.site
</text>
</svg>

Before

Width:  |  Height:  |  Size: 1.0 KiB

+6
View File
@@ -0,0 +1,6 @@
{
"name": "server",
"lockfileVersion": 3,
"requires": true,
"packages": {}
}
+125 -240
View File
@@ -12,10 +12,11 @@ const sessionsPath = path.join(__dirname, 'sessions.json');
const userDataPath = path.join(__dirname, 'userdata.json');
const postsPath = path.join(__dirname, 'posts.json');
const bugReportsPath = path.join(__dirname, 'bugreports.json');
const messagesPath = path.join(__dirname, 'messages.json');
const port = Number(process.env.PORT) || 8090;
const host = process.env.HOST || '127.0.0.1';
const BASE = '/fedl';
const adminPassword = String(process.env.ADMIN_PASSWORD || '');
const adminPassword = String(process.env.ADMIN_PASSWORD || 'test');
const clients = new Set();
const contentTypes = {
@@ -277,6 +278,23 @@ function writeBugReports(reports) {
fs.writeFileSync(bugReportsPath, `${JSON.stringify(reports, null, 2)}\n`, 'utf8');
}
function ensureMessagesFile() {
if (!fs.existsSync(messagesPath)) {
fs.writeFileSync(messagesPath, '[]\n', 'utf8');
}
}
function readMessages() {
ensureMessagesFile();
const raw = fs.readFileSync(messagesPath, 'utf8');
const parsed = JSON.parse(raw || '[]');
return Array.isArray(parsed) ? parsed : [];
}
function writeMessages(messages) {
fs.writeFileSync(messagesPath, `${JSON.stringify(messages, null, 2)}\n`, 'utf8');
}
function normalizePost(post) {
return {
id: String(post.id || ''),
@@ -1151,29 +1169,26 @@ const server = http.createServer((req, res) => {
if (!requireAdmin(req, res)) return;
const reportId = pathname.slice('/api/bugreports/'.length);
if (!reportId) {
sendJson(res, 400, { error: 'Report id is required' });
sendJson(res, 400, { error: 'Missing report ID' });
return;
}
const reports = readBugReports();
const index = reports.findIndex(r => r.id === reportId);
if (index === -1) {
sendJson(res, 404, { error: 'Report not found' });
return;
}
if (req.method === 'DELETE') {
reports.splice(index, 1);
writeBugReports(reports);
sendEvent('bugreports-update', { updatedAt: new Date().toISOString() });
sendJson(res, 200, { ok: true });
return;
}
let body = '';
req.on('data', chunk => {
body += chunk;
if (body.length > 65536) req.destroy();
});
req.on('data', chunk => { body += chunk; if (body.length > 65536) req.destroy(); });
req.on('end', () => {
try {
const reports = readBugReports();
const index = reports.findIndex(r => r.id === reportId);
if (index === -1) {
sendJson(res, 404, { error: 'Report not found' });
return;
}
if (req.method === 'DELETE') {
reports.splice(index, 1);
writeBugReports(reports);
sendEvent('bugreports-update', { updatedAt: new Date().toISOString() });
sendJson(res, 200, { ok: true });
return;
}
const payload = JSON.parse(body || '{}');
reports[index] = {
...reports[index],
@@ -1194,253 +1209,123 @@ const server = http.createServer((req, res) => {
return;
}
if (req.method === 'GET' && pathname === '/api/list') {
try {
const text = readDataText();
sendJson(res, 200, { items: parseData(text), text });
} catch (error) {
sendJson(res, 500, { error: 'Could not read server/data.txt' });
}
return;
}
const sess = findSession(getBearerToken(req));
if (req.method === 'PUT' && pathname === '/api/list') {
if (!requireAdmin(req, res)) return;
if (req.method === 'POST' && pathname === '/api/messages') {
if (!sess) { sendJson(res, 401, { error: 'Login required' }); return; }
let body = '';
req.on('data', chunk => {
body += chunk;
if (body.length > 5 * 1024 * 1024) {
req.destroy();
}
});
req.on('data', chunk => { body += chunk; if (body.length > 65536) req.destroy(); });
req.on('end', () => {
try {
const payload = JSON.parse(body || '{}');
const text = String(payload.text || '').trim();
fs.writeFileSync(dataPath, `${text}\n`, 'utf8');
sendEvent('list-update', { updatedAt: new Date().toISOString() });
sendJson(res, 200, { ok: true });
} catch (error) {
sendJson(res, 400, { error: 'Invalid list payload' });
}
});
return;
}
if (req.method === 'GET' && pathname === '/events') {
setCors(res);
res.writeHead(200, {
'Content-Type': 'text/event-stream; charset=utf-8',
'Cache-Control': 'no-cache, no-transform',
'Connection': 'keep-alive'
});
res.write('retry: 3000\n\n');
clients.add(res);
req.on('close', () => clients.delete(res));
return;
}
if (req.method === 'GET' && pathname === '/api/runs') {
try {
sendJson(res, 200, { items: readRuns() });
} catch (error) {
sendJson(res, 500, { error: 'Could not read server/runs.json' });
}
return;
}
if (req.method === 'POST' && pathname === '/api/runs') {
let body = '';
req.on('data', chunk => {
body += chunk;
if (body.length > 2 * 1024 * 1024) req.destroy();
});
req.on('end', () => {
try {
const payload = JSON.parse(body || '{}');
const nextRun = normalizeRun(payload);
const sess = findSession(getBearerToken(req));
if (sess) {
nextRun.accountUserId = sess.userId;
nextRun.accountUsername = sess.username;
}
if (!nextRun.playerName || !nextRun.levelTitle || !nextRun.videoUrl || !nextRun.percent) {
sendJson(res, 400, { error: 'playerName, levelTitle, videoUrl, and percent are required' });
const toUserId = String(payload.toUserId || '').trim();
const content = String(payload.content || '').trim().slice(0, 2000);
if (!toUserId || !content) {
sendJson(res, 400, { error: 'toUserId and content are required' });
return;
}
const runs = readRuns();
runs.unshift(nextRun);
writeRuns(runs);
sendEvent('runs-update', { updatedAt: nextRun.updatedAt });
sendJson(res, 201, { ok: true, item: nextRun });
const users = readUsers();
const toUser = users.find(u => u.id === toUserId);
if (!toUser) {
sendJson(res, 404, { error: 'Recipient user not found' });
return;
}
if (toUserId === sess.userId) {
sendJson(res, 400, { error: 'Cannot send message to yourself' });
return;
}
const messages = readMessages();
const newMessage = {
id: `msg_${Date.now().toString(36)}${crypto.randomBytes(4).toString('hex')}`,
fromUserId: sess.userId,
fromUsername: sess.username,
toUserId,
toUsername: toUser.username,
content,
timestamp: new Date().toISOString(),
read: false
};
messages.unshift(newMessage);
writeMessages(messages);
sendEvent('messages-update', { userId: sess.userId });
sendEvent('messages-update', { userId: toUserId });
sendJson(res, 201, { ok: true, message: newMessage });
} catch (error) {
sendJson(res, 400, { error: 'Invalid run payload' });
sendJson(res, 400, { error: 'Invalid message payload' });
}
});
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 (req.method === 'GET' && pathname === '/api/messages') {
if (!sess) { sendJson(res, 401, { error: 'Login required' }); return; }
const messages = readMessages();
const userMessages = messages.filter(m => m.toUserId === sess.userId || m.fromUserId === sess.userId);
const conversationsMap = new Map();
userMessages.forEach(m => {
const otherId = m.fromUserId === sess.userId ? m.toUserId : m.fromUserId;
const otherName = m.fromUserId === sess.userId ? m.toUsername : m.fromUsername;
if (!conversationsMap.has(otherId)) {
conversationsMap.set(otherId, {
userId: otherId,
username: otherName,
lastMessage: m,
unreadCount: 0
});
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' });
}
if (m.toUserId === sess.userId && !m.read) {
conversationsMap.get(otherId).unreadCount++;
}
});
const conversations = Array.from(conversationsMap.values()).sort((a, b) =>
new Date(b.lastMessage.timestamp) - new Date(a.lastMessage.timestamp)
);
sendJson(res, 200, { conversations });
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()
.then(records => appendImportedRuns(records.map(mapPointercrateRecord), 'Pointercrate'))
.then(summary => sendJson(res, 200, Object.assign({ ok: true, source: 'pointercrate' }, summary)))
.catch(error => sendJson(res, 500, { error: String(error.message || error) }));
return;
}
if (req.method === 'POST' && pathname === '/api/import/aredl') {
if (!requireAdmin(req, res)) return;
fetchAredlRecords()
.then(records => appendImportedRuns(records.map(mapAredlRecord), 'AREDL'))
.then(summary => sendJson(res, 200, Object.assign({ ok: true, source: 'aredl' }, summary)))
.catch(error => sendJson(res, 500, { error: String(error.message || error) }));
return;
}
if ((req.method === 'PUT' || req.method === 'DELETE') && pathname.startsWith('/api/runs/')) {
if (!requireAdmin(req, res)) return;
const runId = pathname.slice('/api/runs/'.length);
if (!runId) {
sendJson(res, 400, { error: 'Run id is required' });
if (req.method === 'GET' && pathname.startsWith('/api/messages/')) {
if (!sess) { sendJson(res, 401, { error: 'Login required' }); return; }
const otherUserId = pathname.slice('/api/messages/'.length);
if (!otherUserId) {
sendJson(res, 400, { error: 'Missing user ID' });
return;
}
let body = '';
req.on('data', chunk => {
body += chunk;
if (body.length > 2 * 1024 * 1024) req.destroy();
const messages = readMessages();
const userMessages = messages.filter(m =>
(m.fromUserId === sess.userId && m.toUserId === otherUserId) ||
(m.fromUserId === otherUserId && m.toUserId === sess.userId)
).sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp));
messages.forEach(m => {
if (m.fromUserId === otherUserId && m.toUserId === sess.userId && !m.read) {
m.read = true;
}
});
writeMessages(messages);
sendJson(res, 200, { messages: userMessages });
return;
}
if (req.method === 'POST' && pathname === '/api/users/search') {
if (!sess) { sendJson(res, 401, { error: 'Login required' }); return; }
let body = '';
req.on('data', chunk => { body += chunk; if (body.length > 65536) req.destroy(); });
req.on('end', () => {
try {
const runs = readRuns();
const index = runs.findIndex(run => run.id === runId);
if (index === -1) {
sendJson(res, 404, { error: 'Run not found' });
return;
}
if (req.method === 'DELETE') {
runs.splice(index, 1);
writeRuns(runs);
sendEvent('runs-update', { updatedAt: new Date().toISOString() });
sendJson(res, 200, { ok: true });
return;
}
const payload = JSON.parse(body || '{}');
runs[index] = normalizeRun(payload, runs[index]);
writeRuns(runs);
sendEvent('runs-update', { updatedAt: runs[index].updatedAt });
sendJson(res, 200, { ok: true, item: runs[index] });
const query = String(payload.query || '').trim().toLowerCase();
if (!query || query.length < 2) {
sendJson(res, 400, { error: 'Query must be at least 2 characters' });
return;
}
const users = readUsers();
const results = users
.filter(u => u.username.toLowerCase().includes(query) && u.id !== sess.userId)
.map(u => ({ userId: u.id, username: u.username }))
.slice(0, 10);
sendJson(res, 200, { results });
} catch (error) {
sendJson(res, 400, { error: 'Invalid run update payload' });
sendJson(res, 400, { error: 'Invalid search payload' });
}
});
return;
+2 -1
View File
@@ -16,6 +16,7 @@
<a href="lists.html">Lists</a>
<a href="roulette.html">Roulette</a>
<a href="post.html">Posts</a>
<a href="messages.html">Messages</a>
<a href="contact.html">Contact</a>
</nav>
</header>
@@ -41,7 +42,7 @@
<p id="signup-status" class="muted" role="status"></p>
<div class="auth-actions">
<button type="submit" class="btn" id="signup-submit">Create account</button>
<a class="text-link" href="login.html">Already have an account? Log in</a>
<a class="text-link" href="login.html?return=signup.html">Already have an account? Log in</a>
</div>
</form>
</section>