From cde03367c336040a9884e0b939c2229d33208c71 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 25 Apr 2025 02:32:40 +0300 Subject: [PATCH] feat: :sparkles: webrtc answer --- client/src/webrtc.rs | 59 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 58 insertions(+), 1 deletion(-) diff --git a/client/src/webrtc.rs b/client/src/webrtc.rs index 34e1b9f..8f29887 100644 --- a/client/src/webrtc.rs +++ b/client/src/webrtc.rs @@ -8,7 +8,10 @@ use web_sys::{ wasm_bindgen::{JsCast, JsValue, prelude::Closure}, }; -use crate::signal::{receive_answer, receive_ice_candidate, send_ice_candidate, send_offer}; +use crate::signal::{ + receive_answer, receive_ice_candidate, receive_offer, send_answer, send_ice_candidate, + send_offer, +}; pub struct WebRTC { audio_stream: Option, @@ -160,4 +163,58 @@ impl WebRTC { } return Err(Error::WebRTCOffer); } + + async fn answer(&mut self) -> Result<(), Error> { + if let Ok(received_offer) = receive_offer() { + let offer = RtcSessionDescriptionInit::new(RtcSdpType::Offer); + offer.set_sdp(&received_offer.get_data()); + + let set_remote_description_promise = + self.peer_connection.set_remote_description(&offer); + JsFuture::from(set_remote_description_promise) + .await + .map_err(|_| Error::WebRTCSetRemoteDescription)?; + + let answer_promise = self.peer_connection.create_answer(); + match JsFuture::from(answer_promise) + .await + .map_err(|_| Error::WebRTCAnswer) + { + Ok(answer) => { + let answer_session_description_protocol = + Reflect::get(&answer, &JsValue::from_str("sdp")) + .map_err(|_| Error::WebRTCSessionDescriptionProtocol)?; + match answer_session_description_protocol + .as_string() + .ok_or_else(|| Error::WebRTCAnswer) + { + Ok(answer_session_description_protocol) => { + let answer = RtcSessionDescriptionInit::new(RtcSdpType::Answer); + answer.set_sdp(&answer_session_description_protocol); + + let set_local_description_promise = + self.peer_connection.set_local_description(&answer); + JsFuture::from(set_local_description_promise) + .await + .map_err(|_| Error::WebRTCSetLocalDescription)?; + + send_answer(&answer_session_description_protocol)?; + + return Ok(()); + } + Err(err_val) => { + log!( + "Error: WebRTC Answer | Session Description Protocol String Transformation | {}", + err_val + ); + } + } + } + Err(err_val) => { + log!("Error: WebRTC Answer | Promise | {}", err_val); + } + } + } + Err(Error::WebRTCAnswer) + } }