am_api/resource/
artwork.rs

1//! Artwork information
2
3use crate::error::Error;
4use serde::{Deserialize, Serialize};
5use tinytemplate::TinyTemplate;
6
7/// Artwork information
8#[derive(Serialize, Deserialize, Default, Debug, Clone, PartialEq, Eq, Hash)]
9#[serde(rename_all = "camelCase")]
10pub struct Artwork {
11    /// Original image width in pixels
12    pub width: Option<u32>,
13    /// Original image height in pixels
14    pub height: Option<u32>,
15    /// Template image url
16    ///
17    /// DO NOT USE FOR REQUESTS:
18    /// for getting the image use the [`Artwork::get_image`] method
19    pub url: String,
20    /// Text color 1 in rgb hex
21    #[serde(with = "crate::utils::hex::option", default)]
22    pub text_color_1: Option<u32>,
23    /// Text color 2 in rgb hex
24    #[serde(with = "crate::utils::hex::option", default)]
25    pub text_color_2: Option<u32>,
26    /// Text color 3 in rgb hex
27    #[serde(with = "crate::utils::hex::option", default)]
28    pub text_color_3: Option<u32>,
29    /// Text color 4 in rgb hex
30    #[serde(with = "crate::utils::hex::option", default)]
31    pub text_color_4: Option<u32>,
32}
33
34/// Artwork image formats
35#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
36pub enum ArtworkImageFormat {
37    /// Png image format,
38    Png,
39    /// Webp image format
40    Webp,
41    /// Jpeg image format
42    Jpeg,
43}
44
45impl ArtworkImageFormat {
46    fn get_format_string(&self) -> &str {
47        match self {
48            ArtworkImageFormat::Png => "png",
49            ArtworkImageFormat::Webp => "webp",
50            ArtworkImageFormat::Jpeg => "jpg",
51        }
52    }
53}
54
55impl Artwork {
56    /// Get artwork image url
57    ///
58    /// # Parameters
59    ///
60    /// * width - preferred width
61    ///
62    /// * height - preferred height
63    ///
64    /// * image_format - image format in which the image should be retrieved
65    pub fn get_image_url(
66        &self,
67        width: u32,
68        height: u32,
69        image_format: ArtworkImageFormat,
70    ) -> Result<String, Error> {
71        let mut tt = TinyTemplate::new();
72        tt.add_template("url", &self.url)?;
73
74        #[derive(Serialize)]
75        struct UrlContext<'a> {
76            w: u32,
77            h: u32,
78            f: &'a str,
79        }
80
81        let context = UrlContext {
82            w: width,
83            h: height,
84            f: image_format.get_format_string(),
85        };
86
87        Ok(tt.render("url", &context)?)
88    }
89}