summaryrefslogtreecommitdiff
path: root/client-native-rift/src/signaling.rs
blob: c61b98236fc8ec9a1f32ee8c7ce16cad7d83f518 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
use crate::protocol::ClientboundPacket;
use crate::{crypto::hash, protocol::ServerboundPacket};
use futures_util::{SinkExt, StreamExt};
use tokio_tungstenite::tungstenite::{self, Message};

pub async fn signaling_connect(
    host: &str,
    secret: &str,
) -> (
    impl SinkExt<ServerboundPacket>,
    impl StreamExt<Item = Option<ClientboundPacket>>,
) {
    let (conn, _) = tokio_tungstenite::connect_async(
        url::Url::parse(&format!("wss://{host}/signaling/{}", hash(secret))).unwrap(),
    )
    .await
    .unwrap();

    let (tx, rx) = conn.split();
    let prx = rx.map(|mesg| {
        let mesg = mesg.unwrap();
        match mesg {
            tungstenite::Message::Text(t) => {
                let p: ClientboundPacket = serde_json::from_str(t.as_str()).unwrap();
                Some(p)
            }
            tungstenite::Message::Close(_) => {
                eprintln!("ws closed :(");
                None
            }
            _ => None,
        }
    });
    let ptx = tx.with(async move |p| {
        Ok::<_, tokio_tungstenite::tungstenite::error::Error>(Message::Text(
            serde_json::to_string::<ServerboundPacket>(&p).unwrap(),
        ))
    });
    (ptx, prx)
}