use core::fmt::Write as _;
use core::time::Duration;
use std::net::SocketAddr;
use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
use tokio::net::{TcpListener, TcpStream};
use tokio::task::JoinHandle;
#[derive(Debug, Clone)]
pub struct Scripted {
pub hold: Option<Duration>,
pub status: &'static str,
pub content_type: &'static str,
pub body: Vec<u8>,
}
impl Scripted {
#[must_use]
pub const fn frame(body: Vec<u8>) -> Self {
Self {
hold: Some(Duration::ZERO),
status: "200 OK",
content_type: "image/jpeg",
body,
}
}
#[must_use]
pub fn refusing(status: &'static str, said: &str) -> Self {
Self {
hold: Some(Duration::ZERO),
status,
content_type: "text/plain",
body: said.as_bytes().to_vec(),
}
}
#[must_use]
pub fn exit_status_69() -> Self {
Self::refusing("500 Internal Server Error", GO2RTC_FAILURE)
}
#[must_use]
pub const fn silent() -> Self {
Self {
hold: None,
status: "200 OK",
content_type: "image/jpeg",
body: Vec::new(),
}
}
#[must_use]
pub const fn held(mut self, hold: Duration) -> Self {
self.hold = Some(hold);
self
}
}
pub const GO2RTC_FAILURE: &str = "exit status 69";
#[derive(Debug, Clone, Copy)]
pub struct Exchange {
pub received: std::time::Instant,
pub answered: Option<std::time::Instant>,
}
#[derive(Debug)]
pub struct ScriptedHost {
pub address: SocketAddr,
exchanges: std::sync::Arc<std::sync::Mutex<Vec<Exchange>>>,
serving: JoinHandle<()>,
}
impl ScriptedHost {
pub async fn answering(script: Vec<Scripted>) -> Self {
assert!(!script.is_empty(), "a script answers something");
let listener = TcpListener::bind("127.0.0.1:0")
.await
.expect("a loopback port");
let address = listener.local_addr().expect("the bound address");
let exchanges: std::sync::Arc<std::sync::Mutex<Vec<Exchange>>> = std::sync::Arc::default();
let recorded = std::sync::Arc::clone(&exchanges);
let serving = tokio::spawn(async move {
let mut next = 0_usize;
while let Ok((stream, _)) = listener.accept().await {
let answer = script[next.min(script.len() - 1)].clone();
next += 1;
let recorded = std::sync::Arc::clone(&recorded);
tokio::spawn(async move {
exchange(stream, answer, &recorded).await;
});
}
});
Self {
address,
exchanges,
serving,
}
}
#[must_use]
pub fn url(&self) -> String {
format!("http://{}/api/frame.jpeg?src=camera", self.address)
}
#[must_use]
pub fn exchanges(&self) -> Vec<Exchange> {
self.exchanges
.lock()
.expect("the record is not poisoned")
.clone()
}
}
impl Drop for ScriptedHost {
fn drop(&mut self) {
self.serving.abort();
}
}
async fn exchange(
mut stream: TcpStream,
answer: Scripted,
recorded: &std::sync::Mutex<Vec<Exchange>>,
) {
let mut request = Vec::new();
let mut buffer = [0_u8; 1024];
while !request.windows(4).any(|window| window == b"\r\n\r\n") {
match stream.read(&mut buffer).await {
Ok(0) | Err(_) => return,
Ok(read) => request.extend_from_slice(&buffer[..read]),
}
}
let index = {
let mut held = recorded.lock().expect("the record is not poisoned");
held.push(Exchange {
received: std::time::Instant::now(),
answered: None,
});
held.len() - 1
};
let Some(hold) = answer.hold else {
let _ = stream.read(&mut buffer).await;
return;
};
tokio::time::sleep(hold).await;
let mut head = format!("HTTP/1.1 {}\r\n", answer.status);
let _ = write!(head, "Content-Type: {}\r\n", answer.content_type);
let _ = write!(head, "Content-Length: {}\r\n", answer.body.len());
head.push_str("Connection: close\r\n\r\n");
if stream.write_all(head.as_bytes()).await.is_err() {
return;
}
if stream.write_all(&answer.body).await.is_err() {
return;
}
let _ = stream.flush().await;
recorded.lock().expect("the record is not poisoned")[index].answered =
Some(std::time::Instant::now());
let _ = stream.shutdown().await;
}
pub async fn refusing_url() -> String {
let listener = TcpListener::bind("127.0.0.1:0")
.await
.expect("a loopback port");
let address = listener.local_addr().expect("the bound address");
drop(listener);
format!("http://{address}/api/frame.jpeg?src=camera")
}