Skip to main content

kodik_api/
player.rs

1use serde::{Deserialize, Serialize};
2
3use crate::{
4    Client,
5    error::Error,
6    util::serialize_into_query_parts,
7};
8
9/// Response returned by `/get-player`.
10#[derive(Deserialize, Debug, Clone)]
11pub struct PlayerResponse {
12    pub found: bool,
13    pub allowed: i32,
14    pub quality: Option<String>,
15    pub translation: Option<String>,
16    pub link: Option<String>,
17}
18
19#[derive(Deserialize, Debug, Clone)]
20#[serde(untagged)]
21enum PlayerApiResponse {
22    Result(PlayerResponse),
23    Error { error: String },
24}
25
26#[derive(Debug, Serialize, Clone)]
27pub struct PlayerQuery<'a> {
28    #[serde(skip_serializing_if = "Option::is_none")]
29    title: Option<&'a str>,
30
31    #[serde(
32        rename = "hasPlayer",
33        skip_serializing_if = "Option::is_none"
34    )]
35    has_player: Option<bool>,
36
37    #[serde(skip_serializing_if = "Option::is_none")]
38    url: Option<&'a str>,
39
40    #[serde(
41        rename = "ID",
42        skip_serializing_if = "Option::is_none"
43    )]
44    id: Option<&'a str>,
45}
46
47impl<'a> PlayerQuery<'a> {
48    pub fn new() -> PlayerQuery<'a> {
49        PlayerQuery {
50            title: None,
51            has_player: None,
52            url: None,
53            id: None,
54        }
55    }
56
57    pub fn with_title<'b>(
58        &'b mut self,
59        title: &'a str,
60    ) -> &'b mut PlayerQuery<'a> {
61        self.title = Some(title);
62        self
63    }
64
65    pub fn with_has_player<'b>(
66        &'b mut self,
67        has_player: bool,
68    ) -> &'b mut PlayerQuery<'a> {
69        self.has_player = Some(has_player);
70        self
71    }
72
73    pub fn with_url<'b>(
74        &'b mut self,
75        url: &'a str,
76    ) -> &'b mut PlayerQuery<'a> {
77        self.url = Some(url);
78        self
79    }
80
81    pub fn with_id<'b>(
82        &'b mut self,
83        id: &'a str,
84    ) -> &'b mut PlayerQuery<'a> {
85        self.id = Some(id);
86        self
87    }
88
89    /// Execute the query and fetch the player.
90    pub async fn execute<'b>(
91        &'a self,
92        client: &'b Client,
93    ) -> Result<PlayerResponse, Error> {
94        let payload = serialize_into_query_parts(self)?;
95
96        let response = client
97            .init_get_request("/get-player")
98            .query(&payload)
99            .send()
100            .await
101            .map_err(Error::HttpError)?;
102
103        let result = response
104            .json::<PlayerApiResponse>()
105            .await
106            .map_err(Error::HttpError)?;
107
108        match result {
109            PlayerApiResponse::Result(result) => Ok(result),
110            PlayerApiResponse::Error { error } => {
111                Err(Error::KodikError(error))
112            }
113        }
114    }
115}
116
117impl<'a> Default for PlayerQuery<'a> {
118    fn default() -> Self {
119        Self::new()
120    }
121}