use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct IceCandidate {
pub candidate: String,
pub sdp_mid: Option<String>,
pub sdp_m_line_index: Option<u16>,
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[serde(tag = "type")]
pub enum WebRtcSignal {
Offer { sdp: String },
Answer { sdp: String },
IceCandidate(IceCandidate),
}
#[cfg(target_arch = "wasm32")]
mod wasm_peer {
use super::{IceCandidate, WebRtcSignal};
use js_sys::{Object, Reflect};
use wasm_bindgen::prelude::*;
use wasm_bindgen_futures::JsFuture;
use web_sys::{
RtcConfiguration, RtcDataChannel, RtcDataChannelInit, RtcDataChannelState, RtcIceCandidate,
RtcIceCandidateInit, RtcPeerConnection, RtcSdpType, RtcSessionDescriptionInit,
};
fn create_peer_connection() -> Result<RtcPeerConnection, JsValue> {
let config = RtcConfiguration::new();
RtcPeerConnection::new_with_configuration(&config)
.map_err(|e| JsValue::from_str(&format!("RtcPeerConnection::new failed: {e:?}")))
}
fn make_sdp_init(sdp_type: RtcSdpType, sdp: &str) -> RtcSessionDescriptionInit {
let desc = RtcSessionDescriptionInit::new(sdp_type);
desc.set_sdp(sdp);
desc
}
async fn apply_ice_candidate(
pc: &RtcPeerConnection,
candidate_json: &str,
) -> Result<(), JsValue> {
let ice: IceCandidate = serde_json::from_str(candidate_json)
.map_err(|e| JsValue::from_str(&format!("IceCandidate JSON parse error: {e}")))?;
let mut init = RtcIceCandidateInit::new(&ice.candidate);
if let Some(mid) = &ice.sdp_mid {
init.sdp_mid(Some(mid.as_str()));
}
if let Some(idx) = ice.sdp_m_line_index {
init.sdp_m_line_index(Some(idx));
}
let rtc_ice = RtcIceCandidate::new(&init)
.map_err(|e| JsValue::from_str(&format!("RtcIceCandidate::new failed: {e:?}")))?;
JsFuture::from(
pc.add_ice_candidate_with_opt_rtc_ice_candidate(Some(&rtc_ice))
.map_err(|e| JsValue::from_str(&format!("addIceCandidate failed: {e:?}")))?,
)
.await
.map(|_| ())
}
#[wasm_bindgen]
pub struct IpfrsPeer {
peer_id: String,
#[wasm_bindgen(skip)]
inner: RtcPeerConnection,
#[wasm_bindgen(skip)]
data_channel: Option<RtcDataChannel>,
}
#[wasm_bindgen]
impl IpfrsPeer {
#[wasm_bindgen(constructor)]
pub fn new(peer_id: &str) -> Result<IpfrsPeer, JsValue> {
let pc = create_peer_connection()?;
let mut dc_init = RtcDataChannelInit::new();
dc_init.ordered(true);
let dc = pc
.create_data_channel_with_data_channel_dict("ipfrs-blocks", &dc_init)
.map_err(|e| JsValue::from_str(&format!("createDataChannel failed: {e:?}")))?;
Ok(IpfrsPeer {
peer_id: peer_id.to_string(),
inner: pc,
data_channel: Some(dc),
})
}
pub async fn create_offer(&self) -> Result<String, JsValue> {
let offer_promise = self
.inner
.create_offer()
.map_err(|e| JsValue::from_str(&format!("createOffer() failed: {e:?}")))?;
let offer_value = JsFuture::from(offer_promise).await?;
let sdp = Reflect::get(&offer_value, &JsValue::from_str("sdp"))
.map_err(|_| JsValue::from_str("offer missing 'sdp' field"))?
.as_string()
.ok_or_else(|| JsValue::from_str("offer 'sdp' is not a string"))?;
let local_desc = make_sdp_init(RtcSdpType::Offer, &sdp);
JsFuture::from(
self.inner.set_local_description(&local_desc).map_err(|e| {
JsValue::from_str(&format!("setLocalDescription failed: {e:?}"))
})?,
)
.await?;
Ok(sdp)
}
pub async fn set_answer(&self, answer_sdp: &str) -> Result<(), JsValue> {
let remote_desc = make_sdp_init(RtcSdpType::Answer, answer_sdp);
JsFuture::from(
self.inner
.set_remote_description(&remote_desc)
.map_err(|e| {
JsValue::from_str(&format!("setRemoteDescription failed: {e:?}"))
})?,
)
.await
.map(|_| ())
}
pub fn add_ice_candidate(&self, candidate_json: &str) -> Result<(), JsValue> {
let ice: IceCandidate = serde_json::from_str(candidate_json)
.map_err(|e| JsValue::from_str(&format!("IceCandidate JSON parse error: {e}")))?;
let mut init = RtcIceCandidateInit::new(&ice.candidate);
if let Some(mid) = &ice.sdp_mid {
init.sdp_mid(Some(mid.as_str()));
}
if let Some(idx) = ice.sdp_m_line_index {
init.sdp_m_line_index(Some(idx));
}
let rtc_ice = RtcIceCandidate::new(&init)
.map_err(|e| JsValue::from_str(&format!("RtcIceCandidate::new: {e:?}")))?;
let pc = self.inner.clone();
wasm_bindgen_futures::spawn_local(async move {
if let Ok(promise) = pc.add_ice_candidate_with_opt_rtc_ice_candidate(Some(&rtc_ice))
{
let _ = JsFuture::from(promise).await;
}
});
Ok(())
}
pub fn send_block(&self, cid: &str, data: &[u8]) -> Result<(), JsValue> {
let dc = self
.data_channel
.as_ref()
.ok_or_else(|| JsValue::from_str("DataChannel not initialised"))?;
if dc.ready_state() != RtcDataChannelState::Open {
return Err(JsValue::from_str(
"DataChannel is not open; wait for is_connected() == true",
));
}
let cid_bytes = cid.as_bytes();
let cid_len = cid_bytes.len() as u32;
let mut buf = Vec::with_capacity(4 + cid_bytes.len() + data.len());
buf.extend_from_slice(&cid_len.to_be_bytes());
buf.extend_from_slice(cid_bytes);
buf.extend_from_slice(data);
dc.send_with_u8_array(&buf)
.map_err(|e| JsValue::from_str(&format!("DataChannel.send failed: {e:?}")))
}
pub fn peer_id(&self) -> String {
self.peer_id.clone()
}
pub fn is_connected(&self) -> bool {
self.data_channel
.as_ref()
.map(|dc| dc.ready_state() == RtcDataChannelState::Open)
.unwrap_or(false)
}
}
#[wasm_bindgen]
pub struct IpfrsPeerAnswerer {
#[wasm_bindgen(skip)]
inner: RtcPeerConnection,
}
#[wasm_bindgen]
impl IpfrsPeerAnswerer {
pub async fn from_offer(offer_sdp: &str) -> Result<IpfrsPeerAnswerer, JsValue> {
let pc = create_peer_connection()?;
let remote_desc = make_sdp_init(RtcSdpType::Offer, offer_sdp);
JsFuture::from(pc.set_remote_description(&remote_desc).map_err(|e| {
JsValue::from_str(&format!("setRemoteDescription(offer) failed: {e:?}"))
})?)
.await?;
Ok(IpfrsPeerAnswerer { inner: pc })
}
pub async fn create_answer(&self) -> Result<String, JsValue> {
let answer_promise = self
.inner
.create_answer()
.map_err(|e| JsValue::from_str(&format!("createAnswer() failed: {e:?}")))?;
let answer_value = JsFuture::from(answer_promise).await?;
let sdp = Reflect::get(&answer_value, &JsValue::from_str("sdp"))
.map_err(|_| JsValue::from_str("answer missing 'sdp' field"))?
.as_string()
.ok_or_else(|| JsValue::from_str("answer 'sdp' is not a string"))?;
let local_desc = make_sdp_init(RtcSdpType::Answer, &sdp);
JsFuture::from(
self.inner.set_local_description(&local_desc).map_err(|e| {
JsValue::from_str(&format!("setLocalDescription failed: {e:?}"))
})?,
)
.await?;
Ok(sdp)
}
pub async fn add_ice_candidate(&self, candidate_json: &str) -> Result<(), JsValue> {
apply_ice_candidate(&self.inner, candidate_json).await
}
pub fn is_connected(&self) -> bool {
use web_sys::RtcIceConnectionState;
let state = self.inner.ice_connection_state();
state == RtcIceConnectionState::Connected || state == RtcIceConnectionState::Completed
}
}
pub use IpfrsPeer;
pub use IpfrsPeerAnswerer;
}
#[cfg(target_arch = "wasm32")]
pub use wasm_peer::{IpfrsPeer, IpfrsPeerAnswerer};
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
use super::{IceCandidate, WebRtcSignal};
#[test]
fn test_webrtc_signal_offer_roundtrip() {
let original = WebRtcSignal::Offer {
sdp: "v=0\r\no=- 1234 2 IN IP4 127.0.0.1\r\n".to_string(),
};
let json = serde_json::to_string(&original).expect("serialise Offer");
assert!(
json.contains("\"type\":\"Offer\""),
"type tag missing: {json}"
);
assert!(json.contains("\"sdp\""), "sdp field missing: {json}");
let roundtripped: WebRtcSignal = serde_json::from_str(&json).expect("deserialise Offer");
assert_eq!(original, roundtripped);
}
#[test]
fn test_webrtc_signal_answer_roundtrip() {
let original = WebRtcSignal::Answer {
sdp: "v=0\r\no=- 5678 2 IN IP4 127.0.0.1\r\n".to_string(),
};
let json = serde_json::to_string(&original).expect("serialise Answer");
assert!(
json.contains("\"type\":\"Answer\""),
"type tag missing: {json}"
);
let roundtripped: WebRtcSignal = serde_json::from_str(&json).expect("deserialise Answer");
assert_eq!(original, roundtripped);
}
#[test]
fn test_webrtc_signal_ice_candidate() {
let ice = IceCandidate {
candidate: "candidate:0 1 UDP 2122252543 192.168.1.42 54321 typ host".to_string(),
sdp_mid: Some("0".to_string()),
sdp_m_line_index: Some(0),
};
let signal = WebRtcSignal::IceCandidate(ice.clone());
let json = serde_json::to_string(&signal).expect("serialise IceCandidate");
assert!(
json.contains("\"type\":\"IceCandidate\""),
"type tag missing: {json}"
);
assert!(
json.contains("\"candidate\""),
"candidate field missing: {json}"
);
let roundtripped: WebRtcSignal =
serde_json::from_str(&json).expect("deserialise IceCandidate");
match roundtripped {
WebRtcSignal::IceCandidate(rt_ice) => {
assert_eq!(rt_ice.candidate, ice.candidate);
assert_eq!(rt_ice.sdp_mid, ice.sdp_mid);
assert_eq!(rt_ice.sdp_m_line_index, ice.sdp_m_line_index);
}
other => panic!("expected IceCandidate, got {other:?}"),
}
}
#[test]
fn test_ice_candidate_none_fields_roundtrip() {
let ice = IceCandidate {
candidate: "candidate:1 1 TCP 1518280447 ::1 9 typ host tcptype active".to_string(),
sdp_mid: None,
sdp_m_line_index: None,
};
let json = serde_json::to_string(&ice).expect("serialise IceCandidate None");
let rt: IceCandidate = serde_json::from_str(&json).expect("deserialise");
assert_eq!(rt, ice);
assert!(rt.sdp_mid.is_none());
assert!(rt.sdp_m_line_index.is_none());
}
#[test]
fn test_signal_type_tag() {
let offer = WebRtcSignal::Offer {
sdp: "dummy".to_string(),
};
let json = serde_json::to_string(&offer).expect("serialise");
assert!(
json.starts_with(r#"{"type":"Offer""#),
"JSON must start with {{\"type\":\"Offer\": got {json}"
);
let answer = WebRtcSignal::Answer {
sdp: "dummy".to_string(),
};
let json_a = serde_json::to_string(&answer).expect("serialise");
assert!(
json_a.starts_with(r#"{"type":"Answer""#),
"JSON must start with {{\"type\":\"Answer\": got {json_a}"
);
let ice = WebRtcSignal::IceCandidate(IceCandidate {
candidate: "c".to_string(),
sdp_mid: None,
sdp_m_line_index: None,
});
let json_i = serde_json::to_string(&ice).expect("serialise");
assert!(
json_i.starts_with(r#"{"type":"IceCandidate""#),
"JSON must start with {{\"type\":\"IceCandidate\": got {json_i}"
);
}
#[test]
fn test_deserialise_known_offer_json() {
let json = "{\"type\":\"Offer\",\"sdp\":\"v=0\\r\\n\"}";
let signal: WebRtcSignal = serde_json::from_str(json).expect("parse known Offer JSON");
match signal {
WebRtcSignal::Offer { sdp } => {
assert!(
sdp.starts_with("v=0"),
"SDP must start with v=0, got: {sdp:?}"
);
assert!(sdp.contains('\r'), "SDP must contain CR after JSON decode");
assert!(sdp.contains('\n'), "SDP must contain LF after JSON decode");
}
other => panic!("expected Offer, got {other:?}"),
}
}
#[test]
fn test_deserialise_known_ice_json() {
let json = r#"{"type":"IceCandidate","candidate":"candidate:0 1 UDP 123 10.0.0.1 5000 typ host","sdp_mid":"audio","sdp_m_line_index":0}"#;
let signal: WebRtcSignal = serde_json::from_str(json).expect("parse known ICE JSON");
match signal {
WebRtcSignal::IceCandidate(ice) => {
assert!(ice.candidate.starts_with("candidate:0"));
assert_eq!(ice.sdp_mid.as_deref(), Some("audio"));
assert_eq!(ice.sdp_m_line_index, Some(0));
}
other => panic!("expected IceCandidate, got {other:?}"),
}
}
#[test]
fn test_signal_clone_and_debug() {
let sig = WebRtcSignal::Offer {
sdp: "test".to_string(),
};
let cloned = sig.clone();
assert_eq!(sig, cloned);
let _ = format!("{sig:?}");
}
#[test]
fn test_ice_candidate_clone_and_debug() {
let ice = IceCandidate {
candidate: "cand".to_string(),
sdp_mid: Some("m".to_string()),
sdp_m_line_index: Some(1),
};
let cloned = ice.clone();
assert_eq!(ice, cloned);
let _ = format!("{ice:?}");
}
}