1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
use crate::{Call, Callsign, News, Node, Rubric, Statistics, Transmitter, TransmitterGroup};
use anyhow::{anyhow, Result};
use reqwest::{StatusCode, Url};
use serde::{Deserialize, Serialize};

#[derive(Clone, Debug)]
pub struct ClientConfig {
    pub api_url: Url,
}

impl Default for ClientConfig {
    fn default() -> Self {
        Self {
            api_url: Url::parse("https://hampager.de/api/").unwrap(),
        }
    }
}

#[derive(Clone, Debug)]
pub struct Client {
    client: reqwest::Client,
    username: String,
    password: String,
    config: ClientConfig,
}

impl Client {
    /// Creates a new instance of the client with the default configuration.
    ///
    /// Example:
    /// ```
    /// use dapnet_api::Client;
    /// let client = Client::new("m0nxn", "my_super_secret_password");
    /// ```
    pub fn new(username: &str, password: &str) -> Self {
        Self {
            client: reqwest::Client::new(),
            username: username.to_string(),
            password: password.to_string(),
            config: ClientConfig::default(),
        }
    }

    async fn get<T: for<'de> Deserialize<'de>>(&self, path: &str) -> Result<Option<T>> {
        let result = self
            .client
            .get(self.config.api_url.join(path)?)
            .basic_auth(&self.username, Some(&self.password))
            .send()
            .await?;

        if result.status().is_success() {
            Ok(Some(result.json().await?))
        } else if result.status() == StatusCode::NOT_FOUND {
            Ok(None)
        } else {
            Err(anyhow! {"API error: {}", result.status()})
        }
    }

    async fn get_many<T: for<'de> Deserialize<'de>>(&self, path: &str) -> Result<Option<Vec<T>>> {
        let result = self
            .client
            .get(self.config.api_url.join(path)?)
            .basic_auth(&self.username, Some(&self.password))
            .send()
            .await?;

        if result.status().is_success() {
            Ok(Some(result.json().await?))
        } else if result.status() == StatusCode::NOT_FOUND {
            Ok(None)
        } else {
            Err(anyhow! {"API error: {}", result.status()})
        }
    }

    async fn post<T: Serialize + ?Sized>(&self, path: &str, item: &T) -> Result<()> {
        let result = self
            .client
            .post(self.config.api_url.join(path)?)
            .basic_auth(&self.username, Some(&self.password))
            .json(item)
            .send()
            .await?;

        if result.status().is_success() {
            Ok(())
        } else {
            Err(anyhow! {"API error: {}", result.status()})
        }
    }

    pub async fn get_statistics(&self) -> Result<Option<Statistics>> {
        self.get("stats").await
    }

    pub async fn get_calls_by(&self, owner: &str) -> Result<Option<Vec<Call>>> {
        self.get_many(&format!("calls?ownerName={}", owner)).await
    }

    /// Sends a new call/message.
    ///
    /// Example:
    /// ```no_run
    /// # use dapnet_api::{Call, Client};
    /// # #[tokio::main]
    /// # async fn main() {
    /// # let client = Client::new("m0nxn", "my_super_secret_password");
    /// client
    ///     .new_call(&Call::new(
    ///         "M0NXN: this is a test".to_string(),
    ///         vec!["m0nxn".to_string()],
    ///         vec!["uk-all".to_string()],
    ///     ))
    ///     .await
    ///     .unwrap();
    /// # }
    /// ```
    pub async fn new_call(&self, call: &Call) -> Result<()> {
        self.post("calls", call).await
    }

    pub async fn get_all_nodes(&self) -> Result<Option<Vec<Node>>> {
        self.get_many("nodes").await
    }

    pub async fn get_node(&self, name: &str) -> Result<Option<Node>> {
        self.get(&format!("nodes/{}", name)).await
    }

    pub async fn get_all_callsigns(&self) -> Result<Option<Vec<Callsign>>> {
        self.get_many("callsigns").await
    }

    pub async fn get_callsign(&self, name: &str) -> Result<Option<Callsign>> {
        self.get(&format!("callsigns/{}", name)).await
    }

    pub async fn get_all_transmitters(&self) -> Result<Option<Vec<Transmitter>>> {
        self.get_many("transmitters").await
    }

    pub async fn get_transmitter(&self, name: &str) -> Result<Option<Transmitter>> {
        self.get(&format!("transmitters/{}", name)).await
    }

    pub async fn get_all_transmitter_groups(&self) -> Result<Option<Vec<TransmitterGroup>>> {
        self.get_many("transmitterGroups").await
    }

    pub async fn get_transmitter_group(&self, name: &str) -> Result<Option<TransmitterGroup>> {
        self.get(&format!("transmitterGroups/{}", name)).await
    }

    pub async fn get_all_rubrics(&self) -> Result<Option<Vec<Rubric>>> {
        self.get_many("rubrics").await
    }

    pub async fn get_rubric(&self, name: &str) -> Result<Option<Rubric>> {
        self.get(&format!("rubrics/{}", name)).await
    }

    pub async fn get_news(&self, name: &str) -> Result<Option<Vec<News>>> {
        match self
            .get_many::<Option<News>>(&format!("news?rubricName={}", name))
            .await?
        {
            Some(v) => Ok(Some(v.into_iter().flatten().collect())),
            None => Ok(None),
        }
    }

    /// Sends news to a rubric.
    ///
    /// Example:
    /// ```no_run
    /// # use dapnet_api::{Client, News};
    /// # #[tokio::main]
    /// # async fn main() {
    /// # let client = Client::new("m0nxn", "my_super_secret_password");
    /// client
    ///     .new_news(&News::new(
    ///         "some_rubric_name".to_string(),
    ///         "M0NXN: this is a test".to_string(),
    ///     ))
    ///     .await
    ///     .unwrap();
    /// # }
    /// ```
    pub async fn new_news(&self, news: &News) -> Result<()> {
        self.post("news", news).await
    }
}