barkust 0.2.1

A Rust client library and CLI for the Bark push notification service
Documentation
use reqwest::{Client, Url};
use serde::{Deserialize, Serialize};
use std::fmt;

pub use builder::NotificationBuilder;

mod builder;

/// Errors that can occur when interacting with the Bark push service.
#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// The provided base URL could not be parsed.
    #[error("invalid bark server url: {0}")]
    InvalidUrl(#[from] url::ParseError),

    /// An HTTP error occurred while sending the request.
    #[error("http request failed: {0}")]
    Http(#[from] reqwest::Error),

    /// The Bark server returned a non-success status code or error payload.
    #[error("bark api error ({code}): {message}")]
    Api { code: i32, message: String },
}

/// A response returned by the Bark server.
#[derive(Debug, Clone, Deserialize)]
pub struct BarkResponse {
    pub code: i32,
    pub message: String,
    #[serde(default)]
    pub data: Option<serde_json::Value>,
    #[serde(default)]
    pub timestamp: Option<i64>,
}

/// Priority level of a Bark notification.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Level {
    /// Critical notification, ignores Do Not Disturb and mute switch.
    Critical,
    /// Active notification (default).
    Active,
    /// Time-sensitive notification, can break through Focus.
    TimeSensitive,
    /// Passive notification, delivered silently.
    Passive,
}

impl fmt::Display for Level {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Level::Critical => write!(f, "critical"),
            Level::Active => write!(f, "active"),
            Level::TimeSensitive => write!(f, "timeSensitive"),
            Level::Passive => write!(f, "passive"),
        }
    }
}

/// A Bark notification payload.
///
/// Construct one with [`Notification::builder`] or [`NotificationBuilder`].
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Notification {
    #[serde(rename = "device_key", skip_serializing_if = "Option::is_none")]
    device_key: Option<String>,

    #[serde(rename = "device_keys", skip_serializing_if = "Option::is_none")]
    device_keys: Option<Vec<String>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    title: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    subtitle: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    body: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    markdown: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    image: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    sound: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    badge: Option<i32>,

    #[serde(skip_serializing_if = "Option::is_none")]
    icon: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    group: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    url: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    copy: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    action: Option<String>,

    #[serde(rename = "isArchive", skip_serializing_if = "Option::is_none")]
    is_archive: Option<i32>,

    #[serde(rename = "isUrlEncode", skip_serializing_if = "Option::is_none")]
    is_url_encode: Option<i32>,

    #[serde(rename = "autoCopy", skip_serializing_if = "Option::is_none")]
    auto_copy: Option<i32>,

    #[serde(skip_serializing_if = "Option::is_none")]
    level: Option<Level>,

    #[serde(skip_serializing_if = "Option::is_none")]
    volume: Option<i32>,

    #[serde(skip_serializing_if = "Option::is_none")]
    call: Option<i32>,

    #[serde(skip_serializing_if = "Option::is_none")]
    id: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    delete: Option<i32>,

    #[serde(skip_serializing_if = "Option::is_none")]
    ttl: Option<i32>,
}

impl Notification {
    /// Create a new notification builder.
    pub fn builder() -> NotificationBuilder {
        NotificationBuilder::new()
    }

    /// Convenience constructor for a simple title/body notification.
    pub fn new(title: impl Into<String>, body: impl Into<String>) -> Self {
        Self::builder().title(title).body(body).build()
    }
}

/// A client for the Bark push notification service.
#[derive(Debug, Clone)]
pub struct BarkClient {
    client: Client,
    base_url: Url,
    device_key: Option<String>,
}

impl BarkClient {
    /// Create a new client with the default Bark server.
    ///
    /// The `device_key` is optional here; if omitted it must be set on each
    /// [`Notification`] sent.
    pub fn new(device_key: Option<String>) -> Result<Self, Error> {
        Self::with_url("https://api.day.app", device_key)
    }

    /// Create a new client with a custom Bark server URL.
    pub fn with_url(base_url: impl AsRef<str>, device_key: Option<String>) -> Result<Self, Error> {
        let base_url = Url::parse(base_url.as_ref())?;
        Ok(Self {
            client: Client::new(),
            base_url,
            device_key,
        })
    }

    /// Return the configured base URL.
    pub fn base_url(&self) -> &Url {
        &self.base_url
    }

    /// Return the default device key, if one was configured.
    pub fn device_key(&self) -> Option<&str> {
        self.device_key.as_deref()
    }

    /// Send a notification to the Bark server.
    ///
    /// If the notification does not contain a device key, the client's default
    /// key is used. If neither is set, the server will return an error.
    pub async fn send(&self, notification: &Notification) -> Result<BarkResponse, Error> {
        let mut payload = notification.clone();
        if payload.device_key.is_none() {
            payload.device_key.clone_from(&self.device_key);
        }

        let url = self.base_url.join("push")?;
        let response = self.client.post(url).json(&payload).send().await?;

        let status = response.status();
        let body: BarkResponse = response.json().await?;

        if !status.is_success() || body.code != 200 {
            return Err(Error::Api {
                code: body.code,
                message: body.message,
            });
        }

        Ok(body)
    }

    /// Send a simple title/body notification using the client's default key.
    pub async fn send_simple(
        &self,
        title: impl Into<String>,
        body: impl Into<String>,
    ) -> Result<BarkResponse, Error> {
        let notification = Notification::new(title, body);
        self.send(&notification).await
    }

    /// Send a notification to multiple devices.
    ///
    /// `device_keys` overrides any single `device_key` set on the notification
    /// or client.
    pub async fn send_batch(
        &self,
        notification: &Notification,
        device_keys: Vec<String>,
    ) -> Result<BarkResponse, Error> {
        let mut payload = notification.clone();
        if payload.device_keys.is_none() {
            payload.device_keys = Some(device_keys);
        }

        let url = self.base_url.join("push")?;
        let response = self.client.post(url).json(&payload).send().await?;

        let status = response.status();
        let body: BarkResponse = response.json().await?;

        if !status.is_success() || body.code != 200 {
            return Err(Error::Api {
                code: body.code,
                message: body.message,
            });
        }

        Ok(body)
    }
}

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

    #[test]
    fn notification_builder_serializes_expected_fields() {
        let n = Notification::builder()
            .device_key("abc123")
            .title("Hello")
            .body("World")
            .sound("minuet")
            .badge(1)
            .group("test")
            .level(Level::TimeSensitive)
            .auto_copy(true)
            .build();

        let json = serde_json::to_value(&n).unwrap();
        assert_eq!(json["device_key"], "abc123");
        assert_eq!(json["title"], "Hello");
        assert_eq!(json["body"], "World");
        assert_eq!(json["sound"], "minuet");
        assert_eq!(json["badge"], 1);
        assert_eq!(json["group"], "test");
        assert_eq!(json["level"], "timeSensitive");
        assert_eq!(json["autoCopy"], 1);
        assert!(json.get("icon").is_none());
    }

    #[test]
    fn client_default_url_is_official_bark_server() {
        let client = BarkClient::new(Some("key".into())).unwrap();
        assert_eq!(client.base_url().as_str(), "https://api.day.app/");
        assert_eq!(client.device_key(), Some("key"));
    }

    #[test]
    fn client_custom_url() {
        let client = BarkClient::with_url("https://bark.example.com", None).unwrap();
        assert_eq!(client.base_url().as_str(), "https://bark.example.com/");
    }

    #[test]
    fn notification_without_device_key_uses_client_key() {
        let client = BarkClient::new(Some("client-key".into())).unwrap();
        let n = Notification::new("t", "b");
        let mut payload = n.clone();
        if payload.device_key.is_none() {
            payload.device_key.clone_from(&client.device_key);
        }
        assert_eq!(payload.device_key.as_deref(), Some("client-key"));
    }

    #[test]
    fn level_serializes_to_camel_case() {
        assert_eq!(serde_json::to_value(Level::Critical).unwrap(), "critical");
        assert_eq!(serde_json::to_value(Level::Active).unwrap(), "active");
        assert_eq!(
            serde_json::to_value(Level::TimeSensitive).unwrap(),
            "timeSensitive"
        );
        assert_eq!(serde_json::to_value(Level::Passive).unwrap(), "passive");
    }

    #[test]
    fn level_display_matches_serde() {
        assert_eq!(Level::Critical.to_string(), "critical");
        assert_eq!(Level::Active.to_string(), "active");
        assert_eq!(Level::TimeSensitive.to_string(), "timeSensitive");
        assert_eq!(Level::Passive.to_string(), "passive");
    }

    #[test]
    fn boolean_fields_serialize_to_one_or_zero() {
        let n = Notification::builder()
            .archive(true)
            .url_encode(true)
            .auto_copy(false)
            .call(true)
            .build();
        let json = serde_json::to_value(&n).unwrap();
        assert_eq!(json["isArchive"], 1);
        assert_eq!(json["isUrlEncode"], 1);
        assert_eq!(json["autoCopy"], 0);
        assert_eq!(json["call"], 1);
    }

    #[test]
    fn default_notification_is_empty_json_object() {
        let n = Notification::default();
        let json = serde_json::to_value(&n).unwrap();
        assert_eq!(json, serde_json::json!({}));
    }

    #[test]
    fn send_simple_creates_title_body_notification() {
        let client = BarkClient::new(Some("key".into())).unwrap();
        let n = Notification::new("title", "body");
        let json = serde_json::to_value(&n).unwrap();
        assert_eq!(json["title"], "title");
        assert_eq!(json["body"], "body");
        assert!(json["device_key"].is_null());

        let mut payload = n;
        if payload.device_key.is_none() {
            payload.device_key.clone_from(&client.device_key);
        }
        let json = serde_json::to_value(&payload).unwrap();
        assert_eq!(json["device_key"], "key");
    }

    #[test]
    fn bark_response_deserialization() {
        let raw = r#"{"code":200,"message":"success","data":null,"timestamp":1690000000}"#;
        let resp: BarkResponse = serde_json::from_str(raw).unwrap();
        assert_eq!(resp.code, 200);
        assert_eq!(resp.message, "success");
        assert!(resp.data.is_none());
        assert_eq!(resp.timestamp, Some(1690000000));
    }

    #[test]
    fn advanced_fields_serialize_correctly() {
        let n = Notification::builder()
            .subtitle("subtitle text")
            .markdown("# markdown")
            .image("https://example.com/img.png")
            .id("msg-123")
            .delete(true)
            .ttl(3600)
            .build();
        let json = serde_json::to_value(&n).unwrap();
        assert_eq!(json["subtitle"], "subtitle text");
        assert_eq!(json["markdown"], "# markdown");
        assert_eq!(json["image"], "https://example.com/img.png");
        assert_eq!(json["id"], "msg-123");
        assert_eq!(json["delete"], 1);
        assert_eq!(json["ttl"], 3600);
    }

    #[test]
    fn device_keys_serializes_as_array() {
        let n = Notification::builder()
            .device_keys(vec!["key1".into(), "key2".into()])
            .title("batch")
            .build();
        let json = serde_json::to_value(&n).unwrap();
        assert_eq!(json["device_keys"], serde_json::json!(["key1", "key2"]));
    }
}