From 6027da6a92b53198b2b4c0c489376d8cb8a5aa50 Mon Sep 17 00:00:00 2001 From: wow22831 Date: Thu, 24 Oct 2024 21:07:18 +0700 Subject: [PATCH] zanova --- src/components/ExploreContainer.tsx | 141 ++++++++++++++++------------ 1 file changed, 83 insertions(+), 58 deletions(-) diff --git a/src/components/ExploreContainer.tsx b/src/components/ExploreContainer.tsx index ebe287a..dd7807b 100644 --- a/src/components/ExploreContainer.tsx +++ b/src/components/ExploreContainer.tsx @@ -8,116 +8,137 @@ import { call as callIcon, close as hangUpIcon } from 'ionicons/icons'; import Peer, { MediaConnection } from 'peerjs'; const ExploreContainer: React.FC = () => { - const [callIp, setCallIp] = useState(""); + const [callString, setCallString] = useState(""); + const [isEnable, setIsEnable] = useState(true); const [peer, setPeer] = useState(null); const [localStream, setLocalStream] = useState(null); - const [remoteStream, setRemoteStream] = useState(null); - const [isCallActive, setIsCallActive] = useState(false); + const [connectionInfo, setConnectionInfo] = useState(null); + const [isLoading, setIsLoading] = useState(false); + const [isCallActive, setIsCallActive] = useState(false); const [callDuration, setCallDuration] = useState(0); const [callInterval, setCallInterval] = useState(null); - const [currentCall, setCurrentCall] = useState(null); + const [currentCallId, setCurrentCallId] = useState(null); useEffect(() => { - const peerId = Math.floor(Math.random() * 10000).toString(); - const newPeer: Peer = new Peer(peerId, { - host: 'localhost', - port: 8100, // Используемый порт - path: '/peerjs', - debug: 3 - }); + const initializePeer = () => { + const newPeer = new Peer({ debug: 3 }); + setPeer(newPeer); - newPeer.on('call', (call: MediaConnection) => { - console.log('Получен входящий звонок'); - navigator.mediaDevices.getUserMedia({ audio: true }).then((stream: MediaStream) => { - setLocalStream(stream); - call.answer(stream); - call.on('stream', (remoteStream: MediaStream) => { - console.log('Получен удалённый поток'); - setRemoteStream(remoteStream); - playAudio(remoteStream); - startCallTimer(); - setIsCallActive(true); - }); - setCurrentCall(call); - }).catch((err: Error) => { - console.error('Не удалось получить локальный поток для ответа', err); + newPeer.on('open', (id) => { + console.log(`Peer успешно открыт с ID: ${id}`); + setConnectionInfo(id); }); - }); - setPeer(newPeer); + newPeer.on('call', (call: MediaConnection) => handleIncomingCall(call)); + newPeer.on('error', (err) => console.error('Ошибка Peer:', err)); - return () => { - newPeer.destroy(); + return () => { + newPeer.destroy(); + }; }; + + const cleanup = initializePeer(); + return cleanup; + }, []); + + 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(); + setIsCallActive(true); + }); + }).catch((err) => { + console.error('Не удалось получить локальный поток для ответа', err); + }); }, []); const makeCall = useCallback(() => { - if (peer && callIp) { - navigator.mediaDevices.getUserMedia({ audio: true }).then((stream: MediaStream) => { + if (peer && callString) { + setIsLoading(true); + console.log(`Попытка звонка на: ${callString}`); + navigator.mediaDevices.getUserMedia({ audio: true }).then((stream) => { setLocalStream(stream); - const call: MediaConnection = peer.call(callIp, stream); + const call = peer.call(callString, stream); + setCurrentCallId(callString); call.on('stream', (remoteStream: MediaStream) => { console.log('Получен удалённый поток во время вызова'); - setRemoteStream(remoteStream); playAudio(remoteStream); + setIsLoading(false); startCallTimer(); setIsCallActive(true); }); - setCurrentCall(call); - }).catch((err: Error) => { + }).catch((err) => { console.error('Не удалось получить локальный поток', err); + setIsLoading(false); }); } else { - console.warn('Звонок невозможен: отсутствует Peer или callIp'); + console.warn('Звонок невозможен: отсутствует Peer или callString'); } - }, [peer, callIp]); + }, [peer, callString]); const endCall = useCallback(() => { if (localStream) { - localStream.getTracks().forEach((track: MediaStreamTrack) => track.stop()); - } - if (remoteStream) { - remoteStream.getTracks().forEach((track: MediaStreamTrack) => track.stop()); - } - if (currentCall) { - currentCall.close(); + localStream.getTracks().forEach(track => track.stop()); } setIsCallActive(false); + setIsEnable(true); if (callInterval) { clearInterval(callInterval); } setCallDuration(0); - setCurrentCall(null); - }, [localStream, remoteStream, currentCall, callInterval]); + setCurrentCallId(null); + }, [localStream, callInterval]); const startCallTimer = useCallback(() => { - const interval: NodeJS.Timeout = setInterval(() => { - setCallDuration((prevDuration: number) => prevDuration + 1); + const interval = setInterval(() => { + setCallDuration(prevDuration => prevDuration + 1); }, 1000); setCallInterval(interval); }, []); const playAudio = useCallback((stream: MediaStream) => { - const audioElement: HTMLAudioElement = document.createElement('audio'); + const audioElement = document.createElement('audio'); audioElement.srcObject = stream; audioElement.play().then(() => { console.log('Аудио начато воспроизведение'); - }).catch((error: Error) => { + }).catch((error) => { console.error('Ошибка воспроизведения аудио', error); }); }, []); + const copyPeerId = useCallback(() => { + if (connectionInfo) { + navigator.clipboard.writeText(connectionInfo) + .then(() => { + console.log('Peer ID скопирован в буфер обмена'); + }) + .catch((err) => { + console.error('Не удалось скопировать Peer ID', err); + }); + } + }, [connectionInfo]); + return ( <>
+
+ Ваш Peer ID: {connectionInfo} + +
- +
@@ -127,10 +148,14 @@ const ExploreContainer: React.FC = () => {
- IP: {callIp} + {/* Добавляем гифку */} + Monkey with Drone + Peer ID: {currentCallId} {Math.floor(callDuration / 60)}:{callDuration % 60}
@@ -140,4 +165,4 @@ const ExploreContainer: React.FC = () => { ); }; -export default ExploreContainer; +export default ExploreContainer; \ No newline at end of file