use std::fs;
use std::path::Path;
use serde::Deserialize;
use crate::embedded;
use crate::files::Files;
pub const FRAMES_JSON: &str = "frames.json";
pub const PREFIX: &str = "/frames/";
#[derive(Deserialize)]
struct Named {
hash: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Frames(Option<Build>);
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Build {
pub hash: String,
pub files: Files,
}
impl Frames {
#[must_use]
pub fn embedded() -> Self {
Self::embedded_as(embedded::HASH, embedded::FILES)
}
fn embedded_as(hash: Option<&str>, files: &'static [(&'static str, &'static [u8])]) -> Self {
Self(hash.map(|hash| Build {
hash: hash.to_owned(),
files: Files::Embedded(files),
}))
}
#[must_use]
pub fn read(folder: &Path) -> Self {
let named = fs::read_to_string(folder.join(FRAMES_JSON))
.ok()
.and_then(|text| serde_json::from_str::<Named>(&text).ok());
Self(
named
.filter(|named| is_hash(&named.hash))
.map(|named| Build {
files: Files::Folder(folder.join(&named.hash)),
hash: named.hash,
}),
)
}
#[must_use]
pub const fn none() -> Self {
Self(None)
}
#[must_use]
pub const fn build(&self) -> Option<&Build> {
self.0.as_ref()
}
#[must_use]
pub fn base(&self, scheme: &str) -> Option<String> {
self.base_over(scheme, OVER_HTTP)
}
fn base_over(&self, scheme: &str, over_http: bool) -> Option<String> {
let build = self.build()?;
let origin = if over_http {
format!("http://{scheme}.localhost")
} else {
format!("{scheme}://localhost")
};
Some(format!("{origin}{PREFIX}{}/", build.hash))
}
}
const OVER_HTTP: bool = cfg!(any(windows, target_os = "android"));
fn is_hash(name: &str) -> bool {
name.len() == 16
&& name
.bytes()
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
}
#[cfg(test)]
pub(crate) mod tests;