use compmd_pack::{FilePath, Place};
use http::header::{self, HeaderValue};
use http::{Method, Request, Response, StatusCode};
use crate::bundle::Bundle;
use crate::content_type::content_type;
use crate::store::Store;
const HEADERS: [(&str, &str); 5] = [
("content-security-policy", "sandbox allow-scripts"),
(ALLOW_ORIGIN, "*"),
("access-control-expose-headers", "*"),
("x-content-type-options", "nosniff"),
("cache-control", "max-age=31536000, immutable"),
];
const ALLOW_ORIGIN: &str = "access-control-allow-origin";
const NOT_SERVED: &str = "not a file of the frames or packs this host serves";
const ONLY_GET: &str = "the frames and packs are only read, with GET";
pub fn respond<B>(bundle: &Bundle, store: &dyn Store, request: &Request<B>) -> Response<Vec<u8>> {
if request.method() != Method::GET {
return refused(StatusCode::METHOD_NOT_ALLOWED, ONLY_GET);
}
let path = request.uri().path();
file(bundle, store, path).map_or_else(
|| refused(StatusCode::NOT_FOUND, NOT_SERVED),
|(body, path)| served(&path, body),
)
}
fn file(bundle: &Bundle, store: &dyn Store, path: &str) -> Option<(Vec<u8>, FilePath)> {
let parts: Vec<&str> = path.strip_prefix('/')?.split('/').collect();
match parts.as_slice() {
["frames", hash, file @ ..] if *hash == bundle.manifest().frames.hash.as_str() => {
let path = FilePath::new(file.join("/")).ok()?;
Some((bundle.frame_file(&path)?, path))
}
["packs", place @ ..] => {
let place = Place::from_parts(place)?;
let body = bundle.pack_file(&place).or_else(|| store.file(&place))?;
Some((body, place.path))
}
_ => None,
}
}
fn served(path: &FilePath, body: Vec<u8>) -> Response<Vec<u8>> {
let mut response = with_type(StatusCode::OK, content_type(path.as_str()), body);
let headers = response.headers_mut();
for (name, value) in HEADERS {
headers.insert(name, HeaderValue::from_static(value));
}
response
}
fn refused(status: StatusCode, why: &str) -> Response<Vec<u8>> {
let mut response = with_type(status, "text/plain; charset=utf-8", why.as_bytes().to_vec());
response
.headers_mut()
.insert(ALLOW_ORIGIN, HeaderValue::from_static("*"));
response
}
fn with_type(status: StatusCode, kind: &'static str, body: Vec<u8>) -> Response<Vec<u8>> {
let mut response = Response::new(body);
*response.status_mut() = status;
response
.headers_mut()
.insert(header::CONTENT_TYPE, HeaderValue::from_static(kind));
response
}
#[cfg(test)]
mod tests;