Понял вашу задачу. Вы хотите, чтобы текущий пользователь не отображался в списке онлайн пользователей, а интерфейс чата выглядел более похожим на веб-версию Telegram. Я внесу необходимые изменения в ваш код, чтобы достичь этих целей.
Изменения:
-
Не отображать самого себя в списке онлайн пользователей:
- Удалим вызов
addOnlineUser(id, true) при инициализации, чтобы текущий пользователь не добавлялся в список.
- Обновим функцию
addOnlineUser для более оптимальной обработки.
-
Сделать интерфейс чата похожим на Telegram Web:
- Обновим CSS для улучшения внешнего вида сообщений.
- Добавим аватары для пользователей.
- Улучшим выравнивание сообщений и стиль списка онлайн пользователей.
Вот обновленный код с внесенными изменениями:
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<title>Децентрализованный P2P Чат</title>
<style>
/* Сброс базовых стилей */
*, *::before, *::after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: #e5ddd5;
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
padding: 20px;
}
.chat-container {
background-color: #ffffff;
width: 100%;
max-width: 1200px;
height: 80vh;
border-radius: 8px;
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
display: flex;
overflow: hidden;
}
header {
background-color: #0088cc;
color: white;
padding: 15px 20px;
text-align: center;
width: 100%;
position: relative;
}
header h1 {
font-size: 1.5rem;
}
.main {
display: flex;
flex: 1;
overflow: hidden;
}
.sidebar {
width: 300px;
background-color: #f7f7f7;
border-right: 1px solid #ddd;
padding: 20px;
display: flex;
flex-direction: column;
}
.connect-section,
.online-section {
margin-bottom: 30px;
}
.sidebar label {
display: block;
margin-bottom: 8px;
font-weight: bold;
color: #555;
}
.sidebar input[type="text"],
.sidebar input[type="password"] {
width: 100%;
padding: 10px;
border: 1px solid #ccc;
border-radius: 6px;
margin-bottom: 10px;
transition: border-color 0.3s;
}
.sidebar input[type="text"]:focus,
.sidebar input[type="password"]:focus {
border-color: #0088cc;
outline: none;
}
.sidebar button {
width: 100%;
padding: 10px;
background-color: #0088cc;
border: none;
border-radius: 6px;
color: white;
font-weight: bold;
cursor: pointer;
transition: background-color 0.3s;
}
.sidebar button:hover {
background-color: #006f99;
}
.online-section h3 {
margin-bottom: 15px;
color: #333;
display: flex;
align-items: center;
justify-content: space-between;
}
#online-users {
list-style: none;
max-height: 400px;
overflow-y: auto;
}
#online-users li {
display: flex;
align-items: center;
padding: 10px;
border-bottom: 1px solid #eee;
transition: background-color 0.3s;
}
#online-users li:hover {
background-color: #f0f0f0;
}
.user-info {
display: flex;
align-items: center;
flex: 1;
}
.user-info .avatar {
width: 40px;
height: 40px;
border-radius: 50%;
background-color: #ccc;
margin-right: 10px;
flex-shrink: 0;
}
.user-info .user-id {
font-size: 0.9rem;
color: #333;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
max-width: 180px;
}
.user-actions button {
padding: 6px 12px;
background-color: #25D366;
border: none;
border-radius: 4px;
color: white;
cursor: pointer;
font-size: 0.8rem;
transition: background-color 0.3s;
}
.user-actions button:hover {
background-color: #1da851;
}
.chat-section {
flex: 1;
display: flex;
flex-direction: column;
padding: 20px;
background-color: #e5ddd5;
}
#messages {
flex: 1;
overflow-y: auto;
padding-right: 10px;
margin-bottom: 20px;
}
.message {
max-width: 60%;
padding: 10px 15px;
border-radius: 8px;
margin-bottom: 10px;
position: relative;
word-wrap: break-word;
clear: both;
}
.message.self {
background-color: #dcf8c6;
align-self: flex-end;
margin-left: auto;
border-bottom-right-radius: 0;
}
.message.other {
background-color: #ffffff;
border: 1px solid #ddd;
align-self: flex-start;
border-bottom-left-radius: 0;
}
.message .meta {
font-size: 0.7rem;
color: #555;
margin-top: 5px;
text-align: right;
}
.input-section {
display: flex;
align-items: center;
gap: 10px;
}
.input-section input[type="text"] {
flex: 1;
padding: 10px 15px;
border: 1px solid #ccc;
border-radius: 20px;
transition: border-color 0.3s;
}
.input-section input[type="text"]:focus {
border-color: #0088cc;
outline: none;
}
.input-section button {
padding: 10px 20px;
background-color: #0088cc;
border: none;
border-radius: 20px;
color: white;
font-weight: bold;
cursor: pointer;
transition: background-color 0.3s;
}
.input-section button:hover {
background-color: #006f99;
}
.file-section {
display: flex;
align-items: center;
gap: 10px;
margin-top: 10px;
}
.file-section input[type="file"] {
flex: 1;
padding: 10px;
border: 1px solid #ccc;
border-radius: 6px;
transition: border-color 0.3s;
}
.file-section input[type="file"]:focus {
border-color: #0088cc;
outline: none;
}
.file-section button {
padding: 10px 15px;
background-color: #FF9800;
border: none;
border-radius: 6px;
color: white;
font-weight: bold;
cursor: pointer;
transition: background-color 0.3s;
}
.file-section button:hover {
background-color: #F57C00;
}
/* Стили для окна звонка */
.call-window {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: #ffffff;
padding: 30px;
border: 2px solid #0088cc;
border-radius: 12px;
box-shadow: 0 8px 16px rgba(0,0,0,0.3);
display: none;
z-index: 1000;
width: 300px;
text-align: center;
}
.call-window.active {
display: block;
}
.call-window p {
margin-bottom: 20px;
font-size: 1rem;
color: #333;
}
.call-window button {
padding: 10px 20px;
border: none;
border-radius: 6px;
cursor: pointer;
font-weight: bold;
transition: background-color 0.3s;
margin: 0 10px;
}
.call-window #accept-call-btn {
background-color: #25D366;
color: white;
}
.call-window #accept-call-btn:hover {
background-color: #1da851;
}
.call-window #reject-call-btn {
background-color: #f44336;
color: white;
}
.call-window #reject-call-btn:hover {
background-color: #d32f2f;
}
/* Аудио элемент */
.audio-chat {
margin-top: 10px;
width: 100%;
outline: none;
}
/* Медиа запросы для адаптивности */
@media (max-width: 992px) {
.sidebar {
width: 250px;
padding: 15px;
}
.chat-container {
max-width: 1000px;
}
}
@media (max-width: 768px) {
.main {
flex-direction: column;
}
.sidebar {
width: 100%;
border-right: none;
border-bottom: 1px solid #ddd;
padding: 15px;
}
.chat-section {
padding: 15px;
}
.input-section, .file-section {
flex-direction: column;
}
.input-section input[type="text"],
.file-section input[type="file"] {
margin-right: 0;
margin-bottom: 10px;
width: 100%;
}
.input-section button,
.file-section button {
width: 100%;
}
}
</style>
</head>
<body>
<div class="chat-container">
<header>
<h1>Децентрализованный P2P Чат</h1>
<p class="peer-id">Ваш Peer ID: <span id="peer-id">Подключение...</span></p>
</header>
<div class="main">
<div class="sidebar">
<div class="connect-section">
<label for="remote-id">Подключиться к Peer ID:</label>
<input type="text" id="remote-id" placeholder="Введите Peer ID другого пользователя">
<button id="connect-btn">Подключиться</button>
</div>
<div class="online-section">
<h3>Онлайн пользователи:</h3>
<ul id="online-users">
<!-- Список онлайн пользователей будет здесь -->
</ul>
</div>
</div>
<div class="chat-section">
<div id="messages"></div>
<div class="input-section">
<input type="text" id="message-input" placeholder="Введите сообщение">
<button id="send-btn">Отправить</button>
</div>
<div class="file-section">
<input type="file" id="file-input">
<button id="send-file-btn">Отправить файл</button>
</div>
<button id="call-btn" style="margin-top: 15px; background-color: #25D366; color: white;">Позвонить</button>
</div>
</div>
</div>
<!-- Окно звонка -->
<div class="call-window" id="call-window">
<p id="call-status">Входящий звонок от <span id="caller-id"></span></p>
<button id="accept-call-btn">Принять</button>
<button id="reject-call-btn">Отклонить</button>
</div>
<!-- Подключение необходимых библиотек через CDN -->
<script src="https://unpkg.com/peerjs@1.4.7/dist/peerjs.min.js"></script>
<script>
// Инициализация Peer
const peer = new Peer();
// Элементы интерфейса
const peerIdDisplay = document.getElementById('peer-id');
const connectBtn = document.getElementById('connect-btn');
const remoteIdInput = document.getElementById('remote-id');
const messagesArea = document.getElementById('messages');
const sendBtn = document.getElementById('send-btn');
const messageInput = document.getElementById('message-input');
const onlineUsersList = document.getElementById('online-users');
const fileInput = document.getElementById('file-input');
const sendFileBtn = document.getElementById('send-file-btn');
const callBtn = document.getElementById('call-btn');
// Элементы окна звонка
const callWindow = document.getElementById('call-window');
const callerIdSpan = document.getElementById('caller-id');
const acceptCallBtn = document.getElementById('accept-call-btn');
const rejectCallBtn = document.getElementById('reject-call-btn');
// Хранение соединений
let connections = {};
let currentCall = null;
let localStream = null;
// Отображение вашего Peer ID
peer.on('open', (id) => {
peerIdDisplay.textContent = id;
// Не добавляем себя в список онлайн пользователей
// addOnlineUser(id, true);
});
// Обработка входящих соединений
peer.on('connection', (connection) => {
if (connections[connection.peer]) {
connection.close();
return;
}
connections[connection.peer] = connection;
setupConnection(connection);
addOnlineUser(connection.peer);
});
// Обработка входящих звонков
peer.on('call', (call) => {
// Показываем окно звонка
callWindow.classList.add('active');
callerIdSpan.textContent = call.peer;
// Принять звонок
acceptCallBtn.onclick = () => {
navigator.mediaDevices.getUserMedia({ audio: true, video: false })
.then(stream => {
localStream = stream;
call.answer(stream);
setupCall(call);
callWindow.classList.remove('active');
})
.catch(err => {
console.error('Ошибка доступа к микрофону:', err);
alert('Не удалось получить доступ к микрофону.');
});
};
// Отклонить звонок
rejectCallBtn.onclick = () => {
call.close();
callWindow.classList.remove('active');
appendSystemMessage(`Вы отклонили звонок от ${call.peer}.`);
};
});
// Обработка ошибок
peer.on('error', (err) => {
console.error(err);
alert('Произошла ошибка: ' + err);
});
// Функция подключения к другому Peer
connectBtn.addEventListener('click', () => {
const remoteId = remoteIdInput.value.trim();
if (!remoteId) {
alert('Введите Peer ID для подключения.');
return;
}
// Проверяем, нет ли уже соединения с этим Peer
if (connections[remoteId]) {
alert('Уже подключены к этому Peer.');
return;
}
const conn = peer.connect(remoteId);
connections[remoteId] = conn;
conn.on('open', () => {
setupConnection(conn);
addOnlineUser(remoteId);
appendSystemMessage(`Соединение с ${remoteId} установлено.`);
});
conn.on('error', (err) => {
console.error('Соединение ошибка:', err);
appendSystemMessage(`Ошибка соединения с ${remoteId}: ${err}`);
delete connections[remoteId];
});
});
// Функция настройки соединения
function setupConnection(conn) {
conn.on('data', (data) => {
try {
const parsedData = JSON.parse(data);
if (parsedData.type === 'message') {
appendMessage(parsedData.content, 'other');
} else if (parsedData.type === 'file') {
handleIncomingFile(parsedData);
}
} catch (e) {
console.error('Ошибка при разборе данных:', e);
appendMessage(data, 'other');
}
});
conn.on('close', () => {
appendSystemMessage(`Соединение с ${conn.peer} закрыто.`);
removeOnlineUser(conn.peer);
delete connections[conn.peer];
});
// Отправка уведомления о подключении
appendSystemMessage(`Соединение с ${conn.peer} установлено.`);
}
// Функция добавления сообщения в область сообщений
function appendMessage(message, type) {
const messageDiv = document.createElement('div');
messageDiv.classList.add('message', type);
messageDiv.textContent = message;
messagesArea.appendChild(messageDiv);
messagesArea.scrollTop = messagesArea.scrollHeight;
}
// Функция добавления системных сообщений
function appendSystemMessage(message) {
const messageDiv = document.createElement('div');
messageDiv.classList.add('message', 'system');
messageDiv.style.backgroundColor = '#e0e0e0';
messageDiv.style.textAlign = 'center';
messageDiv.style.maxWidth = '100%';
messageDiv.textContent = message;
messagesArea.appendChild(messageDiv);
messagesArea.scrollTop = messagesArea.scrollHeight;
}
// Обработка отправки текстовых сообщений
sendBtn.addEventListener('click', () => {
const message = messageInput.value.trim();
if (!message) return;
const data = JSON.stringify({ type: 'message', content: message });
let hasOpenConnections = false;
Object.values(connections).forEach((conn) => {
if (conn.open) {
conn.send(data);
hasOpenConnections = true;
}
});
if (hasOpenConnections) {
appendMessage(message, 'self');
messageInput.value = '';
} else {
alert('Нет открытых соединений для отправки сообщения.');
}
});
// Обработка отправки по нажатию Enter
messageInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
sendBtn.click();
}
});
// Функции для обновления списка онлайн-пользователей
function addOnlineUser(userId) {
// Проверяем, есть ли уже пользователь в списке
if (![...onlineUsersList.children].some(li => li.querySelector('.user-id').textContent === userId)) {
const li = document.createElement('li');
const userInfo = document.createElement('div');
userInfo.classList.add('user-info');
const avatar = document.createElement('div');
avatar.classList.add('avatar');
// Здесь можно добавить аватарку пользователя, если есть URL
// Например: avatar.style.backgroundImage = 'url(avatar_url)';
// avatar.style.backgroundSize = 'cover';
const userIdSpan = document.createElement('span');
userIdSpan.classList.add('user-id');
userIdSpan.textContent = userId;
userInfo.appendChild(avatar);
userInfo.appendChild(userIdSpan);
li.appendChild(userInfo);
const userActions = document.createElement('div');
userActions.classList.add('user-actions');
const callButton = document.createElement('button');
callButton.textContent = 'Позвонить';
callButton.onclick = () => initiateCall(userId);
userActions.appendChild(callButton);
li.appendChild(userActions);
onlineUsersList.appendChild(li);
appendSystemMessage(`${userId} подключился.`);
}
}
function removeOnlineUser(userId) {
[...onlineUsersList.children].forEach(li => {
if (li.querySelector('.user-id').textContent === userId) {
onlineUsersList.removeChild(li);
appendSystemMessage(`${userId} отключился.`);
}
});
}
// Обработка отправки файлов
sendFileBtn.addEventListener('click', () => {
const file = fileInput.files[0];
if (!file) {
alert('Пожалуйста, выберите файл для отправки.');
return;
}
const reader = new FileReader();
reader.onload = () => {
const arrayBuffer = reader.result;
const base64String = arrayBufferToBase64(arrayBuffer);
const data = JSON.stringify({
type: 'file',
content: base64String,
fileName: file.name,
fileType: file.type
});
let hasOpenConnections = false;
Object.values(connections).forEach((conn) => {
if (conn.open) {
conn.send(data);
hasOpenConnections = true;
}
});
if (hasOpenConnections) {
appendSystemMessage(`Вы отправили файл: ${file.name}`);
fileInput.value = ''; // Очистка поля выбора файла
} else {
alert('Нет открытых соединений для отправки файла.');
}
};
reader.readAsArrayBuffer(file);
});
// Функция обработки входящих файлов
function handleIncomingFile(data) {
const { content, fileName, fileType } = data;
try {
const arrayBuffer = base64ToArrayBuffer(content);
const blob = new Blob([arrayBuffer], { type: fileType });
// Создаем ссылку для скачивания файла
const link = document.createElement('a');
const url = URL.createObjectURL(blob);
link.href = url;
link.download = fileName;
link.textContent = `Скачать файл: ${fileName}`;
link.className = 'file-link';
link.style.color = '#0066cc';
link.style.textDecoration = 'none';
link.style.display = 'block';
link.style.marginTop = '5px';
link.target = '_blank';
// Добавляем ссылку в область сообщений
const fileMessage = document.createElement('div');
fileMessage.classList.add('message', 'other');
fileMessage.innerHTML = `Друг отправил файл: ${fileName}`;
fileMessage.appendChild(link);
messagesArea.appendChild(fileMessage);
messagesArea.scrollTop = messagesArea.scrollHeight;
} catch (e) {
console.error('Ошибка при получении файла:', e);
appendSystemMessage(`Ошибка при получении файла: ${fileName}`);
}
}
// Вспомогательные функции для преобразования ArrayBuffer в Base64 и обратно
function arrayBufferToBase64(buffer) {
let binary = '';
const bytes = new Uint8Array(buffer);
const len = bytes.byteLength;
for (let i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return window.btoa(binary);
}
function base64ToArrayBuffer(base64) {
const binary_string = window.atob(base64);
const len = binary_string.length;
const bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) {
bytes[i] = binary_string.charCodeAt(i);
}
return bytes.buffer;
}
// Функции для звонков
function initiateCall(peerId) {
navigator.mediaDevices.getUserMedia({ audio: true, video: false })
.then(stream => {
localStream = stream;
const call = peer.call(peerId, stream);
setupCall(call);
appendSystemMessage(`Вы позвонили ${peerId}.`);
})
.catch(err => {
console.error('Ошибка доступа к микрофону:', err);
alert('Не удалось получить доступ к микрофону.');
});
}
function setupCall(call) {
if (currentCall) {
currentCall.close();
}
currentCall = call;
call.on('stream', (remoteStream) => {
// Создание аудио элемента для воспроизведения входящего аудио
const audio = document.createElement('audio');
audio.srcObject = remoteStream;
audio.autoplay = true;
audio.controls = true;
audio.classList.add('audio-chat');
messagesArea.appendChild(audio);
messagesArea.scrollTop = messagesArea.scrollHeight;
});
call.on('close', () => {
appendSystemMessage('Звонок завершен.');
});
call.on('error', (err) => {
console.error('Ошибка звонка:', err);
appendSystemMessage('Произошла ошибка во время звонка.');
});
}
// Кнопка для инициирования звонка (альтернативный способ)
callBtn.addEventListener('click', () => {
const remoteId = remoteIdInput.value.trim();
if (!remoteId) {
alert('Введите Peer ID для звонка.');
return;
}
if (remoteId === peer.id) {
alert('Вы не можете звонить себе.');
return;
}
initiateCall(remoteId);
});
</script>
</body>
</html>
Описание внесенных изменений:
-
Удаление отображения текущего пользователя:
- В обработчике
peer.on('open', ...) я закомментировал строку addOnlineUser(id, true);, чтобы текущий пользователь не добавлялся в список онлайн пользователей.
-
Обновление функции addOnlineUser:
- Теперь функция
addOnlineUser не принимает параметр isSelf, так как мы уже исключили добавление себя.
- Добавлены аватары для пользователей (пустые, можно настроить под свои нужды).
- Улучшено выравнивание и стилизация кнопок.
-
Обновление CSS:
- Изменен цвет фона и элементов для схожести с Telegram.
- Улучшена стилизация сообщений, добавлено более приятное выравнивание и цвета для сообщений от самого себя и от других пользователей.
- Добавлены медиа-запросы для лучшей адаптивности интерфейса.
-
Дополнительные улучшения:
- Добавлены комментарии для возможности добавления аватаров.
- Улучшен интерфейс отправки и получения файлов.
- Обновлены цвета кнопок для звонков и отправки сообщений, чтобы они были более интуитивно понятными.
Дополнительные рекомендации:
-
Аватары пользователей: Вы можете добавить аватарки пользователей, установив изображение в стиль .avatar. Например:
avatar.style.backgroundImage = 'url(путь_к_аватару)';
avatar.style.backgroundSize = 'cover';
-
Управление состоянием онлайн: В текущей реализации список онлайн пользователей обновляется только при установлении или закрытии соединений. Для более точного отслеживания онлайн состояния можно использовать heartbeat-сообщения или другие методы синхронизации.
-
Безопасность: Учитывайте безопасность при обмене данными и файлами. Возможно, стоит добавить механизмы аутентификации или шифрования.
Если у вас возникнут дополнительные вопросы или потребуется дальнейшая настройка, не стесняйтесь обращаться!