1#![warn(rust_2018_idioms)]
2#![allow(dead_code)]
3
4use std::net::SocketAddr;
5use std::str::FromStr;
6use std::sync::Arc;
7
8use anyhow::Result;
9use base64::prelude::BASE64_STANDARD;
10use base64::Engine;
11use hyper::service::{make_service_fn, service_fn};
12use hyper::{Body, Method, Request, Response, Server, StatusCode};
13use tokio::sync::{mpsc, Mutex};
14
15#[macro_use]
16extern crate lazy_static;
17
18lazy_static! {
19 static ref SDP_CHAN_TX_MUTEX: Arc<Mutex<Option<mpsc::Sender<String>>>> =
20 Arc::new(Mutex::new(None));
21}
22
23async fn remote_handler(req: Request<Body>) -> Result<Response<Body>, hyper::Error> {
25 match (req.method(), req.uri().path()) {
26 (&Method::POST, "/sdp") => {
28 let sdp_str = match std::str::from_utf8(&hyper::body::to_bytes(req.into_body()).await?)
30 {
31 Ok(s) => s.to_owned(),
32 Err(err) => panic!("{}", err),
33 };
34
35 {
36 let sdp_chan_tx = SDP_CHAN_TX_MUTEX.lock().await;
37 if let Some(tx) = &*sdp_chan_tx {
38 let _ = tx.send(sdp_str).await;
39 }
40 }
41
42 let mut response = Response::new(Body::empty());
43 *response.status_mut() = StatusCode::OK;
44 Ok(response)
45 }
46 _ => {
48 let mut not_found = Response::default();
49 *not_found.status_mut() = StatusCode::NOT_FOUND;
50 Ok(not_found)
51 }
52 }
53}
54
55pub async fn http_sdp_server(port: u16) -> mpsc::Receiver<String> {
57 let (sdp_chan_tx, sdp_chan_rx) = mpsc::channel::<String>(1);
58 {
59 let mut tx = SDP_CHAN_TX_MUTEX.lock().await;
60 *tx = Some(sdp_chan_tx);
61 }
62
63 tokio::spawn(async move {
64 let addr = SocketAddr::from_str(&format!("0.0.0.0:{port}")).unwrap();
65 let service =
66 make_service_fn(|_| async { Ok::<_, hyper::Error>(service_fn(remote_handler)) });
67 let server = Server::bind(&addr).serve(service);
68 if let Err(e) = server.await {
70 eprintln!("server error: {e}");
71 }
72 });
73
74 sdp_chan_rx
75}
76
77#[allow(clippy::assigning_clones)]
79pub fn must_read_stdin() -> Result<String> {
80 let mut line = String::new();
81
82 std::io::stdin().read_line(&mut line)?;
83 line = line.trim().to_owned();
84 println!();
85
86 Ok(line)
87}
88
89pub fn encode(b: &str) -> String {
95 BASE64_STANDARD.encode(b)
100}
101
102pub fn decode(s: &str) -> Result<String> {
105 let b = BASE64_STANDARD.decode(s)?;
106
107 let s = String::from_utf8(b)?;
112 Ok(s)
113}
114