From c5bf5bf064fcceb783f878fff1694619cad3df9c Mon Sep 17 00:00:00 2001 From: Matheo Bonucia Date: Tue, 2 Apr 2024 17:15:33 -0400 Subject: [PATCH] Adaptacoes para teste fora do servidor local --- react-native-webrtc-app/client/App.js | 183 +++++++++++++---------- react-native-webrtc-app/server/socket.js | 3 +- 2 files changed, 108 insertions(+), 78 deletions(-) diff --git a/react-native-webrtc-app/client/App.js b/react-native-webrtc-app/client/App.js index f37cd73..c683f64 100644 --- a/react-native-webrtc-app/client/App.js +++ b/react-native-webrtc-app/client/App.js @@ -41,7 +41,7 @@ export default function App({}) { Math.floor(100000 + Math.random() * 900000).toString(), ); const otherUserId = useRef(null); - const socket = SocketIOClient('http://192.168.115.179:3500', { + const socket = SocketIOClient('http://129.148.58.190:8088', { transports: ['websocket'], query: { callerId, @@ -53,9 +53,10 @@ export default function App({}) { const [localWebcamOn, setlocalWebcamOn] = useState(true); const [iniciarChamada, setIniciarChamada] = useState(false); let remoteRTCMessage = useRef(null); + const peerConnection = useRef(null); - const peerConnection = useRef( - new RTCPeerConnection({ + const createPeerConnection = () => { + return new RTCPeerConnection({ iceServers: [ { urls: 'stun:stun.l.google.com:19302', @@ -63,12 +64,19 @@ export default function App({}) { { urls: 'stun:stun1.l.google.com:19302', }, - { - urls: 'stun:stun2.l.google.com:19302', - }, + {urls: 'stun:stun2.l.google.com:19302'}, ], - }), - ); + }); + }; + + const initializePeerConnection = async () => { + try { + peerConnection.current = createPeerConnection(); + console.log('PeerConnection initialized successfully.'); + } catch (error) { + console.error('Error initializing PeerConnection:', error); + } + }; //Função para limpar todos os listeners do socket const cleanUp = () => { @@ -141,22 +149,19 @@ export default function App({}) { } }; - socket.on('endCall', () => { - console.log('Received endCall event'); - try { - closePeerConnection(); - setlocalStream(null); - setType('JOIN'); - socket.emit('leaveRoom'); // Informa ao servidor que deixou a sala - console.log('Successfully closed call automatically'); - } catch (error) { - console.error('Failed to close call automatically', error); - } + // No cliente, ouvir o evento "endCallAndLeaveRoom" do servidor + socket.on('endCallAndLeaveRoom', () => { + // Deixar a sala após encerrar a chamada + socket.emit('leaveRoom'); // Envia um evento para o servidor para deixar a sala + closePeerConnection(); + setlocalStream(null); + setType('JOIN'); }); // Lógica para sair da sala no cliente socket.on('leaveRoom', () => { - socket.leave(roomId); + socket.leave(socket.user); // Deixa a sala com o mesmo nome do usuário + console.log(`${socket.user} left the conference room.`); }); socket.on('ICEcandidate', data => { @@ -198,14 +203,15 @@ export default function App({}) { const constraints = { audio: true, - video: { - mandatory: { - minWidth: 500, - minHeight: 300, - minFrameRate: 30, - }, - facingMode: isFront ? 'user' : 'environment', - }, + video: false, + // video: { + // mandatory: { + // minWidth: 500, + // minHeight: 300, + // minFrameRate: 30, + // }, + // facingMode: isFront ? 'user' : 'environment', + // }, }; if (videoSourceId) { @@ -225,31 +231,50 @@ export default function App({}) { } }; - const handleIniciarChamada = () => { + const handleIniciarChamada = async () => { setIniciarChamada(true); + await initializeApp(); // Aguarda a conclusão da inicialização + setType('OUTGOING_CALL'); + await processCall(); }; - useEffect(() => { - socketConfig(); - mediaConfig(); - - peerConnection.current.addEventListener('signalingstatechange', event => { - console.log( - 'Signaling state changed:', - event.type, - ':', - peerConnection.current.signalingState, - ); - }); + const handleAceitarChamada = async () => { + setType('WEBRTC_ROOM'); + await processAccept(); + }; + + async function initializeApp() { + try { + await initializePeerConnection(); + await mediaConfig(); + socketConfig(); + + peerConnection.current.addEventListener('signalingstatechange', event => { + console.log( + 'Signaling state changed:', + event.type, + ':', + peerConnection.current.signalingState, + ); + }); + + setIniciarChamada(false); + } catch (error) { + console.error('Erro durante a inicialização:', error); + // Trate o erro conforme necessário + } + } + useEffect(() => { + initializeApp(); setIniciarChamada(false); - return () => { - // socket.off('call'); - // socket.off('answerCall'); - // socket.off('ICEcandidate'); - // socket.off('endCall'); - socket.removeAllListeners(); - }; + }, []); + + useEffect(() => { + if (iniciarChamada) { + initializeApp(); + setIniciarChamada(false); + } }, [iniciarChamada]); //useEffect para iniciar o gerenciamento de chamadas @@ -284,31 +309,39 @@ export default function App({}) { async function processAccept() { console.log('Processing call acceptance...'); - peerConnection.current.setRemoteDescription( - new RTCSessionDescription(remoteRTCMessage.current), - ); - const sessionDescription = await peerConnection.current.createAnswer(); - await peerConnection.current.setLocalDescription(sessionDescription); + try { + await peerConnection.current.setRemoteDescription( + new RTCSessionDescription(remoteRTCMessage.current), + ); - answerCall({ - callerId: otherUserId.current, - rtcMessage: sessionDescription, - }); - // Setup ice handling apenas quamndo aceitar a chamada - peerConnection.current.onicecandidate = event => { - if (event.candidate) { - sendICEcandidate({ - calleeId: otherUserId.current, - rtcMessage: { - label: event.candidate.sdpMLineIndex, - id: event.candidate.sdpMid, - candidate: event.candidate.candidate, - }, - }); - } else { - console.log('End of candidates.'); - } - }; + const sessionDescription = await peerConnection.current.createAnswer(); + await peerConnection.current.setLocalDescription(sessionDescription); + + answerCall({ + callerId: otherUserId.current, + rtcMessage: sessionDescription, + }); + + // Adicionar evento onicecandidate após a criação da resposta local + peerConnection.current.onicecandidate = event => { + if (event.candidate) { + // Enviar ICE candidate apenas quando estiver disponível + sendICEcandidate({ + calleeId: otherUserId.current, + rtcMessage: { + label: event.candidate.sdpMLineIndex, + id: event.candidate.sdpMid, + candidate: event.candidate.candidate, + }, + }); + } else { + console.log('End of candidates.'); + } + }; + } catch (error) { + console.error('Error processing call acceptance:', error); + // Tratar o erro conforme necessário + } } function answerCall(data) { @@ -446,8 +479,7 @@ export default function App({}) { /> { - setType('OUTGOING_CALL'); - processCall(); + handleIniciarChamada(); }} style={styles.buttonCall}> Realizar chamada @@ -548,8 +580,7 @@ export default function App({}) { }}> { - processAccept(); - setType('WEBRTC_ROOM'); + handleAceitarChamada(); }}> { const otherPeer = data.otherPeer; // ID do outro peer if (otherPeer) { // Emitir evento para notificar o outro peer - socket.to(otherPeer).emit("endCall"); + socket.to(otherPeer).emit("endCallAndLeaveRoom"); console.log("Call ended by user:", socket.user); - // Deixar a sala após encerrar a chamada socket.leave(socket.user); // Deixa a sala com o mesmo nome do usuário } else {