kutt/
api.rs

1use crate::constants::*;
2use crate::errors::{Error, Result};
3use crate::utils::get_id_from_link;
4use reqwest::Client;
5
6#[derive(Debug, Serialize, Deserialize, Clone)]
7pub struct ListLinks {
8    pub list: Vec<Link>,
9    #[serde(rename = "countAll")]
10    pub count_all: u32,
11}
12
13#[derive(Debug, Serialize, Deserialize, Clone)]
14pub struct Link {
15    count: u32,
16    #[serde(rename = "createdAt")]
17    created_at: String,
18    id: String,
19    target: String,
20    password: bool,
21    #[serde(rename = "shortUrl")]
22    short_url: String,
23}
24
25#[derive(Debug, Serialize, Deserialize)]
26pub struct Kutt {
27    target: String,
28    customurl: Option<String>,
29    password: Option<String>,
30    reuse: bool,
31}
32
33impl Kutt {
34    pub fn target_url(target: &str) -> Self {
35        Kutt {
36            target: target.to_owned(),
37            customurl: None,
38            password: None,
39            reuse: false,
40        }
41    }
42    pub fn custom_url<S: Into<String>>(mut self, customurl: S) -> Self {
43        self.customurl = Some(customurl.into());
44        self
45    }
46    pub fn password<S: Into<String>>(mut self, password: S) -> Self {
47        self.password = Some(password.into());
48        self
49    }
50    pub fn reuse(mut self) -> Self {
51        self.reuse = true;
52        self
53    }
54
55    pub fn create_short_link(&self) -> Result<String> {
56        #[derive(Debug, Serialize, Deserialize)]
57        pub struct Response {
58            #[serde(rename = "createdAt")]
59            created_at: String,
60            id: String,
61            target: String,
62            password: bool,
63            #[serde(rename = "shortUrl")]
64            short_url: String,
65        }
66        let request = serde_json::to_string(self).unwrap();
67        let response: Response = Client::new()
68            .post(&format!("{}/{}", BASE_URL, "api/url/submit"))
69            .header("X-API-Key", &*KUTT_API_KEY.as_str())
70            .header("Content-Type", "application/json")
71            .body(request)
72            .send()
73            .map_err(|e| {
74                eprintln!("{}", e);
75                Error::SendRequsetError
76            })?
77            .json()
78            .map_err(|e| {
79                eprintln!("{}", e);
80                Error::ParseJsonError
81            })?;
82        Ok(response.short_url)
83    }
84    pub fn delete_link(short_link: &str) -> Result {
85        let body = match get_id_from_link(short_link) {
86            Ok(id) => r#"{"id":""#.to_owned() + id.as_str() + r#"","domain":null}"#,
87            Err(e) => return Err(e),
88        };
89        let resp: reqwest::Response = Client::new()
90            .post(&format!("{}/{}", BASE_URL, "api/url/deleteurl"))
91            .header("X-API-Key", &*KUTT_API_KEY.as_str())
92            .header("Content-Type", "application/json")
93            .body(body.clone())
94            .send()
95            .map_err(|e| {
96                eprintln!("{}", e);
97                Error::SendRequsetError
98            })?;
99        if resp.status() == 200 {
100            Ok(())
101        } else {
102            Err(Error::UnsuccessResponseError)
103        }
104    }
105    #[allow(dead_code)]
106    pub fn list_links() -> Result<ListLinks> {
107        let resp: ListLinks = Client::new()
108            .get(&format!("{}/{}", BASE_URL, "api/url/geturls"))
109            .header("X-API-Key", &*KUTT_API_KEY.as_str())
110            .send()
111            .map_err(|e| {
112                eprintln!("{}", e);
113                Error::SendRequsetError
114            })?
115            .json()
116            .map_err(|e| {
117                eprintln!("{}", e);
118                Error::ParseJsonError
119            })?;
120        Ok(resp)
121    }
122}