1use axum::http::StatusCode;
9use image::{imageops::FilterType, DynamicImage, Rgba, RgbaImage};
10use serde_json::{json, Value};
11
12const MAX_SIDE: u32 = 480;
14const QUALITY: u8 = 70;
16const MARK: Rgba<u8> = Rgba([255, 0, 170, 255]);
17const HALO: Rgba<u8> = Rgba([255, 255, 255, 255]);
18
19fn ring(img: &mut RgbaImage, (cx, cy): (f64, f64), radius: f64, width: f64, colour: Rgba<u8>) {
21 let reach = (radius + width).ceil() as i64;
22 let (w, h) = (i64::from(img.width()), i64::from(img.height()));
23 for dy in -reach..=reach {
24 for dx in -reach..=reach {
25 let d = ((dx * dx + dy * dy) as f64).sqrt();
26 let (x, y) = (cx.round() as i64 + dx, cy.round() as i64 + dy);
27 if d >= radius - width / 2.0 && d <= radius + width / 2.0 && (0..w).contains(&x) && (0..h).contains(&y) {
28 img.put_pixel(x as u32, y as u32, colour);
29 }
30 }
31 }
32}
33
34fn mark(img: &mut RgbaImage, at: (f64, f64)) {
36 ring(img, at, 9.0, 4.0, HALO);
37 ring(img, at, 9.0, 2.0, MARK);
38 ring(img, at, 2.0, 5.0, HALO);
39 ring(img, at, 1.0, 3.0, MARK);
40}
41
42fn line(img: &mut RgbaImage, a: (f64, f64), b: (f64, f64), width: f64, colour: Rgba<u8>) {
44 let steps = ((b.0 - a.0).hypot(b.1 - a.1)).ceil().max(1.0) as u32;
45 for i in 0..=steps {
46 let t = f64::from(i) / f64::from(steps);
47 ring(img, (a.0 + (b.0 - a.0) * t, a.1 + (b.1 - a.1) * t), 0.0, width, colour);
48 }
49}
50
51pub(crate) fn marked(mut img: RgbaImage, points: &[(f64, f64)], drawn: (f64, f64)) -> RgbaImage {
54 if img.width().max(img.height()) > MAX_SIDE {
55 let k = f64::from(MAX_SIDE) / f64::from(img.width().max(img.height()));
56 img = image::imageops::resize(&img, (f64::from(img.width()) * k).round().max(1.0) as u32, (f64::from(img.height()) * k).round().max(1.0) as u32, FilterType::Triangle);
57 }
58 let at: Vec<(f64, f64)> = points.iter().map(|p| (p.0 / drawn.0 * f64::from(img.width()), p.1 / drawn.1 * f64::from(img.height()))).collect();
59 if let [a, b] = at[..] {
60 line(&mut img, a, b, 5.0, HALO);
61 line(&mut img, a, b, 2.5, MARK);
62 }
63 for p in at {
64 mark(&mut img, p);
65 }
66 img
67}
68
69fn jpeg_url(img: &RgbaImage) -> Result<String, String> {
70 use base64::Engine as _;
71 let rgb = DynamicImage::ImageRgba8(img.clone()).to_rgb8();
72 let mut out = Vec::new();
73 image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, QUALITY).encode_image(&rgb).map_err(|e| format!("write the picture: {e}"))?;
74 Ok(format!("data:image/jpeg;base64,{}", base64::engine::general_purpose::STANDARD.encode(out)))
75}
76
77pub(crate) fn with_card(first: &Value, mut ask: Value) -> Result<Value, (StatusCode, String)> {
81 use base64::Engine as _;
82 if ask.get("canvas").and_then(Value::as_bool) != Some(true) {
83 return Ok(ask);
84 }
85 let refuse = |why: String| (StatusCode::BAD_GATEWAY, format!("the canvas could not be shown to the person, so nothing was asked and nothing was done: {why}"));
86 let card = first.get("card").ok_or_else(|| refuse("the page gave no picture of it".to_string()))?;
87 let bytes = card
88 .get("png_base64")
89 .and_then(Value::as_str)
90 .and_then(|b| base64::engine::general_purpose::STANDARD.decode(b).ok())
91 .ok_or_else(|| refuse("its picture could not be read".to_string()))?;
92 let mut img = image::load_from_memory(&bytes).map_err(|e| refuse(format!("its picture could not be read ({e})")))?.to_rgba8();
93 super::screenshot_redact::redact_image(&json!({ "data": card }), &mut img).map_err(refuse)?;
94 let pair = |key: &str| {
95 let a = ask.get(key)?.as_array()?;
96 Some((a.first()?.as_f64()?, a.get(1)?.as_f64()?))
97 };
98 let drawn = pair("drawn").filter(|d| d.0 >= 1.0 && d.1 >= 1.0).ok_or_else(|| refuse("the canvas has no size".to_string()))?;
99 let points: Vec<(f64, f64)> = ask.get("points").and_then(Value::as_array).map(|a| a.iter().filter_map(|p| Some((p.get(0)?.as_f64()?, p.get(1)?.as_f64()?))).collect()).unwrap_or_default();
100 if points.is_empty() || points.len() > 2 {
101 return Err(refuse("it has no point".to_string()));
102 }
103 let url = jpeg_url(&marked(img, &points, drawn)).map_err(refuse)?;
104 if let Some(o) = ask.as_object_mut() {
105 o.insert("image".to_string(), json!(url));
106 }
107 Ok(ask)
108}
109
110#[cfg(test)]
111mod tests {
112 use super::*;
113 use image::ImageFormat;
114
115 fn png(w: u32, h: u32, colour: [u8; 4]) -> String {
116 use base64::Engine as _;
117 let img = RgbaImage::from_pixel(w, h, Rgba(colour));
118 let mut out = Vec::new();
119 DynamicImage::ImageRgba8(img).write_to(&mut std::io::Cursor::new(&mut out), ImageFormat::Png).unwrap();
120 base64::engine::general_purpose::STANDARD.encode(out)
121 }
122
123 fn decoded(url: &str) -> RgbaImage {
124 use base64::Engine as _;
125 let b = base64::engine::general_purpose::STANDARD.decode(url.strip_prefix("data:image/jpeg;base64,").unwrap()).unwrap();
126 image::load_from_memory(&b).unwrap().to_rgba8()
127 }
128
129 fn near(p: &Rgba<u8>, c: [u8; 3]) -> bool {
130 p.0[..3].iter().zip(c).all(|(a, b)| (i32::from(*a) - i32::from(b)).abs() < 60)
131 }
132
133 fn ask(points: Value) -> Value {
134 json!({ "what": "Click at (100, 50) in a canvas", "canvas": true, "points": points, "drawn": [200.0, 100.0], "page": "https://a.test/" })
135 }
136
137 #[test]
138 fn a_question_about_something_else_is_left_as_it_is() {
139 let a = json!({ "what": "Click \"Send\"" });
140 assert_eq!(with_card(&json!({}), a.clone()).unwrap(), a);
141 }
142
143 #[test]
144 fn the_point_is_marked_on_the_picture_where_it_is_in_the_canvas() {
145 let first = json!({ "card": { "png_base64": png(200, 100, [250, 250, 250, 255]), "secret_boxes": [], "css_width": 200.0, "secrets_unchecked": false } });
146 let asked = with_card(&first, ask(json!([[100.0, 50.0]]))).unwrap();
147 let img = decoded(asked["image"].as_str().unwrap());
148 assert_eq!(img.dimensions(), (200, 100));
149 assert!(near(img.get_pixel(100, 50), [255, 0, 170]), "the middle of the picture is marked: {:?}", img.get_pixel(100, 50));
150 assert!(near(img.get_pixel(10, 10), [250, 250, 250]), "and the rest is the canvas");
151 }
152
153 #[test]
154 fn a_large_picture_is_shrunk_and_the_mark_keeps_its_place() {
155 let first = json!({ "card": { "png_base64": png(960, 480, [250, 250, 250, 255]), "secret_boxes": [], "css_width": 480.0, "secrets_unchecked": false } });
156 let asked = with_card(&first, json!({ "canvas": true, "points": [[480.0, 240.0]], "drawn": [960.0, 480.0] })).unwrap();
157 let img = decoded(asked["image"].as_str().unwrap());
158 assert_eq!(img.dimensions(), (480, 240));
159 assert!(near(img.get_pixel(240, 120), [255, 0, 170]));
160 }
161
162 #[test]
163 fn a_drag_is_two_marks_and_a_line() {
164 let first = json!({ "card": { "png_base64": png(200, 100, [250, 250, 250, 255]), "secret_boxes": [], "css_width": 200.0, "secrets_unchecked": false } });
165 let asked = with_card(&first, ask(json!([[20.0, 50.0], [180.0, 50.0]]))).unwrap();
166 let img = decoded(asked["image"].as_str().unwrap());
167 assert!(near(img.get_pixel(20, 50), [255, 0, 170]) && near(img.get_pixel(180, 50), [255, 0, 170]));
168 assert!(near(img.get_pixel(100, 50), [255, 0, 170]), "the line joins them");
169 }
170
171 #[test]
172 fn a_secret_field_in_the_picture_is_black() {
173 let first = json!({ "card": { "png_base64": png(200, 100, [250, 250, 250, 255]), "secret_boxes": [[150.0, 10.0, 40.0, 20.0]], "css_width": 200.0, "secrets_unchecked": false } });
174 let asked = with_card(&first, ask(json!([[20.0, 80.0]]))).unwrap();
175 let img = decoded(asked["image"].as_str().unwrap());
176 assert!(near(img.get_pixel(170, 20), [0, 0, 0]), "{:?}", img.get_pixel(170, 20));
177 }
178
179 #[test]
180 fn a_capture_that_could_not_be_checked_for_secrets_is_not_shown_and_nothing_is_asked() {
181 let first = json!({ "card": { "png_base64": png(200, 100, [250, 250, 250, 255]), "secret_boxes": [], "css_width": 200.0, "secrets_unchecked": true } });
182 let (code, why) = with_card(&first, ask(json!([[20.0, 80.0]]))).unwrap_err();
183 assert_eq!(code, StatusCode::BAD_GATEWAY);
184 assert!(why.contains("nothing was asked"), "{why}");
185 assert!(with_card(&json!({}), ask(json!([[1.0, 1.0]]))).is_err(), "no picture, no question");
186 }
187}