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; display: flex;
flex-direction: column; flex-direction: column;
align-items: center; align-items: center;
justify-content: space-around; /* Распределение элементов с равным отступом */ justify-content: space-around;
height: 100vh; /* Высота на весь экран для центрирования */ height: 100vh;
text-align: center; text-align: center;
} }
.peer-id-container { .peer-id-container {
margin-bottom: 10px; margin-bottom: 10px;
display: flex;
align-items: center;
} }
.peer-id-text { .peer-id-text {
font-size: 16px; font-size: 16px;
color: #fff; color: #fff;
margin-right: 10px;
} }
.copy-button { .copy-button {
background: none; background: none;
border: none; border: none;
color: #007aff;
cursor: pointer; 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; font-size: 16px;
z-index: 1000;
} }
.input-container { .input-container {
@ -30,7 +46,7 @@
justify-content: center; justify-content: center;
margin-bottom: 10px; margin-bottom: 10px;
width: 100%; width: 100%;
max-width: 400px; /* Ограничение ширины для компактности */ max-width: 400px;
} }
.call-info-container { .call-info-container {
@ -43,13 +59,13 @@
.call-info-text { .call-info-text {
font-size: 18px; font-size: 18px;
margin-bottom: 5px; /* Небольшой отступ снизу для Peer ID */ margin-bottom: 5px;
color: #ffffff; color: #ffffff;
} }
.call-duration-text { .call-duration-text {
font-size: 18px; font-size: 18px;
margin-bottom: 15px; /* Отступ снизу для времени */ margin-bottom: 15px;
color: #ffffff; color: #ffffff;
} }
@ -66,7 +82,7 @@
} }
.custom-hang-up-button:hover svg { .custom-hang-up-button:hover svg {
transform: scale(1.1); /* Увеличение кнопки при наведении */ transform: scale(1.1);
} }
.call-button { .call-button {
@ -76,7 +92,14 @@
cursor: pointer; cursor: pointer;
font-size: 24px; font-size: 24px;
margin-left: 10px; 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 { .panel-optimizer {
@ -89,11 +112,17 @@
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
height: 100vh; /* Центрирование всего контента по высоте экрана */ height: 100vh;
} }
.drone-gif { .drone-gif {
width: 300px; /* Задайте нужный размер */ width: 300px;
height: auto; height: auto;
margin-bottom: 20px; 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 './ExploreContainer.css';
import InputContainer from './Input'; import InputContainer from './Input';
import { import {
IonButton, IonContent, IonText, IonModal, IonIcon IonButton, IonContent, IonFooter, IonToolbar, IonText, IonModal, IonIcon
} from '@ionic/react'; } from '@ionic/react';
import { call as callIcon, close as hangUpIcon } from 'ionicons/icons'; import { call as callIcon, close as hangUpIcon } from 'ionicons/icons';
import Peer, { MediaConnection } from 'peerjs';
const socket = new WebSocket('ws://192.168.0.160:8080'); // Адрес вашего WebSocket сервера
const ExploreContainer: React.FC = () => { const ExploreContainer: React.FC = () => {
const [callString, setCallString] = useState(""); // Здесь будет храниться IP-адрес получателя звонка const [callString, setCallString] = useState("");
const [isEnable, setIsEnable] = useState(true); const [isEnable, setIsEnable] = useState(true);
const [peer, setPeer] = useState<Peer | null>(null);
const [localStream, setLocalStream] = useState<MediaStream | null>(null); const [localStream, setLocalStream] = useState<MediaStream | null>(null);
const [connectionInfo, setConnectionInfo] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const [isCallActive, setIsCallActive] = useState(false); const [isCallActive, setIsCallActive] = useState(false);
const [callDuration, setCallDuration] = useState<number>(0); const [callDuration, setCallDuration] = useState<number>(0);
const [callInterval, setCallInterval] = useState<NodeJS.Timeout | null>(null); const [callInterval, setCallInterval] = useState<NodeJS.Timeout | null>(null);
const [peerConnection, setPeerConnection] = useState<RTCPeerConnection | null>(null); const [currentCallId, setCurrentCallId] = useState<string | null>(null);
const [remoteStream, setRemoteStream] = useState<MediaStream | null>(null); const [showCopyNotification, setShowCopyNotification] = useState(false);
// Инициализация WebRTC соединения
useEffect(() => { useEffect(() => {
const pc = new RTCPeerConnection(); const initializePeer = () => {
setPeerConnection(pc); const newPeer = new Peer({ debug: 3 });
setPeer(newPeer);
pc.ontrack = (event) => { newPeer.on('open', (id) => {
const [stream] = event.streams; console.log(`Peer успешно открыт с ID: ${id}`);
setRemoteStream(stream); setConnectionInfo(id);
playAudio(stream); });
};
pc.onicecandidate = (event) => { newPeer.on('call', (call: MediaConnection) => handleIncomingCall(call));
if (event.candidate) { newPeer.on('error', (err) => console.error('Ошибка Peer:', err));
socket.send(JSON.stringify({
type: 'ice-candidate',
candidate: event.candidate,
target: callString,
}));
}
};
return () => { return () => {
pc.close(); newPeer.destroy();
}; };
}, [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 cleanup = initializePeer();
const makeCall = useCallback(async () => { return cleanup;
if (peerConnection && callString) { }, []);
setIsLoading(true);
try { const handleIncomingCall = useCallback((call: MediaConnection) => {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true }); console.log('Получен входящий звонок');
setCurrentCallId(call.peer);
navigator.mediaDevices.getUserMedia({ audio: true }).then((stream) => {
setLocalStream(stream); setLocalStream(stream);
call.answer(stream);
stream.getTracks().forEach(track => peerConnection.addTrack(track, stream)); call.on('stream', (remoteStream: MediaStream) => {
console.log('Получен удалённый поток');
const offer = await peerConnection.createOffer(); playAudio(remoteStream);
await peerConnection.setLocalDescription(offer);
socket.send(JSON.stringify({
type: 'offer',
offer: offer,
target: callString,
}));
setIsLoading(false);
setIsCallActive(true);
startCallTimer(); 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); console.error('Не удалось получить локальный поток', err);
setIsLoading(false); setIsLoading(false);
} });
} else { } 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(() => { const endCall = useCallback(() => {
if (localStream) { if (localStream) {
localStream.getTracks().forEach(track => track.stop()); localStream.getTracks().forEach(track => track.stop());
} }
if (peerConnection) {
peerConnection.close();
}
setIsCallActive(false); setIsCallActive(false);
setIsEnable(true); setIsEnable(true);
if (callInterval) { if (callInterval) {
clearInterval(callInterval); clearInterval(callInterval);
} }
setCallDuration(0); setCallDuration(0);
}, [localStream, peerConnection, callInterval]); setCurrentCallId(null);
}, [localStream, callInterval]);
// Таймер звонка
const startCallTimer = useCallback(() => { const startCallTimer = useCallback(() => {
const interval = setInterval(() => { const interval = setInterval(() => {
setCallDuration(prevDuration => prevDuration + 1); setCallDuration(prevDuration => prevDuration + 1);
@ -148,7 +103,6 @@ const ExploreContainer: React.FC = () => {
setCallInterval(interval); setCallInterval(interval);
}, []); }, []);
// Воспроизведение аудио потока
const playAudio = useCallback((stream: MediaStream) => { const playAudio = useCallback((stream: MediaStream) => {
const audioElement = document.createElement('audio'); const audioElement = document.createElement('audio');
audioElement.srcObject = stream; audioElement.srcObject = stream;
@ -159,9 +113,40 @@ const ExploreContainer: React.FC = () => {
}); });
}, []); }, []);
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]);
return ( return (
<>
<IonContent fullscreen={true} className="ion-padding"> <IonContent fullscreen={true} className="ion-padding">
<div id="container"> <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"> <div className="input-container">
<InputContainer <InputContainer
callString={callString} callString={callString}
@ -174,18 +159,24 @@ const ExploreContainer: React.FC = () => {
</div> </div>
</div> </div>
{/* Модальное окно для звонка */}
<IonModal isOpen={isCallActive}> <IonModal isOpen={isCallActive}>
<IonContent className="ion-padding"> <IonContent className="ion-padding">
<div className="call-info-container"> <div className="call-info-container">
<IonText className="call-info-text">Звонок на IP: {callString}</IonText> {/* Добавляем гифку */}
<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> <IonText className="call-duration-text">{Math.floor(callDuration / 60)}:{callDuration % 60}</IonText>
<IonButton onClick={endCall}> <button onClick={endCall} className="custom-hang-up-button">
<IonIcon icon={hangUpIcon} /> <svg width="51" height="51" fill="#cd1818" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
</IonButton> <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> </div>
</IonContent> </IonContent>
</IonModal> </IonModal>
</IonContent> </IonContent>
</>
); );
}; };