1use crate::attach::{self, Staged};
22use crate::db::{now, Db, State};
23use crate::model::{Part, Revision, Thumbnail, User};
24use crate::Error;
25
26pub const MAX_BYTES: u64 = 1024 * 1024;
28
29pub const MAX_EDGE: u32 = 1024;
31
32pub const MEDIA_TYPE: &str = "image/png";
34
35pub fn png_size(bytes: &[u8]) -> Result<(u32, u32), Error> {
37 const SIGNATURE: [u8; 8] = [0x89, b'P', b'N', b'G', b'\r', b'\n', 0x1a, b'\n'];
38 if bytes.len() < 24 || bytes[..8] != SIGNATURE || &bytes[12..16] != b"IHDR" {
39 return Err(Error::bad_request("a thumbnail must be a PNG image"));
40 }
41 let word = |at: usize| u32::from_be_bytes([bytes[at], bytes[at + 1], bytes[at + 2], bytes[at + 3]]);
42 let (width, height) = (word(16), word(20));
43 if width == 0 || height == 0 || width > MAX_EDGE || height > MAX_EDGE {
44 return Err(Error::bad_request(format!(
45 "a thumbnail is at most {MAX_EDGE}×{MAX_EDGE} pixels; this one is {width}×{height}"
46 )));
47 }
48 Ok((width, height))
49}
50
51pub fn current(revision: &Revision) -> Option<&Thumbnail> {
53 revision
54 .thumbnail
55 .as_ref()
56 .filter(|t| !revision.content_hash.is_empty() && t.content_hash == revision.content_hash)
57}
58
59pub fn of_part(part: &Part) -> Option<(&Revision, &Thumbnail)> {
62 part.revisions.iter().rev().find_map(|r| current(r).map(|t| (r, t)))
63}
64
65pub fn part_url(part: &Part) -> String {
68 of_part(part).map(|(_, t)| format!("/api/parts/{}/thumbnail?v={}", crate::identity::segment(&part.id), t.sha256)).unwrap_or_default()
69}
70
71pub fn revision_url(part_id: &str, revision: &Revision) -> String {
73 current(revision)
74 .map(|t| format!("/api/parts/{}/revisions/{}/thumbnail?v={}", crate::identity::segment(part_id), crate::identity::segment(&revision.id), t.sha256))
75 .unwrap_or_default()
76}
77
78#[derive(Debug, Clone, Default)]
80pub struct Claim {
81 pub content_hash: String,
83 pub renderer: String,
84}
85
86pub(crate) struct Embedded {
89 staged: attach::Staged,
90 width: u32,
91 height: u32,
92 renderer: String,
93}
94
95impl Embedded {
96 pub(crate) fn place(&self, root: &std::path::Path, content_hash: &str, user: &str) -> Result<Thumbnail, Error> {
97 attach::place(root, &self.staged)?;
98 Ok(Thumbnail {
99 sha256: self.staged.sha256.clone(), size: self.staged.size,
100 width: self.width, height: self.height, content_hash: content_hash.into(),
101 renderer: self.renderer.clone(), uploaded_by: user.into(), uploaded_at: now(),
102 })
103 }
104}
105
106pub(crate) fn embedded(root: &std::path::Path, body: &str) -> Result<Option<Embedded>, Error> {
107 use base64::Engine;
108 let Ok(document) = serde_json::from_str::<serde_json::Value>(body) else { return Ok(None) };
109 let Some(image) = document.get("thumbnail").filter(|v| !v.is_null()) else { return Ok(None) };
110 if image.get("mimeType").and_then(|v| v.as_str()) != Some(MEDIA_TYPE) {
111 return Err(Error::bad_request("the embedded thumbnail must have mimeType image/png"));
112 }
113 let data = image.get("data").and_then(|v| v.as_str())
114 .ok_or_else(|| Error::bad_request("the embedded thumbnail needs base64 PNG data"))?;
115 if data.len() as u64 > MAX_BYTES.div_ceil(3) * 4 {
116 return Err(Error::bad_request("the embedded thumbnail exceeds 1 MiB"));
117 }
118 let bytes = base64::engine::general_purpose::STANDARD.decode(data)
119 .map_err(|_| Error::bad_request("the embedded thumbnail is not valid base64"))?;
120 if bytes.len() as u64 > MAX_BYTES { return Err(Error::bad_request("the embedded thumbnail exceeds 1 MiB")); }
121 let (width, height) = png_size(&bytes)?;
122 let renderer = image.get("renderer").and_then(|v| v.as_str()).unwrap_or("embedded-png").trim();
123 if renderer.is_empty() || renderer.len() > 64 { return Err(Error::bad_request("invalid embedded thumbnail renderer")); }
124 let mut upload = attach::Upload::start(root, MAX_BYTES).map_err(Error::internal)?;
125 upload.write(&bytes)?;
126 Ok(Some(Embedded { staged: upload.finish()?, width, height, renderer: renderer.into() }))
127}
128
129impl Db {
130 pub fn put_thumbnail(
134 &self,
135 user: &User,
136 part_key: &str,
137 revision_key: &str,
138 staged: Staged,
139 (width, height): (u32, u32),
140 claim: &Claim,
141 ) -> Result<Thumbnail, Error> {
142 if !user.can_author() && !user.can_bake() {
143 return Err(Error::forbidden("a thumbnail is uploaded by an author or the bake worker"));
144 }
145 let renderer = claim.renderer.trim().to_string();
146 if renderer.is_empty() || renderer.len() > 64 {
147 return Err(Error::bad_request("name the renderer that made the thumbnail (renderer=…, at most 64 characters)"));
148 }
149 let root = self.root().to_path_buf();
150 let user_id = user.id.clone();
151 let (part_key, revision_key, claimed) = (part_key.to_string(), revision_key.to_string(), claim.content_hash.trim().to_string());
152 self.mutate(move |state| {
153 let part = state.part_by_id_or_number(&part_key).ok_or_else(|| Error::not_found("part"))?;
154 let (part_id, number) = (part.id.clone(), part.number.clone());
155 let revision = crate::bom::find_revision(part, &revision_key).ok_or_else(|| Error::not_found("revision"))?;
156 let revision_id = revision.id.clone();
157 if revision.content_hash.is_empty() {
158 return Err(Error::conflict(format!("{number} revision {} has no document to picture", revision.label)));
159 }
160 if claimed != revision.content_hash {
161 return Err(Error::conflict(format!(
162 "the thumbnail pictures document {}, but {number} revision {} is now {} — render it again",
163 short(&claimed),
164 revision.label,
165 short(&revision.content_hash)
166 )));
167 }
168 attach::place(&root, &staged)?;
169 let thumbnail = Thumbnail {
170 sha256: staged.sha256.clone(),
171 size: staged.size,
172 width,
173 height,
174 content_hash: claimed,
175 renderer,
176 uploaded_by: user_id,
177 uploaded_at: now(),
178 };
179 let part = state.parts.get_mut(&part_id).ok_or_else(|| Error::not_found("part"))?;
180 let revision = part.revision_mut(&revision_id).ok_or_else(|| Error::not_found("revision"))?;
181 let old = revision.thumbnail.replace(thumbnail.clone());
182 if let Some(old) = old.filter(|o| o.sha256 != thumbnail.sha256) {
183 attach::remove_if_unreferenced(state, &root, &old.sha256)?;
184 }
185 state.touch(crate::identity::document_key(&part_id, &revision_id));
188 Ok(thumbnail)
189 })
190 }
191
192 pub fn thumbnail(&self, part_key: &str, revision_key: &str) -> Result<Option<(String, Thumbnail)>, Error> {
196 self.read(|state: &State| {
197 let part = state.part_by_id_or_number(part_key).ok_or_else(|| Error::not_found("part"))?;
198 if revision_key.is_empty() {
199 return Ok(of_part(part).map(|(r, t)| (r.label.clone(), t.clone())));
200 }
201 let revision = crate::bom::find_revision(part, revision_key).ok_or_else(|| Error::not_found("revision"))?;
202 Ok(current(revision).map(|t| (revision.label.clone(), t.clone())))
203 })
204 }
205}
206
207fn short(hash: &str) -> &str {
208 if hash.is_empty() { "(none)" } else { &hash[..hash.len().min(12)] }
209}