511 lines
19 KiB
JavaScript
511 lines
19 KiB
JavaScript
// public/app.js - front-end entry point. Wires state, UI, API, and SSE event stream.
|
|
//
|
|
// Architecture:
|
|
// - State is a small in-memory object (conversations, buddies, invites, active tab).
|
|
// - SSE events arrive from /api/events; handlers normalize/dedupe and update state + UI.
|
|
// - Dedupe matters because TOC/Web API paths and SSE replay can surface the same message;
|
|
// we use msgId when present, otherwise a short recent text/from/mine heuristic.
|
|
// - UI rendering is delegated to js/ui.js; API calls to js/api.js; SSE to js/stream.js.
|
|
import { api } from './js/api.js?v=36';
|
|
import { createStream } from './js/stream.js?v=36';
|
|
import * as ui from './js/ui.js?v=36';
|
|
|
|
window.addEventListener('error', (e) => {
|
|
console.error('[ui] error', e.error || e.message);
|
|
try { ui.setChatError(`UI error: ${e.message}`); } catch {}
|
|
});
|
|
window.addEventListener('unhandledrejection', (e) => {
|
|
console.error('[ui] unhandled rejection', e.reason);
|
|
try { ui.setChatError(`UI error: ${e.reason?.message || e.reason}`); } catch {}
|
|
});
|
|
|
|
const state = {
|
|
screenName: null,
|
|
active: null,
|
|
conversations: {}, // key -> { key, type: 'im'|'chat', name, messages: [], roomId?, roomName? }
|
|
buddies: [],
|
|
invites: [], // { roomId, roomName, from, message, time }
|
|
selectConversation(key) {
|
|
state.active = key;
|
|
ui.renderConversations(state, closeConversation);
|
|
ui.renderMessages(state);
|
|
},
|
|
};
|
|
|
|
const stream = createStream();
|
|
|
|
function convKey(type, name) {
|
|
return `${type}:${String(name).toLowerCase()}`;
|
|
}
|
|
|
|
function ensureConversation(type, name) {
|
|
const key = convKey(type, name);
|
|
if (!state.conversations[key]) {
|
|
state.conversations[key] = { key, type, name, messages: [] };
|
|
}
|
|
return state.conversations[key];
|
|
}
|
|
|
|
// NOTE: Dedupe is required here. Sent messages can be added optimistically and also
|
|
// arrive via SSE replay/broadcast (e.g. TOC sentIM buffer). Never remove this guard
|
|
// or duplicates will reappear in the UI.
|
|
function addMessage(type, name, msg) {
|
|
if (!name || name === 'unknown') return;
|
|
const conv = ensureConversation(type, name);
|
|
if (msg?.msgId && conv.messages.some((m) => m.msgId && m.msgId === msg.msgId)) return;
|
|
if (msg?.text && conv.messages.slice(-6).some((m) => m.text === msg.text && normalizeName(m.from) === normalizeName(msg.from) && !!m.mine === !!msg.mine)) return;
|
|
conv.messages.push(msg);
|
|
if (!state.active) state.active = conv.key;
|
|
ui.renderConversations(state, closeConversation);
|
|
ui.renderMessages(state);
|
|
}
|
|
|
|
function openIM(name) {
|
|
const conv = ensureConversation('im', name);
|
|
state.selectConversation(conv.key);
|
|
}
|
|
|
|
function openChat(name) {
|
|
const existing = Object.values(state.conversations).find((c) => c.type === 'chat' && normalizeName(c.roomName || c.name) === normalizeName(name));
|
|
if (existing) { state.selectConversation(existing.key); return; }
|
|
const conv = ensureConversation('chat', name);
|
|
state.selectConversation(conv.key);
|
|
}
|
|
|
|
async function closeConversation(key) {
|
|
const conv = state.conversations[key];
|
|
if (!conv) return;
|
|
if (conv.type === 'chat') {
|
|
try { await api.leaveRoom(conv.roomId || conv.name); } catch (err) { console.warn('[chat] leave failed', err.message); }
|
|
}
|
|
delete state.conversations[key];
|
|
if (state.active === key) {
|
|
const keys = Object.keys(state.conversations);
|
|
state.active = keys[keys.length - 1] || null;
|
|
}
|
|
ui.renderConversations(state, closeConversation);
|
|
ui.renderMessages(state);
|
|
}
|
|
|
|
function plainText(s) {
|
|
if (typeof s !== 'string') return '';
|
|
// AIM messages often arrive as HTML; render as plain text safely.
|
|
if (s.includes('<') && s.includes('>')) {
|
|
try {
|
|
const doc = new DOMParser().parseFromString(s, 'text/html');
|
|
return (doc.body.textContent || '').trim();
|
|
} catch { /* fall through */ }
|
|
}
|
|
return s;
|
|
}
|
|
|
|
function normalizeName(s) {
|
|
return String(s || '').toLowerCase().replace(/\s+/g, '');
|
|
}
|
|
|
|
function buddyName(b) {
|
|
if (typeof b === 'string') return b;
|
|
return String(b?.aimId || b?.displayId || b?.screenName || b?.name || '');
|
|
}
|
|
|
|
// --- Event handlers (M0 partially confirmed) ---
|
|
|
|
function aimId(obj) {
|
|
return obj?.aimId || obj?.displayId || obj?.screenName || obj?.sender || 'unknown';
|
|
}
|
|
|
|
stream.on('im', (event) => {
|
|
const d = event.data || event.raw?.eventData || {};
|
|
const from = aimId(d.source || d.sender || d);
|
|
const to = aimId(d.dest || d.target || {});
|
|
const text = plainText(d.message || d.text || d.msg || '');
|
|
const mine = normalizeName(from) === normalizeName(state.screenName);
|
|
const peer = mine ? (to && to !== 'unknown' ? to : from) : from;
|
|
const key = convKey('im', peer);
|
|
const conv = state.conversations[key];
|
|
if (conv && d.msgId && conv.messages.some((m) => m.msgId && m.msgId === d.msgId)) return;
|
|
if (conv) {
|
|
const recent = conv.messages.slice(-6).some((m) => m.text === text && normalizeName(m.from) === normalizeName(from));
|
|
if (recent) return;
|
|
}
|
|
addMessage('im', peer, { from, text, time: event.time, mine, msgId: d.msgId });
|
|
});
|
|
|
|
stream.on('sentIM', (event) => {
|
|
const d = event.data || event.raw?.eventData || {};
|
|
if (!d.iSent) return;
|
|
let to = aimId(d.dest || d.target || {});
|
|
const text = plainText(d.message || d.text || d.msg || '');
|
|
if (!to || to === 'unknown') {
|
|
// Fallback: find conv where optimistic message was just added.
|
|
for (const c of Object.values(state.conversations)) {
|
|
if (c.type !== 'im') continue;
|
|
if (d.msgId && c.messages.some((m) => m.msgId && m.msgId === d.msgId)) { to = c.name; break; }
|
|
if (c.messages.slice(-6).some((m) => m.mine && m.text === text)) { to = c.name; break; }
|
|
}
|
|
}
|
|
if (!to || to === 'unknown') return; // can't place it safely
|
|
const key = convKey('im', to);
|
|
const conv = state.conversations[key];
|
|
if (conv && d.msgId && conv.messages.some((m) => m.msgId && m.msgId === d.msgId)) return;
|
|
if (conv && conv.messages.slice(-6).some((m) => m.mine && m.text === text)) return;
|
|
addMessage('im', to, { from: state.screenName || 'me', text, time: event.time, mine: true, msgId: d.msgId });
|
|
});
|
|
|
|
stream.on('chat', (event) => {
|
|
const d = event.data || event.raw?.eventData || {};
|
|
const room = d.room || d.chat || d.chatId || d.exchange || 'room';
|
|
const from = aimId(d.source || d.sender || d);
|
|
const text = plainText(d.message || d.text || d.msg || '');
|
|
const mine = normalizeName(from) === normalizeName(state.screenName);
|
|
const key = convKey('chat', room);
|
|
const conv = state.conversations[key];
|
|
if (conv && d.msgId && conv.messages.some((m) => m.msgId && m.msgId === d.msgId)) return;
|
|
if (conv && conv.messages.slice(-6).some((m) => m.text === text && normalizeName(m.from) === normalizeName(from))) return;
|
|
addMessage('chat', room, { from, text, time: event.time, mine, msgId: d.msgId });
|
|
});
|
|
|
|
function renderInvites() {
|
|
ui.renderInvites(state.invites, async (roomId) => {
|
|
try { await api.acceptChat(roomId); } catch (err) { ui.setChatError(err.message); }
|
|
}, (roomId) => {
|
|
state.invites = state.invites.filter((i) => i.roomId !== roomId);
|
|
renderInvites();
|
|
});
|
|
}
|
|
|
|
stream.on('chat_invite', (event) => {
|
|
const d = event.data || {};
|
|
const invite = {
|
|
roomId: String(d.roomId || ''),
|
|
roomName: String(d.roomName || 'Chat room'),
|
|
from: String(d.from || 'unknown'),
|
|
message: plainText(d.message || ''),
|
|
time: event.time,
|
|
};
|
|
state.invites.unshift(invite);
|
|
renderInvites();
|
|
// Also surface as a system message so it's visible.
|
|
const key = convKey('im', invite.from);
|
|
addMessage('im', invite.from, { from: 'system', text: `Chat invite: "${invite.roomName}" - use Invites panel to join.`, time: event.time, mine: false, system: true });
|
|
});
|
|
|
|
stream.on('chat_join', (event) => {
|
|
const d = event.data || {};
|
|
const roomId = String(d.roomId || d.roomName || 'room');
|
|
const roomName = String(d.roomName || d.roomId || 'Chat room');
|
|
const key = convKey('chat', roomId);
|
|
if (!state.conversations[key]) {
|
|
state.conversations[key] = { key, type: 'chat', name: roomName, roomId, roomName, messages: [] };
|
|
} else {
|
|
state.conversations[key].name = roomName;
|
|
state.conversations[key].roomId = roomId;
|
|
state.conversations[key].roomName = roomName;
|
|
}
|
|
// Merge any duplicate conv created by name before roomId was known.
|
|
const nameKey = convKey('chat', roomName);
|
|
if (nameKey !== key && state.conversations[nameKey]) {
|
|
const old = state.conversations[nameKey];
|
|
const target = state.conversations[key];
|
|
for (const m of old.messages || []) {
|
|
if (m.msgId && target.messages.some((x) => x.msgId && x.msgId === m.msgId)) continue;
|
|
if (target.messages.some((x) => x.text === m.text && x.from === m.from && x.mine === m.mine)) continue;
|
|
target.messages.push(m);
|
|
}
|
|
target.messages.sort((a, b) => (a.time || 0) - (b.time || 0));
|
|
delete state.conversations[nameKey];
|
|
if (state.active === nameKey) state.active = key;
|
|
}
|
|
// remove matching invite
|
|
state.invites = state.invites.filter((i) => i.roomId !== roomId);
|
|
renderInvites();
|
|
state.selectConversation(key);
|
|
});
|
|
|
|
stream.on('chat_in', (event) => {
|
|
const d = event.data || {};
|
|
const roomId = String(d.roomId || 'room');
|
|
const from = String(d.from || 'unknown');
|
|
const text = plainText(d.message || '');
|
|
const mine = normalizeName(from) === normalizeName(state.screenName);
|
|
const key = convKey('chat', roomId);
|
|
if (!state.conversations[key]) state.conversations[key] = { key, type: 'chat', name: roomId, roomId, messages: [] };
|
|
const conv = state.conversations[key];
|
|
if (d.msgId && conv.messages.some((m) => m.msgId && m.msgId === d.msgId)) return;
|
|
if (conv.messages.slice(-6).some((m) => m.text === text && normalizeName(m.from) === normalizeName(from))) return;
|
|
addMessage('chat', roomId, { from, text, time: event.time, mine, msgId: d.msgId });
|
|
});
|
|
|
|
stream.on('chat_left', (event) => {
|
|
const d = event.data || {};
|
|
const roomId = String(d.roomId || '');
|
|
const key = convKey('chat', roomId);
|
|
if (state.conversations[key]) {
|
|
state.conversations[key].messages.push({ from: 'system', text: 'You left the chat.', time: event.time, mine: false, system: true });
|
|
ui.renderMessages(state);
|
|
}
|
|
});
|
|
|
|
stream.on('toc_status', (event) => {
|
|
const d = event.data || {};
|
|
const detail = d.error || d.code ? String(d.error || d.code) : '';
|
|
ui.setTocStatus(!!d.connected, detail);
|
|
});
|
|
|
|
stream.on('toc_error', (event) => {
|
|
const code = String(event.data?.code || '');
|
|
if (['980', '981', '982'].includes(code)) {
|
|
console.warn('[toc]', event.data?.message || event.data?.raw);
|
|
return; // expected auth/rate-limit noise when TOC unavailable
|
|
}
|
|
const msg = event.data?.message || 'TOC error';
|
|
ui.setChatError(msg);
|
|
});
|
|
|
|
function mergeBuddyPreservePresence(incoming) {
|
|
const prev = new Map();
|
|
for (const b of (state.buddies || [])) {
|
|
prev.set(normalizeName(buddyName(b)), b);
|
|
}
|
|
return (incoming || []).map((b) => {
|
|
const name = buddyName(b);
|
|
const old = prev.get(normalizeName(name));
|
|
if (!old || typeof old === 'string') return b;
|
|
const base = typeof b === 'string' ? { screenName: b } : { ...b };
|
|
// Preserve presence fields from previous state unless incoming has explicit ones.
|
|
if (base.online === undefined && old.online !== undefined) base.online = old.online;
|
|
if (base.idleMins === undefined && old.idleMins !== undefined) base.idleMins = old.idleMins;
|
|
if (base.state === undefined && old.state !== undefined) base.state = old.state;
|
|
if (base.status === undefined && old.status !== undefined) base.status = old.status;
|
|
return base;
|
|
});
|
|
}
|
|
|
|
stream.on('buddylist', (event) => {
|
|
const d = event.data || event.raw?.eventData || {};
|
|
const groups = Array.isArray(d.groups) ? d.groups : [];
|
|
const buddies = groups.flatMap((g) => Array.isArray(g.buddies) ? g.buddies : []);
|
|
state.buddies = mergeBuddyPreservePresence(buddies);
|
|
ui.renderBuddies(state.buddies, (name) => openIM(name));
|
|
});
|
|
|
|
stream.on('presence', (event) => {
|
|
const d = event.data || event.raw?.eventData || {};
|
|
const name = String(d.screenName || d.aimId || d.displayId || d.name || '');
|
|
if (!name) return;
|
|
const norm = normalizeName(name);
|
|
let found = false;
|
|
state.buddies = (state.buddies || []).map((b) => {
|
|
const bName = typeof b === 'string' ? b : (b.aimId || b.displayId || b.screenName || b.name || '');
|
|
if (normalizeName(bName) !== norm) return b;
|
|
found = true;
|
|
const base = typeof b === 'string' ? { screenName: b } : { ...b };
|
|
return { ...base, ...d, screenName: base.screenName || name };
|
|
});
|
|
if (!found) state.buddies.push({ screenName: name, ...d });
|
|
ui.renderBuddies(state.buddies, (n) => openIM(n));
|
|
});
|
|
|
|
stream.on('broadcast', (event) => {
|
|
const d = event.data || event.raw?.eventData || {};
|
|
const text = event.text || d.message || d.text || d.msg || '';
|
|
if (text) ui.showBroadcast(text);
|
|
});
|
|
|
|
// Fallback: show unknown events in console to help M0 discovery.
|
|
stream.on('*', (event) => {
|
|
if (!['im', 'chat', 'broadcast'].includes(event.type)) {
|
|
console.debug('[stream] unhandled event', event);
|
|
}
|
|
});
|
|
|
|
// --- UI wiring ---
|
|
|
|
async function loadChallenge() {
|
|
try {
|
|
const c = await api.challenge();
|
|
document.getElementById('captchaQuestion').textContent = `${c.a} + ${c.b} =`;
|
|
document.getElementById('captchaAnswer').value = '';
|
|
const d = c.defaults || {};
|
|
const host = document.getElementById('serverHost');
|
|
const wp = document.getElementById('webapiPort');
|
|
const tp = document.getElementById('tocPort');
|
|
if (host && !host.value) host.value = d.host || 'oscar.claytonia.net';
|
|
if (wp && !wp.value) wp.value = String(d.webapiPort || 8081);
|
|
if (tp && !tp.value) tp.value = String(d.tocPort || 9898);
|
|
} catch (err) {
|
|
console.warn('[challenge] load failed', err);
|
|
}
|
|
}
|
|
|
|
document.getElementById('loginForm').addEventListener('submit', async (e) => {
|
|
e.preventDefault();
|
|
ui.setLoginError('');
|
|
const submitBtn = e.currentTarget.querySelector('.login-submit');
|
|
const originalBtnHtml = submitBtn ? submitBtn.innerHTML : '';
|
|
if (submitBtn) {
|
|
submitBtn.disabled = true;
|
|
submitBtn.innerHTML = '<span class="spinner" aria-hidden="true"></span>Signing in...';
|
|
}
|
|
const screenName = document.getElementById('screenName').value.trim();
|
|
const password = document.getElementById('password').value;
|
|
const host = document.getElementById('serverHost').value.trim();
|
|
const webapiPort = Number(document.getElementById('webapiPort').value);
|
|
const tocPort = Number(document.getElementById('tocPort').value);
|
|
const captchaAnswer = Number(document.getElementById('captchaAnswer').value);
|
|
try {
|
|
await api.login({ screenName, password, host, webapiPort, tocPort, captchaAnswer });
|
|
await afterLogin(screenName);
|
|
} catch (err) {
|
|
ui.setLoginError(err.message);
|
|
loadChallenge().catch(() => {});
|
|
} finally {
|
|
if (submitBtn) {
|
|
submitBtn.disabled = false;
|
|
submitBtn.innerHTML = originalBtnHtml || 'Sign in';
|
|
}
|
|
}
|
|
});
|
|
|
|
document.getElementById('logoutBtn').addEventListener('click', async () => {
|
|
try { await api.logout(); } catch { /* ignore */ }
|
|
stream.close();
|
|
state.screenName = null;
|
|
state.active = null;
|
|
state.conversations = {};
|
|
ui.showLogin();
|
|
loadChallenge().catch(() => {});
|
|
});
|
|
|
|
const messageInput = document.getElementById('messageInput');
|
|
messageInput.addEventListener('keydown', (e) => {
|
|
if (e.key === 'Enter' && !e.shiftKey) {
|
|
e.preventDefault();
|
|
document.getElementById('messageForm').requestSubmit();
|
|
}
|
|
});
|
|
|
|
document.getElementById('messageForm').addEventListener('submit', async (e) => {
|
|
e.preventDefault();
|
|
ui.setChatError('');
|
|
const input = document.getElementById('messageInput');
|
|
const text = input.value.trim();
|
|
if (!text || !state.active) return;
|
|
const conv = state.conversations[state.active];
|
|
try {
|
|
let msgId;
|
|
if (conv.type === 'im') {
|
|
const res = await api.sendIM(conv.name, text);
|
|
msgId = res?.data?.msgId;
|
|
} else {
|
|
const res = await api.sendChat(conv.roomId || conv.name, text);
|
|
msgId = res?.data?.msgId;
|
|
}
|
|
// addMessage dedupes by msgId/text - see note in addMessage().
|
|
addMessage(conv.type, conv.roomId || conv.name, {
|
|
from: state.screenName,
|
|
text,
|
|
time: Date.now(),
|
|
mine: true,
|
|
msgId,
|
|
});
|
|
input.value = '';
|
|
input.style.height = 'auto';
|
|
} catch (err) {
|
|
ui.setChatError(err.message);
|
|
}
|
|
});
|
|
|
|
document.getElementById('userSearchForm').addEventListener('submit', async (e) => {
|
|
e.preventDefault();
|
|
ui.setChatError('');
|
|
const q = document.getElementById('userSearch').value.trim();
|
|
if (!q) return;
|
|
try {
|
|
const data = await api.searchUsers(q);
|
|
const users = Array.isArray(data.users) ? data.users : [];
|
|
// Always offer the exact typed name so users can open IM directly even if search is unavailable.
|
|
if (!users.map((u) => u.toLowerCase()).includes(q.toLowerCase())) users.unshift(q);
|
|
ui.renderUserResults(users, (name) => openIM(name));
|
|
} catch (err) {
|
|
// Management API may be unreachable; still allow direct IM by screen name.
|
|
ui.renderUserResults([q], (name) => openIM(name));
|
|
ui.setChatError(`User search unavailable (${err.message}). You can still click the name to open an IM.`);
|
|
}
|
|
});
|
|
|
|
document.getElementById('addBuddyForm').addEventListener('submit', async (e) => {
|
|
e.preventDefault();
|
|
ui.setChatError('');
|
|
const name = document.getElementById('buddyName').value.trim();
|
|
if (!name) return;
|
|
try {
|
|
await api.addBuddy(name);
|
|
document.getElementById('buddyName').value = '';
|
|
if (!state.buddies.some((b) => (b.aimId || b.displayId || b.screenName || b.name || b).toString().toLowerCase() === name.toLowerCase())) {
|
|
state.buddies.push({ aimId: name, displayId: name, state: 'unknown' });
|
|
}
|
|
ui.renderBuddies(state.buddies, (name) => openIM(name));
|
|
await loadBuddies();
|
|
} catch (err) {
|
|
ui.setChatError(err.message);
|
|
}
|
|
});
|
|
|
|
document.getElementById('joinRoomForm').addEventListener('submit', async (e) => {
|
|
e.preventDefault();
|
|
ui.setChatError('');
|
|
const room = document.getElementById('roomName').value.trim();
|
|
if (!room) return;
|
|
try {
|
|
await api.joinRoom(room);
|
|
openChat(room);
|
|
document.getElementById('roomName').value = '';
|
|
} catch (err) {
|
|
ui.setChatError(err.message);
|
|
}
|
|
});
|
|
|
|
async function loadBuddies() {
|
|
try {
|
|
const data = await api.buddies();
|
|
// M0: buddylist event buffer preferred; presence/get is fallback.
|
|
const groups = Array.isArray(data?.data?.groups) ? data.data.groups : [];
|
|
const users = Array.isArray(data?.data?.users) ? data.data.users : [];
|
|
const buddies = [
|
|
...groups.flatMap((g) => Array.isArray(g.buddies) ? g.buddies : []),
|
|
...users,
|
|
];
|
|
if (buddies.length) state.buddies = mergeBuddyPreservePresence(buddies);
|
|
ui.renderBuddies(state.buddies, (name) => openIM(name));
|
|
} catch (err) {
|
|
console.warn('[buddies] load failed', err.message);
|
|
}
|
|
}
|
|
|
|
async function afterLogin(screenName) {
|
|
state.screenName = screenName;
|
|
ui.showChat(screenName);
|
|
ui.setMessageStyle(ui.getMessageStyle());
|
|
ui.setTocStatus(false);
|
|
ui.renderConversations(state, closeConversation);
|
|
ui.renderMessages(state);
|
|
stream.connect();
|
|
await loadBuddies();
|
|
}
|
|
|
|
async function boot() {
|
|
try {
|
|
const me = await api.me();
|
|
if (me.loggedIn) {
|
|
await afterLogin(me.screenName);
|
|
return;
|
|
}
|
|
} catch {
|
|
// fall through to login
|
|
}
|
|
ui.showLogin();
|
|
loadChallenge().catch(() => {});
|
|
}
|
|
|
|
boot();
|