brep_plm/api/
thumbnails.rs1use axum::body::Body;
14use axum::extract::{Path, Query, State};
15use axum::http::{header, HeaderMap, HeaderValue, StatusCode};
16use axum::response::{IntoResponse, Response};
17use axum::Json;
18use serde::Deserialize;
19use serde_json::{json, Value};
20
21use super::{blocking, require_user, Shared};
22use crate::thumbnail::{self, Claim};
23use crate::Error;
24
25#[derive(Debug, Deserialize, Default)]
26pub struct PutQuery {
27 #[serde(default)]
28 pub content_hash: String,
29 #[serde(default)]
30 pub renderer: String,
31}
32
33pub async fn put(
35 State(db): State<Shared>,
36 headers: HeaderMap,
37 Path((id, rev)): Path<(String, String)>,
38 Query(query): Query<PutQuery>,
39 body: Body,
40) -> Result<Json<Value>, Error> {
41 let user = require_user(&db, &headers)?;
42 if !user.can_author() && !user.can_bake() {
43 return Err(Error::forbidden("a thumbnail is uploaded by an author or the bake worker"));
44 }
45 let bytes = axum::body::to_bytes(body, thumbnail::MAX_BYTES as usize).await.map_err(|_| Error {
46 status: StatusCode::PAYLOAD_TOO_LARGE,
47 message: format!("a thumbnail is at most {} KB", thumbnail::MAX_BYTES / 1024),
48 })?;
49 let size = thumbnail::png_size(&bytes)?;
50 let mut upload = db.start_upload()?;
51 upload.write(&bytes)?;
52 let staged = upload.finish()?;
53 let claim = Claim { content_hash: query.content_hash, renderer: query.renderer };
54 let kept = blocking(move || db.put_thumbnail(&user, &id, &rev, staged, size, &claim)).await?;
55 Ok(Json(json!({ "ok": true, "thumbnail": kept })))
56}
57
58#[derive(Debug, Deserialize, Default)]
59pub struct GetQuery {
60 #[serde(default)]
63 pub v: String,
64}
65
66pub async fn get_revision(
68 State(db): State<Shared>,
69 headers: HeaderMap,
70 Path((id, rev)): Path<(String, String)>,
71 Query(query): Query<GetQuery>,
72) -> Result<Response, Error> {
73 require_user(&db, &headers)?;
74 let found = db.thumbnail(&id, &rev)?;
75 serve(&db, &headers, found, &query.v).await
76}
77
78pub async fn get_part(
80 State(db): State<Shared>,
81 headers: HeaderMap,
82 Path(id): Path<String>,
83 Query(query): Query<GetQuery>,
84) -> Result<Response, Error> {
85 require_user(&db, &headers)?;
86 let found = db.thumbnail(&id, "")?;
87 serve(&db, &headers, found, &query.v).await
88}
89
90async fn serve(
91 db: &Shared,
92 headers: &HeaderMap,
93 found: Option<(String, crate::model::Thumbnail)>,
94 asked: &str,
95) -> Result<Response, Error> {
96 let Some((label, t)) = found else {
97 let mut none = StatusCode::NO_CONTENT.into_response();
98 none.headers_mut().insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"));
99 return Ok(none);
100 };
101 let etag = format!("\"{}\"", t.sha256);
102 let cache = if asked == t.sha256 { "private, max-age=31536000, immutable" } else { "private, no-cache" };
103 let matches = headers
104 .get(header::IF_NONE_MATCH)
105 .and_then(|v| v.to_str().ok())
106 .is_some_and(|v| v.split(',').any(|tag| tag.trim() == etag || tag.trim() == "*"));
107 let mut response = if matches {
108 StatusCode::NOT_MODIFIED.into_response()
109 } else {
110 let bytes = tokio::fs::read(db.blob_path(&t.sha256))
111 .await
112 .map_err(|e| Error::internal(format!("the thumbnail's file is missing: {e}")))?;
113 let mut r = Body::from(bytes).into_response();
114 r.headers_mut().insert(header::CONTENT_TYPE, HeaderValue::from_static(thumbnail::MEDIA_TYPE));
115 r
116 };
117 let h = response.headers_mut();
118 h.insert(header::CACHE_CONTROL, HeaderValue::from_static(cache));
119 if let Ok(v) = HeaderValue::from_str(&etag) {
120 h.insert(header::ETAG, v);
121 }
122 if let Ok(v) = HeaderValue::from_str(&ascii(&label)) {
124 h.insert("x-thumbnail-revision", v);
125 }
126 if let Ok(v) = HeaderValue::from_str(&t.content_hash) {
127 h.insert("x-thumbnail-content-hash", v);
128 }
129 if let Ok(v) = HeaderValue::from_str(&t.renderer) {
130 h.insert("x-thumbnail-renderer", v);
131 }
132 Ok(response)
133}
134
135fn ascii(text: &str) -> String {
137 text.chars().map(|c| if c.is_ascii_graphic() || c == ' ' { c } else { '_' }).collect()
138}