use crate::attach::{self, Staged};
use crate::db::{now, Db, State};
use crate::model::{Part, Revision, Thumbnail, User};
use crate::Error;
pub const MAX_BYTES: u64 = 1024 * 1024;
pub const MAX_EDGE: u32 = 1024;
pub const MEDIA_TYPE: &str = "image/png";
pub fn png_size(bytes: &[u8]) -> Result<(u32, u32), Error> {
const SIGNATURE: [u8; 8] = [0x89, b'P', b'N', b'G', b'\r', b'\n', 0x1a, b'\n'];
if bytes.len() < 24 || bytes[..8] != SIGNATURE || &bytes[12..16] != b"IHDR" {
return Err(Error::bad_request("a thumbnail must be a PNG image"));
}
let word = |at: usize| u32::from_be_bytes([bytes[at], bytes[at + 1], bytes[at + 2], bytes[at + 3]]);
let (width, height) = (word(16), word(20));
if width == 0 || height == 0 || width > MAX_EDGE || height > MAX_EDGE {
return Err(Error::bad_request(format!(
"a thumbnail is at most {MAX_EDGE}×{MAX_EDGE} pixels; this one is {width}×{height}"
)));
}
Ok((width, height))
}
pub fn current(revision: &Revision) -> Option<&Thumbnail> {
revision
.thumbnail
.as_ref()
.filter(|t| !revision.content_hash.is_empty() && t.content_hash == revision.content_hash)
}
pub fn of_part(part: &Part) -> Option<(&Revision, &Thumbnail)> {
part.revisions.iter().rev().find_map(|r| current(r).map(|t| (r, t)))
}
pub fn part_url(part: &Part) -> String {
of_part(part).map(|(_, t)| format!("/api/parts/{}/thumbnail?v={}", crate::identity::segment(&part.id), t.sha256)).unwrap_or_default()
}
pub fn revision_url(part_id: &str, revision: &Revision) -> String {
current(revision)
.map(|t| format!("/api/parts/{}/revisions/{}/thumbnail?v={}", crate::identity::segment(part_id), crate::identity::segment(&revision.id), t.sha256))
.unwrap_or_default()
}
#[derive(Debug, Clone, Default)]
pub struct Claim {
pub content_hash: String,
pub renderer: String,
}
pub(crate) struct Embedded {
staged: attach::Staged,
width: u32,
height: u32,
renderer: String,
}
impl Embedded {
pub(crate) fn place(&self, root: &std::path::Path, content_hash: &str, user: &str) -> Result<Thumbnail, Error> {
attach::place(root, &self.staged)?;
Ok(Thumbnail {
sha256: self.staged.sha256.clone(), size: self.staged.size,
width: self.width, height: self.height, content_hash: content_hash.into(),
renderer: self.renderer.clone(), uploaded_by: user.into(), uploaded_at: now(),
})
}
}
pub(crate) fn embedded(root: &std::path::Path, body: &str) -> Result<Option<Embedded>, Error> {
use base64::Engine;
let Ok(document) = serde_json::from_str::<serde_json::Value>(body) else { return Ok(None) };
let Some(image) = document.get("thumbnail").filter(|v| !v.is_null()) else { return Ok(None) };
if image.get("mimeType").and_then(|v| v.as_str()) != Some(MEDIA_TYPE) {
return Err(Error::bad_request("the embedded thumbnail must have mimeType image/png"));
}
let data = image.get("data").and_then(|v| v.as_str())
.ok_or_else(|| Error::bad_request("the embedded thumbnail needs base64 PNG data"))?;
if data.len() as u64 > MAX_BYTES.div_ceil(3) * 4 {
return Err(Error::bad_request("the embedded thumbnail exceeds 1 MiB"));
}
let bytes = base64::engine::general_purpose::STANDARD.decode(data)
.map_err(|_| Error::bad_request("the embedded thumbnail is not valid base64"))?;
if bytes.len() as u64 > MAX_BYTES { return Err(Error::bad_request("the embedded thumbnail exceeds 1 MiB")); }
let (width, height) = png_size(&bytes)?;
let renderer = image.get("renderer").and_then(|v| v.as_str()).unwrap_or("embedded-png").trim();
if renderer.is_empty() || renderer.len() > 64 { return Err(Error::bad_request("invalid embedded thumbnail renderer")); }
let mut upload = attach::Upload::start(root, MAX_BYTES).map_err(Error::internal)?;
upload.write(&bytes)?;
Ok(Some(Embedded { staged: upload.finish()?, width, height, renderer: renderer.into() }))
}
impl Db {
pub fn put_thumbnail(
&self,
user: &User,
part_key: &str,
revision_key: &str,
staged: Staged,
(width, height): (u32, u32),
claim: &Claim,
) -> Result<Thumbnail, Error> {
if !user.can_author() && !user.can_bake() {
return Err(Error::forbidden("a thumbnail is uploaded by an author or the bake worker"));
}
let renderer = claim.renderer.trim().to_string();
if renderer.is_empty() || renderer.len() > 64 {
return Err(Error::bad_request("name the renderer that made the thumbnail (renderer=…, at most 64 characters)"));
}
let root = self.root().to_path_buf();
let user_id = user.id.clone();
let (part_key, revision_key, claimed) = (part_key.to_string(), revision_key.to_string(), claim.content_hash.trim().to_string());
self.mutate(move |state| {
let part = state.part_by_id_or_number(&part_key).ok_or_else(|| Error::not_found("part"))?;
let (part_id, number) = (part.id.clone(), part.number.clone());
let revision = crate::bom::find_revision(part, &revision_key).ok_or_else(|| Error::not_found("revision"))?;
let revision_id = revision.id.clone();
if revision.content_hash.is_empty() {
return Err(Error::conflict(format!("{number} revision {} has no document to picture", revision.label)));
}
if claimed != revision.content_hash {
return Err(Error::conflict(format!(
"the thumbnail pictures document {}, but {number} revision {} is now {} — render it again",
short(&claimed),
revision.label,
short(&revision.content_hash)
)));
}
attach::place(&root, &staged)?;
let thumbnail = Thumbnail {
sha256: staged.sha256.clone(),
size: staged.size,
width,
height,
content_hash: claimed,
renderer,
uploaded_by: user_id,
uploaded_at: now(),
};
let part = state.parts.get_mut(&part_id).ok_or_else(|| Error::not_found("part"))?;
let revision = part.revision_mut(&revision_id).ok_or_else(|| Error::not_found("revision"))?;
let old = revision.thumbnail.replace(thumbnail.clone());
if let Some(old) = old.filter(|o| o.sha256 != thumbnail.sha256) {
attach::remove_if_unreferenced(state, &root, &old.sha256)?;
}
state.touch(crate::identity::document_key(&part_id, &revision_id));
Ok(thumbnail)
})
}
pub fn thumbnail(&self, part_key: &str, revision_key: &str) -> Result<Option<(String, Thumbnail)>, Error> {
self.read(|state: &State| {
let part = state.part_by_id_or_number(part_key).ok_or_else(|| Error::not_found("part"))?;
if revision_key.is_empty() {
return Ok(of_part(part).map(|(r, t)| (r.label.clone(), t.clone())));
}
let revision = crate::bom::find_revision(part, revision_key).ok_or_else(|| Error::not_found("revision"))?;
Ok(current(revision).map(|t| (revision.label.clone(), t.clone())))
})
}
}
fn short(hash: &str) -> &str {
if hash.is_empty() { "(none)" } else { &hash[..hash.len().min(12)] }
}