CS460-Projects/chatserver/templates/index.html

352 lines
No EOL
14 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Web Chat Client</title>
<script src="https://cdn.socket.io/4.5.0/socket.io.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/dompurify/dist/purify.min.js"></script>
<style>
/* Light Mode Styles */
body.light-mode {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
height: 100vh;
background-color: white;
color: black;
}
body.light-mode #topBar {
background-color: #007bff;
color: white;
}
body.light-mode #topBar button {
background-color: white;
color: #007bff;
}
body.light-mode #topBar button:hover {
background-color: #e6e6e6;
}
body.light-mode #chat {
background-color: #f9f9f9;
}
body.light-mode #messageInput button {
background-color: #007bff;
color: white;
}
body.light-mode #messageInput button:hover {
background-color: #0056b3;
}
/* Dark Mode Styles */
body.dark-mode {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
height: 100vh;
background-color: #121212;
color: white;
}
body.dark-mode #topBar {
background-color: #1e1e1e;
color: white;
}
body.dark-mode #topBar button {
background-color: #333;
color: white;
}
body.dark-mode #topBar button:hover {
background-color: #555;
}
body.dark-mode #chat {
background-color: #1e1e1e;
}
body.dark-mode #messageInput button {
background-color: #333;
color: white;
}
body.dark-mode #messageInput button:hover {
background-color: #555;
}
/* Shared Styles */
#topBar {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px;
}
#topBar span {
font-size: 16px;
}
#chat {
flex: 1;
overflow-y: auto;
padding: 10px;
border-bottom: 1px solid #ccc;
}
#messageInput {
display: flex;
padding: 10px;
}
#messageInput input {
flex: 1;
padding: 10px;
font-size: 16px;
}
#messageInput button {
padding: 10px;
font-size: 16px;
border: none;
cursor: pointer;
border-radius: 5px;
}
</style>
</head>
<body class="dark-mode">
<!-- Top Bar -->
<div id="topBar">
<span id="userInfo">Username: <strong id="currentUsername"></strong> | Chat Room: <strong id="currentChatRoom"></strong> | Server: <strong id="currentServer"></strong></span>
<div>
<button onclick="changeUsername()">Change Username</button>
<button onclick="changeChatRoom()">Change Chat Room</button>
<button onclick="toggleTheme()">Toggle Theme</button>
<button onclick="disconnectServer()">Disconnect</button>
<button onclick="changeServer()">Change Server</button>
</div>
</div>
<!-- Chat Messages -->
<div id="chat"></div>
<!-- Message Input -->
<div id="messageInput">
<input type="text" id="message" placeholder="Type a message..." onkeydown="handleKeyPress(event)">
<button onclick="sendMessage()">Send</button>
</div>
<script>
// Determine the default server URL based on the web client's host
const defaultServerUrl = `${window.location.protocol}//${window.location.hostname}:5000`;
// Ask the user for the server URL, defaulting to the web client's host
let serverUrl = prompt(`Enter the WebSocket server URL (default: ${defaultServerUrl}):`) || defaultServerUrl;
// Connect to the WebSocket server
const socket = io(serverUrl);
const chatDiv = document.getElementById('chat');
const messageInput = document.getElementById('message');
const currentUsernameElement = document.getElementById('currentUsername');
const currentChatRoomElement = document.getElementById('currentChatRoom');
const currentServerElement = document.getElementById('currentServer');
// Set the initial server URL in the top bar
currentServerElement.textContent = serverUrl;
// Ask the user for their username and chat room
let username = prompt("Enter your username:") || "Anonymous";
let chatRoom = prompt("Enter chat room (default: 'default')") || "default";
// Update the top bar with the current username and chat room
currentUsernameElement.textContent = username;
currentChatRoomElement.textContent = chatRoom;
// Join the chat room
console.log('Joining chat room:', { username: username, chat_room: chatRoom });
socket.emit('join', { username: username, chat_room: chatRoom });
// Fetch message history for the initial chat room
const serverBaseUrl = `${window.location.protocol}//${window.location.hostname}:5000`;
fetch(`${serverBaseUrl}/get_history?chat_room=${encodeURIComponent(chatRoom)}`)
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(data => {
if (data.messages && data.messages.length > 0) {
// Display each message in the chat history
data.messages.forEach(message => {
const messageElement = document.createElement('div');
messageElement.textContent = message;
chatDiv.appendChild(messageElement);
});
chatDiv.scrollTop = chatDiv.scrollHeight; // Auto-scroll to the bottom
} else {
console.log("No message history found for this chat room.");
}
})
.catch(error => {
console.error("Error fetching message history:", error);
});
// Log connection status
socket.on('connect', () => {
console.log('Connected to WebSocket server');
});
socket.on('disconnect', () => {
console.log('Disconnected from WebSocket server');
});
// Listen for messages from the server
socket.on('message', (data) => {
const messageElement = document.createElement('div');
const timestamp = data.timestamp ? `[${data.timestamp}]` : '';
const chatRoomInfo = data.chat_room ? `(${data.chat_room})` : '';
// Render the message as HTML using marked.js
const renderedMessage = marked.parse(data.message);
// Sanitize the HTML using DOMPurify
const sanitizedMessage = DOMPurify.sanitize(renderedMessage);
// Set the inner HTML of the message element
messageElement.innerHTML = `${timestamp} ${data.username || 'Server'} ${chatRoomInfo}: ${sanitizedMessage}`;
chatDiv.appendChild(messageElement);
chatDiv.scrollTop = chatDiv.scrollHeight; // Auto-scroll to the bottom
});
// Send a message to the server
function sendMessage() {
const message = messageInput.value;
if (message.trim() !== '') {
console.log('Sending message:', { username: username, chat_room: chatRoom, message: message });
socket.emit('send_message', { username: username, chat_room: chatRoom, message: message });
messageInput.value = ''; // Clear the input field
}
}
// Handle the "Enter" key to send a message
function handleKeyPress(event) {
if (event.key === "Enter") {
sendMessage();
}
}
// Change the username
function changeUsername() {
const newUsername = prompt("Enter your new username:");
if (newUsername && newUsername.trim() !== "") {
username = newUsername.trim();
currentUsernameElement.textContent = username;
console.log(`Username changed to: ${username}`);
socket.emit('send_message', { username: 'Server', chat_room: chatRoom, message: `${username} has changed their username.` });
}
}
// Change the chat room
function changeChatRoom() {
const newChatRoom = prompt("Enter the new chat room:");
if (newChatRoom && newChatRoom.trim() !== "") {
// Leave the current chat room
socket.emit('leave', { username: username, chat_room: chatRoom });
// Update the chat room
chatRoom = newChatRoom.trim();
currentChatRoomElement.textContent = chatRoom;
console.log(`Switched to chat room: ${chatRoom}`);
// Join the new chat room
socket.emit('join', { username: username, chat_room: chatRoom });
// Clear the chat history in the UI
chatDiv.innerHTML = "";
// Fetch message history for the new chat room
fetch(`${serverBaseUrl}/get_history?chat_room=${encodeURIComponent(chatRoom)}`)
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(data => {
if (data.messages && data.messages.length > 0) {
// Display each message in the chat history
data.messages.forEach(message => {
const messageElement = document.createElement('div');
messageElement.textContent = message;
chatDiv.appendChild(messageElement);
});
chatDiv.scrollTop = chatDiv.scrollHeight; // Auto-scroll to the bottom
} else {
console.log("No message history found for this chat room.");
}
})
.catch(error => {
console.error("Error fetching message history:", error);
});
}
}
// Disconnect from the current server
function disconnectServer() {
if (socket.connected) {
socket.disconnect();
console.log("Disconnected from the server");
alert("You have been disconnected from the server.");
currentServerElement.textContent = "Disconnected"; // Update the displayed server URL
} else {
alert("You are not connected to any server.");
}
}
// Change the server to connect to
function changeServer() {
if (socket.connected) {
socket.disconnect();
console.log("Disconnected from the current server");
}
const newServerUrl = prompt("Enter the new WebSocket server URL (e.g., http://localhost:5000):");
if (newServerUrl && newServerUrl.trim() !== "") {
serverUrl = newServerUrl.trim();
console.log(`Connecting to new server: ${serverUrl}`);
socket.io.uri = serverUrl; // Update the server URL
socket.connect(); // Reconnect to the new server
currentServerElement.textContent = serverUrl; // Update the displayed server URL
alert(`Connected to the new server: ${serverUrl}`);
} else {
alert("Server URL cannot be empty.");
}
}
// Reconnect to the server
function reconnectServer() {
if (!socket.connected) {
console.log("Reconnecting to the server...");
socket.connect();
alert("Reconnected to the server.");
} else {
alert("You are already connected to the server.");
}
}
// Toggle between light mode and dark mode
function toggleTheme() {
const body = document.body;
if (body.classList.contains('light-mode')) {
body.classList.remove('light-mode');
body.classList.add('dark-mode');
localStorage.setItem('theme', 'dark-mode'); // Save preference
} else {
body.classList.remove('dark-mode');
body.classList.add('light-mode');
localStorage.setItem('theme', 'light-mode'); // Save preference
}
}
// Apply saved theme on page load
const savedTheme = localStorage.getItem('theme') || 'dark-mode'; // Default to dark mode
document.body.classList.add(savedTheme);
</script>
</body>
</html>