Added API endpoint to edit configuration

This commit is contained in:
Antoine Gersant 2017-07-01 18:04:52 -07:00
parent c2efeb9e44
commit f42e40b766
6 changed files with 53 additions and 22 deletions

View file

@ -3,6 +3,7 @@ use iron::prelude::*;
use iron::headers::{Authorization, Basic};
use iron::{AroundMiddleware, Handler, status};
use mount::Mount;
use router::Router;
use params;
use secure_session::middleware::{SessionMiddleware, SessionConfig};
use secure_session::session::{SessionManager, ChaCha20Poly1305SessionManager};
@ -122,10 +123,16 @@ fn get_endpoints(db: Arc<DB>) -> Mount {
move |request: &mut Request| self::serve(request, db.deref()));
}
{
let db = db.clone();
auth_api_mount.mount("/settings/", move |request: &mut Request| {
self::get_config(request, db.deref())
});
let mut settings_router = Router::new();
let get_db = db.clone();
let put_db = db.clone();
settings_router.get("/",
move |request: &mut Request| self::get_config(request, get_db.deref()),
"get_settings");
settings_router.put("/",
move |request: &mut Request| self::put_config(request, put_db.deref()),
"put_config");
auth_api_mount.mount("/settings/", settings_router);
}
let mut auth_api_chain = Chain::new(auth_api_mount);
@ -339,3 +346,14 @@ fn get_config(_: &mut Request, db: &DB) -> IronResult<Response> {
};
Ok(Response::with((status::Ok, result_json)))
}
fn put_config(request: &mut Request, db: &DB) -> IronResult<Response> {
let input = request.get_ref::<params::Params>().unwrap();
let config = match input.find(&["config"]) {
Some(&params::Value::String(ref config)) => config,
_ => return Err(Error::from(ErrorKind::MissingConfig).into()),
};
let config = config::parse_json(config)?;
config::ammend(db, &config)?;
Ok(Response::with(status::Ok))
}

View file

@ -2,6 +2,7 @@ use core::ops::Deref;
use diesel;
use diesel::prelude::*;
use regex::Regex;
use serde_json;
use std::fs;
use std::io::Read;
use std::path;
@ -38,25 +39,33 @@ pub struct Config {
pub ydns: Option<DDNSConfig>,
}
pub fn parse(path: &path::Path) -> Result<Config> {
println!("Config file path: {}", path.to_string_lossy());
impl Config {
fn clean_paths(&mut self) -> Result<()> {
if let Some(ref mut mount_dirs) = self.mount_dirs {
for mount_dir in mount_dirs {
match clean_path_string(&mount_dir.source).to_str() {
Some(p) => mount_dir.source = p.to_owned(),
_ => bail!("Bad mount directory path"),
}
}
}
Ok(())
}
}
// Parse user config
pub fn parse_json(content: &str) -> Result<Config> {
let mut config = serde_json::from_str::<Config>(content)?;
config.clean_paths()?;
Ok(config)
}
pub fn parse_toml_file(path: &path::Path) -> Result<Config> {
println!("Config file path: {}", path.to_string_lossy());
let mut config_file = fs::File::open(path)?;
let mut config_file_content = String::new();
config_file.read_to_string(&mut config_file_content)?;
let mut config = toml::de::from_str::<Config>(config_file_content.as_str())?;
// Clean path
if let Some(ref mut mount_dirs) = config.mount_dirs {
for mount_dir in mount_dirs {
match clean_path_string(&mount_dir.source).to_str() {
Some(p) => mount_dir.source = p.to_owned(),
_ => bail!("Bad mount directory path"),
}
}
}
let mut config = toml::de::from_str::<Config>(&config_file_content)?;
config.clean_paths()?;
Ok(config)
}

View file

@ -74,7 +74,7 @@ impl ConnectionSource for DB {
fn _get_test_db(name: &str) -> DB {
use config;
let config_path = Path::new("test/config.toml");
let config = config::parse(&config_path).unwrap();
let config = config::parse_toml_file(&config_path).unwrap();
let mut db_path = PathBuf::new();
db_path.push("test");

View file

@ -10,6 +10,7 @@ use iron::status::Status;
use lewton;
use metaflac;
use regex;
use serde_json;
use std;
use toml;
@ -26,6 +27,7 @@ error_chain! {
Id3(id3::Error);
Image(image::ImageError);
Io(std::io::Error);
Json(serde_json::Error);
Time(std::time::SystemTimeError);
Toml(toml::de::Error);
Regex(regex::Error);
@ -37,6 +39,7 @@ error_chain! {
AuthenticationRequired {}
MissingUsername {}
MissingPassword {}
MissingConfig {}
IncorrectCredentials {}
CannotServeDirectory {}
UnsupportedFileType {}

View file

@ -546,7 +546,7 @@ pub fn get_recent_albums<T>(db: &T, count: i64) -> Result<Vec<Directory>>
fn _get_test_db(name: &str) -> DB {
use config;
let config_path = Path::new("test/config.toml");
let config = config::parse(&config_path).unwrap();
let config = config::parse_toml_file(&config_path).unwrap();
let mut db_path = PathBuf::new();
db_path.push("test");

View file

@ -22,6 +22,7 @@ extern crate rand;
extern crate reqwest;
extern crate regex;
extern crate ring;
extern crate router;
extern crate secure_session;
extern crate serde;
#[macro_use]
@ -118,7 +119,7 @@ fn run() -> Result<()> {
let config_file_name = matches.opt_str("c");
let config_file_path = config_file_name.map(|p| Path::new(p.as_str()).to_path_buf());
if let Some(path) = config_file_path {
let config = config::parse(&path)?;
let config = config::parse_toml_file(&path)?;
config::overwrite(db.deref(), &config)?;
}