убери шифрование <!DOCTYPE html> <html lang="ru"> <head> <meta charset="UTF-8">…
- User
убери шифрование
code - Assistant
убери шифрование
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(135deg, #c3ec52, #0ba29d);
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
padding: 20px;
}
.chat-container {
background-color: #ffffff;
width: 100%;
max-width: 70%;
height: 90vh;
border-radius: 12px;
box-shadow: 0 8px 16px rgba(0,0,0,0.2);
display: flex;
flex-direction: column;
overflow: hidden;
}
header {
background-color: #4CAF50;
color: white;
padding: 20px;
text-align: center;
position: relative;
}
header h1 {
font-size: 1.8rem;
}
.peer-id {
font-size: 0.9rem;
margin-top: 5px;
opacity: 0.8;
}
.main {
flex: 1;
display: flex;
overflow: hidden;
}
.sidebar {
width: 250px;
background-color: #f4f4f4;
border-right: 1px solid #ddd;
padding: 20px;
display: flex;
flex-direction: column;
}
.sidebar .connect-section,
.sidebar .online-section {
margin-bottom: 30px;
}
.sidebar label {
display: block;
margin-bottom: 8px;
font-weight: bold;
color: #333;
}
.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: #4CAF50;
outline: none;
}
.sidebar button {
width: 100%;
padding: 10px;
background-color: #4CAF50;
border: none;
border-radius: 6px;
color: white;
font-weight: bold;
cursor: pointer;
transition: background-color 0.3s;
}
.sidebar button:hover {
background-color: #45a049;
}
.online-section h3 {
margin-bottom: 10px;
color: #333;
}
#online-users {
list-style: none;
max-height: 300px;
overflow-y: auto;
}
#online-users li {
display: flex;
justify-content: space-between;
align-items: center;
padding: 8px 10px;
border-bottom: 1px solid #ddd;
border-radius: 6px;
margin-bottom: 5px;
background-color: #fff;
transition: background-color 0.3s;
}
#online-users li:hover {
background-color: #f1f1f1;
}
.user-info {
display: flex;
align-items: center;
}
.user-info .status {
width: 10px;
height: 10px;
border-radius: 50%;
background-color: #4CAF50;
margin-right: 10px;
}
.user-info .user-id {
font-size: 0.9rem;
color: #333;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
max-width: 140px;
}
.user-actions button {
padding: 5px 10px;
background-color: #2196F3;
border: none;
border-radius: 4px;
color: white;
cursor: pointer;
font-size: 0.8rem;
transition: background-color 0.3s;
}
.user-actions button:hover {
background-color: #1976D2;
}
.chat-section {
flex: 1;
display: flex;
flex-direction: column;
padding: 20px;
background-color: #fafafa;
}
#messages {
flex: 1;
overflow-y: auto;
padding-right: 10px;
}
.message {
margin-bottom: 15px;
max-width: 70%;
padding: 10px 15px;
border-radius: 20px;
position: relative;
word-wrap: break-word;
}
.message.self {
background-color: #DCF8C6;
align-self: flex-end;
border-bottom-right-radius: 0;
}
.message.other {
background-color: #FFFFFF;
border: 1px solid #ddd;
align-self: flex-start;
border-bottom-left-radius: 0;
}
.message.system {
background-color: #e0e0e0;
text-align: center;
max-width: 100%;
margin: 10px auto;
border-radius: 10px;
padding: 8px 12px;
font-style: italic;
}
.message .meta {
font-size: 0.7rem;
color: #555;
margin-top: 5px;
text-align: right;
}
.input-section {
display: flex;
align-items: center;
margin-top: 10px;
}
.input-section input[type="text"] {
flex: 1;
padding: 10px;
border: 1px solid #ccc;
border-radius: 6px;
margin-right: 10px;
transition: border-color 0.3s;
}
.input-section input[type="text"]:focus {
border-color: #4CAF50;
outline: none;
}
.input-section button {
padding: 10px 15px;
background-color: #4CAF50;
border: none;
border-radius: 6px;
color: white;
font-weight: bold;
cursor: pointer;
transition: background-color 0.3s;
}
.input-section button:hover {
background-color: #45a049;
}
.file-section {
display: flex;
align-items: center;
margin-top: 10px;
}
.file-section input[type="file"] {
flex: 1;
padding: 10px;
border: 1px solid #ccc;
border-radius: 6px;
margin-right: 10px;
transition: border-color 0.3s;
}
.file-section input[type="file"]:focus {
border-color: #4CAF50;
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 #4CAF50;
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: #4CAF50;
color: white;
}
.call-window #accept-call-btn:hover {
background-color: #45a049;
}
.call-window #reject-call-btn {
background-color: #f44336;
color: white;
}
.call-window #reject-call-btn:hover {
background-color: #d32f2f;
}
/* Аудио элемент */
.audio-chat {
margin-top: 10px;
}
/* Медиа запросы для адаптивности */
@media (max-width: 768px) {
.main {
flex-direction: column;
}
.sidebar {
width: 100%;
border-right: none;
border-bottom: 1px solid #ddd;
}
.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>
<!-- Окно звонка -->
<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://cdnjs.cloudflare.com/ajax/libs/libsodium-wrappers/0.7.9/libsodium-wrappers.min.js"></script>
<script src="https://unpkg.com/peerjs@1.4.7/dist/peerjs.min.js"></script>
<script>
// Инициализация переменных
let sodium;
let keyPair; // Хранит ключевую пару текущего пользователя
let userPublicKeys = {}; // Хранит публичные ключи других пользователей: { peerId: publicKey Uint8Array }
const connections = {}; // Хранит текущие соединения: { peerId: conn }
let currentCall = null;
let localStream = null;
// Элементы интерфейса
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');
// Функции для управления ключами и шифрованием
async function initializeSodium() {
await sodium.ready;
sodium = window.sodium;
keyPair = sodium.crypto_box_keypair(); // Генерация ключевой пары
console.log('Ключевая пара сгенерирована.');
}
// Инициализация libsodium
initializeSodium();
// Инициализация PeerJS
const peer = new Peer();
// Отображение вашего Peer ID
peer.on('open', (id) => {
peerIdDisplay.textContent = id;
addOnlineUser(id, true);
});
// Обработка входящих соединений
peer.on('connection', (conn) => {
if (connections[conn.peer]) {
console.warn(`Уже есть соединение с ${conn.peer}`);
conn.close();
return;
}
connections[conn.peer] = conn;
setupConnection(conn);
addOnlineUser(conn.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}.`);
};
});
// Обработка ошибок PeerJS
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];
});
});
// Функция настройки соединения с добавлением E2E шифрования
function setupConnection(conn) {
conn.on('data', (data) => {
try {
const parsedData = JSON.parse(data);
if (parsedData.type === 'public-key') {
handlePublicKey(parsedData.content, conn.peer);
} else if (parsedData.type === 'message') {
handleEncryptedMessage(parsedData.content, conn.peer);
} else if (parsedData.type === 'file') {
handleIncomingFile(parsedData, conn.peer);
}
} catch (e) {
console.error('Ошибка при разборе данных:', e);
appendMessage(data, 'other');
}
});
conn.on('close', () => {
appendSystemMessage(`Соединение с ${conn.peer} закрыто.`);
removeOnlineUser(conn.peer);
delete connections[conn.peer];
delete userPublicKeys[conn.peer];
});
// Отправка публичного ключа сразу после установления соединения
sendPublicKey(conn);
// Отправка уведомления о подключении
appendSystemMessage(`Соединение с ${conn.peer} установлено.`);
}
// Функция отправки публичного ключа
function sendPublicKey(conn) {
if (!keyPair) {
console.error('Ключевая пара еще не сгенерирована.');
return;
}
const publicKeyBase64 = sodium.to_base64(keyPair.publicKey, sodium.base64_variants.ORIGINAL);
const keyMessage = JSON.stringify({
type: 'public-key',
content: publicKeyBase64
});
conn.send(keyMessage);
console.log(`Публичный ключ отправлен ${conn.peer}`);
}
// Функция обработки полученного публичного ключа
function handlePublicKey(publicKeyBase64, peerId) {
const publicKey = sodium.from_base64(publicKeyBase64, sodium.base64_variants.ORIGINAL);
userPublicKeys[peerId] = publicKey;
appendSystemMessage(`Получен публичный ключ от ${peerId}.`);
}
// Функция шифрования сообщений
function encryptMessage(message, peerId) {
const nonce = sodium.randombytes_buf(sodium.crypto_box_NONCEBYTES);
const messageUint8 = sodium.from_string(message);
const encrypted = sodium.crypto_box_easy(messageUint8, nonce, userPublicKeys[peerId], keyPair.privateKey);
const nonceBase64 = sodium.to_base64(nonce, sodium.base64_variants.ORIGINAL);
const encryptedBase64 = sodium.to_base64(encrypted, sodium.base64_variants.ORIGINAL);
return `${nonceBase64}:${encryptedBase64}`;
}
// Функция дешифрования сообщений
function decryptMessage(encryptedMessage, peerId) {
const [nonceBase64, encryptedBase64] = encryptedMessage.split(':');
const nonce = sodium.from_base64(nonceBase64, sodium.base64_variants.ORIGINAL);
const encrypted = sodium.from_base64(encryptedBase64, sodium.base64_variants.ORIGINAL);
const decrypted = sodium.crypto_box_open_easy(encrypted, nonce, userPublicKeys[peerId], keyPair.privateKey);
return decrypted ? sodium.to_string(decrypted) : null;
}
// Функция обработки зашифрованных сообщений
function handleEncryptedMessage(encryptedContent, peerId) {
const decryptedMessage = decryptMessage(encryptedContent, peerId);
if (decryptedMessage) {
appendMessage(decryptedMessage, 'other');
} else {
appendSystemMessage(`Не удалось расшифровать сообщение от ${peerId}.`);
}
}
// Функция добавления сообщения в область сообщений
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.textContent = message;
messagesArea.appendChild(messageDiv);
messagesArea.scrollTop = messagesArea.scrollHeight;
}
// Функции для обновления списка онлайн-пользователей
function addOnlineUser(userId, isSelf = false) {
// Проверяем, есть ли уже пользователь в списке
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 status = document.createElement('span');
status.classList.add('status');
status.style.backgroundColor = isSelf ? '#4CAF50' : '#4CAF50';
const userIdSpan = document.createElement('span');
userIdSpan.classList.add('user-id');
userIdSpan.textContent = userId;
userInfo.appendChild(status);
userInfo.appendChild(userIdSpan);
li.appendChild(userInfo);
if (!isSelf) { // Не отображать кнопку для самого себя
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);
if (!isSelf) {
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 remoteId = remoteIdInput.value.trim();
if (!remoteId) {
alert('Укажите Peer ID для отправки файла.');
return;
}
if (!userPublicKeys[remoteId]) {
alert('Публичный ключ получателя неизвестен.');
return;
}
const reader = new FileReader();
reader.onload = () => {
const arrayBuffer = reader.result;
const uint8Array = new Uint8Array(arrayBuffer);
const nonce = sodium.randombytes_buf(sodium.crypto_box_NONCEBYTES);
const encrypted = sodium.crypto_box_easy(uint8Array, nonce, userPublicKeys[remoteId], keyPair.privateKey);
const nonceBase64 = sodium.to_base64(nonce, sodium.base64_variants.ORIGINAL);
const encryptedBase64 = sodium.to_base64(encrypted, sodium.base64_variants.ORIGINAL);
const encryptedContent = `${nonceBase64}:${encryptedBase64}`;
const data = JSON.stringify({
type: 'file',
content: encryptedContent,
fileName: file.name,
fileType: file.type
});
const conn = connections[remoteId];
if (conn && conn.open) {
conn.send(data);
appendSystemMessage(`Вы отправили зашифрованный файл: ${file.name} пользователю ${remoteId}.`);
fileInput.value = ''; // Очистка поля выбора файла
} else {
alert('Нет открытого соединения для отправки файла.');
}
};
reader.readAsArrayBuffer(file);
});
// Функция обработки входящих файлов с дешифрованием
function handleIncomingFile(data, peerId) {
const { content, fileName, fileType } = data;
const decryptedArrayBuffer = decryptFile(content, peerId);
if (!decryptedArrayBuffer) {
appendSystemMessage(`Не удалось расшифровать файл от ${peerId}.`);
return;
}
const blob = new Blob([decryptedArrayBuffer], { 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;
}
// Функция дешифрования файла
function decryptFile(encryptedContent, peerId) {
const [nonceBase64, encryptedBase64] = encryptedContent.split(':');
const nonce = sodium.from_base64(nonceBase64, sodium.base64_variants.ORIGINAL);
const encrypted = sodium.from_base64(encryptedBase64, sodium.base64_variants.ORIGINAL);
const decrypted = sodium.crypto_box_open_easy(encrypted, nonce, userPublicKeys[peerId], keyPair.privateKey);
return decrypted ? decrypted : null;
}
// Функция обработки отправки текстовых сообщений с шифрованием
sendBtn.addEventListener('click', () => {
const message = messageInput.value.trim();
if (!message) return;
const remoteId = remoteIdInput.value.trim();
if (!remoteId) {
alert('Укажите Peer ID для отправки сообщения.');
return;
}
if (!userPublicKeys[remoteId]) {
alert('Публичный ключ получателя неизвестен.');
return;
}
const encrypted = encryptMessage(message, remoteId);
const data = JSON.stringify({ type: 'message', content: encrypted });
const conn = connections[remoteId];
if (conn && conn.open) {
conn.send(data);
appendMessage(message, 'self');
messageInput.value = '';
} else {
alert('Нет открытого соединения для отправки сообщения.');
}
});
// Обработка отправки по нажатию Enter
messageInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
sendBtn.click();
}
});
// Функции для звонков (без изменений, так как WebRTC уже шифрует звонки)
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>
Конечно! Я помогу вам убрать E2E шифрование из вашего P2P чата. Ниже представлен обновленный код, в котором удалены все компоненты, связанные с шифрованием. Теперь чат будет передавать сообщения и файлы напрямую без дополнительной защиты.
Удалены библиотеки для шифрования:
libsodium-wrappers.Убраны все элементы, связанные с генерацией и управлением ключами:
sodium, keyPair, userPublicKeys были удалены.Удалены функции шифрования и дешифрования сообщений и файлов.
Обновлена логика отправки и получения сообщений и файлов без шифрования.
Вот обновленный код:
<!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: linear-gradient(135deg, #c3ec52, #0ba29d);
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
padding: 20px;
}
.chat-container {
background-color: #ffffff;
width: 100%;
max-width: 70%;
height: 90vh;
border-radius: 12px;
box-shadow: 0 8px 16px rgba(0,0,0,0.2);
display: flex;
flex-direction: column;
overflow: hidden;
}
header {
background-color: #4CAF50;
color: white;
padding: 20px;
text-align: center;
position: relative;
}
header h1 {
font-size: 1.8rem;
}
.peer-id {
font-size: 0.9rem;
margin-top: 5px;
opacity: 0.8;
}
.main {
flex: 1;
display: flex;
overflow: hidden;
}
.sidebar {
width: 250px;
background-color: #f4f4f4;
border-right: 1px solid #ddd;
padding: 20px;
display: flex;
flex-direction: column;
}
.sidebar .connect-section,
.sidebar .online-section {
margin-bottom: 30px;
}
.sidebar label {
display: block;
margin-bottom: 8px;
font-weight: bold;
color: #333;
}
.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: #4CAF50;
outline: none;
}
.sidebar button {
width: 100%;
padding: 10px;
background-color: #4CAF50;
border: none;
border-radius: 6px;
color: white;
font-weight: bold;
cursor: pointer;
transition: background-color 0.3s;
}
.sidebar button:hover {
background-color: #45a049;
}
.online-section h3 {
margin-bottom: 10px;
color: #333;
}
#online-users {
list-style: none;
max-height: 300px;
overflow-y: auto;
}
#online-users li {
display: flex;
justify-content: space-between;
align-items: center;
padding: 8px 10px;
border-bottom: 1px solid #ddd;
border-radius: 6px;
margin-bottom: 5px;
background-color: #fff;
transition: background-color 0.3s;
}
#online-users li:hover {
background-color: #f1f1f1;
}
.user-info {
display: flex;
align-items: center;
}
.user-info .status {
width: 10px;
height: 10px;
border-radius: 50%;
background-color: #4CAF50;
margin-right: 10px;
}
.user-info .user-id {
font-size: 0.9rem;
color: #333;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
max-width: 140px;
}
.user-actions button {
padding: 5px 10px;
background-color: #2196F3;
border: none;
border-radius: 4px;
color: white;
cursor: pointer;
font-size: 0.8rem;
transition: background-color 0.3s;
}
.user-actions button:hover {
background-color: #1976D2;
}
.chat-section {
flex: 1;
display: flex;
flex-direction: column;
padding: 20px;
background-color: #fafafa;
}
#messages {
flex: 1;
overflow-y: auto;
padding-right: 10px;
}
.message {
margin-bottom: 15px;
max-width: 70%;
padding: 10px 15px;
border-radius: 20px;
position: relative;
word-wrap: break-word;
}
.message.self {
background-color: #DCF8C6;
align-self: flex-end;
border-bottom-right-radius: 0;
}
.message.other {
background-color: #FFFFFF;
border: 1px solid #ddd;
align-self: flex-start;
border-bottom-left-radius: 0;
}
.message.system {
background-color: #e0e0e0;
text-align: center;
max-width: 100%;
margin: 10px auto;
border-radius: 10px;
padding: 8px 12px;
font-style: italic;
}
.message .meta {
font-size: 0.7rem;
color: #555;
margin-top: 5px;
text-align: right;
}
.input-section {
display: flex;
align-items: center;
margin-top: 10px;
}
.input-section input[type="text"] {
flex: 1;
padding: 10px;
border: 1px solid #ccc;
border-radius: 6px;
margin-right: 10px;
transition: border-color 0.3s;
}
.input-section input[type="text"]:focus {
border-color: #4CAF50;
outline: none;
}
.input-section button {
padding: 10px 15px;
background-color: #4CAF50;
border: none;
border-radius: 6px;
color: white;
font-weight: bold;
cursor: pointer;
transition: background-color 0.3s;
}
.input-section button:hover {
background-color: #45a049;
}
.file-section {
display: flex;
align-items: center;
margin-top: 10px;
}
.file-section input[type="file"] {
flex: 1;
padding: 10px;
border: 1px solid #ccc;
border-radius: 6px;
margin-right: 10px;
transition: border-color 0.3s;
}
.file-section input[type="file"]:focus {
border-color: #4CAF50;
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 #4CAF50;
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: #4CAF50;
color: white;
}
.call-window #accept-call-btn:hover {
background-color: #45a049;
}
.call-window #reject-call-btn {
background-color: #f44336;
color: white;
}
.call-window #reject-call-btn:hover {
background-color: #d32f2f;
}
/* Аудио элемент */
.audio-chat {
margin-top: 10px;
}
/* Медиа запросы для адаптивности */
@media (max-width: 768px) {
.main {
flex-direction: column;
}
.sidebar {
width: 100%;
border-right: none;
border-bottom: 1px solid #ddd;
}
.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: #2196F3; 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>
// Инициализация переменных
const connections = {}; // Хранит текущие соединения: { peerId: conn }
let currentCall = null;
let localStream = null;
// Элементы интерфейса
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');
// Инициализация PeerJS
const peer = new Peer();
// Отображение вашего Peer ID
peer.on('open', (id) => {
peerIdDisplay.textContent = id;
addOnlineUser(id, true);
});
// Обработка входящих соединений
peer.on('connection', (conn) => {
if (connections[conn.peer]) {
console.warn(`Уже есть соединение с ${conn.peer}`);
conn.close();
return;
}
connections[conn.peer] = conn;
setupConnection(conn);
addOnlineUser(conn.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}.`);
};
});
// Обработка ошибок PeerJS
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') {
handleMessage(parsedData.content, conn.peer);
} else if (parsedData.type === 'file') {
handleIncomingFile(parsedData, conn.peer);
}
} 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.textContent = message;
messagesArea.appendChild(messageDiv);
messagesArea.scrollTop = messagesArea.scrollHeight;
}
// Функции для обновления списка онлайн-пользователей
function addOnlineUser(userId, isSelf = false) {
// Проверяем, есть ли уже пользователь в списке
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 status = document.createElement('span');
status.classList.add('status');
status.style.backgroundColor = isSelf ? '#4CAF50' : '#4CAF50';
const userIdSpan = document.createElement('span');
userIdSpan.classList.add('user-id');
userIdSpan.textContent = userId;
userInfo.appendChild(status);
userInfo.appendChild(userIdSpan);
li.appendChild(userInfo);
if (!isSelf) { // Не отображать кнопку для самого себя
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);
if (!isSelf) {
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 remoteId = remoteIdInput.value.trim();
if (!remoteId) {
alert('Укажите Peer ID для отправки файла.');
return;
}
const reader = new FileReader();
reader.onload = () => {
const arrayBuffer = reader.result;
const uint8Array = new Uint8Array(arrayBuffer);
const data = JSON.stringify({
type: 'file',
content: Array.from(uint8Array),
fileName: file.name,
fileType: file.type
});
const conn = connections[remoteId];
if (conn && conn.open) {
conn.send(data);
appendSystemMessage(`Вы отправили файл: ${file.name} пользователю ${remoteId}.`);
fileInput.value = ''; // Очистка поля выбора файла
} else {
alert('Нет открытого соединения для отправки файла.');
}
};
reader.readAsArrayBuffer(file);
});
// Функция обработки входящих файлов
function handleIncomingFile(data, peerId) {
const { content, fileName, fileType } = data;
const uint8Array = new Uint8Array(content);
const blob = new Blob([uint8Array], { 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;
}
// Функция обработки отправки текстовых сообщений
sendBtn.addEventListener('click', () => {
const message = messageInput.value.trim();
if (!message) return;
const remoteId = remoteIdInput.value.trim();
if (!remoteId) {
alert('Укажите Peer ID для отправки сообщения.');
return;
}
const data = JSON.stringify({ type: 'message', content: message });
const conn = connections[remoteId];
if (conn && conn.open) {
conn.send(data);
appendMessage(message, 'self');
messageInput.value = '';
} else {
alert('Нет открытого соединения для отправки сообщения.');
}
});
// Обработка отправки по нажатию Enter
messageInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
sendBtn.click();
}
});
// Функции для звонков (без изменений, так как WebRTC уже шифрует звонки)
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>
Удаление Шифрования:
libsodium-wrappers, а также весь код, связанный с генерацией и управлением ключами.Обмен Сообщениями:
message или file) и обрабатывается соответствующим образом.Обмен Файлами:
Упрощенная Логика:
Безопасность: Удаление шифрования означает, что все передаваемые данные могут быть перехвачены или изменены третьими лицами. Если безопасность и конфиденциальность важны для вашего приложения, рекомендуется использовать надежные методы шифрования.
WebRTC Шифрование: Хотя текстовые сообщения и файлы передаются без дополнительного шифрования, звонки через WebRTC все еще защищены встроенными средствами шифрования этого протокола.
PeerJS: Убедитесь, что PeerJS сервер, который вы используете, надежен и безопасен, так как он играет ключевую роль в установлении соединений между пользователями.
Если у вас возникнут дополнительные вопросы или потребуется дальнейшая помощь, дайте знать!
Not yet included in a published release.