This commit is contained in:
wow22831 2024-10-28 03:26:52 +07:00
parent 8c7b33c853
commit 741206df0d
2 changed files with 162 additions and 142 deletions

View File

@ -2,26 +2,42 @@
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-around; /* Распределение элементов с равным отступом */
height: 100vh; /* Высота на весь экран для центрирования */
justify-content: space-around;
height: 100vh;
text-align: center;
}
.peer-id-container {
margin-bottom: 10px;
display: flex;
align-items: center;
}
.peer-id-text {
font-size: 16px;
color: #fff;
margin-right: 10px;
}
.copy-button {
background: none;
border: none;
color: #007aff;
cursor: pointer;
padding: 0;
}
.copy-notification {
position: fixed;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
background-color: #4caf50;
color: white;
padding: 10px 20px;
border-radius: 5px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
font-size: 16px;
z-index: 1000;
}
.input-container {
@ -30,7 +46,7 @@
justify-content: center;
margin-bottom: 10px;
width: 100%;
max-width: 400px; /* Ограничение ширины для компактности */
max-width: 400px;
}
.call-info-container {
@ -43,13 +59,13 @@
.call-info-text {
font-size: 18px;
margin-bottom: 5px; /* Небольшой отступ снизу для Peer ID */
margin-bottom: 5px;
color: #ffffff;
}
.call-duration-text {
font-size: 18px;
margin-bottom: 15px; /* Отступ снизу для времени */
margin-bottom: 15px;
color: #ffffff;
}
@ -66,7 +82,7 @@
}
.custom-hang-up-button:hover svg {
transform: scale(1.1); /* Увеличение кнопки при наведении */
transform: scale(1.1);
}
.call-button {
@ -76,7 +92,14 @@
cursor: pointer;
font-size: 24px;
margin-left: 10px;
padding: 10px; /* Увеличение кнопки для удобства */
padding: 15px;
border-radius: 50%;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
transition: background 0.3s ease;
}
.call-button:hover {
background: #005bb5;
}
.panel-optimizer {
@ -89,11 +112,17 @@
display: flex;
align-items: center;
justify-content: center;
height: 100vh; /* Центрирование всего контента по высоте экрана */
height: 100vh;
}
.drone-gif {
width: 300px; /* Задайте нужный размер */
width: 300px;
height: auto;
margin-bottom: 20px;
}
.screen-off {
background-color: #000;
color: #000;
opacity: 0;
}

View File

@ -2,145 +2,100 @@ import React, { useState, useEffect, useCallback } from 'react';
import './ExploreContainer.css';
import InputContainer from './Input';
import {
IonButton, IonContent, IonText, IonModal, IonIcon
IonButton, IonContent, IonFooter, IonToolbar, IonText, IonModal, IonIcon
} from '@ionic/react';
import { call as callIcon, close as hangUpIcon } from 'ionicons/icons';
const socket = new WebSocket('ws://192.168.0.160:8080'); // Адрес вашего WebSocket сервера
import Peer, { MediaConnection } from 'peerjs';
const ExploreContainer: React.FC = () => {
const [callString, setCallString] = useState(""); // Здесь будет храниться IP-адрес получателя звонка
const [callString, setCallString] = useState("");
const [isEnable, setIsEnable] = useState(true);
const [peer, setPeer] = useState<Peer | null>(null);
const [localStream, setLocalStream] = useState<MediaStream | null>(null);
const [connectionInfo, setConnectionInfo] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [isCallActive, setIsCallActive] = useState(false);
const [callDuration, setCallDuration] = useState<number>(0);
const [callInterval, setCallInterval] = useState<NodeJS.Timeout | null>(null);
const [peerConnection, setPeerConnection] = useState<RTCPeerConnection | null>(null);
const [remoteStream, setRemoteStream] = useState<MediaStream | null>(null);
const [currentCallId, setCurrentCallId] = useState<string | null>(null);
const [showCopyNotification, setShowCopyNotification] = useState(false);
// Инициализация WebRTC соединения
useEffect(() => {
const pc = new RTCPeerConnection();
setPeerConnection(pc);
const initializePeer = () => {
const newPeer = new Peer({ debug: 3 });
setPeer(newPeer);
pc.ontrack = (event) => {
const [stream] = event.streams;
setRemoteStream(stream);
playAudio(stream);
newPeer.on('open', (id) => {
console.log(`Peer успешно открыт с ID: ${id}`);
setConnectionInfo(id);
});
newPeer.on('call', (call: MediaConnection) => handleIncomingCall(call));
newPeer.on('error', (err) => console.error('Ошибка Peer:', err));
return () => {
newPeer.destroy();
};
};
pc.onicecandidate = (event) => {
if (event.candidate) {
socket.send(JSON.stringify({
type: 'ice-candidate',
candidate: event.candidate,
target: callString,
}));
}
};
const cleanup = initializePeer();
return cleanup;
}, []);
return () => {
pc.close();
};
}, [callString]);
// Обработка входящих сообщений WebSocket
useEffect(() => {
socket.onmessage = async (event) => {
const data = JSON.parse(event.data);
if (data.type === 'offer') {
await handleIncomingCall(data.offer);
} else if (data.type === 'answer') {
if (peerConnection) {
await peerConnection.setRemoteDescription(new RTCSessionDescription(data.answer));
}
} else if (data.type === 'ice-candidate' && peerConnection) {
try {
await peerConnection.addIceCandidate(new RTCIceCandidate(data.candidate));
} catch (error) {
console.error('Ошибка добавления ICE-кандидата', error);
}
}
};
}, [peerConnection]);
// Запуск вызова
const makeCall = useCallback(async () => {
if (peerConnection && callString) {
setIsLoading(true);
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
setLocalStream(stream);
stream.getTracks().forEach(track => peerConnection.addTrack(track, stream));
const offer = await peerConnection.createOffer();
await peerConnection.setLocalDescription(offer);
socket.send(JSON.stringify({
type: 'offer',
offer: offer,
target: callString,
}));
setIsLoading(false);
setIsCallActive(true);
const handleIncomingCall = useCallback((call: MediaConnection) => {
console.log('Получен входящий звонок');
setCurrentCallId(call.peer);
navigator.mediaDevices.getUserMedia({ audio: true }).then((stream) => {
setLocalStream(stream);
call.answer(stream);
call.on('stream', (remoteStream: MediaStream) => {
console.log('Получен удалённый поток');
playAudio(remoteStream);
startCallTimer();
} catch (err) {
setIsCallActive(true);
});
}).catch((err) => {
console.error('Не удалось получить локальный поток для ответа', err);
});
}, []);
const makeCall = useCallback(() => {
if (peer && callString) {
setIsLoading(true);
console.log(`Попытка звонка на: ${callString}`);
navigator.mediaDevices.getUserMedia({ audio: true }).then((stream) => {
setLocalStream(stream);
const call = peer.call(callString, stream);
setCurrentCallId(callString);
call.on('stream', (remoteStream: MediaStream) => {
console.log('Получен удалённый поток во время вызова');
playAudio(remoteStream);
setIsLoading(false);
startCallTimer();
setIsCallActive(true);
});
}).catch((err) => {
console.error('Не удалось получить локальный поток', err);
setIsLoading(false);
}
});
} else {
console.warn('Звонок невозможен: отсутствует соединение или IP-адрес');
console.warn('Звонок невозможен: отсутствует Peer или callString');
}
}, [peerConnection, callString]);
}, [peer, callString]);
// Принятие входящего звонка
const handleIncomingCall = useCallback(async (offer: RTCSessionDescriptionInit) => {
if (peerConnection) {
try {
await peerConnection.setRemoteDescription(new RTCSessionDescription(offer));
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
setLocalStream(stream);
stream.getTracks().forEach(track => peerConnection.addTrack(track, stream));
const answer = await peerConnection.createAnswer();
await peerConnection.setLocalDescription(answer);
socket.send(JSON.stringify({
type: 'answer',
answer: answer,
target: callString,
}));
setIsCallActive(true);
startCallTimer();
} catch (err) {
console.error('Ошибка обработки входящего вызова', err);
}
}
}, [peerConnection, callString]);
// Завершение звонка
const endCall = useCallback(() => {
if (localStream) {
localStream.getTracks().forEach(track => track.stop());
}
if (peerConnection) {
peerConnection.close();
}
setIsCallActive(false);
setIsEnable(true);
if (callInterval) {
clearInterval(callInterval);
}
setCallDuration(0);
}, [localStream, peerConnection, callInterval]);
setCurrentCallId(null);
}, [localStream, callInterval]);
// Таймер звонка
const startCallTimer = useCallback(() => {
const interval = setInterval(() => {
setCallDuration(prevDuration => prevDuration + 1);
@ -148,7 +103,6 @@ const ExploreContainer: React.FC = () => {
setCallInterval(interval);
}, []);
// Воспроизведение аудио потока
const playAudio = useCallback((stream: MediaStream) => {
const audioElement = document.createElement('audio');
audioElement.srcObject = stream;
@ -159,34 +113,71 @@ const ExploreContainer: React.FC = () => {
});
}, []);
return (
<IonContent fullscreen={true} className="ion-padding">
<div id="container">
<div className="input-container">
<InputContainer
callString={callString}
setCallString={setCallString}
isEnable={isEnable}
/>
<IonButton className="call-button" onClick={makeCall} disabled={!isEnable || !callString || isLoading}>
<IonIcon icon={callIcon} />
</IonButton>
</div>
</div>
const copyPeerId = useCallback(() => {
if (connectionInfo) {
navigator.clipboard.writeText(connectionInfo)
.then(() => {
console.log('Peer ID скопирован в буфер обмена');
setShowCopyNotification(true);
setTimeout(() => {
setShowCopyNotification(false);
}, 2000);
})
.catch((err) => {
console.error('Не удалось скопировать Peer ID', err);
});
}
}, [connectionInfo]);
<IonModal isOpen={isCallActive}>
<IonContent className="ion-padding">
<div className="call-info-container">
<IonText className="call-info-text">Звонок на IP: {callString}</IonText>
<IonText className="call-duration-text">{Math.floor(callDuration / 60)}:{callDuration % 60}</IonText>
<IonButton onClick={endCall}>
<IonIcon icon={hangUpIcon} />
return (
<>
<IonContent fullscreen={true} className="ion-padding">
<div id="container">
<div className="peer-id-container">
<IonText className="peer-id-text">Ваш Peer ID: {connectionInfo}</IonText>
<button className="copy-button" onClick={copyPeerId}>
<svg width="51" height="51" fill="none" stroke="#34554a" strokeLinecap="round" strokeLinejoin="round" strokeWidth="2.5" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<path d="M19.078 6H8.672A2.672 2.672 0 0 0 6 8.672v10.406a2.672 2.672 0 0 0 2.672 2.672h10.406a2.672 2.672 0 0 0 2.672-2.672V8.672A2.672 2.672 0 0 0 19.078 6Z"></path>
<path d="M17.977 6 18 4.875a2.633 2.633 0 0 0-2.625-2.625H5.25a3.009 3.009 0 0 0-3 3v10.125A2.633 2.633 0 0 0 4.875 18H6"></path>
</svg>
</button>
</div>
{showCopyNotification && (
<div className="copy-notification">
Peer ID скопирован
</div>
)}
<div className="input-container">
<InputContainer
callString={callString}
setCallString={setCallString}
isEnable={isEnable}
/>
<IonButton className="call-button" onClick={makeCall} disabled={!isEnable || !callString || isLoading}>
<IonIcon icon={callIcon} />
</IonButton>
</div>
</IonContent>
</IonModal>
</IonContent>
</div>
{/* Модальное окно для звонка */}
<IonModal isOpen={isCallActive}>
<IonContent className="ion-padding">
<div className="call-info-container">
{/* Добавляем гифку */}
<img src="/monkey-monkey-with-drone.gif" alt="Monkey with Drone" className="drone-gif" />
<IonText className="call-info-text">Peer ID: {currentCallId}</IonText>
<IonText className="call-duration-text">{Math.floor(callDuration / 60)}:{callDuration % 60}</IonText>
<button onClick={endCall} className="custom-hang-up-button">
<svg width="51" height="51" fill="#cd1818" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<path d="M18.327 22.5c-.915 0-2.2-.331-4.125-1.407-2.34-1.312-4.15-2.524-6.478-4.846-2.245-2.243-3.337-3.695-4.865-6.476C1.132 6.63 1.426 4.984 1.755 4.28c.392-.842.97-1.345 1.718-1.844a8.263 8.263 0 0 1 1.343-.712l.13-.057c.231-.105.583-.263 1.028-.094.297.112.562.34.978.75.852.84 2.015 2.71 2.445 3.63.288.619.479 1.028.48 1.486 0 .537-.27.95-.598 1.397l-.182.242c-.356.469-.435.604-.383.846.104.486.884 1.933 2.165 3.212 1.281 1.278 2.686 2.008 3.174 2.112.253.054.39-.027.875-.397.069-.053.14-.107.215-.162.5-.372.894-.635 1.418-.635h.003c.456 0 .847.198 1.493.524.844.426 2.771 1.575 3.616 2.427.412.415.64.679.753.976.169.447.01.797-.094 1.031l-.057.129a8.27 8.27 0 0 1-.716 1.34c-.499.745-1.004 1.322-1.846 1.714a3.16 3.16 0 0 1-1.386.304Z"></path>
</svg>
</button>
</div>
</IonContent>
</IonModal>
</IonContent>
</>
);
};
export default ExploreContainer;
export default ExploreContainer;