Compare commits
No commits in common. "996924582afe7500af7d1ef3ba6b1ad6b80ebc57" and "606620ae6a64b2b9b4a4b67bcf61a89d3373d67a" have entirely different histories.
996924582a
...
606620ae6a
2 changed files with 145 additions and 196 deletions
|
@ -1,2 +0,0 @@
|
||||||
tab_spaces = 2
|
|
||||||
use_field_init_shorthand = true
|
|
339
src/main.rs
339
src/main.rs
|
@ -1,246 +1,197 @@
|
||||||
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};
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use std::collections::{BTreeMap, HashMap};
|
use std::collections::{BTreeMap, HashMap};
|
||||||
use std::error::Error;
|
|
||||||
use std::fmt;
|
|
||||||
use std::fs::{File, OpenOptions};
|
use std::fs::{File, OpenOptions};
|
||||||
use std::io::Write;
|
use std::io::{Error, Write};
|
||||||
use std::sync::{Arc, RwLock};
|
use std::sync::{Arc, RwLock};
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
static DEFAULT_CONFIG: &[u8] = include_bytes!("../bunbun.default.toml");
|
static DEFAULT_CONFIG: &[u8] = include_bytes!("../bunbun.default.toml");
|
||||||
static CONFIG_FILE: &str = "bunbun.toml";
|
static CONFIG_FILE: &str = "bunbun.toml";
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
enum BunBunError {
|
|
||||||
IoError(std::io::Error),
|
|
||||||
ParseError(serde_yaml::Error),
|
|
||||||
WatchError(hotwatch::Error),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl fmt::Display for BunBunError {
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
||||||
match self {
|
|
||||||
BunBunError::IoError(e) => e.fmt(f),
|
|
||||||
BunBunError::ParseError(e) => e.fmt(f),
|
|
||||||
BunBunError::WatchError(e) => e.fmt(f),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Error for BunBunError {}
|
|
||||||
|
|
||||||
macro_rules! from_error {
|
|
||||||
($from:ty, $to:ident) => {
|
|
||||||
impl From<$from> for BunBunError {
|
|
||||||
fn from(e: $from) -> Self {
|
|
||||||
BunBunError::$to(e)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
from_error!(std::io::Error, IoError);
|
|
||||||
from_error!(serde_yaml::Error, ParseError);
|
|
||||||
from_error!(hotwatch::Error, WatchError);
|
|
||||||
|
|
||||||
#[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);
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
let mut template_args = HashMap::new();
|
// Reform args into url-safe string (probably want to go thru an actual parser)
|
||||||
template_args.insert("query", args);
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
match data.routes.get(command.unwrap()) {
|
let mut template_args = HashMap::new();
|
||||||
Some(template) => HttpResponse::Found()
|
template_args.insert("query", args);
|
||||||
.header(
|
|
||||||
header::LOCATION,
|
match data.routes.get(command.unwrap()) {
|
||||||
data
|
Some(template) => HttpResponse::Found()
|
||||||
.renderer
|
.header(
|
||||||
.render_template(template, &template_args)
|
header::LOCATION,
|
||||||
.unwrap(),
|
data.renderer
|
||||||
)
|
.render_template(template, &template_args)
|
||||||
.finish(),
|
.unwrap(),
|
||||||
None => match &data.default_route {
|
)
|
||||||
Some(route) => {
|
.finish(),
|
||||||
template_args.insert(
|
None => match &data.default_route {
|
||||||
"query",
|
Some(route) => {
|
||||||
format!(
|
template_args.insert(
|
||||||
"{}+{}",
|
"query",
|
||||||
command.unwrap(),
|
format!(
|
||||||
template_args.get("query").unwrap()
|
"{}+{}",
|
||||||
),
|
command.unwrap(),
|
||||||
);
|
template_args.get("query").unwrap()
|
||||||
HttpResponse::Found()
|
),
|
||||||
.header(
|
);
|
||||||
header::LOCATION,
|
HttpResponse::Found()
|
||||||
data
|
.header(
|
||||||
.renderer
|
header::LOCATION,
|
||||||
.render_template(data.routes.get(route).unwrap(), &template_args)
|
data.renderer
|
||||||
.unwrap(),
|
.render_template(data.routes.get(route).unwrap(), &template_args)
|
||||||
)
|
.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<(), BunBunError> {
|
fn main() -> Result<(), Error> {
|
||||||
let conf = read_config(CONFIG_FILE)?;
|
let config_file = match File::open(CONFIG_FILE) {
|
||||||
let renderer = compile_templates();
|
Ok(file) => file,
|
||||||
let state = Arc::from(RwLock::new(State {
|
Err(_) => {
|
||||||
public_address: conf.public_address,
|
eprintln!("Unable to find a {} file. Creating default!", CONFIG_FILE);
|
||||||
default_route: conf.default_route,
|
let mut fd = OpenOptions::new()
|
||||||
routes: conf.routes,
|
.write(true)
|
||||||
renderer,
|
.create_new(true)
|
||||||
}));
|
.open(CONFIG_FILE)
|
||||||
let state_ref = state.clone();
|
.expect("Unable to write to directory!");
|
||||||
|
fd.write_all(DEFAULT_CONFIG)?;
|
||||||
let mut watch = Hotwatch::new_with_custom_delay(Duration::from_millis(500))?;
|
File::open(CONFIG_FILE)?
|
||||||
|
|
||||||
watch.watch(CONFIG_FILE, move |e: Event| {
|
|
||||||
if let Event::Write(_) = e {
|
|
||||||
let mut state = state.write().unwrap();
|
|
||||||
match read_config(CONFIG_FILE) {
|
|
||||||
Ok(conf) => {
|
|
||||||
state.public_address = conf.public_address;
|
|
||||||
state.default_route = conf.default_route;
|
|
||||||
state.routes = conf.routes;
|
|
||||||
}
|
}
|
||||||
Err(e) => eprintln!("Config is malformed: {}", e),
|
};
|
||||||
}
|
|
||||||
}
|
|
||||||
})?;
|
|
||||||
|
|
||||||
HttpServer::new(move || {
|
let renderer = compile_templates();
|
||||||
App::new()
|
let conf: Config = serde_yaml::from_reader(config_file).unwrap();
|
||||||
.data(state_ref.clone())
|
let state = Arc::from(RwLock::new(State {
|
||||||
.service(hop)
|
public_address: conf.public_address,
|
||||||
.service(list)
|
default_route: conf.default_route,
|
||||||
.service(index)
|
routes: conf.routes,
|
||||||
.service(opensearch)
|
renderer: renderer,
|
||||||
})
|
}));
|
||||||
.bind(&conf.bind_address)?
|
let state_ref = state.clone();
|
||||||
.run()?;
|
|
||||||
|
|
||||||
Ok(())
|
let mut watch =
|
||||||
}
|
Hotwatch::new_with_custom_delay(Duration::from_millis(500)).expect("Failed to init watch");
|
||||||
|
|
||||||
fn read_config(config_file_path: &str) -> Result<Config, BunBunError> {
|
watch
|
||||||
let config_file = match File::open(config_file_path) {
|
.watch(CONFIG_FILE, move |e: Event| {
|
||||||
Ok(file) => file,
|
if let Event::Write(_) = e {
|
||||||
Err(_) => {
|
let config_file = File::open(CONFIG_FILE).unwrap();
|
||||||
eprintln!(
|
let conf: Config = serde_yaml::from_reader(config_file).unwrap();
|
||||||
"Unable to find a {} file. Creating default!",
|
let state = state.clone();
|
||||||
config_file_path
|
let mut state = state.write().unwrap();
|
||||||
);
|
state.public_address = conf.public_address;
|
||||||
let mut fd = OpenOptions::new()
|
state.default_route = conf.default_route;
|
||||||
.write(true)
|
state.routes = conf.routes;
|
||||||
.create_new(true)
|
}
|
||||||
.open(config_file_path)
|
})
|
||||||
.expect("Unable to write to directory!");
|
.expect("failed to watch");
|
||||||
fd.write_all(DEFAULT_CONFIG)?;
|
|
||||||
File::open(config_file_path)?
|
HttpServer::new(move || {
|
||||||
}
|
App::new()
|
||||||
};
|
.data(state_ref.clone())
|
||||||
Ok(serde_yaml::from_reader(config_file)?)
|
.service(hop)
|
||||||
|
.service(list)
|
||||||
|
.service(index)
|
||||||
|
.service(opensearch)
|
||||||
|
})
|
||||||
|
.bind(&conf.bind_address)?
|
||||||
|
.run()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn compile_templates() -> Handlebars {
|
fn compile_templates() -> Handlebars {
|
||||||
let mut handlebars = Handlebars::new();
|
let mut handlebars = Handlebars::new();
|
||||||
|
handlebars
|
||||||
macro_rules! register_template {
|
.register_template_string(
|
||||||
( $( $template:expr ),* ) => {
|
"index",
|
||||||
$(
|
String::from_utf8_lossy(include_bytes!("templates/index.hbs")),
|
||||||
handlebars
|
)
|
||||||
.register_template_string(
|
.unwrap();
|
||||||
$template,
|
handlebars
|
||||||
String::from_utf8_lossy(
|
.register_template_string(
|
||||||
include_bytes!(concat!("templates/", $template, ".hbs")))
|
"opensearch",
|
||||||
)
|
String::from_utf8_lossy(include_bytes!("templates/bunbunsearch.xml")),
|
||||||
.unwrap();
|
)
|
||||||
)*
|
.unwrap();
|
||||||
};
|
handlebars
|
||||||
}
|
.register_template_string(
|
||||||
|
"list",
|
||||||
register_template!("index", "list");
|
String::from_utf8_lossy(include_bytes!("templates/list.hbs")),
|
||||||
|
)
|
||||||
handlebars
|
.unwrap();
|
||||||
.register_template_string(
|
handlebars
|
||||||
"opensearch",
|
|
||||||
String::from_utf8_lossy(include_bytes!(concat!("templates/", "bunbunsearch.xml"))),
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
handlebars
|
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue