picsum_rs/api.rs
1use crate::PicsumClient;
2use reqwest::StatusCode;
3use serde::{Deserialize, Serialize};
4use std::cmp::min;
5use thiserror::Error;
6use typed_builder::TypedBuilder;
7
8#[derive(Debug, Ord, PartialOrd, Eq, PartialEq, Hash, Copy, Clone, Serialize, Deserialize)]
9pub enum FileType {
10 Jpeg,
11 Webp,
12}
13
14impl FileType {
15 fn as_string(&self) -> &'static str {
16 match self {
17 FileType::Jpeg => "jpg",
18 FileType::Webp => "webp",
19 }
20 }
21}
22
23#[derive(Error, Debug, Eq, PartialEq, Clone, Hash, Serialize, Deserialize)]
24pub enum RequestError {
25 #[error("Request error: {0}")]
26 InvalidRequest(String),
27
28 #[error("Invalid response: {0}")]
29 InvalidResponse(String),
30
31 #[error("Server error: {0}")]
32 ServerError(String),
33
34 #[error("Unexpected error: {0}")]
35 UnexpectedError(String),
36}
37
38#[allow(dead_code)]
39#[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Default, Serialize, Deserialize)]
40pub struct Image {
41 pub id: String,
42 pub data: Vec<u8>,
43}
44
45#[derive(TypedBuilder)]
46pub struct ImageSettings {
47 #[builder(setter(doc = "Set `width`."))]
48 width: u16,
49 #[builder(setter(doc = "Set `height`."))]
50 height: u16,
51 #[builder(
52 default = false,
53 setter(
54 doc = "Set `grayscale`. Defines if the image should be grayscale. Defaults to false."
55 )
56 )]
57 grayscale: bool,
58 #[builder(
59 default = 0,
60 setter(
61 doc = "Set `blur`. Defines the amount of blur between 0-10. Defaults to no blur (0)."
62 )
63 )]
64 blur: u8,
65 #[builder(
66 default = FileType::Jpeg,
67 setter(
68 doc = "Set `file_type`. Defines the file type of the requested image. Defaults to no jpeg."
69 )
70 )]
71 file_type: FileType,
72}
73
74impl ImageSettings {
75 pub fn get_blur_value(&self) -> u8 {
76 min(10, self.blur)
77 }
78
79 pub fn has_blur(&self) -> bool {
80 self.blur > 0
81 }
82
83 pub fn is_grayscale(&self) -> bool {
84 self.grayscale
85 }
86
87 fn generate_query_params(&self) -> Vec<(&str, String)> {
88 [
89 self.is_grayscale()
90 .then_some(("grayscale", "true".to_string())),
91 self.has_blur()
92 .then_some(("blur", self.get_blur_value().to_string())),
93 ]
94 .iter()
95 .filter_map(|param| param.clone())
96 .collect()
97 }
98}
99
100impl Default for ImageSettings {
101 fn default() -> Self {
102 Self {
103 width: 400,
104 height: 400,
105 grayscale: false,
106 blur: 0,
107 file_type: FileType::Jpeg,
108 }
109 }
110}
111
112#[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Default, Deserialize, Serialize)]
113pub struct ImageDetails {
114 pub id: String,
115 pub author: String,
116 pub width: u16,
117 pub height: u16,
118 pub url: String,
119 pub download_url: String,
120}
121
122impl PicsumClient {
123 /// Retrieve image details of a specific image id.
124 ///
125 /// # Examples
126 ///
127 /// ```
128 /// use picsum_rs::PicsumClient;
129 /// # use picsum_rs::api::ImageDetails;
130 ///
131 /// # tokio_test::block_on(async {
132 /// // Retrieve the image details for the image with the id `1`.
133 /// # let result =
134 /// match PicsumClient::default().get_image_details("1").await {
135 /// Ok(image_details) => {
136 /// # Ok(
137 /// image_details
138 /// # )
139 /// }
140 /// Err(e) => {
141 /// // Do your error handling
142 /// # Err(e)
143 /// }
144 /// }
145 /// # ;
146 /// # assert!(
147 /// # result.is_ok(),
148 /// # "Retrieving the image details for the image with the id 1 failed: {}",
149 /// # result.unwrap_err().to_string()
150 /// # );
151 /// # let details = result.unwrap();
152 /// # let expected_details = ImageDetails {
153 /// # id: "1".to_string(),
154 /// # author: "Alejandro Escamilla".to_string(),
155 /// # width: 5000,
156 /// # height: 3333,
157 /// # url: "https://unsplash.com/photos/LNRyGwIJr5c".to_string(),
158 /// # download_url: "https://picsum.photos/id/1/5000/3333".to_string(),
159 /// # };
160 /// # assert_eq!(expected_details, details);
161 /// # });
162 pub async fn get_image_details(&self, id: &str) -> Result<ImageDetails, RequestError> {
163 let response = self
164 .inner
165 .client
166 .get(format!("{}/id/{}/info", self.inner.base_url, id))
167 .send()
168 .await;
169
170 match response {
171 Ok(r) => match r.error_for_status() {
172 Ok(res) => res
173 .json::<ImageDetails>()
174 .await
175 .map_err(|err| RequestError::InvalidResponse(err.to_string())),
176 Err(err) => match err.status() {
177 Some(StatusCode::BAD_REQUEST) => {
178 Err(RequestError::InvalidRequest(err.to_string()))
179 }
180 Some(StatusCode::INTERNAL_SERVER_ERROR) => {
181 Err(RequestError::ServerError(err.to_string()))
182 }
183 Some(code) => Err(RequestError::UnexpectedError(format!("{} {}", code, err))),
184 None => Err(RequestError::UnexpectedError(err.to_string())),
185 },
186 },
187 Err(err) => Err(RequestError::UnexpectedError(err.to_string())),
188 }
189 }
190
191 /// Retrieve a list of available images.
192 ///
193 /// # Examples
194 ///
195 /// ```
196 /// use picsum_rs::PicsumClient;
197 ///
198 /// # tokio_test::block_on(async {
199 /// // Retrieve a list of images, fetching page 1 with a limit of 10 images per page.
200 /// # let result =
201 /// match PicsumClient::default().get_images(1, 10).await {
202 /// Ok(image_list) => {
203 /// # Ok(
204 /// image_list
205 /// # )
206 /// }
207 /// Err(e) => {
208 /// // Do your error handling
209 /// # Err(e)
210 /// }
211 /// }
212 /// # ;
213 /// # assert!(
214 /// # result.is_ok(),
215 /// # "Retrieving page one with a limit of 10 images per page failed: {}",
216 /// # result.unwrap_err().to_string()
217 /// # );
218 /// # let page1 = result.unwrap();
219 /// # assert_eq!(10, page1.len());
220 /// # })
221 /// ```
222 pub async fn get_images(
223 &self,
224 page: u16,
225 limit: u8,
226 ) -> Result<Vec<ImageDetails>, RequestError> {
227 let response = self
228 .inner
229 .client
230 .get(format!("{}/v2/list", self.inner.base_url))
231 .query(&vec![("page", page), ("limit", limit as u16)])
232 .send()
233 .await;
234
235 match response {
236 Ok(r) => match r.error_for_status() {
237 Ok(res) => res
238 .json::<Vec<ImageDetails>>()
239 .await
240 .map_err(|err| RequestError::InvalidResponse(err.to_string())),
241 Err(err) => match err.status() {
242 Some(StatusCode::BAD_REQUEST) => {
243 Err(RequestError::InvalidRequest(err.to_string()))
244 }
245 Some(StatusCode::INTERNAL_SERVER_ERROR) => {
246 Err(RequestError::ServerError(err.to_string()))
247 }
248 Some(code) => Err(RequestError::UnexpectedError(format!("{} {}", code, err))),
249 None => Err(RequestError::UnexpectedError(err.to_string())),
250 },
251 },
252 Err(err) => Err(RequestError::UnexpectedError(err.to_string())),
253 }
254 }
255
256 /// Retrieve a specific image by its id.
257 ///
258 /// # Examples
259 ///
260 /// ```
261 /// use picsum_rs::PicsumClient;
262 /// use picsum_rs::api::ImageSettings;
263 ///
264 /// # tokio_test::block_on(async {
265 /// # let result =
266 /// // Retrieve the image with the id `1` in the size 400x400px.
267 /// match PicsumClient::default()
268 /// .get_image("1", &ImageSettings::builder().width(400).height(400).build())
269 /// .await
270 /// {
271 /// Ok(image_list) => {
272 /// # Ok(
273 /// image_list
274 /// # )
275 /// }
276 /// Err(e) => {
277 /// // Do your error handling
278 /// # Err(e)
279 /// }
280 /// }
281 /// # ;
282 /// # assert!(
283 /// # result.is_ok(),
284 /// # "Retrieving the image with the id 1 failed: {}",
285 /// # result.unwrap_err().to_string()
286 /// # );
287 /// # let image = result.unwrap();
288 /// # assert_eq!(
289 /// # "1".to_string(),
290 /// # image.id,
291 /// # "Expected image id to be `1`, actually: {}",
292 /// # image.id
293 /// # );
294 /// # assert!(image.data.len() > 0);
295 /// # })
296 /// ```
297 pub async fn get_image(
298 &self,
299 id: &str,
300 image_settings: &ImageSettings,
301 ) -> Result<Image, RequestError> {
302 let response = self
303 .inner
304 .client
305 .get(format!(
306 "{}/id/{}/{}/{}.{}",
307 self.inner.base_url,
308 id,
309 image_settings.width,
310 image_settings.height,
311 image_settings.file_type.as_string()
312 ))
313 .query(&image_settings.generate_query_params())
314 .send()
315 .await;
316
317 match response {
318 Ok(r) => match r.error_for_status() {
319 Ok(res) => {
320 let id = match res.headers().get("picsum-id") {
321 None => {
322 return Err(RequestError::UnexpectedError(
323 "Couldn't retrieve `picsum-id` header.".into(),
324 ));
325 }
326 Some(v) => match v.to_str() {
327 Ok(value) => value,
328 Err(e) => return Err(RequestError::UnexpectedError(e.to_string())),
329 },
330 };
331
332 Ok(Image {
333 id: id.into(),
334 data: match res.bytes().await {
335 Ok(bytes) => bytes.to_vec(),
336 Err(err) => {
337 return Err(RequestError::UnexpectedError(format!(
338 "Couldn't read response body: {}",
339 err
340 )));
341 }
342 },
343 })
344 }
345 Err(err) => match err.status() {
346 Some(StatusCode::BAD_REQUEST) => {
347 Err(RequestError::InvalidRequest(err.to_string()))
348 }
349 Some(StatusCode::INTERNAL_SERVER_ERROR) => {
350 Err(RequestError::ServerError(err.to_string()))
351 }
352 Some(code) => Err(RequestError::UnexpectedError(format!("{} {}", code, err))),
353 None => Err(RequestError::UnexpectedError(err.to_string())),
354 },
355 },
356 Err(err) => Err(RequestError::UnexpectedError(err.to_string())),
357 }
358 }
359
360 /// Retrieve a random image with the given settings
361 ///
362 /// # Examples
363 ///
364 /// ```
365 /// use picsum_rs::PicsumClient;
366 /// use picsum_rs::api::ImageSettings;
367 ///
368 /// # tokio_test::block_on(async {
369 /// # let result =
370 /// // Retrieve a random 400x400px image.
371 /// match PicsumClient::default()
372 /// .get_random_image(&ImageSettings::builder().width(400).height(400).build())
373 /// .await
374 /// {
375 /// Ok(image_list) => {
376 /// # Ok(
377 /// image_list
378 /// # )
379 /// }
380 /// Err(e) => {
381 /// // Do your error handling
382 /// # Err(e)
383 /// }
384 /// }
385 /// # ;
386 /// # assert!(
387 /// # result.is_ok(),
388 /// # "Random image request failed: {}",
389 /// # result.unwrap_err().to_string()
390 /// # );
391 /// # let image = result.unwrap();
392 /// # assert!(image.data.len() > 0);
393 /// # assert!(image.id.len() > 0)
394 /// # })
395 /// ```
396 pub async fn get_random_image(
397 &self,
398 image_settings: &ImageSettings,
399 ) -> Result<Image, RequestError> {
400 let response = self
401 .inner
402 .client
403 .get(format!(
404 "{}/{}/{}.{}",
405 self.inner.base_url,
406 image_settings.width,
407 image_settings.height,
408 image_settings.file_type.as_string()
409 ))
410 .query(&image_settings.generate_query_params())
411 .send()
412 .await;
413
414 match response {
415 Ok(r) => match r.error_for_status() {
416 Ok(res) => {
417 let id = match res.headers().get("picsum-id") {
418 None => {
419 return Err(RequestError::UnexpectedError(
420 "Couldn't retrieve `picsum-id` header.".into(),
421 ));
422 }
423 Some(v) => match v.to_str() {
424 Ok(value) => value,
425 Err(e) => return Err(RequestError::UnexpectedError(e.to_string())),
426 },
427 };
428
429 Ok(Image {
430 id: id.into(),
431 data: match res.bytes().await {
432 Ok(bytes) => bytes.to_vec(),
433 Err(err) => {
434 return Err(RequestError::UnexpectedError(format!(
435 "Couldn't read response body: {}",
436 err
437 )));
438 }
439 },
440 })
441 }
442 Err(err) => match err.status() {
443 Some(StatusCode::BAD_REQUEST) => {
444 Err(RequestError::InvalidRequest(err.to_string()))
445 }
446 Some(StatusCode::INTERNAL_SERVER_ERROR) => {
447 Err(RequestError::ServerError(err.to_string()))
448 }
449 Some(code) => Err(RequestError::UnexpectedError(format!("{} {}", code, err))),
450 None => Err(RequestError::UnexpectedError(err.to_string())),
451 },
452 },
453 Err(err) => Err(RequestError::UnexpectedError(err.to_string())),
454 }
455 }
456}