43 lines
1.1 KiB
Rust
43 lines
1.1 KiB
Rust
|
use crate::mail::{Mail, Mailbox};
|
||
|
use poem::{
|
||
|
endpoint::{EmbeddedFileEndpoint, EmbeddedFilesEndpoint},
|
||
|
get, handler,
|
||
|
listener::TcpListener,
|
||
|
middleware::AddData,
|
||
|
web::{Data, Json},
|
||
|
EndpointExt, Route, Server,
|
||
|
};
|
||
|
use rust_embed::RustEmbed;
|
||
|
|
||
|
#[derive(RustEmbed)]
|
||
|
#[folder = "ui/build"]
|
||
|
pub struct Files;
|
||
|
|
||
|
#[handler]
|
||
|
async fn messages(mailbox: Data<&Mailbox>) -> Json<Vec<Mail>> {
|
||
|
Json(mailbox.all().await)
|
||
|
}
|
||
|
|
||
|
#[handler]
|
||
|
async fn clear(mailbox: Data<&Mailbox>) -> String {
|
||
|
mailbox.clear().await;
|
||
|
"OK".to_string()
|
||
|
}
|
||
|
|
||
|
pub async fn server(mailbox: Mailbox, port: u16) -> anyhow::Result<()> {
|
||
|
tokio::spawn(async move {
|
||
|
let app = Route::new()
|
||
|
.at("/messages", get(messages))
|
||
|
.at("/", EmbeddedFileEndpoint::<Files>::new("index.html"))
|
||
|
.nest("/", EmbeddedFilesEndpoint::<Files>::new())
|
||
|
.with(AddData::new(mailbox));
|
||
|
if let Err(e) = Server::new(TcpListener::bind(format!("localhost:{}", port)))
|
||
|
.run(app)
|
||
|
.await
|
||
|
{
|
||
|
tracing::error!("Webserver error: {}", e);
|
||
|
}
|
||
|
});
|
||
|
Ok(())
|
||
|
}
|