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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
//! An idiomatic Rust client for Gotify.
//!
//! ## Overview
//!
//! By default, this crate only exposes the [`Client::health()`](crate::Client::health), [`Client::version()`](crate::Client::version) methods.
//! All other categories of endpoints must be enabled by the correspondig feature flags.
//!
//! | Feature flag | Enabled methods | Note |
//! | ------------ | --------------- | ---- |
//! | `app` | [`Client::create_message()`](crate::Client::create_message) | |
//! | `manage-clients` | [`Client::get_clients()`](crate::Client::get_clients), [`Client::create_client()`](crate::Client::create_client), [`Client::update_client()`](crate::Client::update_client), [`Client::delete_client()`](crate::Client::delete_client) | |
//! | `manage-messages` | [`Client::get_application_messages()`](crate::Client::get_application_messages), [`Client::delete_application_messages()`](crate::Client::delete_application_messages), [`Client::get_messages()`](crate::Client::get_messages), [`Client::delete_messages()`](crate::Client::delete_messages), [`Client::delete_message()`](crate::Client::delete_message) | doesn't include [`Client::create_message()`](crate::Client::create_message) and [`Client::message_stream()`](crate::Client::message_stream) |
//! | `manage-plugins` | [`Client::get_plugins()`](crate::Client::get_plugins), [`Client::get_plugin_config()`](crate::Client::get_plugin_config), [`Client::update_plugin_config()`](crate::Client::update_plugin_config), [`Client::disable_plugin()`](crate::Client::disable_plugin), [`Client::get_plugin_display()`](crate::Client::get_plugin_display), [`Client::enable_plugin()`](crate::Client::enable_plugin) | |
//! | `websocket` | [`Client::message_stream()`](crate::Client::message_stream) | enables additional dependencies (mainly [`tokio-tungstenite`](https://docs.rs/tokio-tungstenite)) |
//!
//! ## Examples
//!
//! ### Creating a message
//!
//! ```ignore
//! let client: gotify::AppClient = gotify::Client::new(GOTIFY_URL, GOTIFY_APP_TOKEN)?;
//!
//! client.create_message("Lorem ipsum dolor sit amet").with_title("Lorem Ipsum").await?;
//! ```
//!
//! ### Listening for new messages
//!
//! ```ignore
//! use futures_util::StreamExt;
//!
//! let client: gotify::ClientClient = gotify::Client::new(GOTIFY_URL, GOTIFY_CLIENT_TOKEN)?;
//!
//! let mut messages = client.message_stream().await?;
//!
//! while let Some(result) = messages.next().await {
//!     let message = result?;
//!
//!     println!("{message:#?}")
//! }
//! ```

#![warn(missing_docs)]

use std::marker::PhantomData;

use reqwest::{
    header::{HeaderMap, HeaderValue, InvalidHeaderValue},
    Method,
};
use url::Url;

use crate::utils::UrlAppend;

pub use crate::error::{Error, InitError, Result};
#[cfg(feature = "websocket")]
pub use crate::websocket::{WebsocketConnectError, WebsocketError};

pub mod models;

/// Builder structs used by some methods that send data to Gotify's API.
///
/// While they provide a `send()` method, they also implement
/// [`IntoFuture`](std::future::IntoFuture) and can be `await`ed directly.
pub mod builder {
    #[cfg(feature = "app")]
    pub use crate::app::MessageBuilder;
    #[cfg(feature = "manage-applications")]
    pub use crate::applications::{ApplicationBuilder, ApplicationUpdateBuilder};
    #[cfg(feature = "manage-clients")]
    pub use crate::clients::{ClientBuilder, ClientUpdateBuilder};
    #[cfg(feature = "manage-messages")]
    pub use crate::messages::{GetApplicationMessagesBuilder, GetMessagesBuilder};
    #[cfg(feature = "manage-users")]
    pub use crate::users::{CreateUserBuilder, UpdateCurrentUserBuilder, UpdateUserBuilder};
}

#[cfg(feature = "app")]
mod app;
#[cfg(feature = "manage-applications")]
mod applications;
#[cfg(feature = "manage-clients")]
mod clients;
mod error;
mod health;
#[cfg(feature = "manage-messages")]
mod messages;
#[cfg(feature = "manage-plugins")]
mod plugins;
#[cfg(feature = "manage-users")]
mod users;
mod version;
#[cfg(feature = "websocket")]
mod websocket;

#[cfg(test)]
pub(crate) mod testsuite;
mod utils;

/// A client for a specific Gotify server. The main entrypoint of this crate.
///
/// It comes in three varieties to perform different tasks.
///
/// | Type | Explanation | Feature flag |
/// | ---- | ------------ | ----------------- |
/// | [`UnauthenticatedClient = Client<Unauthenticated>`](crate::UnauthenticatedClient) | get server status and version info | always enabled |
/// | [`AppClient = Client<AppToken>`](crate::AppClient) | create messages | `app` |
/// | [`ClientClient = Client<ClientToken>`](crate::ClientClient) | manage the server (anything else) | any of `manage-*` or `websocket` |
#[derive(Clone, Debug)]
pub struct Client<T> {
    base_url: Url,
    http: reqwest::Client,
    token: PhantomData<T>,
}

/// A client that is authenticated to create messages.
#[cfg(feature = "app")]
pub type AppClient = Client<AppToken>;

/// A client that is authenticated to manage the server.
#[cfg(feature = "client-core")]
pub type ClientClient = Client<ClientToken>;

/// A client that is unauthenticated.
pub type UnauthenticatedClient = Client<Unauthenticated>;

/// Marks a client as authenticated to create messages.
#[cfg(feature = "app")]
#[derive(Clone, Debug)]
pub struct AppToken;

/// Marks a client as authenticated to manage the server.
#[cfg(feature = "client-core")]
#[derive(Clone, Debug)]
pub struct ClientToken;

/// Marks a client as unauthenticated.
#[derive(Clone, Debug)]
pub struct Unauthenticated;

/// Sealed trait to represent an [`AppToken`] or [`ClientToken`].
pub trait TokenType: private::Sealed {}

#[cfg(feature = "app")]
impl TokenType for AppToken {}

#[cfg(feature = "client-core")]
impl TokenType for ClientToken {}

mod private {
    pub trait Sealed {}

    #[cfg(feature = "app")]
    impl Sealed for super::AppToken {}

    #[cfg(feature = "client-core")]
    impl Sealed for super::ClientToken {}
}

#[cfg(any(feature = "app", feature = "client-core"))]
impl<T: TokenType> Client<T> {
    /// Create a new authenticated client.
    ///
    /// The type of the used access token (app token or client token)
    /// must be provided as a generic parameter or be inferable.
    pub fn new(
        server_url: impl TryInto<Url, Error = url::ParseError>,
        access_token: impl TryInto<HeaderValue, Error = InvalidHeaderValue>,
    ) -> core::result::Result<Self, InitError> {
        Ok(Client {
            base_url: server_url.try_into()?,
            http: reqwest::Client::builder()
                .default_headers({
                    let mut headers = HeaderMap::new();
                    headers.insert("X-Gotify-Key", access_token.try_into()?);
                    headers
                })
                .build()
                .map_err(InitError::Reqwest)?,
            token: PhantomData,
        })
    }
}

impl Client<Unauthenticated> {
    /// Create a new unauthenticated client.
    ///
    /// This type by itself has very limited capabilities but can be authenticated later on.
    pub fn new_unauthenticated(
        server_url: impl TryInto<Url, Error = url::ParseError>,
    ) -> core::result::Result<Self, InitError> {
        Ok(Client {
            base_url: server_url.try_into()?,
            http: reqwest::Client::new(),
            token: PhantomData,
        })
    }

    /// Create an authenticated client from this unauthenicated client.
    ///
    /// The type of the used access token (app token or client token)
    /// must be provided as a generic parameter or be inferable.
    pub fn authenticate<T: TokenType>(
        self,
        access_token: impl TryInto<HeaderValue, Error = InvalidHeaderValue>,
    ) -> core::result::Result<Client<T>, InitError> {
        Ok(Client {
            base_url: self.base_url,
            http: reqwest::Client::builder()
                .default_headers({
                    let mut headers = HeaderMap::new();
                    headers.insert("X-Gotify-Key", access_token.try_into()?);
                    headers
                })
                .build()
                .map_err(InitError::Reqwest)?,
            token: PhantomData,
        })
    }
}

impl<T> Client<T> {
    async fn request<R: for<'a> serde::Deserialize<'a> + 'static>(
        &self,
        method: Method,
        uri: impl IntoIterator<Item = impl AsRef<str>>,
    ) -> Result<R> {
        let r = self
            .http
            .request(method, self.base_url.append(uri))
            .send()
            .await?;

        if r.status().is_success() {
            if std::any::TypeId::of::<R>() == std::any::TypeId::of::<()>() {
                Ok(serde_json::de::from_str("null").unwrap())
            } else {
                Ok(r.json().await?)
            }
        } else {
            Err(Error::Response(r.json().await?))
        }
    }
    #[cfg(any(feature = "app", feature = "client-core"))]
    async fn request_with_body<R: for<'a> serde::Deserialize<'a> + 'static>(
        &self,
        method: Method,
        uri: impl IntoIterator<Item = impl AsRef<str>>,
        body: impl serde::Serialize,
    ) -> Result<R> {
        let r = match method {
            Method::GET => self
                .http
                .request(method, self.base_url.append(uri))
                .query(&body),
            _ => self
                .http
                .request(method, self.base_url.append(uri))
                .json(&body),
        }
        .send()
        .await?;

        if r.status().is_success() {
            if std::any::TypeId::of::<R>() == std::any::TypeId::of::<()>() {
                Ok(serde_json::de::from_str("null").unwrap())
            } else {
                Ok(r.json().await?)
            }
        } else {
            Err(Error::Response(r.json().await?))
        }
    }
    #[cfg(feature = "manage-messages")]
    async fn request_with_binary_body<R: for<'a> serde::Deserialize<'a> + 'static>(
        &self,
        method: Method,
        uri: impl IntoIterator<Item = impl AsRef<str>>,
        file_name: impl Into<std::borrow::Cow<'static, str>>,
        file_content: impl Into<std::borrow::Cow<'static, [u8]>>,
    ) -> Result<R> {
        use reqwest::multipart::{Form, Part};

        let r = self
            .http
            .request(method, self.base_url.append(uri))
            .multipart(Form::new().part("file", Part::bytes(file_content).file_name(file_name)))
            .send()
            .await?;

        if r.status().is_success() {
            if std::any::TypeId::of::<R>() == std::any::TypeId::of::<()>() {
                Ok(serde_json::de::from_str("null").unwrap())
            } else {
                Ok(r.json().await?)
            }
        } else {
            Err(Error::Response(r.json().await?))
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::testsuite::*;

    #[apply(run_test_server!)]
    #[test]
    async fn authenticate() -> eyre::Result<()> {
        use crate::{AppToken, ClientToken};

        let client = unauthenticated_client();

        let app_client = client
            .as_ref()
            .clone()
            .authenticate::<AppToken>(GOTIFY_APP_TOKEN)?;
        let client_client = client
            .as_ref()
            .clone()
            .authenticate::<ClientToken>(GOTIFY_CLIENT_TOKEN)?;

        app_client.create_message("foobar").await?;
        client_client.get_messages().await?;

        Ok(())
    }
}