1pub use ntfy_types::{
2 NtfyAction, NtfyActionType, NtfyAttachment, NtfyErrorResponse, NtfyMsg, NtfyPriority,
3 NtfyResponse,
4};
5use reqwest::{Client, Method, RequestBuilder};
6
7#[derive(Clone, Debug)]
8pub struct NtfySettings {
9 pub host: String,
10 pub authorization: Option<NtfyAuthorization>,
11}
12
13#[derive(Clone, Debug)]
14pub struct NtfyAuthorization {
15 pub username: String,
16 pub password: String,
17}
18
19#[derive(Clone, Debug)]
20pub struct NtfyApi {
21 settings: NtfySettings,
22 client: Client,
23}
24
25impl NtfyApi {
26 pub fn new(settings: NtfySettings) -> NtfyApi {
27 let client = Client::new();
28 NtfyApi { settings, client }
29 }
30
31 fn request_builder(&self, method: Method, url: &str) -> RequestBuilder {
32 let req = self.client.request(method, url);
33 if let Some(creds) = &self.settings.authorization {
34 req.basic_auth(&creds.username, Some(&creds.password))
35 } else {
36 req
37 }
38 }
39
40 pub async fn post(&self, body: &NtfyMsg) -> Result<NtfyResponse, NtfyError> {
41 let response = self
42 .request_builder(Method::POST, &self.settings.host)
43 .json(&body)
44 .send()
45 .await?;
46 if response.status().is_success() {
47 Ok(response.json::<NtfyResponse>().await?)
48 } else {
49 Err(NtfyError::ApiError(
50 response.json::<NtfyErrorResponse>().await?,
51 ))
52 }
53 }
54}
55
56impl Default for NtfyApi {
57 fn default() -> Self {
58 Self {
59 settings: Default::default(),
60 client: Default::default(),
61 }
62 }
63}
64
65impl Default for NtfySettings {
66 fn default() -> Self {
67 Self {
68 host: String::from("https://ntfy.sh/"),
69 authorization: None,
70 }
71 }
72}
73
74#[derive(Debug)]
75pub enum NtfyError {
76 ApiError(NtfyErrorResponse),
77 ReqwestError(reqwest::Error),
78}
79
80impl From<reqwest::Error> for NtfyError {
81 fn from(e: reqwest::Error) -> Self {
82 NtfyError::ReqwestError(e)
83 }
84}