torrust_index_backend/ui/
proxy.rs

1use std::sync::Once;
2
3use bytes::Bytes;
4use text_to_png::TextRenderer;
5
6use crate::cache::image::manager::Error;
7
8pub static ERROR_IMAGE_LOADER: Once = Once::new();
9
10static mut ERROR_IMAGE_URL_IS_UNREACHABLE: Bytes = Bytes::new();
11static mut ERROR_IMAGE_URL_IS_NOT_AN_IMAGE: Bytes = Bytes::new();
12static mut ERROR_IMAGE_TOO_BIG: Bytes = Bytes::new();
13static mut ERROR_IMAGE_USER_QUOTA_MET: Bytes = Bytes::new();
14static mut ERROR_IMAGE_UNAUTHENTICATED: Bytes = Bytes::new();
15
16const ERROR_IMG_FONT_SIZE: u8 = 16;
17const ERROR_IMG_COLOR: &str = "Red";
18
19const ERROR_IMAGE_URL_IS_UNREACHABLE_TEXT: &str = "Could not find image.";
20const ERROR_IMAGE_URL_IS_NOT_AN_IMAGE_TEXT: &str = "Invalid image.";
21const ERROR_IMAGE_TOO_BIG_TEXT: &str = "Image is too big.";
22const ERROR_IMAGE_USER_QUOTA_MET_TEXT: &str = "Image proxy quota met.";
23const ERROR_IMAGE_UNAUTHENTICATED_TEXT: &str = "Sign in to see image.";
24
25pub fn load_error_images() {
26    ERROR_IMAGE_LOADER.call_once(|| unsafe {
27        ERROR_IMAGE_URL_IS_UNREACHABLE = generate_img_from_text(ERROR_IMAGE_URL_IS_UNREACHABLE_TEXT);
28        ERROR_IMAGE_URL_IS_NOT_AN_IMAGE = generate_img_from_text(ERROR_IMAGE_URL_IS_NOT_AN_IMAGE_TEXT);
29        ERROR_IMAGE_TOO_BIG = generate_img_from_text(ERROR_IMAGE_TOO_BIG_TEXT);
30        ERROR_IMAGE_USER_QUOTA_MET = generate_img_from_text(ERROR_IMAGE_USER_QUOTA_MET_TEXT);
31        ERROR_IMAGE_UNAUTHENTICATED = generate_img_from_text(ERROR_IMAGE_UNAUTHENTICATED_TEXT);
32    });
33}
34
35pub fn map_error_to_image(error: &Error) -> Bytes {
36    load_error_images();
37    unsafe {
38        match error {
39            Error::UrlIsUnreachable => ERROR_IMAGE_URL_IS_UNREACHABLE.clone(),
40            Error::UrlIsNotAnImage => ERROR_IMAGE_URL_IS_NOT_AN_IMAGE.clone(),
41            Error::ImageTooBig => ERROR_IMAGE_TOO_BIG.clone(),
42            Error::UserQuotaMet => ERROR_IMAGE_USER_QUOTA_MET.clone(),
43            Error::Unauthenticated => ERROR_IMAGE_UNAUTHENTICATED.clone(),
44        }
45    }
46}
47
48fn generate_img_from_text(text: &str) -> Bytes {
49    let renderer = TextRenderer::default();
50
51    Bytes::from(
52        renderer
53            .render_text_to_png_data(text, ERROR_IMG_FONT_SIZE, ERROR_IMG_COLOR)
54            .unwrap()
55            .data,
56    )
57}