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";
#[derive(Clone, Serialize)]
#[serde(tag = "msgtype")]
#[non_exhaustive]
pub enum WeComRobotMessage {
#[serde(rename = "text")]
Text {
text: WeComTextContent,
},
#[serde(rename = "markdown")]
Markdown {
markdown: WeComMarkdownContent,
},
#[serde(rename = "markdown_v2")]
MarkdownV2 {
markdown_v2: WeComMarkdownV2Content,
},
#[serde(rename = "image")]
Image {
image: WeComImageContent,
},
#[serde(rename = "news")]
News {
news: WeComNewsContent,
},
#[serde(rename = "file")]
File {
file: WeComMediaContent,
},
#[serde(rename = "voice")]
Voice {
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()
}
#[must_use]
pub fn markdown(content: impl Into<String>) -> Self {
WeComMarkdownContent::new(content).into()
}
#[must_use]
pub fn markdown_v2(content: impl Into<String>) -> Self {
WeComMarkdownV2Content::new(content).into()
}
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()
}
#[must_use]
pub fn file(media_id: impl Into<String>) -> Self {
Self::File {
file: WeComMediaContent::new(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()),
}
}
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 {
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"));
}
}