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={}", part.id, t.sha256)).unwrap_or_default()
}
pub fn revision_url(part_id: &str, revision: &Revision) -> String {
current(revision)
.map(|t| format!("/api/parts/{part_id}/revisions/{}/thumbnail?v={}", revision.id, t.sha256))
.unwrap_or_default()
}
#[derive(Debug, Clone, Default)]
pub struct Claim {
pub content_hash: String,
pub renderer: String,
}
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)?;
}
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)] }
}