rusty_booru/safebooru/
client.rs

1use derive_more::From;
2
3use crate::{
4    generic::AutoCompleteItem,
5    shared::{
6        self,
7        client::{
8            ClientBuilder, ClientInformation, ClientQueryDispatcher, ClientTypes,
9            ImplementedWithCommonQuery, QueryDispatcher, QueryLike, QueryMode, WithCommonQuery,
10        },
11    },
12};
13
14use super::*;
15
16#[derive(From, Debug, Clone)]
17pub struct SafebooruClient(pub ClientBuilder<Self>);
18
19impl ClientInformation for SafebooruClient {
20    const URL: &'static str = "https://safebooru.org";
21    const SORT: &'static str = "sort:";
22}
23
24impl ClientTypes for SafebooruClient {
25    type Post = SafebooruPost;
26    type Rating = SafebooruRating;
27}
28
29impl WithCommonQuery for SafebooruClient {
30    fn common_query_type() -> QueryLike {
31        QueryLike::Gelbooru
32    }
33}
34
35impl QueryDispatcher<SafebooruClient> for ClientQueryDispatcher<SafebooruClient> {
36    async fn get_autocomplete<In: Into<String> + Send>(
37        &self,
38        input: In,
39    ) -> Result<Vec<crate::generic::AutoCompleteItem>, reqwest::Error> {
40        self.builder
41            .client
42            .get(format!("{}/autocomplete.php", self.builder.url))
43            .query(&[("q", input.into())])
44            .send()
45            .await?
46            .json::<Vec<AutoCompleteItem>>()
47            .await
48    }
49
50    async fn get_by_id(&self, id: u32) -> Result<Option<SafebooruPost>, shared::Error> {
51        self.builder
52            .client
53            .get(&format!("{}/index.php", &self.builder.url))
54            .query(&Self::get_query(QueryMode::Single(id)))
55            .send()
56            .await?
57            .json::<Vec<SafebooruPost>>()
58            .await
59            .map(|r| r.into_iter().next())
60            .map_err(Into::into)
61    }
62
63    async fn get(&self) -> Result<Vec<SafebooruPost>, shared::Error> {
64        self.builder
65            .client
66            .get(format!("{}/index.php", &self.builder.url))
67            .query(&Self::get_query(QueryMode::Multiple(&self.query)))
68            .send()
69            .await?
70            .json::<Vec<SafebooruPost>>()
71            .await
72            .map_err(Into::into)
73    }
74}