Add HTML template and cleanup the web service

This commit is contained in:
lemon-sh 2022-01-26 17:00:27 +01:00
parent 4e197fc4c0
commit 948cac5fe5
2 changed files with 26 additions and 25 deletions

11
src/res/quote_tmpl.html Normal file
View file

@ -0,0 +1,11 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<title># überbot quotes</title>
</head>
<body>
</body>
</html>

View file

@ -2,46 +2,37 @@ use crate::ExecutorConnection;
use serde_json::Value::Null; use serde_json::Value::Null;
use std::net::SocketAddr; use std::net::SocketAddr;
use tokio::sync::mpsc::Sender; use tokio::sync::mpsc::Sender;
use warp::Filter; use warp::{Filter, Reply, reply};
pub async fn run( pub async fn run(
db: ExecutorConnection, db: ExecutorConnection,
tx: Sender<String>, webhook_tx: Sender<String>,
listen: SocketAddr, listen: SocketAddr,
) -> anyhow::Result<()> { ) -> anyhow::Result<()> {
let db_filter = warp::any().map(move || db.clone()); let quote_get = warp::get()
let db_filter = warp::get().and(db_filter).and_then(handle); .and(warp::get())
.and(warp::any().map(move || db.clone()))
.then(handle_get_quote);
let tx_filter = warp::any().map(move || tx.clone()); let webhook_post = warp::path("webhook")
let tx_filter = warp::path("webhook")
.and(warp::post()) .and(warp::post())
.and(warp::body::json()) .and(warp::body::json())
.and(tx_filter) .and(warp::any().map(move || webhook_tx.clone()))
.and_then(handle_webhook); .then(handle_webhook);
let filter = db_filter.or(tx_filter); let filter = quote_get.or(webhook_post);
warp::serve(filter).run(listen).await; warp::serve(filter).run(listen).await;
Ok(()) Ok(())
} }
async fn handle(db: ExecutorConnection) -> Result<impl warp::Reply, warp::Rejection> { async fn handle_get_quote(_: ExecutorConnection) -> impl Reply {
if let Some((a, b)) = db.get_quote(None).await { reply::html(include_str!("res/quote_tmpl.html"))
Ok(warp::reply::with_status(
format!("{} {}", a, b),
warp::http::StatusCode::OK,
))
} else {
Ok(warp::reply::with_status(
"None".into(),
warp::http::StatusCode::NO_CONTENT,
))
}
} }
pub async fn handle_webhook( async fn handle_webhook(
json: serde_json::Value, json: serde_json::Value,
tx: Sender<String>, tx: Sender<String>,
) -> Result<impl warp::Reply, warp::Rejection> { ) -> impl Reply {
if json["commits"] != Null { if json["commits"] != Null {
let commits = json["commits"].as_array().unwrap(); let commits = json["commits"].as_array().unwrap();
let repo = &json["repository"]["full_name"].as_str().unwrap().trim(); let repo = &json["repository"]["full_name"].as_str().unwrap().trim();
@ -67,6 +58,5 @@ pub async fn handle_webhook(
.expect("Failed to send string to main thread"); .expect("Failed to send string to main thread");
} }
} }
warp::reply::with_status("Ok", warp::http::StatusCode::OK)
Ok(warp::reply::with_status("Ok", warp::http::StatusCode::OK))
} }