<!-- Окно звонка -->
<div class="call-window" id="call-window">
<p id="call-status">Входящий звонок от <span id="caller-id"></span></p>
<div class="accept-buttons">
<button class="btn-audio">Принять аудио звонок</button>
<button class="btn-video">Принять видео звонок</button>
<button class="btn-screen">Принять демонстрацию экрана</button>
</div>
<button class="reject">Отклонить</button>
</div>
<!-- Подключение PeerJS через CDN -->
<script src="https://unpkg.com/peerjs@1.4.7/dist/peerjs.min.js"></script>
<script>
class P2PChat {
constructor() {
this.peer = null;
this.connections = new Map();
this.currentCall = null;
this.localStream = null;
this.activePeerId = null; // Активный Peer ID для чата
// Элементы интерфейса
this.peerIdDisplay = document.getElementById('peer-id');
this.connectBtn = document.getElementById('connect-btn');
this.remoteIdInput = document.getElementById('remote-id');
this.messagesArea = document.getElementById('messages');
this.sendBtn = document.getElementById('send-btn');
this.messageInput = document.getElementById('message-input');
this.onlineUsersList = document.getElementById('online-users');
this.fileInput = document.getElementById('file-input');
this.sendFileBtn = document.getElementById('send-file-btn');
this.callBtn = document.getElementById('call-btn');
this.videoCallBtn = document.getElementById('video-call-btn'); // Новая кнопка
this.shareScreenBtn = document.getElementById('share-screen-btn'); // Новая кнопка
this.activePeerDisplay = document.getElementById('active-peer');
// Элементы окна звонка
this.callWindow = document.getElementById('call-window');
this.callerIdSpan = document.getElementById('caller-id');
this.acceptAudioBtn = this.callWindow.querySelector('.btn-audio');
this.acceptVideoBtn = this.callWindow.querySelector('.btn-video');
this.acceptScreenBtn = this.callWindow.querySelector('.btn-screen');
this.rejectCallBtn = this.callWindow.querySelector('.reject');
this.currentIncomingCall = null; // Ссылка на текущий входящий звонок
this.initPeer();
this.bindEvents();
}
initPeer() {
// Инициализация PeerJS с генерацией уникального ID
this.peer = new Peer();
this.peer.on('open', (id) => {
this.peerIdDisplay.textContent = id;
this.addOnlineUser(id, true); // Добавить себя в список онлайн пользователей
});
this.peer.on('connection', (conn) => this.handleConnection(conn));
this.peer.on('call', (call) => this.handleIncomingCall(call));
this.peer.on('error', (err) => {
console.error(err);
alert('Произошла ошибка: ' + err);
});
}
bindEvents() {
this.connectBtn.addEventListener('click', () => this.connectToPeer());
this.sendBtn.addEventListener('click', () => this.sendMessage());
this.messageInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') this.sendMessage();
});
this.sendFileBtn.addEventListener('click', () => this.sendFile());
this.callBtn.addEventListener('click', () => this.initiateCallButtonHandler());
this.videoCallBtn.addEventListener('click', () => this.initiateVideoCall()); // Обработчик видео-звонка
this.shareScreenBtn.addEventListener('click', () => this.initiateScreenShare()); // Обработчик демонстрации экрана
// Обработчики для окна звонка
this.acceptAudioBtn.addEventListener('click', () => this.acceptCall('audio'));
this.acceptVideoBtn.addEventListener('click', () => this.acceptCall('video'));
this.acceptScreenBtn.addEventListener('click', () => this.acceptCall('screen'));
this.rejectCallBtn.addEventListener('click', () => this.rejectCall());
// Обработчик клика по пользователю для выбора активного чата
this.onlineUsersList.addEventListener('click', (e) => {
const li = e.target.closest('li');
if (li && !li.classList.contains('active')) {
this.selectActivePeer(li);
}
});
}
connectToPeer() {
const remoteId = this.remoteIdInput.value.trim();
if (!remoteId) {
alert('Введите Peer ID для подключения.');
return;
}
if (this.connections.has(remoteId)) {
alert('Уже подключены к этому Peer.');
return;
}
const conn = this.peer.connect(remoteId);
conn.on('open', () => {
this.setupConnection(conn);
this.addOnlineUser(remoteId);
this.appendSystemMessage(`Соединение с ${remoteId} установлено.`);
if (!this.activePeerId) {
this.setActivePeer(remoteId);
}
});
conn.on('error', (err) => {
console.error(`Ошибка соединения с ${remoteId}:`, err);
this.appendSystemMessage(`Ошибка соединения с ${remoteId}: ${err}`);
});
conn.on('close', () => {
this.appendSystemMessage(`Соединение с ${remoteId} закрыто.`);
this.removeOnlineUser(remoteId);
this.connections.delete(remoteId);
if (this.activePeerId === remoteId) {
this.activePeerId = null;
this.activePeerDisplay.textContent = 'Нет активного чата';
}
});
}
handleConnection(conn) {
if (this.connections.has(conn.peer)) {
console.warn(`Уже есть соединение с ${conn.peer}`);
conn.close();
return;
}
this.setupConnection(conn);
this.addOnlineUser(conn.peer);
this.appendSystemMessage(`Peer ${conn.peer} подключился.`);
if (!this.activePeerId) {
this.setActivePeer(conn.peer);
}
}
setupConnection(conn) {
this.connections.set(conn.peer, conn);
conn.on('data', (data) => this.handleIncomingData(data, conn.peer));
conn.on('close', () => {
this.appendSystemMessage(`Соединение с ${conn.peer} закрыто.`);
this.removeOnlineUser(conn.peer);
this.connections.delete(conn.peer);
if (this.activePeerId === conn.peer) {
this.activePeerId = null;
this.activePeerDisplay.textContent = 'Нет активного чата';
}
});
}
handleIncomingData(data, peerId) {
try {
const parsedData = JSON.parse(data);
switch (parsedData.type) {
case 'message':
this.displayMessage(parsedData.content, 'other');
break;
case 'file':
this.receiveFile(parsedData, peerId);
break;
default:
console.warn('Неизвестный тип сообщения:', parsedData.type);
}
} catch (error) {
console.error('Ошибка разбора данных:', error);
this.appendSystemMessage(`Получены некорректные данные от ${peerId}.`);
}
}
sendMessage() {
const message = this.messageInput.value.trim();
if (!message) return;
if (!this.activePeerId) {
alert('Выберите пользователя для отправки сообщения.');
return;
}
const conn = this.connections.get(this.activePeerId);
if (!conn || conn.open === false) {
alert('Нет открытого соединения для отправки сообщения.');
return;
}
const data = JSON.stringify({ type: 'message', content: message });
try {
conn.send(data);
this.displayMessage(message, 'self');
this.messageInput.value = '';
} catch (err) {
console.error('Ошибка отправки сообщения:', err);
this.appendSystemMessage(`Не удалось отправить сообщение пользователю ${this.activePeerId}.`);
}
}
displayMessage(message, type) {
const messageDiv = document.createElement('div');
messageDiv.classList.add('message', type);
messageDiv.textContent = message;
this.messagesArea.appendChild(messageDiv);
this.scrollToBottom();
}
appendSystemMessage(message) {
const messageDiv = document.createElement('div');
messageDiv.classList.add('message', 'system');
messageDiv.textContent = message;
this.messagesArea.appendChild(messageDiv);
this.scrollToBottom();
}
addOnlineUser(userId, isSelf = false) {
if ([...this.onlineUsersList.children].some(li => li.querySelector('.user-id').textContent === userId)) {
return;
}
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.style.backgroundColor = '#2196F3';
callButton.onclick = (e) => {
e.stopPropagation(); // Предотвращает выбор пользователя при нажатии кнопки
this.startCall(userId);
};
const videoCallButton = document.createElement('button'); // Новая кнопка для видео-звонка
videoCallButton.textContent = 'Видео звонок';
videoCallButton.style.backgroundColor = '#FF9800';
videoCallButton.onclick = (e) => {
e.stopPropagation();
this.startVideoCall(userId);
};
const shareScreenButton = document.createElement('button'); // Новая кнопка для демонстрации экрана
shareScreenButton.textContent = 'Демонстрация экрана';
shareScreenButton.style.backgroundColor = '#9C27B0';
shareScreenButton.onclick = (e) => {
e.stopPropagation();
this.shareScreen(userId);
};
userActions.appendChild(callButton);
userActions.appendChild(videoCallButton);
userActions.appendChild(shareScreenButton);
li.appendChild(userActions);
}
this.onlineUsersList.appendChild(li);
if (!isSelf) {
this.appendSystemMessage(`${userId} подключился.`);
}
}
removeOnlineUser(userId) {
[...this.onlineUsersList.children].forEach(li => {
if (li.querySelector('.user-id').textContent === userId) {
this.onlineUsersList.removeChild(li);
this.appendSystemMessage(`${userId} отключился.`);
}
});
}
setActivePeer(peerId) {
// Снять выделение с текущего активного пользователя
[...this.onlineUsersList.children].forEach(li => {
if (li.classList.contains('active')) {
li.classList.remove('active');
}
});
// Выбрать нового активного пользователя
const targetLi = [...this.onlineUsersList.children].find(li => li.querySelector('.user-id').textContent === peerId);
if (targetLi) {
targetLi.classList.add('active');
this.activePeerId = peerId;
this.activePeerDisplay.textContent = `Активный чат с: ${peerId}`;
this.clearMessages();
}
}
selectActivePeer(li) {
const peerId = li.querySelector('.user-id').textContent;
this.setActivePeer(peerId);
}
clearMessages() {
this.messagesArea.innerHTML = '';
}
sendFile() {
const file = this.fileInput.files[0];
if (!file) {
alert('Пожалуйста, выберите файл для отправки.');
return;
}
if (!this.activePeerId) {
alert('Выберите пользователя для отправки файла.');
return;
}
const conn = this.connections.get(this.activePeerId);
if (!conn || conn.open === false) {
alert('Нет открытого соединения для отправки файла.');
return;
}
const reader = new FileReader();
reader.onload = () => {
const arrayBuffer = reader.result;
const uint8Array = Array.from(new Uint8Array(arrayBuffer));
const data = JSON.stringify({
type: 'file',
content: uint8Array,
fileName: file.name,
fileType: file.type
});
try {
conn.send(data);
this.appendSystemMessage(`Вы отправили файл: ${file.name} пользователю ${this.activePeerId}.`);
this.fileInput.value = '';
} catch (err) {
console.error('Ошибка отправки файла:', err);
this.appendSystemMessage(`Не удалось отправить файл пользователю ${this.activePeerId}.`);
}
};
reader.onerror = (error) => {
console.error('Ошибка чтения файла:', error);
alert('Не удалось прочитать файл.');
};
reader.readAsArrayBuffer(file);
}
receiveFile(data, peerId) {
const { content, fileName, fileType } = data;
if (!content || !fileName || !fileType) {
console.error('Получены неполные данные файла:', data);
this.appendSystemMessage(`Получены некорректные данные файла от ${peerId}.`);
return;
}
try {
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);
this.messagesArea.appendChild(fileMessage);
this.scrollToBottom();
} catch (err) {
console.error('Ошибка обработки полученного файла:', err);
this.appendSystemMessage(`Не удалось обработать файл от ${peerId}.`);
}
}
// Инициация аудио-звонка
startCall(peerId) {
navigator.mediaDevices.getUserMedia({ audio: true, video: false })
.then(stream => {
this.localStream = stream;
const call = this.peer.call(peerId, stream);
this.setupCall(call);
this.appendSystemMessage(`Вы позвонили ${peerId}.`);
})
.catch(err => {
console.error('Ошибка доступа к микрофону:', err);
alert('Не удалось получить доступ к микрофону.');
});
}
// Инициация видео-звонка
startVideoCall(peerId) {
navigator.mediaDevices.getUserMedia({ audio: true, video: true })
.then(stream => {
this.localStream = stream;
const call = this.peer.call(peerId, stream);
this.setupCall(call);
this.appendSystemMessage(`Вы начали видео-звонок с ${peerId}.`);
})
.catch(err => {
console.error('Ошибка доступа к камере/микрофону:', err);
alert('Не удалось получить доступ к камере или микрофону.');
});
}
// Инициация демонстрации экрана через кнопку
initiateScreenShare() {
const remoteId = this.activePeerId;
if (!remoteId) {
alert('Выберите пользователя для демонстрации экрана.');
return;
}
if (remoteId === this.peer.id) {
alert('Вы не можете демонстрировать экран себе.');
return;
}
this.shareScreen(remoteId);
}
// Демонстрация экрана
shareScreen(peerId) {
navigator.mediaDevices.getDisplayMedia({ video: true, audio: false })
.then(stream => {
this.localStream = stream;
const call = this.peer.call(peerId, stream);
this.setupCall(call);
this.appendSystemMessage(`Вы начали демонстрацию экрана для ${peerId}.`);
// Отслеживание завершения демонстрации экрана
stream.getVideoTracks()[0].addEventListener('ended', () => {
if (this.currentCall) {
this.currentCall.close();
this.appendSystemMessage(`Демонстрация экрана для ${peerId} завершена.`);
}
});
})
.catch(err => {
console.error('Ошибка при захвате экрана:', err);
alert('Не удалось захватить экран.');
});
}
handleIncomingCall(call) {
this.callWindow.classList.add('active');
this.callerIdSpan.textContent = call.peer;
this.currentIncomingCall = call; // Сохраняем текущий звонок для обработки
}
acceptCall(type) {
if (!this.currentIncomingCall) {
alert('Нет текущего звонка.');
return;
}
let constraints;
switch(type) {
case 'audio':
constraints = { audio: true, video: false };
break;
case 'video':
constraints = { audio: true, video: true };
break;
case 'screen':
constraints = { audio: false, video: true };
break;
default:
constraints = { audio: true, video: false };
}
// Для демонстрации экрана нужно использовать getDisplayMedia, но PeerJS call.answer принимает MediaStream,
// поэтому при принятии демонстрации экрана нужно заранее получить его и использовать
if (type === 'screen') {
navigator.mediaDevices.getDisplayMedia({ video: true, audio: false })
.then(stream => {
this.localStream = stream;
this.currentIncomingCall.answer(stream);
this.setupCall(this.currentIncomingCall);
this.callWindow.classList.remove('active');
this.appendSystemMessage(`Вы приняли демонстрацию экрана от ${this.currentIncomingCall.peer}.`);
this.currentIncomingCall = null;
})
.catch(err => {
console.error('Ошибка доступа к экрану:', err);
alert('Не удалось получить доступ к экрану.');
this.callWindow.classList.remove('active');
this.currentIncomingCall = null;
});
} else {
navigator.mediaDevices.getUserMedia(constraints)
.then(stream => {
this.localStream = stream;
this.currentIncomingCall.answer(stream);
this.setupCall(this.currentIncomingCall);
this.callWindow.classList.remove('active');
this.appendSystemMessage(`Вы приняли ${type === 'audio' ? 'аудио' : 'видео'} звонок от ${this.currentIncomingCall.peer}.`);
this.currentIncomingCall = null;
})
.catch(err => {
console.error(`Ошибка доступа к ${type === 'audio' ? 'микрофону' : 'камере'}:`, err);
alert(`Не удалось получить доступ к ${type === 'audio' ? 'микрофону' : 'камере'}.`);
this.callWindow.classList.remove('active');
this.currentIncomingCall = null;
});
}
}
rejectCall() {
if (!this.currentIncomingCall) {
alert('Нет текущего звонка.');
return;
}
this.currentIncomingCall.close();
this.callWindow.classList.remove('active');
this.appendSystemMessage(`Вы отклонили звонок от ${this.currentIncomingCall.peer}.`);
this.currentIncomingCall = null;
}
setupCall(call) {
if (this.currentCall) {
this.currentCall.close();
}
this.currentCall = call;
call.on('stream', (remoteStream) => {
// Проверяем, содержит ли поток видео или аудио
const hasVideo = remoteStream.getVideoTracks().length > 0;
const hasAudio = remoteStream.getAudioTracks().length > 0;
const mediaContainer = document.createElement('div');
mediaContainer.classList.add('media-chat');
if (hasVideo) {
const video = document.createElement('video');
video.srcObject = remoteStream;
video.autoplay = true;
video.controls = true;
mediaContainer.appendChild(video);
}
if (hasAudio) {
const audio = document.createElement('audio');
audio.srcObject = remoteStream;
audio.autoplay = true;
audio.controls = true;
mediaContainer.appendChild(audio);
}
this.messagesArea.appendChild(mediaContainer);
this.scrollToBottom();
});
call.on('close', () => {
this.appendSystemMessage('Звонок завершен.');
if (this.localStream) {
this.localStream.getTracks().forEach(track => track.stop());
this.localStream = null;
}
this.currentCall = null;
});
call.on('error', (err) => {
console.error('Ошибка звонка:', err);
this.appendSystemMessage('Произошла ошибка во время звонка.');
});
}
initiateCallButtonHandler() {
const remoteId = this.remoteIdInput.value.trim();
if (!remoteId) {
alert('Введите Peer ID для звонка.');
return;
}
if (remoteId === this.peer.id) {
alert('Вы не можете звонить себе.');
return;
}
this.startCall(remoteId); // Вызываем метод startCall
}
initiateVideoCall() {
const remoteId = this.remoteIdInput.value.trim() || this.activePeerId;
if (!remoteId) {
alert('Выберите пользователя для видео-звонка.');
return;
}
if (remoteId === this.peer.id) {
alert('Вы не можете звонить себе.');
return;
}
this.startVideoCall(remoteId);
}
initiateScreenShare() {
const remoteId = this.activePeerId;
if (!remoteId) {
alert('Выберите пользователя для демонстрации экрана.');
return;
}
if (remoteId === this.peer.id) {
alert('Вы не можете демонстрировать экран себе.');
return;
}
this.shareScreen(remoteId);
}
scrollToBottom() {
this.messagesArea.scrollTop = this.messagesArea.scrollHeight;
}
}
document.addEventListener('DOMContentLoaded', () => {
new P2PChat();
});
</script>
Здравствуйте!
Вы предоставили код для децентрализованного P2P чата, который использует библиотеку PeerJS для установления соединений между пользователями. Однако вместе с кодом вы упомянули несколько ошибок, связанных с TensorFlow.js (tfjs). На первый взгляд, в вашем текущем коде нет прямого использования TensorFlow.js, поэтому ошибки могут возникать из-за дополнительного скрипта или интеграции, которую вы, возможно, добавили позже.
Давайте разберёмся с вашими ошибками по порядку:
1. Ошибка при инициализации бекенда: TypeError: tf.backendNames is not a function
Причина:
Функция tf.backendNames() была доступна в более ранних версиях TensorFlow.js. Если вы используете более новую версию библиотеки, эта функция могла быть удалена или заменена.
Решение:
-
Проверьте версию TensorFlow.js: Убедитесь, что используете совместимую версию TensorFlow.js с вашим кодом. Например, если вы используете код, написанный для версии 1.x, а подключили версию 3.x, некоторые функции могут отсутствовать.
-
Обновите код под текущую версию:
В более новых версиях TensorFlow.js для получения списка бекендов используйте tf.getBackend() или другие актуальные методы.
// Пример замены tf.backendNames()
const currentBackend = tf.getBackend();
console.log('Текущий бекенд:', currentBackend);
2. Предупреждение: Orthogonal initializer is being called on a matrix with more than 2000 (262144) elements: Slowness may result.
Причина:
Этот warning указывает на то, что вы пытаетесь инициализировать матрицу с большим количеством элементов с помощью ортогонального инициализатора. Это может привести к замедлению работы вашего приложения.
Решение:
- Оптимизируйте размер матриц: Проверьте архитектуру вашей модели и убедитесь, что размеры матриц оптимальны.
- Используйте другой инициализатор: Возможно, стоит попробовать другой метод инициализации, который лучше подходит для больших матриц.
3. Ошибка: Uncaught (in promise) Error: Argument 'x' passed to 'floor' must be float32 tensor, but got int32 tensor
Причина:
Функция tf.floor() ожидает тензор типа float32, а ей передаётся тензор типа int32.
Решение:
-
Преобразуйте тензор перед использованием tf.floor(): Используйте tf.cast() для приведения тензора к нужному типу.
// Преобразование тензора к float32 перед применением tf.floor()
const intTensor = tf.tensor([1, 2, 3], 'int32');
const floatTensor = tf.cast(intTensor, 'float32');
const flooredTensor = tf.floor(floatTensor);
flooredTensor.print();
Дополнительные рекомендации:
-
Проверьте все подключенные скрипты:
Убедитесь, что вы не подключаете TensorFlow.js или другие библиотеки, которые могут конфликтовать с вашим текущим проектом, если они не нужны.
-
Изолируйте проблему:
Если вы интегрируете TensorFlow.js в существующий проект, попробуйте временно удалить его и проверить, сохраняются ли ошибки. Это поможет определить, связаны ли ошибки непосредственно с TensorFlow.js или с чем-то другим.
-
Консультация по P2P Чату:
Ваш P2P чат выглядит достаточно продвинутым и функциональным. Однако, если вы планируете интегрировать машинное обучение или другие функции, спросите конкретные вопросы, чтобы получить более точную помощь.
-
Отладка:
Используйте инструменты разработчика в браузере (например, Chrome DevTools) для более детального анализа ошибок. Проверьте, какие скрипты вызывают ошибки, и убедитесь, что все зависимости корректно загружены.
Пример корректировки инициализации TensorFlow.js:
Если вы используете TensorFlow.js для каких-то целей в вашем проекте, убедитесь, что инициализируете его правильно. Вот пример минимальной инициализации:
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<title>Пример TensorFlow.js</title>
</head>
<body>
<!-- Подключение TensorFlow.js через CDN -->
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest"></script>
<script>
// Проверка доступных бекендов
tf.ready().then(() => {
const backend = tf.getBackend();
console.log('Текущий бекенд TensorFlow.js:', backend);
// Пример использования tf.floor()
const intTensor = tf.tensor([1, 2, 3], 'int32');
const floatTensor = tf.cast(intTensor, 'float32');
const flooredTensor = tf.floor(floatTensor);
flooredTensor.print(); // [1, 2, 3]
}).catch(err => {
console.error('Ошибка инициализации TensorFlow.js:', err);
});
</script>
</body>
</html>
Заключение
Похоже, ваши текущие ошибки связаны с использованием TensorFlow.js, который не представлен в вашем первоначальном коде P2P чата. Рекомендую:
- Проверить все подключенные скрипты и убедиться, что TensorFlow.js подключён правильно.
- Соответствовать вашему коду актуальной версии TensorFlow.js.
- Обратиться к документации TensorFlow.js для понимания изменений в API между версиями.
Если вы предоставите дополнительную информацию о том, как и где вы используете TensorFlow.js в вашем проекте, я смогу дать более конкретные рекомендации.
Если у вас есть дополнительные вопросы или требуется помощь с конкретными фрагментами кода, пожалуйста, поделитесь ими, и я постараюсь помочь вам более подробно.