GsDChat/src/GsDChat.Server/wwwroot/app.js

2278 lines
81 KiB
JavaScript

(() => {
// Application State
const state = {
token: localStorage.getItem('gsdchat_token') || null,
user: JSON.parse(localStorage.getItem('gsdchat_user') || 'null'),
publicKey: null,
privateKey: null,
serverPublicKey: null,
serverEncryptedPrivateKey: null,
accountE2eeEnabled: true,
serverInfo: null,
allowDmE2ee: true,
maxGroupChatUsers: 10,
activeChannelId: null,
channels: [],
directMessages: [],
groupChats: [],
messages: {}, // channelId -> array
hasMoreHistory: {}, // channelId -> bool
loadingHistory: {}, // channelId -> bool
e2eePromptedDms: {}, // dmChannelId -> bool (prevent repeated intrusive prompts after dismiss)
users: [],
files: [],
socket: null,
isRegister: false,
reconnectTimer: null
};
// DOM Elements
const el = {
serverTitle: document.getElementById('serverTitle'),
connIndicator: document.getElementById('connIndicator'),
navTabs: document.querySelectorAll('.nav-tab'),
tabViews: document.querySelectorAll('.tab-view'),
currentUsername: document.getElementById('currentUsername'),
currentUserRole: document.getElementById('currentUserRole'),
e2eeVaultBtn: document.getElementById('e2eeVaultBtn'),
logoutBtn: document.getElementById('logoutBtn'),
userBadge: document.getElementById('userBadge'),
// Chat View
activeConvPrefix: document.getElementById('activeConvPrefix'),
channelSelectDropdown: document.getElementById('channelSelectDropdown'),
chatSecurityBadge: document.getElementById('chatSecurityBadge'),
activeChannelTopic: document.getElementById('activeChannelTopic'),
toggleDmE2eeBtn: document.getElementById('toggleDmE2eeBtn'),
inviteGroupBtn: document.getElementById('inviteGroupBtn'),
leaveGroupBtn: document.getElementById('leaveGroupBtn'),
chatMessages: document.getElementById('chatMessages'),
messageInput: document.getElementById('messageInput'),
sendBtn: document.getElementById('sendBtn'),
fileInput: document.getElementById('fileInput'),
welcomeMotd: document.getElementById('welcomeMotd'),
toggleMembersBtn: document.getElementById('toggleMembersBtn'),
chatMembersSidebar: document.getElementById('chatMembersSidebar'),
chatOnlineUsersList: document.getElementById('chatOnlineUsersList'),
chatOnlineCountBadge: document.getElementById('chatOnlineCountBadge'),
chatHeaderOnlineCount: document.getElementById('chatHeaderOnlineCount'),
// Channels, Groups & DMs View
channelList: document.getElementById('channelList'),
openCreateChannelBtn: document.getElementById('openCreateChannelBtn'),
createChannelCard: document.getElementById('createChannelCard'),
newChannelName: document.getElementById('newChannelName'),
newChannelTopic: document.getElementById('newChannelTopic'),
submitCreateChannelBtn: document.getElementById('submitCreateChannelBtn'),
cancelCreateChannelBtn: document.getElementById('cancelCreateChannelBtn'),
groupChatList: document.getElementById('groupChatList'),
maxGroupUsersHint: document.getElementById('maxGroupUsersHint'),
openCreateGroupBtn: document.getElementById('openCreateGroupBtn'),
createGroupCard: document.getElementById('createGroupCard'),
newGroupName: document.getElementById('newGroupName'),
newGroupMembers: document.getElementById('newGroupMembers'),
newGroupTopic: document.getElementById('newGroupTopic'),
submitCreateGroupBtn: document.getElementById('submitCreateGroupBtn'),
cancelCreateGroupBtn: document.getElementById('cancelCreateGroupBtn'),
dmList: document.getElementById('dmList'),
dmE2eeStatusHint: document.getElementById('dmE2eeStatusHint'),
openE2eeSettingsBtn: document.getElementById('openE2eeSettingsBtn'),
openStartDmBtn: document.getElementById('openStartDmBtn'),
startDmCard: document.getElementById('startDmCard'),
dmTargetUsername: document.getElementById('dmTargetUsername'),
submitStartDmBtn: document.getElementById('submitStartDmBtn'),
cancelStartDmBtn: document.getElementById('cancelStartDmBtn'),
// Users View
userList: document.getElementById('userList'),
userCountBadge: document.getElementById('userCountBadge'),
// Files View
filesList: document.getElementById('filesList'),
filesViewUploadInput: document.getElementById('filesViewUploadInput'),
// E2EE Vault Modal
e2eeModal: document.getElementById('e2eeModal'),
e2eeModalTitle: document.getElementById('e2eeModalTitle'),
e2eeModalSubtitle: document.getElementById('e2eeModalSubtitle'),
e2eeVaultStatusBanner: document.getElementById('e2eeVaultStatusBanner'),
e2eePinForm: document.getElementById('e2eePinForm'),
e2eePinLabel: document.getElementById('e2eePinLabel'),
e2eePinInput: document.getElementById('e2eePinInput'),
e2eeModalError: document.getElementById('e2eeModalError'),
e2eeSubmitPinBtn: document.getElementById('e2eeSubmitPinBtn'),
e2eeToggleAccountBtn: document.getElementById('e2eeToggleAccountBtn'),
e2eeLockDeviceBtn: document.getElementById('e2eeLockDeviceBtn'),
e2eeResetPinBtn: document.getElementById('e2eeResetPinBtn'),
e2eeCloseModalBtn: document.getElementById('e2eeCloseModalBtn'),
// Auth Modal
authModal: document.getElementById('authModal'),
modalServerName: document.getElementById('modalServerName'),
modalMotd: document.getElementById('modalMotd'),
tabLogin: document.getElementById('tabLogin'),
tabRegister: document.getElementById('tabRegister'),
authForm: document.getElementById('authForm'),
groupServerPassword: document.getElementById('groupServerPassword'),
groupInviteToken: document.getElementById('groupInviteToken'),
authServerPassword: document.getElementById('authServerPassword'),
authUsername: document.getElementById('authUsername'),
authPassword: document.getElementById('authPassword'),
authInviteToken: document.getElementById('authInviteToken'),
authSubmitBtn: document.getElementById('authSubmitBtn'),
authError: document.getElementById('authError'),
toastContainer: document.getElementById('toastContainer'),
dropOverlay: document.getElementById('dropOverlay')
};
function initElements() {
for (const key in el) {
if (!el[key] && typeof key === 'string') {
const found = document.getElementById(key);
if (found) el[key] = found;
}
}
}
// ==========================================
// Local Device E2EE Key Cache Helpers
// ==========================================
function getUserKeyCacheStorageKey(userId) {
return `gsdchat_e2ee_vault_${userId}`;
}
function loadCachedKeysForCurrentUser() {
if (!state.user || !state.user.id) return false;
try {
const raw = localStorage.getItem(getUserKeyCacheStorageKey(state.user.id));
if (raw) {
const cached = JSON.parse(raw);
if (cached && cached.publicKey && cached.privateKey) {
// Verify cached public key matches server public key if server has one
if (!state.serverPublicKey || state.serverPublicKey === cached.publicKey) {
state.publicKey = cached.publicKey;
state.privateKey = cached.privateKey;
if (cached.encryptedPrivateKey && !state.serverEncryptedPrivateKey) {
state.serverEncryptedPrivateKey = cached.encryptedPrivateKey;
}
return true;
}
}
}
} catch {
// Ignore storage error
}
return false;
}
function saveCachedKeysForCurrentUser(pubKey, privKey, encPrivKey) {
if (!state.user || !state.user.id) return;
try {
localStorage.setItem(getUserKeyCacheStorageKey(state.user.id), JSON.stringify({
publicKey: pubKey,
privateKey: privKey,
encryptedPrivateKey: encPrivKey || state.serverEncryptedPrivateKey || null
}));
// Also set legacy keys for compatibility
if (pubKey) localStorage.setItem('gsdchat_e2ee_pub', pubKey);
if (privKey) localStorage.setItem('gsdchat_e2ee_priv', privKey);
} catch {
// Ignore storage error
}
}
function clearCachedKeysForCurrentUser() {
if (state.user && state.user.id) {
localStorage.removeItem(getUserKeyCacheStorageKey(state.user.id));
}
localStorage.removeItem('gsdchat_e2ee_pub');
localStorage.removeItem('gsdchat_e2ee_priv');
state.publicKey = null;
state.privateKey = null;
}
// ==========================================
// Web Crypto E2EE Engine (P-256 ECDH + AES-256-GCM)
// Compatible with GsDChat.Core.Security.E2eeCrypto
// ==========================================
const E2EE_PREFIX = 'E2EE:v1:';
const WRAP_PREFIX = 'WRAP:v1:';
function bytesToBase64(bytes) {
let bin = '';
const arr = new Uint8Array(bytes);
for (let i = 0; i < arr.length; i++) {
bin += String.fromCharCode(arr[i]);
}
return btoa(bin);
}
function base64ToBytes(b64) {
const bin = atob(b64);
const arr = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) {
arr[i] = bin.charCodeAt(i);
}
return arr;
}
async function generateE2eeKeyPair() {
if (!window.crypto || !window.crypto.subtle) {
return { publicKey: '', privateKey: '' };
}
const keyPair = await window.crypto.subtle.generateKey(
{ name: 'ECDH', namedCurve: 'P-256' },
true,
['deriveBits']
);
const spki = await window.crypto.subtle.exportKey('spki', keyPair.publicKey);
const pkcs8 = await window.crypto.subtle.exportKey('pkcs8', keyPair.privateKey);
return {
publicKey: bytesToBase64(spki),
privateKey: bytesToBase64(pkcs8)
};
}
async function deriveWrappingAesKey(pinOrPassphrase, username) {
const enc = new TextEncoder();
const saltInput = enc.encode(`GsDChat-E2EE-KeyWrap:${username.trim().toLowerCase()}`);
const saltHash = await window.crypto.subtle.digest('SHA-256', saltInput);
const baseKey = await window.crypto.subtle.importKey(
'raw',
enc.encode(pinOrPassphrase),
'PBKDF2',
false,
['deriveKey']
);
return window.crypto.subtle.deriveKey(
{
name: 'PBKDF2',
salt: saltHash,
iterations: 100000,
hash: 'SHA-256'
},
baseKey,
{ name: 'AES-GCM', length: 256 },
false,
['encrypt', 'decrypt']
);
}
async function wrapPrivateKey(privateKeyBase64, pinOrPassphrase, username) {
if (!window.crypto || !window.crypto.subtle || !privateKeyBase64) return '';
try {
const wrapKey = await deriveWrappingAesKey(pinOrPassphrase, username);
const nonce = window.crypto.getRandomValues(new Uint8Array(12));
const plainBytes = new TextEncoder().encode(privateKeyBase64);
const cipherBuf = await window.crypto.subtle.encrypt(
{ name: 'AES-GCM', iv: nonce, tagLength: 128 },
wrapKey,
plainBytes
);
return `${WRAP_PREFIX}${bytesToBase64(nonce)}:${bytesToBase64(cipherBuf)}`;
} catch {
return '';
}
}
async function unwrapPrivateKey(wrappedBlob, pinOrPassphrase, username) {
if (!window.crypto || !window.crypto.subtle || !wrappedBlob || !wrappedBlob.startsWith(WRAP_PREFIX)) {
return null;
}
try {
const rest = wrappedBlob.substring(WRAP_PREFIX.length);
const sep = rest.indexOf(':');
if (sep < 0) return null;
const nonce = base64ToBytes(rest.substring(0, sep));
const combined = base64ToBytes(rest.substring(sep + 1));
const wrapKey = await deriveWrappingAesKey(pinOrPassphrase, username);
const plainBuf = await window.crypto.subtle.decrypt(
{ name: 'AES-GCM', iv: nonce, tagLength: 128 },
wrapKey,
combined
);
return new TextDecoder().decode(plainBuf);
} catch {
return null;
}
}
async function deriveSharedAesGcmKey(myPrivateKeyB64, peerPublicKeyB64) {
const privBytes = base64ToBytes(myPrivateKeyB64);
const pubBytes = base64ToBytes(peerPublicKeyB64);
const myPrivKey = await window.crypto.subtle.importKey(
'pkcs8',
privBytes,
{ name: 'ECDH', namedCurve: 'P-256' },
false,
['deriveBits']
);
const peerPubKey = await window.crypto.subtle.importKey(
'spki',
pubBytes,
{ name: 'ECDH', namedCurve: 'P-256' },
false,
[]
);
const rawSecret = await window.crypto.subtle.deriveBits(
{ name: 'ECDH', public: peerPubKey },
myPrivKey,
256
);
const keyHash = await window.crypto.subtle.digest('SHA-256', rawSecret);
return window.crypto.subtle.importKey(
'raw',
keyHash,
{ name: 'AES-GCM' },
false,
['encrypt', 'decrypt']
);
}
async function encryptDmMessage(plaintext, myPrivateKeyB64, peerPublicKeyB64) {
if (!window.crypto || !window.crypto.subtle || !myPrivateKeyB64 || !peerPublicKeyB64) {
return { content: plaintext, isEncrypted: false };
}
try {
const aesKey = await deriveSharedAesGcmKey(myPrivateKeyB64, peerPublicKeyB64);
const nonce = window.crypto.getRandomValues(new Uint8Array(12));
const plainBytes = new TextEncoder().encode(plaintext);
const cipherBuf = await window.crypto.subtle.encrypt(
{ name: 'AES-GCM', iv: nonce, tagLength: 128 },
aesKey,
plainBytes
);
return {
content: `${E2EE_PREFIX}${bytesToBase64(nonce)}:${bytesToBase64(cipherBuf)}`,
isEncrypted: true
};
} catch (err) {
console.error('E2EE encryption failed:', err);
return { content: plaintext, isEncrypted: false };
}
}
async function decryptDmMessage(payload, myPrivateKeyB64, peerPublicKeyB64) {
if (!payload || !payload.startsWith(E2EE_PREFIX)) {
return payload;
}
if (!window.crypto || !window.crypto.subtle || !myPrivateKeyB64 || !peerPublicKeyB64) {
return '[🔒 Encrypted Message - Unlock E2EE Vault with PIN]';
}
try {
const rest = payload.substring(E2EE_PREFIX.length);
const sep = rest.indexOf(':');
if (sep < 0) return '[Encrypted Message - Malformed]';
const nonce = base64ToBytes(rest.substring(0, sep));
const combined = base64ToBytes(rest.substring(sep + 1));
const aesKey = await deriveSharedAesGcmKey(myPrivateKeyB64, peerPublicKeyB64);
const plainBuf = await window.crypto.subtle.decrypt(
{ name: 'AES-GCM', iv: nonce, tagLength: 128 },
aesKey,
combined
);
return new TextDecoder().decode(plainBuf);
} catch {
return '[Encrypted Message - Decryption Failed (Wrong Key Vault)]';
}
}
function getPeerPublicKeyForDm(dm) {
if (!dm) return null;
const memberIds = dm.memberIds || dm.MemberIds || [];
const memberNames = dm.memberUsernames || dm.MemberUsernames || [];
const memberKeys = dm.memberPublicKeys || dm.MemberPublicKeys || {};
const myId = state.user ? state.user.id : '';
const myName = state.user ? state.user.username : '';
const peerId = memberIds.find(id => id.toLowerCase() !== (myId || '').toLowerCase());
if (peerId) {
if (memberKeys[peerId]) return memberKeys[peerId];
const u = state.users.find(user => (user.id || user.Id || '').toLowerCase() === peerId.toLowerCase());
if (u && (u.publicKey || u.PublicKey)) return u.publicKey || u.PublicKey;
}
const rawDmName = (dm.name || dm.Name || '').replace(/^@/, '');
const peerName = memberNames.find(n => n.toLowerCase() !== (myName || '').toLowerCase()) || rawDmName;
if (peerName) {
if (memberKeys[peerName]) return memberKeys[peerName];
const u = state.users.find(user => (user.username || user.Username || '').toLowerCase() === peerName.toLowerCase());
if (u && (u.publicKey || u.PublicKey)) return u.publicKey || u.PublicKey;
}
// Self-DM fallback
if (memberIds.length === 1 && myId && memberIds[0].toLowerCase() === myId.toLowerCase()) {
return state.publicKey || state.serverPublicKey;
}
return null;
}
function isDmPeerE2eeReady(dm) {
return !!getPeerPublicKeyForDm(dm);
}
async function decryptMessageObjectIfNeeded(msg) {
const rawContent = msg._rawCiphertext || msg.content || msg.Content || '';
const isEnc = msg.isEncrypted || msg.IsEncrypted || rawContent.startsWith(E2EE_PREFIX);
if (!isEnc) return msg;
msg.isEncrypted = true;
if (rawContent.startsWith(E2EE_PREFIX)) {
msg._rawCiphertext = rawContent;
} else {
return msg;
}
if (!state.privateKey) {
const lockedPlaceholder = '[🔒 Encrypted Message - Click [🔒 E2EE Vault] and enter PIN to unlock]';
msg.content = lockedPlaceholder;
msg.Content = lockedPlaceholder;
return msg;
}
const senderId = msg.senderId || msg.SenderId || '';
const senderPubKey = msg.senderPublicKey || msg.SenderPublicKey || '';
const recipientPubKey = msg.recipientPublicKey || msg.RecipientPublicKey || '';
const chId = msg.channelId || msg.ChannelId || '';
const isSentByMe = state.user && senderId.toLowerCase() === (state.user.id || '').toLowerCase();
let peerKey = null;
if (isSentByMe) {
if (recipientPubKey) peerKey = recipientPubKey;
} else {
if (senderPubKey) peerKey = senderPubKey;
}
if (!peerKey) {
const conv = getConversationById(chId);
if (conv) peerKey = getPeerPublicKeyForDm(conv);
}
if (!peerKey) {
peerKey = recipientPubKey || senderPubKey || null;
}
if (peerKey && state.privateKey) {
const decrypted = await decryptDmMessage(rawContent, state.privateKey, peerKey);
msg.content = decrypted;
msg.Content = decrypted;
}
return msg;
}
async function reDecryptAllLoadedMessages() {
for (const chId of Object.keys(state.messages)) {
const list = state.messages[chId] || [];
for (const m of list) {
if (m._rawCiphertext || (m.content && m.content.startsWith(E2EE_PREFIX))) {
await decryptMessageObjectIfNeeded(m);
}
}
}
if (state.activeChannelId) {
renderMessages();
}
}
async function unlockOrInitE2eeWithPin(pin, resetKeys = false) {
if (!pin || !pin.trim()) {
return { ok: false, message: 'E2EE PIN / passphrase cannot be empty.' };
}
if (!state.user || !state.user.username) {
return { ok: false, message: 'Not authenticated.' };
}
const cleanPin = pin.trim();
if (!resetKeys && state.serverEncryptedPrivateKey) {
const unwrapped = await unwrapPrivateKey(state.serverEncryptedPrivateKey, cleanPin, state.user.username);
if (!unwrapped) {
return {
ok: false,
message: 'Invalid E2EE PIN/passphrase. Try again or click [Reset PIN / New Keys] if forgotten.'
};
}
state.privateKey = unwrapped;
state.publicKey = state.serverPublicKey || state.publicKey;
saveCachedKeysForCurrentUser(state.publicKey, state.privateKey, state.serverEncryptedPrivateKey);
await reDecryptAllLoadedMessages();
updateUserUI();
updateActiveChannelHeader();
renderChannels();
return { ok: true, message: '🔒 E2EE Key Vault unlocked and cached on this device.' };
}
// Generate new P-256 keypair & wrap with dedicated PIN
const generated = await generateE2eeKeyPair();
if (!generated.publicKey || !generated.privateKey) {
return { ok: false, message: 'Web Crypto P-256 key generation failed.' };
}
const wrappedPriv = await wrapPrivateKey(generated.privateKey, cleanPin, state.user.username);
if (!wrappedPriv) {
return { ok: false, message: 'Failed to wrap E2EE private key with PIN.' };
}
state.publicKey = generated.publicKey;
state.privateKey = generated.privateKey;
state.serverPublicKey = generated.publicKey;
state.serverEncryptedPrivateKey = wrappedPriv;
saveCachedKeysForCurrentUser(state.publicKey, state.privateKey, wrappedPriv);
if (state.socket && state.socket.readyState === WebSocket.OPEN) {
sendEnvelope('PUBLISH_PUBLIC_KEY', {
publicKey: generated.publicKey,
encryptedPrivateKey: wrappedPriv,
resetKeys: !!resetKeys
});
}
await reDecryptAllLoadedMessages();
updateUserUI();
updateActiveChannelHeader();
renderChannels();
return {
ok: true,
message: resetKeys
? '🔒 E2EE PIN & Keypair reset! New encrypted DMs will use your new keypair.'
: '🔒 E2EE Key Vault initialized and backed up to server (zero-knowledge).'
};
}
// ==========================================
// Initialization
// ==========================================
async function init() {
initElements();
setupEventListeners();
await fetchServerInfo();
if (state.token && state.user) {
loadCachedKeysForCurrentUser();
updateUserUI();
hideAuthModal();
connectWebSocket();
} else {
showAuthModal();
}
}
// ==========================================
// REST API Calls
// ==========================================
async function fetchServerInfo() {
try {
const res = await fetch('/api/info');
if (res.ok) {
state.serverInfo = await res.json();
state.allowDmE2ee = state.serverInfo.allowDmE2ee !== undefined
? state.serverInfo.allowDmE2ee
: (state.serverInfo.AllowDmE2ee !== undefined ? state.serverInfo.AllowDmE2ee : true);
state.maxGroupChatUsers = state.serverInfo.maxGroupChatUsers || state.serverInfo.MaxGroupChatUsers || 10;
el.serverTitle.textContent = state.serverInfo.serverName || 'GsDChat';
el.modalServerName.textContent = state.serverInfo.serverName || 'GsDChat';
if (state.serverInfo.motd) {
el.modalMotd.textContent = state.serverInfo.motd;
el.welcomeMotd.textContent = state.serverInfo.motd;
}
if (state.serverInfo.requiresServerPassword) {
el.groupServerPassword.style.display = 'flex';
}
if (state.serverInfo.registrationMode === 'InviteOnly') {
el.groupInviteToken.style.display = 'flex';
}
updateSettingsBadges();
}
} catch (err) {
showToast('Could not reach server info endpoint');
}
}
function updateSettingsBadges() {
if (el.maxGroupUsersHint) {
el.maxGroupUsersHint.textContent = `(Max ${state.maxGroupChatUsers} users)`;
}
if (el.dmE2eeStatusHint) {
if (!state.allowDmE2ee) {
el.dmE2eeStatusHint.textContent = '[Plaintext / Server-Visible]';
} else if (!state.accountE2eeEnabled) {
el.dmE2eeStatusHint.textContent = '[Account E2EE: OFF]';
} else if (state.privateKey) {
el.dmE2eeStatusHint.textContent = '[🔒 Vault Unlocked]';
} else {
el.dmE2eeStatusHint.textContent = '[🔒 Vault Locked - Click E2EE Vault]';
}
}
if (el.e2eeVaultBtn) {
if (!state.allowDmE2ee) {
el.e2eeVaultBtn.textContent = '[E2EE: Server Off]';
} else if (!state.accountE2eeEnabled) {
el.e2eeVaultBtn.textContent = '[E2EE: Account Off]';
} else if (state.privateKey) {
el.e2eeVaultBtn.textContent = '[🔒 E2EE Unlocked]';
} else {
el.e2eeVaultBtn.textContent = '[🔓 Unlock E2EE PIN]';
}
}
}
async function handleAuthSubmit() {
el.authError.textContent = '';
const username = el.authUsername.value.trim();
const password = el.authPassword.value;
const serverPassword = el.authServerPassword.value;
const inviteToken = el.authInviteToken.value.trim();
if (!username || !password) {
el.authError.textContent = 'Please enter username and password.';
return;
}
const endpoint = state.isRegister ? '/api/auth/register' : '/api/auth/login';
try {
el.authSubmitBtn.disabled = true;
el.authSubmitBtn.textContent = '[ Authenticating... ]';
// Strictly username + password login/registration (E2EE keys are lazily unlocked/initialized on DM open)
const body = {
username,
password,
serverPassword: serverPassword || null,
inviteToken: inviteToken || null
};
const res = await fetch(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
});
const data = await res.json();
if (!res.ok || !data.success) {
el.authError.textContent = data.errorMessage || 'Authentication failed.';
return;
}
state.token = data.token || data.Token;
state.user = {
id: data.userId || data.UserId,
username: data.username || data.Username,
role: data.role || data.Role
};
state.serverPublicKey = data.publicKey || data.PublicKey || null;
state.serverEncryptedPrivateKey = data.encryptedPrivateKey || data.EncryptedPrivateKey || null;
state.accountE2eeEnabled = data.e2eeEnabled ?? data.E2eeEnabled ?? true;
state.publicKey = null;
state.privateKey = null;
localStorage.setItem('gsdchat_token', state.token);
localStorage.setItem('gsdchat_user', JSON.stringify(state.user));
// Attempt to restore unlocked E2EE keys from trusted local device cache
loadCachedKeysForCurrentUser();
updateUserUI();
updateSettingsBadges();
hideAuthModal();
connectWebSocket();
} catch (err) {
el.authError.textContent = 'Connection error. Please try again.';
} finally {
el.authSubmitBtn.disabled = false;
el.authSubmitBtn.textContent = state.isRegister ? '[ Register ]' : '[ Login ]';
}
}
// ==========================================
// WebSocket Communication
// ==========================================
function connectWebSocket() {
if (state.socket) {
state.socket.close();
}
const wsProto = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const wsUrl = `${wsProto}//${window.location.host}/ws?token=${encodeURIComponent(state.token)}`;
try {
state.socket = new WebSocket(wsUrl);
state.socket.onopen = () => {
el.connIndicator.classList.add('online');
el.connIndicator.title = 'Connected';
showToast('Connected to chat server');
};
state.socket.onclose = () => {
el.connIndicator.classList.remove('online');
el.connIndicator.title = 'Disconnected';
if (state.token) {
clearTimeout(state.reconnectTimer);
state.reconnectTimer = setTimeout(connectWebSocket, 3000);
}
};
state.socket.onerror = () => {
el.connIndicator.classList.remove('online');
};
state.socket.onmessage = (event) => {
try {
const envelope = JSON.parse(event.data);
handleNetworkEnvelope(envelope);
} catch (err) {
console.error('Failed to parse WebSocket message', err);
}
};
} catch (err) {
console.error('WebSocket connection error', err);
}
}
function sendEnvelope(type, payload) {
if (!state.socket || state.socket.readyState !== WebSocket.OPEN) {
showToast('Not connected to server');
return;
}
const envelope = {
type: type,
payload: JSON.stringify(payload)
};
state.socket.send(JSON.stringify(envelope));
}
function fetchOlderHistory(channelId) {
if (!channelId || state.loadingHistory[channelId]) return;
const currentMsgs = state.messages[channelId] || [];
state.loadingHistory[channelId] = true;
sendEnvelope('FETCH_HISTORY', {
channelId: channelId,
offset: currentMsgs.length,
limit: 50
});
}
async function handleNetworkEnvelope(envelope) {
const type = (envelope.type || envelope.Type || '').toUpperCase();
const payloadRaw = envelope.payload ?? envelope.Payload ?? '{}';
let payload = {};
try {
payload = typeof payloadRaw === 'string' ? JSON.parse(payloadRaw) : payloadRaw;
} catch (e) {
console.error('Failed to parse envelope payload', e);
return;
}
switch (type) {
case 'AUTH_RESULT':
if (payload.success ?? payload.Success) {
const srvPub = payload.publicKey ?? payload.PublicKey;
const srvEnc = payload.encryptedPrivateKey ?? payload.EncryptedPrivateKey;
if (srvPub !== undefined) state.serverPublicKey = srvPub;
if (srvEnc !== undefined) state.serverEncryptedPrivateKey = srvEnc;
if (payload.e2eeEnabled !== undefined || payload.E2eeEnabled !== undefined) {
state.accountE2eeEnabled = payload.e2eeEnabled ?? payload.E2eeEnabled;
}
// Re-validate cached device keys against server public key
if (state.publicKey && state.serverPublicKey && state.publicKey !== state.serverPublicKey) {
clearCachedKeysForCurrentUser();
} else if (!state.privateKey) {
loadCachedKeysForCurrentUser();
}
updateSettingsBadges();
updateActiveChannelHeader();
updateE2eeModalUI();
}
break;
case 'UI_SYNC':
if (payload.allowDmE2ee !== undefined || payload.AllowDmE2ee !== undefined) {
state.allowDmE2ee = payload.allowDmE2ee ?? payload.AllowDmE2ee;
}
if (payload.maxGroupChatUsers || payload.MaxGroupChatUsers) {
state.maxGroupChatUsers = payload.maxGroupChatUsers || payload.MaxGroupChatUsers;
}
updateSettingsBadges();
updateActiveChannelHeader();
break;
case 'CHANNEL_LIST_SYNC':
state.channels = payload.channels || payload.Channels || [];
state.directMessages = payload.directMessages || payload.DirectMessages || [];
state.groupChats = payload.groupChats || payload.GroupChats || [];
const activeCh = payload.activeChannelId || payload.ActiveChannelId;
if (activeCh) {
state.activeChannelId = activeCh;
} else if (!state.activeChannelId && state.channels.length > 0) {
const first = state.channels[0];
state.activeChannelId = first.id || first.Id;
}
renderChannels();
updateActiveChannelHeader();
checkLazyDmE2eePrompt();
break;
case 'HISTORY_SYNC':
const histChId = payload.channelId || payload.ChannelId;
if (histChId) {
const rawMsgs = payload.messages || payload.Messages || [];
const isPrepend = payload.prepend || payload.Prepend || false;
const hasMore = payload.hasMore ?? payload.HasMore ?? false;
state.hasMoreHistory[histChId] = hasMore;
state.loadingHistory[histChId] = false;
const processedMsgs = [];
for (const m of rawMsgs) {
processedMsgs.push(await decryptMessageObjectIfNeeded(m));
}
if (isPrepend && state.messages[histChId]) {
const existingIds = new Set(state.messages[histChId].map(x => x.id || x.Id));
const olderUnique = processedMsgs.filter(x => !existingIds.has(x.id || x.Id));
state.messages[histChId] = [...olderUnique, ...state.messages[histChId]];
} else {
state.messages[histChId] = processedMsgs;
}
if (state.activeChannelId === histChId) {
renderMessages(!isPrepend);
}
}
break;
case 'MESSAGE_BROADCAST':
const msg = payload.message || payload.Message;
if (msg) {
await decryptMessageObjectIfNeeded(msg);
const chId = msg.channelId || msg.ChannelId;
if (!state.messages[chId]) state.messages[chId] = [];
state.messages[chId].push(msg);
if (state.activeChannelId === chId) {
appendMessage(msg);
}
}
break;
case 'USER_LIST_SYNC':
state.users = payload.users || payload.Users || [];
if (state.user) {
const me = state.users.find(u => (u.id || u.Id || '').toLowerCase() === (state.user.id || '').toLowerCase());
if (me) {
if (me.e2eeEnabled !== undefined || me.E2eeEnabled !== undefined) {
state.accountE2eeEnabled = me.e2eeEnabled ?? me.E2eeEnabled;
}
if (me.publicKey || me.PublicKey) {
state.serverPublicKey = me.publicKey || me.PublicKey;
}
}
}
await reDecryptAllLoadedMessages();
renderUsers();
updateSettingsBadges();
updateActiveChannelHeader();
break;
case 'FILE_LIST_SYNC':
state.files = payload.files || payload.Files || [];
renderFiles();
break;
case 'SYSTEM_NOTICE':
const noticeText = payload.text || payload.Text;
if (noticeText) {
showToast(noticeText);
if (state.activeChannelId) {
appendSystemNotice(noticeText);
}
}
break;
case 'COMMAND_RESULT':
const cmdOut = payload.output || payload.Output;
if (cmdOut) {
appendSystemNotice(cmdOut);
}
break;
case 'ERROR':
const errMsg = payload.message || payload.Message;
if (errMsg) {
showToast(`Error: ${errMsg}`);
appendSystemNotice(`[Error] ${errMsg}`);
}
break;
}
}
// ==========================================
// Conversation Lookup & E2EE Vault UI Helpers
// ==========================================
function getAllConversations() {
return [...state.channels, ...state.groupChats, ...state.directMessages];
}
function getConversationById(channelId) {
if (!channelId) return null;
return getAllConversations().find(c => (c.id || c.Id) === channelId) || null;
}
function getConversationType(conv) {
if (!conv) return 'Channel';
return conv.type || conv.Type || 'Channel';
}
function checkLazyDmE2eePrompt() {
const active = getConversationById(state.activeChannelId);
if (!active || getConversationType(active) !== 'DM') return;
const dmId = active.id || active.Id;
const isDmE2ee = (active.isE2ee ?? active.IsE2ee ?? true) && state.allowDmE2ee && state.accountE2eeEnabled;
if (isDmE2ee && !state.privateKey && !state.e2eePromptedDms[dmId]) {
state.e2eePromptedDms[dmId] = true;
showE2eeModal();
}
}
function updateE2eeModalUI() {
if (!el.e2eeVaultStatusBanner) return;
const hasServerVault = !!state.serverEncryptedPrivateKey;
const isUnlocked = !!state.privateKey;
const acctStatus = state.accountE2eeEnabled ? 'ENABLED' : 'DISABLED';
if (!state.allowDmE2ee) {
el.e2eeVaultStatusBanner.textContent = 'Server Setting: DM End-to-End Encryption is disabled by the server administrator.';
} else if (isUnlocked) {
el.e2eeVaultStatusBanner.textContent = `Vault Status: 🔒 UNLOCKED & CACHED ON THIS DEVICE | Account E2EE: ${acctStatus}`;
} else if (hasServerVault) {
el.e2eeVaultStatusBanner.textContent = `Vault Status: 🔓 LOCKED (Existing WRAP:v1 Key Vault on Server) | Account E2EE: ${acctStatus}\nEnter your E2EE PIN below to unlock your DM history on this device.`;
} else {
el.e2eeVaultStatusBanner.textContent = `Vault Status: ✨ NEW VAULT SETUP REQUIRED | Account E2EE: ${acctStatus}\nCreate a dedicated E2EE PIN/passphrase below (never sent to server) to initialize your P-256 keypair.`;
}
if (el.e2eePinLabel) {
el.e2eePinLabel.textContent = hasServerVault && !isUnlocked
? 'Enter E2EE PIN / Passphrase to Unlock Key Vault'
: (isUnlocked ? 'Enter New or Current E2EE PIN' : 'Create Dedicated E2EE PIN / Passphrase');
}
if (el.e2eeSubmitPinBtn) {
el.e2eeSubmitPinBtn.textContent = hasServerVault && !isUnlocked
? '[ Unlock E2EE Key Vault ]'
: '[ Initialize / Unlock E2EE Key Vault ]';
}
if (el.e2eeToggleAccountBtn) {
el.e2eeToggleAccountBtn.textContent = `[Account E2EE: ${state.accountE2eeEnabled ? 'ON' : 'OFF'}]`;
}
}
function showE2eeModal() {
initElements();
if (!el.e2eeModal) return;
if (el.e2eeModalError) el.e2eeModalError.textContent = '';
if (el.e2eePinInput) el.e2eePinInput.value = '';
updateE2eeModalUI();
el.e2eeModal.style.display = 'flex';
if (el.e2eePinInput) {
setTimeout(() => el.e2eePinInput.focus(), 50);
}
}
function hideE2eeModal() {
if (el.e2eeModal) {
el.e2eeModal.style.display = 'none';
}
}
function toggleDmE2ee(channelId) {
const conv = getConversationById(channelId || state.activeChannelId);
if (!conv || getConversationType(conv) !== 'DM') {
showToast('Select a Direct Message to toggle per-DM E2EE');
return;
}
const current = conv.isE2ee ?? conv.IsE2ee ?? true;
sendEnvelope('TOGGLE_E2EE', {
scope: 'dm',
channelId: conv.id || conv.Id,
enabled: !current
});
}
function toggleAccountE2ee(explicitEnabled) {
const nextState = explicitEnabled !== undefined ? explicitEnabled : !state.accountE2eeEnabled;
state.accountE2eeEnabled = nextState;
sendEnvelope('TOGGLE_E2EE', {
scope: 'account',
enabled: nextState
});
updateSettingsBadges();
updateActiveChannelHeader();
updateE2eeModalUI();
}
// ==========================================
// UI Renderers
// ==========================================
function switchTab(tabName) {
el.navTabs.forEach(tab => {
tab.classList.toggle('active', tab.dataset.tab === tabName);
});
el.tabViews.forEach(view => {
view.classList.toggle('active', view.id === `view-${tabName}`);
});
if (tabName === 'users') {
renderUsers();
if (state.socket && state.socket.readyState === WebSocket.OPEN) {
sendEnvelope('USER_LIST_SYNC', {});
}
} else if (tabName === 'channels') {
renderChannels();
} else if (tabName === 'files') {
renderFiles();
} else if (tabName === 'chat') {
renderMessages();
}
}
function updateActiveChannelHeader() {
const active = getConversationById(state.activeChannelId);
if (!active) return;
const chId = active.id || active.Id;
const chName = active.name || active.Name || 'general';
const chTopic = active.topic || active.Topic || '';
const chType = getConversationType(active);
if (el.channelSelectDropdown && el.channelSelectDropdown.value !== chId) {
el.channelSelectDropdown.value = chId;
}
if (chType === 'DM') {
if (el.activeConvPrefix) el.activeConvPrefix.textContent = '@';
const dmIsE2ee = (active.isE2ee ?? active.IsE2ee ?? true) && state.allowDmE2ee && state.accountE2eeEnabled;
const peerReady = isDmPeerE2eeReady(active);
const hasMyKey = !!state.privateKey;
let badgeText = '[Plaintext DM]';
let badgeClass = 'e2ee-off';
if (!state.allowDmE2ee) {
badgeText = '[Plaintext DM (Server E2EE Off)]';
} else if (!dmIsE2ee) {
badgeText = '[Plaintext DM (E2EE Disabled)]';
} else if (!hasMyKey) {
badgeText = '[🔒 E2EE Locked - Click to Enter PIN]';
} else if (!peerReady) {
badgeText = '[⚠️ Peer E2EE Not Set Up (Plaintext)]';
} else {
badgeText = '[🔒 Full E2EE Active]';
badgeClass = 'e2ee-on';
}
if (el.chatSecurityBadge) {
el.chatSecurityBadge.style.display = 'inline-flex';
el.chatSecurityBadge.className = 'conv-security-badge ' + badgeClass;
el.chatSecurityBadge.textContent = badgeText;
}
if (el.toggleDmE2eeBtn) {
el.toggleDmE2eeBtn.style.display = state.allowDmE2ee ? 'inline-flex' : 'none';
el.toggleDmE2eeBtn.textContent = dmIsE2ee ? '[DM E2EE: ON]' : '[DM E2EE: OFF]';
}
if (el.inviteGroupBtn) el.inviteGroupBtn.style.display = 'none';
if (el.leaveGroupBtn) el.leaveGroupBtn.style.display = 'none';
el.activeChannelTopic.textContent = '';
el.messageInput.placeholder = `Direct Message @${chName.replace(/^@/, '')} (${dmIsE2ee && hasMyKey && peerReady ? 'Full E2EE' : 'Plaintext'})...`;
} else if (chType === 'Group') {
if (el.activeConvPrefix) el.activeConvPrefix.textContent = '[G]';
const memberIds = active.memberIds || active.MemberIds || [];
const maxU = active.maxUsers || active.MaxUsers || state.maxGroupChatUsers;
if (el.chatSecurityBadge) {
el.chatSecurityBadge.style.display = 'inline-flex';
el.chatSecurityBadge.className = 'conv-security-badge group-badge';
el.chatSecurityBadge.textContent = `[${memberIds.length}/${maxU} Members]`;
}
if (el.toggleDmE2eeBtn) el.toggleDmE2eeBtn.style.display = 'none';
if (el.inviteGroupBtn) el.inviteGroupBtn.style.display = 'inline-flex';
if (el.leaveGroupBtn) el.leaveGroupBtn.style.display = 'inline-flex';
el.activeChannelTopic.textContent = chTopic ? ` - ${chTopic}` : '';
el.messageInput.placeholder = `Message group ${chName}...`;
} else {
if (el.activeConvPrefix) el.activeConvPrefix.textContent = '#';
if (el.chatSecurityBadge) el.chatSecurityBadge.style.display = 'none';
if (el.toggleDmE2eeBtn) el.toggleDmE2eeBtn.style.display = 'none';
if (el.inviteGroupBtn) el.inviteGroupBtn.style.display = 'none';
if (el.leaveGroupBtn) el.leaveGroupBtn.style.display = 'none';
el.activeChannelTopic.textContent = chTopic ? ` - ${chTopic}` : '';
el.messageInput.placeholder = `Message #${chName}... (or /help)`;
}
}
function renderChannels() {
// 1. Public Channels
if (el.channelList) {
el.channelList.innerHTML = '';
state.channels.forEach(ch => {
const chId = ch.id || ch.Id;
const chName = ch.name || ch.Name;
const chTopic = ch.topic || ch.Topic || '';
const isActive = chId === state.activeChannelId;
const item = document.createElement('div');
item.className = 'channel-item' + (isActive ? ' active' : '');
item.innerHTML = `
<div class="channel-meta">
<span class="channel-title">#${escapeHtml(chName)}</span>
<span class="channel-desc">${escapeHtml(chTopic)}</span>
</div>
${isActive ? '<span class="channel-badge">[ACTIVE]</span>' : ''}
`;
item.addEventListener('click', () => {
joinChannel(chId);
switchTab('chat');
});
el.channelList.appendChild(item);
});
}
// 2. Group Chats
if (el.groupChatList) {
el.groupChatList.innerHTML = '';
if (state.groupChats.length === 0) {
el.groupChatList.innerHTML = '<div style="color:var(--text-muted); padding:8px 12px; font-size:0.82rem;">No group chats yet. Click [+ Create Group] to start one.</div>';
} else {
state.groupChats.forEach(grp => {
const gId = grp.id || grp.Id;
const gName = grp.name || grp.Name;
const gTopic = grp.topic || grp.Topic || '';
const members = grp.memberUsernames || grp.MemberUsernames || [];
const maxU = grp.maxUsers || grp.MaxUsers || state.maxGroupChatUsers;
const isActive = gId === state.activeChannelId;
const item = document.createElement('div');
item.className = 'channel-item' + (isActive ? ' active' : '');
const membersText = members.length > 0 ? `Members: @${members.join(', @')}` : '';
item.innerHTML = `
<div class="channel-meta">
<span class="channel-title">[Group] ${escapeHtml(gName)} <span style="font-size:0.75rem; color:var(--ctp-mauve);">(${members.length}/${maxU})</span></span>
<span class="channel-desc">${escapeHtml(gTopic || membersText)}</span>
</div>
${isActive ? '<span class="channel-badge">[ACTIVE]</span>' : ''}
`;
item.addEventListener('click', () => {
joinChannel(gId);
switchTab('chat');
});
el.groupChatList.appendChild(item);
});
}
}
// 3. Direct Messages
if (el.dmList) {
el.dmList.innerHTML = '';
if (state.directMessages.length === 0) {
el.dmList.innerHTML = '<div style="color:var(--text-muted); padding:8px 12px; font-size:0.82rem;">No direct messages yet. Click [+ New DM] or select a user in [3:users].</div>';
} else {
state.directMessages.forEach(dm => {
const dmId = dm.id || dm.Id;
const dmName = (dm.name || dm.Name || '').replace(/^@/, '');
const isE2ee = (dm.isE2ee ?? dm.IsE2ee ?? true) && state.allowDmE2ee && state.accountE2eeEnabled;
const peerReady = isDmPeerE2eeReady(dm);
const isActive = dmId === state.activeChannelId;
let descText = 'Plaintext (Server-Visible)';
let badgeLabel = 'Plain';
let badgeClass = 'e2ee-off';
if (isE2ee) {
if (!state.privateKey) {
descText = '🔒 E2EE Vault Locked (Click to enter PIN)';
badgeLabel = '🔒 Locked';
} else if (!peerReady) {
descText = '⚠️ Peer has not initialized E2EE PIN yet (Plaintext)';
badgeLabel = '⚠️ Peer Uninit';
} else {
descText = '🔒 Full End-to-End Encrypted';
badgeLabel = '🔒 E2EE';
badgeClass = 'e2ee-on';
}
}
const item = document.createElement('div');
item.className = 'channel-item' + (isActive ? ' active' : '');
item.innerHTML = `
<div class="channel-meta">
<span class="channel-title">@${escapeHtml(dmName)}</span>
<span class="channel-desc">${descText}</span>
</div>
<div style="display:flex; gap:6px; align-items:center;">
<button type="button" class="btn btn-secondary btn-sm btn-toggle-dm-e2ee" title="Toggle E2EE for this DM">[${isE2ee ? 'E2EE: ON' : 'E2EE: OFF'}]</button>
${isActive ? '<span class="channel-badge">[ACTIVE]</span>' : `<span class="conv-security-badge ${badgeClass}">${badgeLabel}</span>`}
</div>
`;
const toggleBtn = item.querySelector('.btn-toggle-dm-e2ee');
if (toggleBtn) {
toggleBtn.addEventListener('click', (e) => {
e.stopPropagation();
toggleDmE2ee(dmId);
});
}
item.addEventListener('click', () => {
joinChannel(dmId);
switchTab('chat');
});
el.dmList.appendChild(item);
});
}
}
// 4. Rebuild In-Chat Selector Dropdown
if (el.channelSelectDropdown) {
el.channelSelectDropdown.innerHTML = '';
if (state.channels.length > 0) {
const chGroup = document.createElement('optgroup');
chGroup.label = 'Channels';
state.channels.forEach(ch => {
const chId = ch.id || ch.Id;
const chName = ch.name || ch.Name;
const opt = document.createElement('option');
opt.value = chId;
opt.textContent = `#${chName}`;
if (chId === state.activeChannelId) opt.selected = true;
chGroup.appendChild(opt);
});
el.channelSelectDropdown.appendChild(chGroup);
}
if (state.groupChats.length > 0) {
const grpGroup = document.createElement('optgroup');
grpGroup.label = 'Group Chats';
state.groupChats.forEach(g => {
const gId = g.id || g.Id;
const gName = g.name || g.Name;
const members = g.memberIds || g.MemberIds || [];
const maxU = g.maxUsers || g.MaxUsers || state.maxGroupChatUsers;
const opt = document.createElement('option');
opt.value = gId;
opt.textContent = `[Group] ${gName} (${members.length}/${maxU})`;
if (gId === state.activeChannelId) opt.selected = true;
grpGroup.appendChild(opt);
});
el.channelSelectDropdown.appendChild(grpGroup);
}
if (state.directMessages.length > 0) {
const dmGroup = document.createElement('optgroup');
dmGroup.label = 'Direct Messages';
state.directMessages.forEach(d => {
const dId = d.id || d.Id;
const dName = (d.name || d.Name || '').replace(/^@/, '');
const isE2ee = (d.isE2ee ?? d.IsE2ee ?? true) && state.allowDmE2ee && state.accountE2eeEnabled;
const opt = document.createElement('option');
opt.value = dId;
opt.textContent = `@${dName} ${isE2ee ? '🔒' : ''}`;
if (dId === state.activeChannelId) opt.selected = true;
dmGroup.appendChild(opt);
});
el.channelSelectDropdown.appendChild(dmGroup);
}
if (state.activeChannelId) {
el.channelSelectDropdown.value = state.activeChannelId;
}
}
// Show create channel button for Admin, Owner, or if allowed for members
const isPrivileged = state.user && (state.user.role === 'Owner' || state.user.role === 'Admin');
const allowMemberChannels = state.serverInfo && state.serverInfo.allowMemberChannelCreation;
if (el.openCreateChannelBtn) {
el.openCreateChannelBtn.style.display = (isPrivileged || allowMemberChannels) ? 'inline-flex' : 'none';
}
}
function joinChannel(channelId) {
if (!channelId) return;
state.activeChannelId = channelId;
sendEnvelope('JOIN_CHANNEL', { channelId });
renderChannels();
updateActiveChannelHeader();
renderMessages();
checkLazyDmE2eePrompt();
}
function renderMessages(scrollToBottom = true) {
const prevScrollHeight = el.chatMessages.scrollHeight;
const prevScrollTop = el.chatMessages.scrollTop;
el.chatMessages.innerHTML = '';
const active = getConversationById(state.activeChannelId);
const activeName = active ? (active.name || active.Name) : 'general';
const chType = getConversationType(active);
const msgs = state.messages[state.activeChannelId] || [];
const hasMore = !!state.hasMoreHistory[state.activeChannelId];
if (hasMore) {
const loadMoreDiv = document.createElement('div');
loadMoreDiv.style.textAlign = 'center';
loadMoreDiv.style.padding = '4px 0';
const loadMoreBtn = document.createElement('button');
loadMoreBtn.type = 'button';
loadMoreBtn.className = 'btn btn-secondary btn-sm';
loadMoreBtn.textContent = state.loadingHistory[state.activeChannelId]
? '[ Loading older history... ]'
: '[ ↑ Load Older Messages ]';
loadMoreBtn.addEventListener('click', () => fetchOlderHistory(state.activeChannelId));
loadMoreDiv.appendChild(loadMoreBtn);
el.chatMessages.appendChild(loadMoreDiv);
}
if (msgs.length === 0) {
let titleText = `Welcome to #${escapeHtml(activeName)}`;
let subText = 'No messages yet. Say hello!';
if (chType === 'DM') {
const isE2ee = (active.isE2ee ?? active.IsE2ee ?? true) && state.allowDmE2ee && state.accountE2eeEnabled;
titleText = `Direct Message with @${escapeHtml(activeName.replace(/^@/, ''))}`;
subText = isE2ee
? (state.privateKey
? '🔒 Full End-to-End Encryption is active. Messages cannot be read by the server.'
: '🔒 E2EE Vault is locked. Click [🔒 E2EE Vault] above to enter your E2EE PIN.')
: 'E2EE is disabled for this conversation. Messages are visible to the server.';
} else if (chType === 'Group') {
titleText = `Group Chat: ${escapeHtml(activeName)}`;
subText = 'Private group conversation. Invite friends up to the group limit!';
}
el.chatMessages.innerHTML = `
<div class="welcome-message">
<h3>${titleText}</h3>
<p>${subText}</p>
</div>
`;
return;
}
msgs.forEach(m => appendMessage(m, false));
if (scrollToBottom) {
el.chatMessages.scrollTop = el.chatMessages.scrollHeight;
} else {
const newScrollHeight = el.chatMessages.scrollHeight;
el.chatMessages.scrollTop = Math.max(0, newScrollHeight - prevScrollHeight + prevScrollTop);
}
}
async function downloadFile(fileId, fileName) {
if (!state.token) {
showToast('Please login to download files');
return;
}
showToast(`Downloading ${fileName}...`);
try {
const res = await fetch(`/api/files/${encodeURIComponent(fileId)}`, {
headers: {
'Authorization': `Bearer ${state.token}`
}
});
if (!res.ok) {
showToast(`Failed to download ${fileName} (HTTP ${res.status})`);
return;
}
const blob = await res.blob();
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = fileName;
document.body.appendChild(a);
a.click();
setTimeout(() => {
document.body.removeChild(a);
URL.revokeObjectURL(url);
}, 200);
} catch (err) {
showToast(`Download error: ${err.message}`);
}
}
function appendMessage(msg, autoScroll = true) {
const welcome = el.chatMessages.querySelector('.welcome-message');
if (welcome) welcome.remove();
const createdAt = msg.createdAt || msg.CreatedAt;
const time = createdAt ? new Date(createdAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) : '';
const rawRole = msg.senderRole || msg.SenderRole || 'member';
const roleClass = rawRole.toLowerCase();
const sender = msg.senderUsername || msg.SenderUsername || 'User';
const rawContent = msg.content || msg.Content || '';
const isEncrypted = msg.isEncrypted || msg.IsEncrypted || false;
const attId = msg.attachmentId || msg.AttachmentId;
const attName = msg.attachmentName || msg.AttachmentName;
const attBytes = msg.attachmentSizeBytes ?? msg.AttachmentSizeBytes ?? 0;
const div = document.createElement('div');
div.className = 'message-item';
let contentHtml = escapeHtml(rawContent);
if (attId) {
const sizeStr = formatBytes(attBytes);
const safeId = escapeHtml(attId);
const safeName = escapeHtml(attName || 'file');
contentHtml += `
<div>
<button type="button" class="attachment-card" data-file-id="${safeId}" data-file-name="${safeName}">
[^] ${safeName} (${sizeStr})
</button>
</div>
`;
}
const e2eeBadgeHtml = isEncrypted ? '<span class="msg-e2ee-tag" title="End-to-End Encrypted">🔒 E2EE</span>' : '';
div.innerHTML = `
<div class="message-meta">
<span class="message-author">@${escapeHtml(sender)}</span>
<span class="role-badge role-${roleClass}">${escapeHtml(rawRole)}</span>
${e2eeBadgeHtml}
<span class="message-time">${time}</span>
</div>
<div class="message-content">${contentHtml}</div>
`;
div.querySelectorAll('.attachment-card').forEach(btn => {
btn.addEventListener('click', (e) => {
e.preventDefault();
downloadFile(btn.dataset.fileId, btn.dataset.fileName);
});
});
el.chatMessages.appendChild(div);
if (autoScroll) {
el.chatMessages.scrollTop = el.chatMessages.scrollHeight;
}
}
function appendSystemNotice(text) {
const div = document.createElement('div');
div.className = 'system-notice';
div.textContent = text;
el.chatMessages.appendChild(div);
el.chatMessages.scrollTop = el.chatMessages.scrollHeight;
}
function checkIsOnline(u) {
if (!u) return false;
const val = u.isOnline !== undefined ? u.isOnline : u.IsOnline;
return val === true || val === 'true' || val === 1 || val === '1';
}
function renderUsers() {
initElements();
const onlineUsers = state.users.filter(checkIsOnline);
const onlineCount = onlineUsers.length;
const totalCount = state.users.length;
// 1. Update in-chat members sidebar and header badge
if (el.chatOnlineCountBadge) {
el.chatOnlineCountBadge.textContent = onlineCount;
}
if (el.chatHeaderOnlineCount) {
el.chatHeaderOnlineCount.textContent = onlineCount;
}
if (el.chatOnlineUsersList) {
el.chatOnlineUsersList.innerHTML = '';
if (onlineUsers.length === 0) {
el.chatOnlineUsersList.innerHTML = '<div style="color:var(--text-muted); font-size:0.8rem; padding:12px 6px; text-align:center;">No members currently online</div>';
} else {
const roleOrder = { owner: 1, admin: 2, member: 3 };
const sortedOnline = [...onlineUsers].sort((a, b) => {
const aRole = (a.role || a.Role || 'member').toLowerCase();
const bRole = (b.role || b.Role || 'member').toLowerCase();
const orderDiff = (roleOrder[aRole] || 99) - (roleOrder[bRole] || 99);
if (orderDiff !== 0) return orderDiff;
const aName = (a.username || a.Username || '').toLowerCase();
const bName = (b.username || b.Username || '').toLowerCase();
return aName.localeCompare(bName);
});
sortedOnline.forEach(u => {
const item = document.createElement('div');
item.className = 'chat-member-item';
const uid = u.id || u.Id || '';
const username = u.username || u.Username || 'User';
const role = u.role || u.Role || 'Member';
const roleClass = role.toLowerCase();
item.innerHTML = `
<div class="chat-member-meta">
<span class="user-dot online"></span>
<span class="chat-member-name" title="Click to DM @${escapeHtml(username)}" style="cursor:pointer;">@${escapeHtml(username)}</span>
</div>
<span class="role-badge role-${roleClass}" style="font-size:0.65rem; padding:1px 6px;">${escapeHtml(role)}</span>
`;
item.addEventListener('click', () => {
startDm(username, uid);
});
el.chatOnlineUsersList.appendChild(item);
});
}
}
// 2. Update dedicated Community Members tab (#view-users)
if (el.userCountBadge) {
el.userCountBadge.textContent = `[ ${onlineCount} Online / ${totalCount} Total ]`;
}
if (el.userList) {
el.userList.innerHTML = '';
if (state.users.length === 0) {
el.userList.innerHTML = '<div style="color:var(--text-muted); text-align:center; padding:20px;">No registered members found.</div>';
return;
}
const roleOrder = { owner: 1, admin: 2, member: 3 };
const sortedAll = [...state.users].sort((a, b) => {
const aOnline = checkIsOnline(a) ? 1 : 0;
const bOnline = checkIsOnline(b) ? 1 : 0;
if (bOnline !== aOnline) return bOnline - aOnline;
const aRole = (a.role || a.Role || 'member').toLowerCase();
const bRole = (b.role || b.Role || 'member').toLowerCase();
const orderDiff = (roleOrder[aRole] || 99) - (roleOrder[bRole] || 99);
if (orderDiff !== 0) return orderDiff;
const aName = (a.username || a.Username || '').toLowerCase();
const bName = (b.username || b.Username || '').toLowerCase();
return aName.localeCompare(bName);
});
sortedAll.forEach(u => {
const item = document.createElement('div');
item.className = 'user-item';
const uid = u.id || u.Id || '';
const username = u.username || u.Username || 'User';
const role = u.role || u.Role || 'Member';
const roleClass = role.toLowerCase();
const isOnline = checkIsOnline(u);
const hasKey = !!(u.publicKey || u.PublicKey);
const userE2ee = u.e2eeEnabled ?? u.E2eeEnabled ?? true;
const keyBadge = (hasKey && userE2ee && state.allowDmE2ee)
? '<span class="conv-security-badge e2ee-on" style="font-size:0.68rem;">🔒 E2EE Ready</span>'
: '<span class="conv-security-badge e2ee-off" style="font-size:0.68rem;">Plaintext</span>';
item.innerHTML = `
<div class="user-meta">
<span class="user-dot ${isOnline ? 'online' : ''}"></span>
<span style="font-weight:600;">@${escapeHtml(username)}</span>
<span class="role-badge role-${roleClass}">${escapeHtml(role)}</span>
${keyBadge}
</div>
<button type="button" class="btn btn-secondary btn-sm btn-dm-user" data-username="${escapeHtml(username)}" data-userid="${escapeHtml(uid)}">[DM]</button>
`;
const dmBtn = item.querySelector('.btn-dm-user');
if (dmBtn) {
dmBtn.addEventListener('click', (e) => {
e.stopPropagation();
startDm(dmBtn.dataset.username, dmBtn.dataset.userid);
});
}
el.userList.appendChild(item);
});
}
}
function renderFiles() {
el.filesList.innerHTML = '';
if (state.files.length === 0) {
el.filesList.innerHTML = '<div style="color:var(--text-muted); text-align:center; padding:20px;">No shared files yet.</div>';
return;
}
state.files.forEach(f => {
const item = document.createElement('div');
item.className = 'file-item';
const fileId = f.id || f.Id;
const fileName = f.originalFileName || f.OriginalFileName || 'file';
const fileBytes = f.fileSizeBytes ?? f.FileSizeBytes ?? 0;
const uploader = f.uploaderUsername || f.UploaderUsername || 'User';
const createdAt = f.createdAt || f.CreatedAt;
const sizeStr = formatBytes(fileBytes);
const dateStr = createdAt ? new Date(createdAt).toLocaleDateString() : '';
item.innerHTML = `
<div class="file-meta">
<div style="font-weight:600;">[^] ${escapeHtml(fileName)}</div>
<div style="font-size:0.8rem; color:var(--text-muted);">${sizeStr} | shared by @${escapeHtml(uploader)} on ${dateStr}</div>
</div>
<button type="button" class="btn btn-primary btn-sm btn-download" data-file-id="${escapeHtml(fileId)}" data-file-name="${escapeHtml(fileName)}">[Download]</button>
`;
const dlBtn = item.querySelector('.btn-download');
if (dlBtn) {
dlBtn.addEventListener('click', (e) => {
e.preventDefault();
downloadFile(dlBtn.dataset.fileId, dlBtn.dataset.fileName);
});
}
el.filesList.appendChild(item);
});
}
function updateUserUI() {
if (state.user) {
el.currentUsername.textContent = `@${state.user.username}`;
el.currentUserRole.textContent = `[${state.user.role}]`;
el.userBadge.style.display = 'flex';
if (el.e2eeVaultBtn) el.e2eeVaultBtn.style.display = 'inline-flex';
el.logoutBtn.style.display = 'inline-flex';
updateSettingsBadges();
} else {
el.userBadge.style.display = 'none';
if (el.e2eeVaultBtn) el.e2eeVaultBtn.style.display = 'none';
el.logoutBtn.style.display = 'none';
}
}
function showAuthModal() {
el.authModal.style.display = 'flex';
}
function hideAuthModal() {
el.authModal.style.display = 'none';
}
function showToast(message) {
const toast = document.createElement('div');
toast.className = 'toast';
toast.textContent = message;
el.toastContainer.appendChild(toast);
setTimeout(() => toast.remove(), 3500);
}
// ==========================================
// Actions
// ==========================================
async function sendMessage() {
const text = el.messageInput.value.trim();
if (!text) return;
el.messageInput.value = '';
if (text.startsWith('/')) {
handleSlashCommand(text);
return;
}
if (!state.activeChannelId) {
showToast('Select a conversation first');
return;
}
const activeConv = getConversationById(state.activeChannelId);
const convType = getConversationType(activeConv);
const shouldEncrypt = convType === 'DM'
&& (activeConv.isE2ee ?? activeConv.IsE2ee ?? true)
&& state.allowDmE2ee
&& state.accountE2eeEnabled;
let contentToSend = text;
let isEncrypted = false;
let senderPubKey = null;
let recipientPubKey = null;
if (shouldEncrypt) {
const peerKey = getPeerPublicKeyForDm(activeConv);
if (state.privateKey && peerKey) {
const encResult = await encryptDmMessage(text, state.privateKey, peerKey);
contentToSend = encResult.content;
isEncrypted = encResult.isEncrypted;
if (isEncrypted) {
senderPubKey = state.publicKey;
recipientPubKey = peerKey;
}
} else if (!peerKey) {
showToast('⚠️ Recipient has not set up their E2EE PIN yet. Sending as unencrypted plaintext.');
} else if (!state.privateKey) {
showToast('⚠️ Your E2EE vault is locked. Sending as unencrypted plaintext.');
}
}
sendEnvelope('SEND_MESSAGE', {
channelId: state.activeChannelId,
content: contentToSend,
isEncrypted: isEncrypted,
senderPublicKey: senderPubKey,
recipientPublicKey: recipientPubKey
});
}
async function handleSlashCommand(input) {
const parts = input.split(' ');
const cmd = parts[0].substring(1).toLowerCase();
const args = parts.slice(1).join(' ').trim();
if (cmd === 'join') {
const target = args.replace(/^[#@]/, '').toLowerCase();
const ch = getAllConversations().find(c => {
const n = (c.name || c.Name || '').replace(/^@/, '').toLowerCase();
const id = (c.id || c.Id || '').toLowerCase();
return n === target || id === target;
});
if (ch) {
joinChannel(ch.id || ch.Id);
} else {
showToast(`Conversation '${args}' not found`);
}
return;
}
if (cmd === 'create') {
const cParts = args.split(' ');
createChannel(cParts[0], cParts.slice(1).join(' '));
return;
}
if (cmd === 'dm') {
const dmTarget = args.split(' ')[0].replace(/^@/, '');
if (!dmTarget) {
showToast('Usage: /dm <username>');
return;
}
startDm(dmTarget);
return;
}
if (cmd === 'history') {
if (state.activeChannelId) {
fetchOlderHistory(state.activeChannelId);
}
return;
}
if (cmd === 'e2ee') {
const eParts = args.split(' ').filter(Boolean);
const sub = (eParts[0] || '').toLowerCase();
if (!sub) {
showE2eeModal();
return;
}
if (sub === 'pin') {
const pin = eParts.slice(1).join(' ');
if (!pin) {
showE2eeModal();
return;
}
const res = await unlockOrInitE2eeWithPin(pin, false);
showToast(res.message);
appendSystemNotice(res.message);
return;
}
if (sub === 'reset') {
const pin = eParts.slice(1).join(' ');
if (!pin) {
showToast('Usage: /e2ee reset <new-pin>');
return;
}
const res = await unlockOrInitE2eeWithPin(pin, true);
showToast(res.message);
appendSystemNotice(res.message);
return;
}
if (sub === 'lock') {
clearCachedKeysForCurrentUser();
await reDecryptAllLoadedMessages();
updateSettingsBadges();
updateActiveChannelHeader();
renderChannels();
showToast('🔒 Local E2EE keys locked and cleared from this browser.');
return;
}
if (sub === 'dm') {
const toggleArg = (eParts[1] || '').toLowerCase();
const activeConv = getConversationById(state.activeChannelId);
if (!activeConv || getConversationType(activeConv) !== 'DM') {
showToast('Switch to a Direct Message first to toggle per-DM E2EE.');
return;
}
const cur = activeConv.isE2ee ?? activeConv.IsE2ee ?? true;
const enable = toggleArg === 'on' ? true : (toggleArg === 'off' ? false : !cur);
sendEnvelope('TOGGLE_E2EE', { scope: 'dm', channelId: state.activeChannelId, enabled: enable });
return;
}
if (sub === 'account') {
const toggleArg = (eParts[1] || '').toLowerCase();
const enable = toggleArg === 'on' ? true : (toggleArg === 'off' ? false : !state.accountE2eeEnabled);
toggleAccountE2ee(enable);
return;
}
}
if (cmd === 'group' || cmd === 'gcreate') {
const gArgs = cmd === 'gcreate' ? `create ${args}` : args;
const gParts = gArgs.split(' ').filter(Boolean);
const sub = (gParts[0] || '').toLowerCase();
if (sub === 'create' && gParts.length >= 2) {
createGroupChat(gParts[1], gParts.slice(2).join(','), '');
return;
}
if (sub === 'invite' && gParts.length >= 2) {
sendEnvelope('INVITE_TO_GROUP', { channelId: state.activeChannelId || '', targetUsername: gParts[1] });
return;
}
if (sub === 'leave') {
sendEnvelope('LEAVE_GROUP', { channelId: state.activeChannelId || '' });
return;
}
}
if (cmd === 'invite') {
if (args) {
sendEnvelope('INVITE_TO_GROUP', { channelId: state.activeChannelId || '', targetUsername: args });
}
return;
}
if (cmd === 'leave') {
sendEnvelope('LEAVE_GROUP', { channelId: state.activeChannelId || '' });
return;
}
sendEnvelope('EXECUTE_COMMAND', {
command: cmd,
args: args,
channelId: state.activeChannelId || ''
});
}
function createChannel(name, topic) {
if (!name) {
showToast('Channel name required');
return;
}
sendEnvelope('CREATE_CHANNEL', { name, topic: topic || '' });
if (el.createChannelCard) el.createChannelCard.style.display = 'none';
if (el.newChannelName) el.newChannelName.value = '';
if (el.newChannelTopic) el.newChannelTopic.value = '';
switchTab('chat');
}
function createGroupChat(name, membersCsv, topic) {
if (!name) {
showToast('Group name required');
return;
}
const memberUsernames = (membersCsv || '')
.split(/[,\s]+/)
.map(s => s.trim().replace(/^@/, ''))
.filter(Boolean);
sendEnvelope('CREATE_GROUP', {
name,
topic: topic || '',
memberUsernames
});
if (el.createGroupCard) el.createGroupCard.style.display = 'none';
if (el.newGroupName) el.newGroupName.value = '';
if (el.newGroupMembers) el.newGroupMembers.value = '';
if (el.newGroupTopic) el.newGroupTopic.value = '';
switchTab('chat');
}
function startDm(targetUsername, targetUserId) {
const clean = (targetUsername || '').trim().replace(/^@/, '');
if (!clean && !targetUserId) {
showToast('Recipient username required');
return;
}
sendEnvelope('START_DM', {
targetUsername: clean,
targetUserId: targetUserId || ''
});
if (el.startDmCard) el.startDmCard.style.display = 'none';
if (el.dmTargetUsername) el.dmTargetUsername.value = '';
switchTab('chat');
}
async function uploadFile(file) {
if (!file) return;
if (!state.activeChannelId) {
showToast('Please join a conversation to share files');
return;
}
const formData = new FormData();
formData.append('file', file);
formData.append('channelId', state.activeChannelId);
showToast(`Uploading ${file.name}...`);
try {
const res = await fetch('/api/files/upload', {
method: 'POST',
headers: {
'Authorization': `Bearer ${state.token}`
},
body: formData
});
const data = await res.json();
if (res.ok && data.success) {
showToast(`Uploaded ${file.name} successfully!`);
} else {
showToast(`Upload failed: ${data.errorMessage || 'Server error'}`);
}
} catch (err) {
showToast(`Upload failed: ${err.message}`);
}
}
function logout() {
state.token = null;
state.user = null;
state.publicKey = null;
state.privateKey = null;
state.serverPublicKey = null;
state.serverEncryptedPrivateKey = null;
localStorage.removeItem('gsdchat_token');
localStorage.removeItem('gsdchat_user');
if (state.socket) state.socket.close();
hideE2eeModal();
updateUserUI();
showAuthModal();
}
// ==========================================
// Event Listeners
// ==========================================
function setupEventListeners() {
// Navigation Tabs
el.navTabs.forEach(tab => {
tab.addEventListener('click', () => switchTab(tab.dataset.tab));
});
// Auth Tabs
el.tabLogin.addEventListener('click', () => {
state.isRegister = false;
el.tabLogin.classList.add('active');
el.tabRegister.classList.remove('active');
el.authSubmitBtn.textContent = '[ Login ]';
el.authError.textContent = '';
});
el.tabRegister.addEventListener('click', () => {
state.isRegister = true;
el.tabRegister.classList.add('active');
el.tabLogin.classList.remove('active');
el.authSubmitBtn.textContent = '[ Register ]';
el.authError.textContent = '';
});
el.authForm.addEventListener('submit', (e) => {
e.preventDefault();
handleAuthSubmit();
});
// E2EE Vault Modal Listeners
if (el.e2eeVaultBtn) {
el.e2eeVaultBtn.addEventListener('click', showE2eeModal);
}
if (el.openE2eeSettingsBtn) {
el.openE2eeSettingsBtn.addEventListener('click', showE2eeModal);
}
if (el.chatSecurityBadge) {
el.chatSecurityBadge.addEventListener('click', () => {
const active = getConversationById(state.activeChannelId);
if (active && getConversationType(active) === 'DM') {
showE2eeModal();
}
});
}
if (el.toggleDmE2eeBtn) {
el.toggleDmE2eeBtn.addEventListener('click', () => toggleDmE2ee(state.activeChannelId));
}
if (el.e2eePinForm) {
el.e2eePinForm.addEventListener('submit', async (e) => {
e.preventDefault();
const pin = el.e2eePinInput ? el.e2eePinInput.value : '';
const res = await unlockOrInitE2eeWithPin(pin, false);
if (!res.ok) {
if (el.e2eeModalError) el.e2eeModalError.textContent = res.message;
} else {
showToast(res.message);
updateE2eeModalUI();
hideE2eeModal();
}
});
}
if (el.e2eeResetPinBtn) {
el.e2eeResetPinBtn.addEventListener('click', async () => {
const pin = el.e2eePinInput ? el.e2eePinInput.value.trim() : '';
if (!pin) {
if (el.e2eeModalError) {
el.e2eeModalError.textContent = 'Enter a new E2EE PIN in the input box above first, then click [Reset PIN / New Keys].';
}
return;
}
const res = await unlockOrInitE2eeWithPin(pin, true);
if (!res.ok) {
if (el.e2eeModalError) el.e2eeModalError.textContent = res.message;
} else {
showToast(res.message);
updateE2eeModalUI();
hideE2eeModal();
}
});
}
if (el.e2eeLockDeviceBtn) {
el.e2eeLockDeviceBtn.addEventListener('click', async () => {
clearCachedKeysForCurrentUser();
await reDecryptAllLoadedMessages();
updateSettingsBadges();
updateActiveChannelHeader();
renderChannels();
updateE2eeModalUI();
showToast('🔒 Local E2EE key cache cleared on this device.');
});
}
if (el.e2eeToggleAccountBtn) {
el.e2eeToggleAccountBtn.addEventListener('click', () => {
toggleAccountE2ee();
});
}
if (el.e2eeCloseModalBtn) {
el.e2eeCloseModalBtn.addEventListener('click', hideE2eeModal);
}
// Scroll-to-top automatic history pagination
if (el.chatMessages) {
el.chatMessages.addEventListener('scroll', () => {
if (el.chatMessages.scrollTop === 0 && state.activeChannelId && state.hasMoreHistory[state.activeChannelId]) {
fetchOlderHistory(state.activeChannelId);
}
});
}
// Chat Input
el.sendBtn.addEventListener('click', sendMessage);
el.messageInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
e.preventDefault();
sendMessage();
}
});
// File Uploads
el.fileInput.addEventListener('change', (e) => {
if (e.target.files.length > 0) {
uploadFile(e.target.files[0]);
e.target.value = '';
}
});
el.filesViewUploadInput.addEventListener('change', (e) => {
if (e.target.files.length > 0) {
uploadFile(e.target.files[0]);
e.target.value = '';
}
});
// Channels Create Form
if (el.openCreateChannelBtn) {
el.openCreateChannelBtn.addEventListener('click', () => {
if (el.createChannelCard) el.createChannelCard.style.display = 'block';
if (el.newChannelName) el.newChannelName.focus();
});
}
if (el.cancelCreateChannelBtn) {
el.cancelCreateChannelBtn.addEventListener('click', () => {
if (el.createChannelCard) el.createChannelCard.style.display = 'none';
});
}
if (el.submitCreateChannelBtn) {
el.submitCreateChannelBtn.addEventListener('click', () => {
createChannel(el.newChannelName.value.trim(), el.newChannelTopic.value.trim());
});
}
if (el.newChannelName) {
el.newChannelName.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
e.preventDefault();
createChannel(el.newChannelName.value.trim(), el.newChannelTopic.value.trim());
}
});
}
if (el.newChannelTopic) {
el.newChannelTopic.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
e.preventDefault();
createChannel(el.newChannelName.value.trim(), el.newChannelTopic.value.trim());
}
});
}
// Group Create Form
if (el.openCreateGroupBtn) {
el.openCreateGroupBtn.addEventListener('click', () => {
if (el.createGroupCard) el.createGroupCard.style.display = 'block';
if (el.newGroupName) el.newGroupName.focus();
});
}
if (el.cancelCreateGroupBtn) {
el.cancelCreateGroupBtn.addEventListener('click', () => {
if (el.createGroupCard) el.createGroupCard.style.display = 'none';
});
}
if (el.submitCreateGroupBtn) {
el.submitCreateGroupBtn.addEventListener('click', () => {
createGroupChat(
el.newGroupName.value.trim(),
el.newGroupMembers ? el.newGroupMembers.value.trim() : '',
el.newGroupTopic ? el.newGroupTopic.value.trim() : ''
);
});
}
// Start DM Form
if (el.openStartDmBtn) {
el.openStartDmBtn.addEventListener('click', () => {
if (el.startDmCard) el.startDmCard.style.display = 'block';
if (el.dmTargetUsername) el.dmTargetUsername.focus();
});
}
if (el.cancelStartDmBtn) {
el.cancelStartDmBtn.addEventListener('click', () => {
if (el.startDmCard) el.startDmCard.style.display = 'none';
});
}
if (el.submitStartDmBtn) {
el.submitStartDmBtn.addEventListener('click', () => {
startDm(el.dmTargetUsername.value.trim());
});
}
if (el.dmTargetUsername) {
el.dmTargetUsername.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
e.preventDefault();
startDm(el.dmTargetUsername.value.trim());
}
});
}
// Active Group Header Buttons
if (el.inviteGroupBtn) {
el.inviteGroupBtn.addEventListener('click', () => {
const target = window.prompt('Enter username to invite to this group chat:');
if (target && target.trim() && state.activeChannelId) {
sendEnvelope('INVITE_TO_GROUP', {
channelId: state.activeChannelId,
targetUsername: target.trim().replace(/^@/, '')
});
}
});
}
if (el.leaveGroupBtn) {
el.leaveGroupBtn.addEventListener('click', () => {
if (state.activeChannelId) {
sendEnvelope('LEAVE_GROUP', { channelId: state.activeChannelId });
}
});
}
// Toggle In-Chat Online Members Sidebar
if (el.toggleMembersBtn && el.chatMembersSidebar) {
el.toggleMembersBtn.addEventListener('click', () => {
el.chatMembersSidebar.classList.toggle('closed');
});
}
// In-chat Channel Selector Dropdown
if (el.channelSelectDropdown) {
el.channelSelectDropdown.addEventListener('change', (e) => {
if (e.target.value) {
joinChannel(e.target.value);
}
});
}
// Global Drag & Drop handling
let dragCounter = 0;
window.addEventListener('dragenter', (e) => {
e.preventDefault();
dragCounter++;
if (el.dropOverlay) {
el.dropOverlay.classList.add('visible');
}
}, false);
window.addEventListener('dragover', (e) => {
e.preventDefault();
if (e.dataTransfer) {
e.dataTransfer.dropEffect = 'copy';
}
}, false);
window.addEventListener('dragleave', (e) => {
e.preventDefault();
dragCounter--;
if (dragCounter <= 0) {
dragCounter = 0;
if (el.dropOverlay) {
el.dropOverlay.classList.remove('visible');
}
}
}, false);
window.addEventListener('drop', (e) => {
e.preventDefault();
dragCounter = 0;
if (el.dropOverlay) {
el.dropOverlay.classList.remove('visible');
}
if (e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files.length > 0) {
uploadFile(e.dataTransfer.files[0]);
}
}, false);
// Logout
el.logoutBtn.addEventListener('click', logout);
}
// ==========================================
// Helper Functions
// ==========================================
function escapeHtml(str) {
if (!str) return '';
const div = document.createElement('div');
div.textContent = str;
return div.innerHTML;
}
function formatBytes(bytes) {
if (bytes === 0) return '0 B';
const k = 1024;
const sizes = ['B', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
// Start app
if (document.readyState === 'loading') {
window.addEventListener('DOMContentLoaded', init);
} else {
init();
}
})();