summaryrefslogtreecommitdiff
path: root/client-native-rift/src/main.rs
blob: 7aa7afe094fb04ff2ba180ee5e4919807b572a09 (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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
#![feature(box_syntax)]

use bytes::Bytes;
use clap::{Parser, Subcommand};
use client_native_lib::{
    connect,
    peer::Peer,
    state::{HasPeer, PeerInit},
    webrtc::data_channel::RTCDataChannel,
    Config,
};
use log::{error, info};
use std::{future::Future, pin::Pin, sync::Arc};
use tokio::{
    fs::File,
    io::{stdin, stdout, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt},
    sync::RwLock,
};

fn main() {
    env_logger::init_from_env("LOG");
    tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .build()
        .unwrap()
        .block_on(run())
}

#[derive(Parser)]
pub struct Args {
    #[clap(long, default_value = "meet.metamuffin.org")]
    signaling_host: String,
    #[clap(short, long)]
    secret: String,
    #[clap(subcommand)]
    action: Action,
}

async fn run() {
    let args = Args::parse();

    connect(
        Config {
            secret: args.secret.clone(),
            signaling_host: args.signaling_host.clone(),
        },
        Arc::new(Conn {
            args: Arc::new(args),
        }),
    )
    .await;

    tokio::signal::ctrl_c().await.unwrap();
    error!("interrupt received, exiting");
}

#[derive(Subcommand)]
pub enum Action {
    Send { filename: Option<String> },
    Receive { filename: Option<String> },
}

impl Action {
    pub async fn create_writer(&self) -> Pin<Box<dyn AsyncWrite + Send + Sync + 'static>> {
        match self {
            Action::Receive { filename } => {
                if let Some(filename) = filename {
                    Box::pin(File::create(filename).await.unwrap())
                } else {
                    Box::pin(stdout())
                }
            }
            _ => unreachable!(),
        }
    }
    pub async fn create_reader(&self) -> Pin<Box<dyn AsyncRead + Send + Sync + 'static>> {
        match self {
            Action::Send { filename } => {
                if let Some(filename) = filename {
                    Box::pin(File::open(filename).await.unwrap())
                } else {
                    Box::pin(stdin())
                }
            }
            _ => unreachable!(),
        }
    }
}

pub struct Conn {
    pub args: Arc<Args>,
}
pub struct PeerState {
    args: Arc<Args>,
    peer: Arc<Peer>,
}

impl PeerInit<PeerState> for Conn {
    fn add_peer(
        &self,
        peer: Arc<Peer>,
    ) -> Pin<Box<(dyn Future<Output = Arc<PeerState>> + Send + Sync + 'static)>> {
        let args = self.args.clone();
        Box::pin(async move {
            let p = Arc::new(PeerState { peer, args });
            p.clone().init().await;
            p
        })
    }
}
impl HasPeer for PeerState {
    fn peer(&self) -> &Arc<Peer> {
        &self.peer
    }
}
impl PeerState {
    pub async fn init(self: Arc<Self>) {
        let s = self.clone();
        match &self.args.action {
            Action::Send { .. } => self.init_send_channel().await,
            Action::Receive { .. } => {
                self.peer
                    .peer_connection
                    .on_data_channel(box move |ch| {
                        let s = s.clone();
                        Box::pin(async move { s.init_receive_channel(ch).await })
                    })
                    .await;
            }
        }
    }

    pub async fn init_receive_channel(self: Arc<Self>, channel: Arc<RTCDataChannel>) {
        info!("got a data channel");
        let writer = Arc::new(RwLock::new(None));
        {
            let writer = writer.clone();
            channel
                .on_open(box move || {
                    info!("channel opened");
                    Box::pin(async move {
                        *writer.write().await = Some(self.args.action.create_writer().await);
                    })
                })
                .await;
        }
        {
            let writer = writer.clone();
            channel
                .on_close(box move || {
                    info!("channel closed");
                    let writer = writer.clone();
                    Box::pin(async move {
                        *writer.write().await = None; // drop the writer, so it closes the file or whatever
                    })
                })
                .await;
        }
        {
            let writer = writer.clone();
            channel
                .on_message(box move |mesg| {
                    let writer = writer.clone();
                    Box::pin(async move {
                        writer
                            .write()
                            .await
                            .as_mut()
                            .unwrap()
                            .write_all(&mesg.data)
                            .await
                            .unwrap();
                    })
                })
                .await;
        }
        channel
            .on_error(box move |err| {
                info!("channel error: {err:?}");
                Box::pin(async {})
            })
            .await;
    }

    pub async fn init_send_channel(&self) {
        info!("creating data channel");
        let data_channel = self
            .peer
            .peer_connection
            .create_data_channel("file-transfer", None)
            .await
            .unwrap();
        let weak = Arc::downgrade(&data_channel);
        let args = self.args.clone();
        data_channel
            .on_open(box move || {
                let args = args.clone();
                let data_channel = weak.upgrade().unwrap();
                Box::pin(async move {
                    let mut reader = args.action.create_reader().await;
                    info!("starting transmission");
                    loop {
                        let mut buf = [0u8; 4096];
                        let size = reader.read(&mut buf).await.unwrap();
                        if size == 0 {
                            break;
                        }
                        data_channel
                            .send(&Bytes::from_iter(buf[0..size].into_iter().map(|e| *e)))
                            .await
                            .unwrap();
                    }
                    info!("transmission finished");
                    drop(reader);
                    info!("now closing the channel again…");
                    data_channel.close().await.unwrap();
                })
            })
            .await;
        data_channel
            .on_close(box || Box::pin(async move { info!("data channel closed") }))
            .await;
        data_channel
            .on_error(box |err| Box::pin(async move { error!("data channel error: {err}") }))
            .await;
    }
}