Spaces:
Sleeping
Sleeping
File size: 24,393 Bytes
5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 cfd4888 5876732 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 | (function() {
'use strict';
// --- State ---
let currentUser = null;
let token = localStorage.getItem('token');
let ws = null;
let wsReconnectTimer = null;
let messages = {};
let messageIds = [];
let oldestMessageId = null;
let replyToId = null;
let typingTimer = null;
let pendingFile = null;
let isConnected = false;
const API = window.location.origin;
// DOM elements
const authScreen = document.getElementById('auth-screen');
const chatScreen = document.getElementById('chat-screen');
const authForm = document.getElementById('auth-form');
const authUsername = document.getElementById('auth-username');
const authPassword = document.getElementById('auth-password');
const authDisplayName = document.getElementById('auth-display-name');
const displayNameGroup = document.getElementById('display-name-group');
const authSubmit = document.getElementById('auth-submit');
const authError = document.getElementById('auth-error');
const loginTab = document.getElementById('login-tab');
const signupTab = document.getElementById('signup-tab');
const messagesList = document.getElementById('messages-list');
const composeForm = document.getElementById('compose-form');
const messageInput = document.getElementById('message-input');
const sendBtn = document.getElementById('send-btn');
const attachBtn = document.getElementById('attach-btn');
const fileInput = document.getElementById('file-input');
const replyPreview = document.getElementById('reply-preview');
const replyPreviewText = document.getElementById('reply-preview-text');
const cancelReply = document.getElementById('cancel-reply');
const typingIndicator = document.getElementById('typing-indicator');
const onlineCountSpan = document.getElementById('online-count');
const loadOlderBtn = document.getElementById('load-older-btn');
const settingsBtn = document.getElementById('settings-btn');
const logoutBtn = document.getElementById('logout-btn');
const settingsModal = document.getElementById('settings-modal');
const saveSettingsBtn = document.getElementById('save-settings');
const closeSettingsBtn = document.getElementById('close-settings');
const themeSelect = document.getElementById('theme-select');
const customThemeSettings = document.getElementById('custom-theme-settings');
const customSelfColor = document.getElementById('custom-self-color');
const customOtherColor = document.getElementById('custom-other-color');
const customTextColor = document.getElementById('custom-text-color');
const settingDisplayName = document.getElementById('setting-display-name');
const settingAvatar = document.getElementById('setting-avatar');
const avatarPreview = document.getElementById('avatar-preview');
const uploadProgress = document.getElementById('upload-progress');
const uploadBar = document.getElementById('upload-bar');
const uploadFilename = document.getElementById('upload-filename');
let isLogin = true;
// --- Theme ---
function applyTheme(name) {
document.body.className = name;
localStorage.setItem('theme', name);
if (name === 'theme-custom') {
const self = localStorage.getItem('customSelfColor') || '#25D366';
const other = localStorage.getItem('customOtherColor') || '#E5E5EA';
const txt = localStorage.getItem('customTextColor') || '#000';
document.documentElement.style.setProperty('--bubble-self', self);
document.documentElement.style.setProperty('--bubble-other', other);
document.documentElement.style.setProperty('--bubble-text-self', txt);
document.documentElement.style.setProperty('--bubble-text-other', txt);
}
}
function loadTheme() {
const saved = localStorage.getItem('theme') || 'theme-light';
themeSelect.value = saved;
if (saved === 'theme-custom') customThemeSettings.classList.remove('hidden');
applyTheme(saved);
}
// --- Auth ---
loginTab.addEventListener('click', () => {
isLogin = true;
loginTab.classList.add('active');
signupTab.classList.remove('active');
displayNameGroup.style.display = 'none';
authSubmit.textContent = 'Login';
});
signupTab.addEventListener('click', () => {
isLogin = false;
signupTab.classList.add('active');
loginTab.classList.remove('active');
displayNameGroup.style.display = 'block';
authSubmit.textContent = 'Sign Up';
});
authForm.addEventListener('submit', async (e) => {
e.preventDefault();
const u = authUsername.value.trim();
const p = authPassword.value;
const d = authDisplayName.value.trim();
if (!u || !p) {
authError.textContent = 'Please fill all fields.';
return;
}
try {
const url = isLogin
? `${API}/login?username=${encodeURIComponent(u)}&password=${encodeURIComponent(p)}`
: `${API}/signup?username=${encodeURIComponent(u)}&password=${encodeURIComponent(p)}&display_name=${encodeURIComponent(d)}`;
const res = await fetch(url, { method: 'POST' });
if (!res.ok) {
const err = await res.json();
throw new Error(err.detail || 'Authentication failed');
}
const data = await res.json();
token = data.token;
currentUser = {
id: data.id,
username: data.username,
display_name: data.display_name,
avatar_path: data.avatar_path
};
localStorage.setItem('token', token);
authError.textContent = '';
showChat();
} catch (err) {
authError.textContent = err.message;
}
});
async function autoLogin() {
if (!token) {
return false;
}
try {
const res = await fetch(`${API}/me`, {
headers: { 'token': token }
});
if (!res.ok) {
token = null;
localStorage.removeItem('token');
return false;
}
currentUser = await res.json();
return true;
} catch (e) {
token = null;
localStorage.removeItem('token');
return false;
}
}
function showAuth() {
authScreen.classList.remove('hidden');
chatScreen.classList.add('hidden');
disconnectWS();
}
function showChat() {
authScreen.classList.add('hidden');
chatScreen.classList.remove('hidden');
connectWS();
loadMessages();
}
// --- WebSocket (fixed β never send null as token) ---
function connectWS() {
// Don't connect if we don't have a valid token
if (!token || token === 'null' || token === 'undefined') {
console.warn('No valid token β not connecting WebSocket');
return;
}
// Don't create duplicate connections
if (ws && ws.readyState === WebSocket.OPEN) {
return;
}
// Close any existing connection
if (ws) {
ws.close();
ws = null;
}
const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
const wsUrl = `${proto}//${location.host}/ws?token=${encodeURIComponent(token)}`;
console.log('Connecting WebSocket...');
ws = new WebSocket(wsUrl);
ws.onopen = () => {
console.log('WebSocket connected');
isConnected = true;
// Clear any reconnect timer
if (wsReconnectTimer) {
clearTimeout(wsReconnectTimer);
wsReconnectTimer = null;
}
// Request initial message load
ws.send(JSON.stringify({ type: 'load_messages', limit: 50 }));
};
ws.onmessage = (ev) => {
try {
handleWSMessage(JSON.parse(ev.data));
} catch (e) {
console.error('Error parsing WS message:', e);
}
};
ws.onclose = () => {
console.log('WebSocket closed');
isConnected = false;
ws = null;
// Only reconnect if we have a valid token
if (token && token !== 'null' && token !== 'undefined' && currentUser) {
wsReconnectTimer = setTimeout(connectWS, 3000);
}
};
ws.onerror = (err) => {
console.error('WebSocket error:', err);
};
}
function disconnectWS() {
if (wsReconnectTimer) {
clearTimeout(wsReconnectTimer);
wsReconnectTimer = null;
}
if (ws) {
ws.close();
ws = null;
}
isConnected = false;
}
function handleWSMessage(msg) {
switch (msg.type) {
case 'online_users':
onlineCountSpan.textContent = `(${msg.users.length} online)`;
break;
case 'new_message':
if (messages[msg.id]) return;
messages[msg.id] = msg;
messageIds.push(msg.id);
renderMessage(msg);
scrollBottom();
// Mark as read if visible
if (document.visibilityState === 'visible' && isConnected) {
ws.send(JSON.stringify({ type: 'mark_read', up_to_message_id: msg.id }));
}
// Browser notification
if (document.visibilityState !== 'visible' && Notification.permission === 'granted') {
new Notification(`New message from ${msg.display_name || msg.username}`, {
body: msg.content || 'Sent a file'
});
}
break;
case 'messages_batch':
if (msg.messages.length > 0) {
for (const m of msg.messages) {
if (!messages[m.id]) {
messages[m.id] = m;
messageIds.unshift(m.id);
}
}
renderAll();
scrollBottom();
}
loadOlderBtn.classList.toggle('hidden', msg.messages.length < 50);
break;
case 'typing_update':
typingIndicator.textContent = msg.is_typing ? `${msg.username} is typing...` : '';
break;
case 'edit_message':
if (messages[msg.message_id]) {
messages[msg.message_id].content = msg.content;
messages[msg.message_id].is_edited = true;
updateBubble(msg.message_id);
}
break;
case 'delete_message':
if (messages[msg.message_id]) {
messages[msg.message_id].is_deleted = true;
updateBubble(msg.message_id);
}
break;
case 'read_receipt':
if (messages[msg.message_id] && messages[msg.message_id].sender_id === currentUser?.id) {
messages[msg.message_id].status = 'read';
updateBubble(msg.message_id);
}
break;
}
}
// --- Message rendering (same as before) ---
function renderMessage(msg) {
const el = document.getElementById(`msg-${msg.id}`);
if (el) {
updateBubble(msg.id);
return;
}
const div = document.createElement('div');
div.id = `msg-${msg.id}`;
div.className = `message-bubble ${msg.sender_id === currentUser?.id ? 'message-self' : 'message-other'}`;
div.innerHTML = buildHTML(msg);
messagesList.appendChild(div);
}
function buildHTML(msg) {
if (msg.is_deleted) return '<em>This message was deleted</em>';
let html = '';
if (msg.reply_to_id && messages[msg.reply_to_id]) {
const reply = messages[msg.reply_to_id];
html += `<div class="reply-indicator">β© ${reply.display_name || reply.username}: ${truncate(reply.content, 40)}</div>`;
}
html += `<div class="message-info">
<span>${msg.display_name || msg.username}</span>
<span class="timestamp">${formatTime(msg.timestamp_ms)}</span>
</div>`;
html += `<div class="message-text">${escapeHtml(msg.content)}</div>`;
if (msg.is_edited) html += ` <em class="edited-label">[edited]</em>`;
if (msg.file_path) html += renderAttachment(msg);
// Status indicators for own messages
if (msg.sender_id === currentUser?.id && !msg.is_deleted) {
const statusIcon = msg.status === 'read' ? 'ββ' : 'β';
html += `<div class="message-status">${statusIcon}</div>`;
html += `<div class="message-actions">
<button onclick="window.editMsg(${msg.id})">βοΈ</button>
<button onclick="window.deleteMsg(${msg.id})">ποΈ</button>
<button onclick="window.replyTo(${msg.id})">β©</button>
</div>`;
}
return html;
}
function renderAttachment(msg) {
const url = `${API}/download/${msg.file_path}?token=${encodeURIComponent(token)}`;
if (msg.file_type.startsWith('image/')) {
return `<div class="attachment"><img src="${url}" alt="${msg.file_name}" onerror="this.parentElement.innerHTML='<em>Failed to decode</em>'"></div>`;
}
if (msg.file_type.startsWith('video/')) {
return `<div class="attachment"><video controls><source src="${url}" type="${msg.file_type}">Your browser doesn't support video</video></div>`;
}
if (msg.file_type.startsWith('audio/')) {
return `<div class="attachment"><audio controls src="${url}"></audio></div>`;
}
return `<div class="attachment"><div class="file-preview" onclick="window.open('${url}')">π ${escapeHtml(msg.file_name)}</div></div>`;
}
function updateBubble(id) {
const el = document.getElementById(`msg-${id}`);
if (!el) return;
const msg = messages[id];
if (!msg) return;
el.className = `message-bubble ${msg.sender_id === currentUser?.id ? 'message-self' : 'message-other'}`;
if (msg.is_deleted) el.classList.add('deleted-bubble');
el.innerHTML = buildHTML(msg);
}
function renderAll() {
messagesList.innerHTML = '';
messageIds.forEach(id => {
if (messages[id]) renderMessage(messages[id]);
});
}
function scrollBottom() {
const container = document.getElementById('messages-container');
container.scrollTop = container.scrollHeight;
}
// --- Message actions ---
window.replyTo = function(id) {
replyToId = id;
const m = messages[id];
if (m) {
replyPreviewText.textContent = `Replying to ${m.display_name || m.username}: ${truncate(m.content, 30)}`;
replyPreview.classList.remove('hidden');
}
};
cancelReply.addEventListener('click', () => {
replyToId = null;
replyPreview.classList.add('hidden');
});
window.editMsg = function(id) {
const newContent = prompt('Edit message:', messages[id]?.content || '');
if (newContent !== null && newContent.trim() !== '' && isConnected) {
ws.send(JSON.stringify({ type: 'edit_message', message_id: id, content: newContent }));
}
};
window.deleteMsg = function(id) {
if (confirm('Delete this message permanently?') && isConnected) {
ws.send(JSON.stringify({ type: 'delete_message', message_id: id }));
}
};
// --- Sending messages ---
composeForm.addEventListener('submit', (e) => {
e.preventDefault();
if (!isConnected) {
console.warn('Not connected β cannot send');
return;
}
const content = messageInput.value.trim();
if (!content && !pendingFile) return;
const msg = {
type: 'chat_message',
content: content || '',
reply_to_id: replyToId,
client_id: Date.now().toString(36) + Math.random().toString(36).slice(2)
};
if (pendingFile) {
msg.file_path = pendingFile.file_path;
msg.file_type = pendingFile.file_type;
msg.file_name = pendingFile.file_name;
pendingFile = null;
}
ws.send(JSON.stringify(msg));
messageInput.value = '';
clearReply();
});
function clearReply() {
replyToId = null;
replyPreview.classList.add('hidden');
}
// --- Typing indicator ---
messageInput.addEventListener('input', () => {
if (!isConnected) return;
ws.send(JSON.stringify({ type: 'typing', is_typing: true }));
clearTimeout(typingTimer);
typingTimer = setTimeout(() => {
if (isConnected) ws.send(JSON.stringify({ type: 'typing', is_typing: false }));
}, 2000);
});
// --- File upload ---
attachBtn.addEventListener('click', () => fileInput.click());
fileInput.addEventListener('change', async (e) => {
const file = e.target.files[0];
if (!file) return;
const CHUNK = 5 * 1024 * 1024; // 5MB
const total = Math.ceil(file.size / CHUNK);
const uploadId = Date.now().toString(36) + Math.random().toString(36).slice(2);
uploadProgress.classList.remove('hidden');
uploadFilename.textContent = file.name;
uploadBar.value = 0;
uploadBar.max = 100;
for (let i = 0; i < total; i++) {
const start = i * CHUNK;
const end = Math.min(start + CHUNK, file.size);
const blob = file.slice(start, end);
const fd = new FormData();
fd.append('file', blob);
const url = `${API}/upload_chunk?chunk_index=${i}&total_chunks=${total}&file_name=${encodeURIComponent(file.name)}&file_type=${encodeURIComponent(file.type || 'application/octet-stream')}&upload_id=${uploadId}`;
try {
const res = await fetch(url, {
method: 'POST',
body: fd,
headers: { 'token': token }
});
if (!res.ok) throw new Error('Upload failed');
const data = await res.json();
if (data.status === 'complete') {
pendingFile = {
file_path: data.file_path,
file_type: data.file_type,
file_name: data.file_name
};
uploadProgress.classList.add('hidden');
break;
}
uploadBar.value = ((i + 1) / total) * 100;
} catch (err) {
alert('Upload error: ' + err.message);
uploadProgress.classList.add('hidden');
break;
}
}
fileInput.value = '';
});
// --- Load older messages ---
loadOlderBtn.addEventListener('click', () => {
if (isConnected && messageIds.length > 0) {
const oldestId = messageIds[0];
ws.send(JSON.stringify({ type: 'load_messages', before_id: oldestId, limit: 50 }));
}
});
function loadMessages() {
if (isConnected) {
ws.send(JSON.stringify({ type: 'load_messages', limit: 50 }));
}
}
// --- Settings ---
settingsBtn.addEventListener('click', () => {
settingDisplayName.value = currentUser?.display_name || '';
if (currentUser?.avatar_path) {
avatarPreview.src = `${API}/download/${currentUser.avatar_path}?token=${encodeURIComponent(token)}`;
avatarPreview.style.display = 'block';
} else {
avatarPreview.style.display = 'none';
}
settingsModal.classList.remove('hidden');
});
closeSettingsBtn.addEventListener('click', () => settingsModal.classList.add('hidden'));
saveSettingsBtn.addEventListener('click', async () => {
const newName = settingDisplayName.value.trim();
if (newName && newName !== currentUser?.display_name) {
await fetch(`${API}/update_profile?display_name=${encodeURIComponent(newName)}`, {
method: 'POST',
headers: { 'token': token }
});
currentUser.display_name = newName;
}
const avatarFile = settingAvatar.files[0];
if (avatarFile) {
const fd = new FormData();
fd.append('file', avatarFile);
const res = await fetch(`${API}/upload_avatar`, {
method: 'POST',
body: fd,
headers: { 'token': token }
});
if (res.ok) {
const data = await res.json();
currentUser.avatar_path = data.avatar_path;
avatarPreview.src = `${API}/download/${data.avatar_path}?token=${encodeURIComponent(token)}`;
avatarPreview.style.display = 'block';
}
}
const theme = themeSelect.value;
if (theme === 'theme-custom') {
localStorage.setItem('customSelfColor', customSelfColor.value);
localStorage.setItem('customOtherColor', customOtherColor.value);
localStorage.setItem('customTextColor', customTextColor.value);
}
applyTheme(theme);
settingsModal.classList.add('hidden');
});
themeSelect.addEventListener('change', (e) => {
customThemeSettings.classList.toggle('hidden', e.target.value !== 'theme-custom');
});
// --- Logout ---
logoutBtn.addEventListener('click', async () => {
if (token) {
try {
await fetch(`${API}/logout?token=${encodeURIComponent(token)}`, { method: 'GET' });
} catch (e) {
console.error('Logout error:', e);
}
}
disconnectWS();
localStorage.removeItem('token');
token = null;
currentUser = null;
messages = {};
messageIds = [];
messagesList.innerHTML = '';
typingIndicator.textContent = '';
onlineCountSpan.textContent = '0';
showAuth();
});
// --- Notification permission ---
if (window.Notification && Notification.permission === 'default') {
Notification.requestPermission();
}
// --- Utilities ---
function truncate(s, n) {
if (!s) return '';
return s.length > n ? s.slice(0, n - 1) + 'β¦' : s;
}
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
function formatTime(ms) {
const d = new Date(ms);
const now = new Date();
if (d.toDateString() === now.toDateString()) {
return `Today at ${d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}`;
}
return d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
}
// --- Initialize ---
loadTheme();
(async () => {
const loggedIn = await autoLogin();
if (loggedIn) {
showChat();
} else {
showAuth();
}
})();
})(); |