summaryrefslogtreecommitdiff
path: root/client-native-lib/src/peer.rs
blob: 64eb641ebc156fc32c7c738243f0c72fa5a4dceb (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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
use log::info;
use std::sync::Arc;
use webrtc::{
    data_channel::data_channel_message::DataChannelMessage,
    ice_transport::{ice_candidate::RTCIceCandidate, ice_server::RTCIceServer},
    peer_connection::{
        configuration::RTCConfiguration, peer_connection_state::RTCPeerConnectionState,
        sdp::session_description::RTCSessionDescription, RTCPeerConnection,
    },
};

use crate::{
    protocol::{self, RTCSessionDescriptionInit, RelayMessage},
    state::State,
};

pub struct Peer {
    state: Arc<State>, // maybe use Weak later
    peer_connection: RTCPeerConnection,
    id: usize,
}

impl Peer {
    pub async fn create(state: Arc<State>, id: usize) -> Arc<Self> {
        info!("({id}) peer joined");
        let config = RTCConfiguration {
            ice_servers: vec![RTCIceServer {
                urls: vec!["stun:metamuffin.org:16900".to_owned()],
                ..Default::default()
            }],
            ..Default::default()
        };

        let peer_connection = state.api.new_peer_connection(config).await.unwrap();

        let peer = Arc::new(Self {
            peer_connection,
            id,
            state: state.clone(),
        });
        peer.peer_connection
            .on_peer_connection_state_change(Box::new(move |s: RTCPeerConnectionState| {
                println!("conn state: {s}");
                Box::pin(async {})
            }))
            .await;

        {
            let peer2 = peer.clone();
            peer.peer_connection
                .on_ice_candidate(box move |c| {
                    let peer = peer2.clone();
                    Box::pin(async move {
                        if let Some(c) = c {
                            peer.on_ice_candidate(c).await
                        }
                    })
                })
                .await;
        }

        {
            let peer2 = peer.clone();
            peer.peer_connection
                .on_negotiation_needed(box move || {
                    let peer = peer2.clone();
                    Box::pin(async { peer.on_negotiation_needed().await })
                })
                .await;
        }

        {
            peer.peer_connection
                .on_data_channel(box move |dc| {
                    Box::pin(async move {
                        dc.on_message(box move |message| {
                            Box::pin(async move { println!("{:?}", message.data) })
                        })
                        .await
                    })
                })
                .await;
        }

        // if let Action::Send { .. } = &peer.state.args.action {
        //     peer.start_transfer().await
        // }

        peer
    }

    pub async fn send_relay(&self, inner: RelayMessage) {
        self.state.send_relay(self.id, inner).await
    }

    pub async fn start_transfer(&self) {
        info!("starting data channel");
        let data_channel = self
            .peer_connection
            .create_data_channel("file-transfer", None)
            .await
            .unwrap();

        data_channel
            .on_message(Box::new(move |msg: DataChannelMessage| {
                let msg_str = String::from_utf8(msg.data.to_vec()).unwrap();
                println!("message! '{}'", msg_str);
                Box::pin(async {})
            }))
            .await;

        {
            let dc2 = data_channel.clone();
            data_channel
                .on_open(box move || {
                    let data_channel = dc2.clone();
                    Box::pin(async move {
                        loop {
                            data_channel
                                .send(&bytes::Bytes::from_static(b"test\n"))
                                .await
                                .unwrap();
                        }
                    })
                })
                .await;
        }
    }

    pub async fn on_relay(&self, p: RelayMessage) {
        match p {
            protocol::RelayMessage::Offer(o) => self.on_offer(o).await,
            protocol::RelayMessage::Answer(a) => self.on_answer(a).await,
            protocol::RelayMessage::IceCandidate(c) => {
                info!("received ICE candidate");
                self.peer_connection.add_ice_candidate(c).await.unwrap();
            }
        }
    }

    pub async fn on_ice_candidate(&self, candidate: RTCIceCandidate) {
        self.send_relay(RelayMessage::IceCandidate(
            candidate.to_json().await.unwrap(),
        ))
        .await;
    }

    pub async fn on_negotiation_needed(self: Arc<Self>) {
        info!("({}) negotiation needed", self.id);
        self.offer().await
    }

    pub async fn offer(&self) {
        info!("sending offer");
        let offer = self.peer_connection.create_offer(None).await.unwrap();
        self.peer_connection
            .set_local_description(offer.clone())
            .await
            .unwrap();
        self.send_relay(protocol::RelayMessage::Offer(RTCSessionDescriptionInit {
            sdp: offer.sdp,
            ty: offer.sdp_type,
        }))
        .await
    }
    pub async fn on_offer(&self, offer: RTCSessionDescriptionInit) {
        info!("received offer");
        let offer = RTCSessionDescription::offer(offer.sdp).unwrap();
        self.peer_connection
            .set_remote_description(offer)
            .await
            .unwrap();
        self.answer().await
    }
    pub async fn answer(&self) {
        info!("sending answer");
        let offer = self.peer_connection.create_answer(None).await.unwrap();
        self.peer_connection
            .set_local_description(offer.clone())
            .await
            .unwrap();
        self.send_relay(protocol::RelayMessage::Answer(RTCSessionDescriptionInit {
            sdp: offer.sdp,
            ty: offer.sdp_type,
        }))
        .await
    }
    pub async fn on_answer(&self, answer: RTCSessionDescriptionInit) {
        info!("received answer");
        let offer = RTCSessionDescription::answer(answer.sdp).unwrap();
        self.peer_connection
            .set_remote_description(offer)
            .await
            .unwrap();
    }
}