use compmd_pack::{FilePath, Place};
use http::Method;
use crate::refusal::Refusal;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Route {
Frame(FilePath),
Pack(Place),
Refused(Refusal),
}
#[must_use]
pub fn route(method: &Method, path: &str, hash: &str) -> Route {
if method != Method::GET {
return Route::Refused(Refusal::ONLY_GET);
}
file_of(path, hash).unwrap_or(Route::Refused(Refusal::NOT_SERVED))
}
fn file_of(path: &str, hash: &str) -> Option<Route> {
let decoded = path
.strip_prefix('/')?
.split('/')
.map(decoded)
.collect::<Option<Vec<String>>>()?;
let parts: Vec<&str> = decoded.iter().map(String::as_str).collect();
match parts.as_slice() {
["frames", given, file @ ..] if *given == hash => {
FilePath::new(file.join("/")).ok().map(Route::Frame)
}
["packs", place @ ..] => Place::from_parts(place).map(Route::Pack),
_ => None,
}
}
fn decoded(segment: &str) -> Option<String> {
let bytes = segment.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut at = 0;
while let Some(&byte) = bytes.get(at) {
if byte == b'%' {
let hex = bytes.get(at + 1..at + 3)?;
if !hex.iter().all(u8::is_ascii_hexdigit) {
return None;
}
out.push(u8::from_str_radix(std::str::from_utf8(hex).ok()?, 16).ok()?);
at += 3;
} else {
out.push(byte);
at += 1;
}
}
String::from_utf8(out)
.ok()
.filter(|text| !text.contains('/'))
}