#[macro_use]
extern crate rocket;
mod cache;
mod config;
mod http_headers;
#[cfg(test)]
mod tests;
mod tile_request;
use cache::Cache;
use cache::CachedFile;
use config::Config;
use figment::Figment;
use rocket::Build;
use rocket::Request;
use rocket::Rocket;
use rocket::State;
use rocket_etag_if_none_match::EtagIfNoneMatch;
use std::env;
use tile_request::WmtsRequest;
use tile_request::XyzRequest;
#[catch(404)]
fn general_not_found(req: &Request) -> String {
format!("Sorry, '{}' is not a valid path.", req.uri())
}
#[get("/wmts/<alias>?<request..>")]
pub async fn wmts_tile(
app_cache: &State<Cache>,
etag_if_none_match: EtagIfNoneMatch<'_>,
alias: &str,
request: WmtsRequest,
) -> Option<CachedFile> {
let req = request.with_alias(alias);
app_cache
.get_or_download_wmts(etag_if_none_match, req)
.await
.ok()
}
#[catch(404)]
fn wmts_tile_not_found(req: &Request) -> String {
format!("Sorry, the WMTS tile for '{}' was not found.", req.uri())
}
#[get("/xyz/<alias>/<a>/<x>/<y>/<z>")]
pub async fn xyz_tile<'a>(
app_cache: &State<Cache>,
etag_if_none_match: EtagIfNoneMatch<'_>,
alias: &str,
a: &str,
x: &str,
y: &str,
z: &str,
) -> Option<CachedFile> {
let request = XyzRequest::new(alias, a, x, y, z);
app_cache
.get_or_download_xyz(etag_if_none_match, request)
.await
.ok()
}
#[catch(404)]
fn xyz_tile_not_found(req: &Request) -> String {
format!("Sorry, the XYZ tile for '{}' was not found.", req.uri())
}
#[get("/")]
fn index() -> &'static str {
"Hello, there is nothing here! Read the fully described manual ;)"
}
#[launch]
fn rocket() -> _ {
match run(env::args().collect()) {
Ok(r) => r,
Err(e) => panic!("Error while launching: {}", e),
}
}
fn run(args: Vec<String>) -> Result<Rocket<Build>, String> {
if let Some(filepath) = args.get(1) {
let app_config: Config = Config::from_file(filepath);
let cache: Cache = Cache::new(app_config.clone());
dbg!(app_config.clone());
let new_figment = Figment::new()
.join(("ident", false)) .join(("port", app_config.port));
let figment = rocket::Config::figment().merge(new_figment);
Ok(rocket::custom(figment)
.attach(http_headers::CacheControl)
.attach(http_headers::Cors)
.manage(cache)
.mount("/", routes![index, wmts_tile, xyz_tile])
.register("/", catchers![general_not_found])
.register("/wmts", catchers![wmts_tile_not_found])
.register("/xyz", catchers![xyz_tile_not_found]))
} else {
Err("No configuration!".to_string())
}
}