This commit is contained in:
Edward Shen 2019-12-21 14:21:13 -05:00
parent 64aec75659
commit be505480c5
Signed by: edward
GPG key ID: F350507060ED6C90
2 changed files with 149 additions and 145 deletions

2
rustfmt.toml Normal file
View file

@ -0,0 +1,2 @@
tab_spaces = 2
use_field_init_shorthand = true

View file

@ -1,8 +1,8 @@
use actix_web::{ use actix_web::{
get, get,
http::header, http::header,
web::{Data, Query}, web::{Data, Query},
App, HttpResponse, HttpServer, Responder, App, HttpResponse, HttpServer, Responder,
}; };
use handlebars::Handlebars; use handlebars::Handlebars;
use hotwatch::{Event, Hotwatch}; use hotwatch::{Event, Hotwatch};
@ -18,184 +18,186 @@ static CONFIG_FILE: &str = "bunbun.toml";
#[get("/ls")] #[get("/ls")]
fn list(data: Data<Arc<RwLock<State>>>) -> impl Responder { fn list(data: Data<Arc<RwLock<State>>>) -> impl Responder {
let data = data.read().unwrap(); let data = data.read().unwrap();
HttpResponse::Ok().body(data.renderer.render("list", &data.routes).unwrap()) HttpResponse::Ok().body(data.renderer.render("list", &data.routes).unwrap())
} }
#[derive(Deserialize)] #[derive(Deserialize)]
struct SearchQuery { struct SearchQuery {
to: String, to: String,
} }
#[get("/hop")] #[get("/hop")]
fn hop(data: Data<Arc<RwLock<State>>>, query: Query<SearchQuery>) -> impl Responder { fn hop(data: Data<Arc<RwLock<State>>>, query: Query<SearchQuery>) -> impl Responder {
let data = data.read().unwrap(); let data = data.read().unwrap();
let mut raw_args = query.to.split_ascii_whitespace(); let mut raw_args = query.to.split_ascii_whitespace();
let command = raw_args.next(); let command = raw_args.next();
if command.is_none() { if command.is_none() {
return HttpResponse::NotFound().body("not found"); return HttpResponse::NotFound().body("not found");
}
// Reform args into url-safe string (probably want to go thru an actual parser)
let mut args = String::new();
if let Some(first_arg) = raw_args.next() {
args.push_str(first_arg);
for arg in raw_args {
args.push_str("+");
args.push_str(arg);
} }
}
// Reform args into url-safe string (probably want to go thru an actual parser) let mut template_args = HashMap::new();
let mut args = String::new(); template_args.insert("query", args);
if let Some(first_arg) = raw_args.next() {
args.push_str(first_arg);
for arg in raw_args {
args.push_str("+");
args.push_str(arg);
}
}
let mut template_args = HashMap::new(); match data.routes.get(command.unwrap()) {
template_args.insert("query", args); Some(template) => HttpResponse::Found()
.header(
match data.routes.get(command.unwrap()) { header::LOCATION,
Some(template) => HttpResponse::Found() data
.header( .renderer
header::LOCATION, .render_template(template, &template_args)
data.renderer .unwrap(),
.render_template(template, &template_args) )
.unwrap(), .finish(),
) None => match &data.default_route {
.finish(), Some(route) => {
None => match &data.default_route { template_args.insert(
Some(route) => { "query",
template_args.insert( format!(
"query", "{}+{}",
format!( command.unwrap(),
"{}+{}", template_args.get("query").unwrap()
command.unwrap(), ),
template_args.get("query").unwrap() );
), HttpResponse::Found()
); .header(
HttpResponse::Found() header::LOCATION,
.header( data
header::LOCATION, .renderer
data.renderer .render_template(data.routes.get(route).unwrap(), &template_args)
.render_template(data.routes.get(route).unwrap(), &template_args) .unwrap(),
.unwrap(), )
) .finish()
.finish() }
} None => HttpResponse::NotFound().body("not found"),
None => HttpResponse::NotFound().body("not found"), },
}, }
}
} }
#[get("/")] #[get("/")]
fn index(data: Data<Arc<RwLock<State>>>) -> impl Responder { fn index(data: Data<Arc<RwLock<State>>>) -> impl Responder {
let data = data.read().unwrap(); let data = data.read().unwrap();
let mut template_args = HashMap::new(); let mut template_args = HashMap::new();
template_args.insert("hostname", &data.public_address); template_args.insert("hostname", &data.public_address);
HttpResponse::Ok().body(data.renderer.render("index", &template_args).unwrap()) HttpResponse::Ok().body(data.renderer.render("index", &template_args).unwrap())
} }
#[get("/bunbunsearch.xml")] #[get("/bunbunsearch.xml")]
fn opensearch(data: Data<Arc<RwLock<State>>>) -> impl Responder { fn opensearch(data: Data<Arc<RwLock<State>>>) -> impl Responder {
let data = data.read().unwrap(); let data = data.read().unwrap();
let mut template_args = HashMap::new(); let mut template_args = HashMap::new();
template_args.insert("hostname", &data.public_address); template_args.insert("hostname", &data.public_address);
HttpResponse::Ok() HttpResponse::Ok()
.header( .header(
header::CONTENT_TYPE, header::CONTENT_TYPE,
"application/opensearchdescription+xml", "application/opensearchdescription+xml",
) )
.body(data.renderer.render("opensearch", &template_args).unwrap()) .body(data.renderer.render("opensearch", &template_args).unwrap())
} }
#[derive(Deserialize)] #[derive(Deserialize)]
struct Config { struct Config {
bind_address: String, bind_address: String,
public_address: String, public_address: String,
default_route: Option<String>, default_route: Option<String>,
routes: BTreeMap<String, String>, routes: BTreeMap<String, String>,
} }
struct State { struct State {
public_address: String, public_address: String,
default_route: Option<String>, default_route: Option<String>,
routes: BTreeMap<String, String>, routes: BTreeMap<String, String>,
renderer: Handlebars, renderer: Handlebars,
} }
fn main() -> Result<(), Error> { fn main() -> Result<(), Error> {
let conf = read_config(CONFIG_FILE)?; let conf = read_config(CONFIG_FILE)?;
let renderer = compile_templates(); let renderer = compile_templates();
let state = Arc::from(RwLock::new(State { let state = Arc::from(RwLock::new(State {
public_address: conf.public_address, public_address: conf.public_address,
default_route: conf.default_route, default_route: conf.default_route,
routes: conf.routes, routes: conf.routes,
renderer, renderer,
})); }));
let state_ref = state.clone(); let state_ref = state.clone();
let mut watch = let mut watch =
Hotwatch::new_with_custom_delay(Duration::from_millis(500)).expect("Failed to init watch"); Hotwatch::new_with_custom_delay(Duration::from_millis(500)).expect("Failed to init watch");
watch watch
.watch(CONFIG_FILE, move |e: Event| { .watch(CONFIG_FILE, move |e: Event| {
if let Event::Write(_) = e { if let Event::Write(_) = e {
let mut state = state.write().unwrap(); let mut state = state.write().unwrap();
let conf = read_config(CONFIG_FILE).unwrap(); let conf = read_config(CONFIG_FILE).unwrap();
state.public_address = conf.public_address; state.public_address = conf.public_address;
state.default_route = conf.default_route; state.default_route = conf.default_route;
state.routes = conf.routes; state.routes = conf.routes;
} }
})
.expect("failed to watch");
HttpServer::new(move || {
App::new()
.data(state_ref.clone())
.service(hop)
.service(list)
.service(index)
.service(opensearch)
}) })
.bind(&conf.bind_address)? .expect("failed to watch");
.run()
HttpServer::new(move || {
App::new()
.data(state_ref.clone())
.service(hop)
.service(list)
.service(index)
.service(opensearch)
})
.bind(&conf.bind_address)?
.run()
} }
fn read_config(config_file_path: &str) -> Result<Config, Error> { fn read_config(config_file_path: &str) -> Result<Config, Error> {
let config_file = match File::open(config_file_path) { let config_file = match File::open(config_file_path) {
Ok(file) => file, Ok(file) => file,
Err(_) => { Err(_) => {
eprintln!( eprintln!(
"Unable to find a {} file. Creating default!", "Unable to find a {} file. Creating default!",
config_file_path config_file_path
); );
let mut fd = OpenOptions::new() let mut fd = OpenOptions::new()
.write(true) .write(true)
.create_new(true) .create_new(true)
.open(config_file_path) .open(config_file_path)
.expect("Unable to write to directory!"); .expect("Unable to write to directory!");
fd.write_all(DEFAULT_CONFIG)?; fd.write_all(DEFAULT_CONFIG)?;
File::open(config_file_path)? File::open(config_file_path)?
} }
}; };
Ok(serde_yaml::from_reader(config_file).unwrap()) Ok(serde_yaml::from_reader(config_file).unwrap())
} }
fn compile_templates() -> Handlebars { fn compile_templates() -> Handlebars {
let mut handlebars = Handlebars::new(); let mut handlebars = Handlebars::new();
handlebars handlebars
.register_template_string( .register_template_string(
"index", "index",
String::from_utf8_lossy(include_bytes!("templates/index.hbs")), String::from_utf8_lossy(include_bytes!("templates/index.hbs")),
) )
.unwrap(); .unwrap();
handlebars handlebars
.register_template_string( .register_template_string(
"opensearch", "opensearch",
String::from_utf8_lossy(include_bytes!("templates/bunbunsearch.xml")), String::from_utf8_lossy(include_bytes!("templates/bunbunsearch.xml")),
) )
.unwrap(); .unwrap();
handlebars handlebars
.register_template_string( .register_template_string(
"list", "list",
String::from_utf8_lossy(include_bytes!("templates/list.hbs")), String::from_utf8_lossy(include_bytes!("templates/list.hbs")),
) )
.unwrap(); .unwrap();
handlebars handlebars
} }