imgurx/src/main.rs

71 lines
3.0 KiB
Rust

use std::convert::Infallible;
use std::convert::TryInto;
use std::env;
use warp::Filter;
mod structs;
mod utils;
use reqwest::Client;
use tokio::runtime;
extern crate warp;
async fn handle_album(id: String, client: Client) -> Result<impl warp::Reply, Infallible> {
let (status_code, reply) = utils::generate_html(utils::get_album(client.clone(), &id).await);
Ok(warp::reply::with_status(
warp::reply::with_header(reply, "Content-Type", "text/html"),
status_code.try_into().unwrap(),
))
}
async fn handle_media(id: String, client: Client) -> Result<impl warp::Reply, Infallible> {
let (status_code, reply) = utils::generate_html(utils::get_media(client.clone(), &id).await);
Ok(warp::reply::with_status(
warp::reply::with_header(reply, "Content-Type", "text/html"),
status_code.try_into().unwrap(),
))
}
async fn async_main(port: u16) {
let client = Client::new();
let client = warp::any().map(move || client.clone());
let album_path = warp::path!("a" / String)
.and(client.clone())
.and_then(handle_album);
let gallery_path = warp::path!("gallery" / String)
.and(client.clone())
.and_then(handle_album);
let media_path = warp::path!(String).and(client).and_then(handle_media);
let root_handler = warp::path::end().map(|| warp::reply::html(
format!("<html><head><title>ImgurX v{0}</title><style>body {{ background-color: black; color: black; text-align: center; }}\ndiv {{ border: 1px solid #008; background: #eef; padding: 0.5em 1em 0.5em 1em; }}</style></head><body><div><b><a href=\"https://gitlab.com/blankX/imgurx\" style=\"text-decoration: none;\">ImgurX v{0}</a></b><br>An alternative JS-less Imgur frontend</div></body></html>", env!("CARGO_PKG_VERSION"))
));
let index_html_handler = warp::path("index.html").and(root_handler);
let index_htm_handler = warp::path("index.htm").and(root_handler);
let not_found_handler = warp::any().map(|| warp::reply::with_status(
warp::reply::html("<html><head><title>404: Not Found</title><style>body { background-color: black; color: white; text-align: center; }\ndiv { border: 1px solid #fcc; background: #fee; padding: 0.5em 1em 0.5em 1em; color: black; }</style></head><body><div><b>404: Not Found</b></div></body></html>"),
404.try_into().unwrap(),
));
let routes = warp::filters::method::get().and(
album_path
.or(gallery_path)
.or(index_html_handler)
.or(index_htm_handler)
.or(media_path)
.or(root_handler)
.or(not_found_handler),
);
eprintln!("Serving on 0.0.0.0:{}", port);
warp::serve(routes).run(([0u8, 0, 0, 0], port)).await;
}
fn main() {
let port = match env::var("PORT") {
Ok(port) => port.parse().unwrap(),
Err(env::VarError::NotPresent) => 8080,
Err(env::VarError::NotUnicode(_)) => panic!("Environment variable PORT isn't unicode"),
};
runtime::Builder::new_multi_thread()
.enable_all()
.build()
.unwrap()
.block_on(async_main(port));
}