loveyu-kit 0.2.0

面向 Axum 项目的可组合 API 工具库
Documentation
//! 企业微信机器人消息类型。

mod media;
mod news;
mod template_card;
mod text;

use std::fmt;

use serde::Serialize;

use crate::messaging::MessagingError;

pub(super) use media::is_amr;
pub use media::{WeComImageContent, WeComMediaContent, WeComMediaType};
pub use news::{WeComNewsArticle, WeComNewsContent};
pub use template_card::{
    WeComCardAction, WeComCardImage, WeComCardSource, WeComEmphasisContent, WeComHorizontalContent,
    WeComImageTextArea, WeComJumpItem, WeComMainTitle, WeComNewsNoticeCard, WeComQuoteArea,
    WeComSourceColor, WeComTemplateCard, WeComTextNoticeCard, WeComVerticalContent,
};
pub use text::{WeComMarkdownContent, WeComMarkdownV2Content, WeComTextContent};

pub(super) const PROVIDER: &str = "wecom_robot";

/// 企业微信群机器人消息。
///
/// 封闭枚举保证 `msgtype` 与对应消息体始终匹配,不接受任意 JSON。
#[derive(Clone, Serialize)]
#[serde(tag = "msgtype")]
#[non_exhaustive]
pub enum WeComRobotMessage {
    /// 文本消息。
    #[serde(rename = "text")]
    Text {
        /// 文本消息体。
        text: WeComTextContent,
    },
    /// Markdown 消息。
    #[serde(rename = "markdown")]
    Markdown {
        /// Markdown 消息体。
        markdown: WeComMarkdownContent,
    },
    /// Markdown V2 消息。
    #[serde(rename = "markdown_v2")]
    MarkdownV2 {
        /// Markdown V2 消息体。
        markdown_v2: WeComMarkdownV2Content,
    },
    /// Base64 图片消息。
    #[serde(rename = "image")]
    Image {
        /// 图片消息体。
        image: WeComImageContent,
    },
    /// 图文消息。
    #[serde(rename = "news")]
    News {
        /// 图文消息体。
        news: WeComNewsContent,
    },
    /// 文件消息。
    #[serde(rename = "file")]
    File {
        /// 已上传文件的媒体 ID。
        file: WeComMediaContent,
    },
    /// 语音消息。
    #[serde(rename = "voice")]
    Voice {
        /// 已上传语音的媒体 ID。
        voice: WeComMediaContent,
    },
    /// 模板卡片消息。
    #[serde(rename = "template_card")]
    TemplateCard {
        /// 文本通知或图文展示卡片。
        template_card: Box<WeComTemplateCard>,
    },
}

impl WeComRobotMessage {
    /// 创建文本消息。
    #[must_use]
    pub fn text(content: impl Into<String>) -> Self {
        WeComTextContent::new(content).into()
    }

    /// 创建 Markdown 消息。
    #[must_use]
    pub fn markdown(content: impl Into<String>) -> Self {
        WeComMarkdownContent::new(content).into()
    }

    /// 创建 Markdown V2 消息。
    #[must_use]
    pub fn markdown_v2(content: impl Into<String>) -> Self {
        WeComMarkdownV2Content::new(content).into()
    }

    /// 从 JPG 或 PNG 原始字节创建图片消息。
    ///
    /// # Errors
    ///
    /// 图片为空、超过 2 MiB 或不是 JPG/PNG 格式时返回错误。
    pub fn image_from_bytes(bytes: &[u8]) -> Result<Self, MessagingError> {
        Ok(WeComImageContent::from_bytes(bytes)?.into())
    }

    /// 创建图文消息。
    #[must_use]
    pub fn news(articles: impl IntoIterator<Item = WeComNewsArticle>) -> Self {
        WeComNewsContent::new(articles).into()
    }

    /// 创建文件消息,`media_id` 需要先由同一机器人上传获取。
    #[must_use]
    pub fn file(media_id: impl Into<String>) -> Self {
        Self::File {
            file: WeComMediaContent::new(media_id),
        }
    }

    /// 创建语音消息,`media_id` 需要先由同一机器人上传获取。
    #[must_use]
    pub fn voice(media_id: impl Into<String>) -> Self {
        Self::Voice {
            voice: WeComMediaContent::new(media_id),
        }
    }

    /// 创建模板卡片消息。
    #[must_use]
    pub fn template_card(card: impl Into<WeComTemplateCard>) -> Self {
        Self::TemplateCard {
            template_card: Box::new(card.into()),
        }
    }

    /// 校验消息是否满足企业微信协议约束,不发送网络请求。
    ///
    /// # Errors
    ///
    /// 当前消息的必填字段、长度、数量或格式不符合协议时返回错误。
    pub fn validate(&self) -> Result<(), MessagingError> {
        match self {
            Self::Text { text } => text.validate(),
            Self::Markdown { markdown } => markdown.validate(),
            Self::MarkdownV2 { markdown_v2 } => markdown_v2.validate(),
            Self::Image { image } => image.validate(),
            Self::News { news } => news.validate(),
            Self::File { file } | Self::Voice { voice: file } => file.validate(),
            Self::TemplateCard { template_card } => template_card.validate(),
        }
    }

    const fn kind(&self) -> &'static str {
        match self {
            Self::Text { .. } => "text",
            Self::Markdown { .. } => "markdown",
            Self::MarkdownV2 { .. } => "markdown_v2",
            Self::Image { .. } => "image",
            Self::News { .. } => "news",
            Self::File { .. } => "file",
            Self::Voice { .. } => "voice",
            Self::TemplateCard { .. } => "template_card",
        }
    }
}

impl fmt::Debug for WeComRobotMessage {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        // 消息内容可能包含业务或个人信息,Debug 只输出协议类型。
        formatter
            .debug_struct("WeComRobotMessage")
            .field("kind", &self.kind())
            .finish_non_exhaustive()
    }
}

impl From<WeComTextContent> for WeComRobotMessage {
    fn from(text: WeComTextContent) -> Self {
        Self::Text { text }
    }
}

impl From<WeComMarkdownContent> for WeComRobotMessage {
    fn from(markdown: WeComMarkdownContent) -> Self {
        Self::Markdown { markdown }
    }
}

impl From<WeComMarkdownV2Content> for WeComRobotMessage {
    fn from(markdown_v2: WeComMarkdownV2Content) -> Self {
        Self::MarkdownV2 { markdown_v2 }
    }
}

impl From<WeComImageContent> for WeComRobotMessage {
    fn from(image: WeComImageContent) -> Self {
        Self::Image { image }
    }
}

impl From<WeComNewsContent> for WeComRobotMessage {
    fn from(news: WeComNewsContent) -> Self {
        Self::News { news }
    }
}

impl From<WeComTemplateCard> for WeComRobotMessage {
    fn from(template_card: WeComTemplateCard) -> Self {
        Self::TemplateCard {
            template_card: Box::new(template_card),
        }
    }
}

pub(super) fn invalid_message(message: impl Into<String>) -> MessagingError {
    MessagingError::InvalidMessage {
        provider: PROVIDER,
        message: message.into(),
    }
}

pub(super) fn require_non_empty(name: &str, value: &str) -> Result<(), MessagingError> {
    if value.trim().is_empty() {
        return Err(invalid_message(format!("{name}不能为空")));
    }
    Ok(())
}

pub(super) fn ensure_max_bytes(
    name: &str,
    value: &str,
    max_bytes: usize,
) -> Result<(), MessagingError> {
    if value.len() > max_bytes {
        return Err(invalid_message(format!(
            "{name}不能超过 {max_bytes} 字节,当前为 {} 字节",
            value.len()
        )));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::*;

    #[test]
    fn text_message_matches_official_protocol() {
        let message = WeComRobotMessage::from(
            WeComTextContent::new("服务告警")
                .mention_user(" zhangsan ")
                .mention_user("zhangsan")
                .mention_mobile(" 13800138000 ")
                .mention_all(),
        );

        assert_eq!(
            serde_json::to_value(message).unwrap(),
            json!({
                "msgtype": "text",
                "text": {
                    "content": "服务告警",
                    "mentioned_list": ["zhangsan", "@all"],
                    "mentioned_mobile_list": ["13800138000"]
                }
            })
        );
    }

    #[test]
    fn markdown_v2_message_uses_distinct_protocol_field() {
        let message =
            WeComRobotMessage::markdown_v2("| 名称 | 状态 |\n| --- | --- |\n| API | 正常 |");

        assert_eq!(
            serde_json::to_value(message).unwrap(),
            json!({
                "msgtype": "markdown_v2",
                "markdown_v2": {
                    "content": "| 名称 | 状态 |\n| --- | --- |\n| API | 正常 |"
                }
            })
        );
    }

    #[test]
    fn file_and_voice_messages_keep_media_type_separate() {
        assert_eq!(
            serde_json::to_value(WeComRobotMessage::file("file-id")).unwrap(),
            json!({"msgtype": "file", "file": {"media_id": "file-id"}})
        );
        assert_eq!(
            serde_json::to_value(WeComRobotMessage::voice("voice-id")).unwrap(),
            json!({"msgtype": "voice", "voice": {"media_id": "voice-id"}})
        );
    }

    #[test]
    fn debug_output_does_not_expose_message_content_or_mobile() {
        let message = WeComRobotMessage::from(
            WeComTextContent::new("内部错误详情").mention_mobile("13800138000"),
        );
        let debug = format!("{message:?}");

        assert!(!debug.contains("内部错误详情"));
        assert!(!debug.contains("13800138000"));
    }
}