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