use std::fmt;
use serde::Serialize;
use crate::messaging::MessagingError;
use super::{invalid_message, require_non_empty};
const MAX_HORIZONTAL_CONTENT: usize = 6;
const MAX_JUMP_ITEMS: usize = 3;
const MAX_VERTICAL_CONTENT: usize = 4;
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub enum WeComSourceColor {
#[default]
Gray,
Black,
Red,
Green,
}
impl WeComSourceColor {
const fn code(self) -> u8 {
match self {
Self::Gray => 0,
Self::Black => 1,
Self::Red => 2,
Self::Green => 3,
}
}
}
#[derive(Clone, Serialize)]
pub struct WeComCardAction {
#[serde(rename = "type")]
action_type: u8,
#[serde(skip_serializing_if = "Option::is_none")]
url: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
appid: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pagepath: Option<String>,
}
impl WeComCardAction {
#[must_use]
pub fn url(url: impl Into<String>) -> Self {
Self {
action_type: 1,
url: Some(url.into()),
appid: None,
pagepath: None,
}
}
#[must_use]
pub fn mini_program(appid: impl Into<String>) -> Self {
Self {
action_type: 2,
url: None,
appid: Some(appid.into()),
pagepath: None,
}
}
#[must_use]
pub fn with_page_path(mut self, page_path: impl Into<String>) -> Self {
self.pagepath = some_non_empty(page_path.into());
self
}
fn validate(&self, name: &str) -> Result<(), MessagingError> {
match self.action_type {
1 => require_non_empty(name, self.url.as_deref().unwrap_or_default()),
2 => require_non_empty(name, self.appid.as_deref().unwrap_or_default()),
_ => Err(invalid_message(format!("{name}类型无效"))),
}
}
}
#[derive(Clone, Default, Serialize)]
pub struct WeComCardSource {
#[serde(skip_serializing_if = "Option::is_none")]
icon_url: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
desc: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
desc_color: Option<u8>,
}
impl WeComCardSource {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with_icon_url(mut self, icon_url: impl Into<String>) -> Self {
self.icon_url = some_non_empty(icon_url.into());
self
}
#[must_use]
pub fn with_description(mut self, description: impl Into<String>) -> Self {
self.desc = some_non_empty(description.into());
self
}
#[must_use]
pub const fn with_color(mut self, color: WeComSourceColor) -> Self {
self.desc_color = Some(color.code());
self
}
}
#[derive(Clone, Serialize)]
pub struct WeComMainTitle {
title: String,
#[serde(skip_serializing_if = "Option::is_none")]
desc: Option<String>,
}
impl WeComMainTitle {
#[must_use]
pub fn new(title: impl Into<String>) -> Self {
Self {
title: title.into(),
desc: None,
}
}
#[must_use]
pub fn with_description(mut self, description: impl Into<String>) -> Self {
self.desc = some_non_empty(description.into());
self
}
}
#[derive(Clone, Default, Serialize)]
pub struct WeComEmphasisContent {
#[serde(skip_serializing_if = "Option::is_none")]
title: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
desc: Option<String>,
}
impl WeComEmphasisContent {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with_title(mut self, title: impl Into<String>) -> Self {
self.title = some_non_empty(title.into());
self
}
#[must_use]
pub fn with_description(mut self, description: impl Into<String>) -> Self {
self.desc = some_non_empty(description.into());
self
}
}
#[derive(Clone, Default, Serialize)]
pub struct WeComQuoteArea {
#[serde(flatten, skip_serializing_if = "Option::is_none")]
action: Option<WeComCardAction>,
#[serde(skip_serializing_if = "Option::is_none")]
title: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
quote_text: Option<String>,
}
impl WeComQuoteArea {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with_action(mut self, action: WeComCardAction) -> Self {
self.action = Some(action);
self
}
#[must_use]
pub fn with_title(mut self, title: impl Into<String>) -> Self {
self.title = some_non_empty(title.into());
self
}
#[must_use]
pub fn with_text(mut self, text: impl Into<String>) -> Self {
self.quote_text = some_non_empty(text.into());
self
}
fn validate(&self) -> Result<(), MessagingError> {
if let Some(action) = &self.action {
action.validate("引用区域跳转参数")?;
}
if self.title.is_none() && self.quote_text.is_none() {
return Err(invalid_message("引用区域标题和文案至少需要一项"));
}
Ok(())
}
}
#[derive(Clone, Serialize)]
pub struct WeComHorizontalContent {
#[serde(rename = "type", skip_serializing_if = "Option::is_none")]
content_type: Option<u8>,
keyname: String,
#[serde(skip_serializing_if = "Option::is_none")]
value: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
url: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
media_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
userid: Option<String>,
}
impl WeComHorizontalContent {
#[must_use]
pub fn text(key: impl Into<String>, value: impl Into<String>) -> Self {
Self::new(None, key, Some(value.into()), None, None, None)
}
#[must_use]
pub fn url(key: impl Into<String>, value: impl Into<String>, url: impl Into<String>) -> Self {
Self::new(
Some(1),
key,
Some(value.into()),
Some(url.into()),
None,
None,
)
}
#[must_use]
pub fn file(
key: impl Into<String>,
file_name: impl Into<String>,
media_id: impl Into<String>,
) -> Self {
Self::new(
Some(2),
key,
Some(file_name.into()),
None,
Some(media_id.into()),
None,
)
}
#[must_use]
pub fn user(
key: impl Into<String>,
value: impl Into<String>,
user_id: impl Into<String>,
) -> Self {
Self::new(
Some(3),
key,
Some(value.into()),
None,
None,
Some(user_id.into()),
)
}
fn new(
content_type: Option<u8>,
key: impl Into<String>,
value: Option<String>,
url: Option<String>,
media_id: Option<String>,
userid: Option<String>,
) -> Self {
Self {
content_type,
keyname: key.into(),
value: value.and_then(some_non_empty),
url: url.and_then(some_non_empty),
media_id: media_id.and_then(some_non_empty),
userid: userid.and_then(some_non_empty),
}
}
fn validate(&self) -> Result<(), MessagingError> {
require_non_empty("卡片水平条目标题", &self.keyname)?;
match self.content_type {
None => Ok(()),
Some(1) => {
require_non_empty("卡片水平条目 URL", self.url.as_deref().unwrap_or_default())
}
Some(2) => require_non_empty(
"卡片水平条目媒体 ID",
self.media_id.as_deref().unwrap_or_default(),
),
Some(3) => require_non_empty(
"卡片水平条目用户 ID",
self.userid.as_deref().unwrap_or_default(),
),
Some(_) => Err(invalid_message("卡片水平条目类型无效")),
}
}
}
#[derive(Clone, Serialize)]
pub struct WeComJumpItem {
#[serde(flatten, skip_serializing_if = "Option::is_none")]
action: Option<WeComCardAction>,
title: String,
}
impl WeComJumpItem {
#[must_use]
pub fn text(title: impl Into<String>) -> Self {
Self {
action: None,
title: title.into(),
}
}
#[must_use]
pub fn url(title: impl Into<String>, url: impl Into<String>) -> Self {
Self {
action: Some(WeComCardAction::url(url)),
title: title.into(),
}
}
#[must_use]
pub fn mini_program(title: impl Into<String>, appid: impl Into<String>) -> Self {
Self {
action: Some(WeComCardAction::mini_program(appid)),
title: title.into(),
}
}
#[must_use]
pub fn with_page_path(mut self, page_path: impl Into<String>) -> Self {
if let Some(action) = self.action.take() {
self.action = Some(action.with_page_path(page_path));
}
self
}
fn validate(&self) -> Result<(), MessagingError> {
require_non_empty("卡片跳转条目标题", &self.title)?;
if let Some(action) = &self.action {
action.validate("卡片跳转条目参数")?;
}
Ok(())
}
}
#[derive(Clone, Serialize)]
pub struct WeComCardImage {
url: String,
#[serde(skip_serializing_if = "Option::is_none")]
aspect_ratio: Option<f64>,
}
impl WeComCardImage {
#[must_use]
pub fn new(url: impl Into<String>) -> Self {
Self {
url: url.into(),
aspect_ratio: None,
}
}
#[must_use]
pub const fn with_aspect_ratio(mut self, aspect_ratio: f64) -> Self {
self.aspect_ratio = Some(aspect_ratio);
self
}
fn validate(&self) -> Result<(), MessagingError> {
require_non_empty("卡片图片 URL", &self.url)?;
if let Some(ratio) = self.aspect_ratio
&& (!(1.3..=2.25).contains(&ratio) || !ratio.is_finite())
{
return Err(invalid_message("卡片图片宽高比必须在 1.3 至 2.25 之间"));
}
Ok(())
}
}
#[derive(Clone, Serialize)]
pub struct WeComImageTextArea {
#[serde(flatten, skip_serializing_if = "Option::is_none")]
action: Option<WeComCardAction>,
#[serde(skip_serializing_if = "Option::is_none")]
title: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
desc: Option<String>,
image_url: String,
}
impl WeComImageTextArea {
#[must_use]
pub fn new(image_url: impl Into<String>) -> Self {
Self {
action: None,
title: None,
desc: None,
image_url: image_url.into(),
}
}
#[must_use]
pub fn with_action(mut self, action: WeComCardAction) -> Self {
self.action = Some(action);
self
}
#[must_use]
pub fn with_title(mut self, title: impl Into<String>) -> Self {
self.title = some_non_empty(title.into());
self
}
#[must_use]
pub fn with_description(mut self, description: impl Into<String>) -> Self {
self.desc = some_non_empty(description.into());
self
}
fn validate(&self) -> Result<(), MessagingError> {
require_non_empty("左图右文图片 URL", &self.image_url)?;
if let Some(action) = &self.action {
action.validate("左图右文跳转参数")?;
}
Ok(())
}
}
#[derive(Clone, Serialize)]
pub struct WeComVerticalContent {
title: String,
#[serde(skip_serializing_if = "Option::is_none")]
desc: Option<String>,
}
impl WeComVerticalContent {
#[must_use]
pub fn new(title: impl Into<String>) -> Self {
Self {
title: title.into(),
desc: None,
}
}
#[must_use]
pub fn with_description(mut self, description: impl Into<String>) -> Self {
self.desc = some_non_empty(description.into());
self
}
fn validate(&self) -> Result<(), MessagingError> {
require_non_empty("卡片垂直内容标题", &self.title)
}
}
#[derive(Clone, Serialize)]
pub struct WeComTextNoticeCard {
card_type: &'static str,
#[serde(skip_serializing_if = "Option::is_none")]
source: Option<WeComCardSource>,
main_title: WeComMainTitle,
#[serde(skip_serializing_if = "Option::is_none")]
emphasis_content: Option<WeComEmphasisContent>,
#[serde(skip_serializing_if = "Option::is_none")]
quote_area: Option<WeComQuoteArea>,
#[serde(skip_serializing_if = "Option::is_none")]
sub_title_text: Option<String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
horizontal_content_list: Vec<WeComHorizontalContent>,
#[serde(skip_serializing_if = "Vec::is_empty")]
jump_list: Vec<WeComJumpItem>,
card_action: WeComCardAction,
}
impl WeComTextNoticeCard {
#[must_use]
pub const fn new(main_title: WeComMainTitle, card_action: WeComCardAction) -> Self {
Self {
card_type: "text_notice",
source: None,
main_title,
emphasis_content: None,
quote_area: None,
sub_title_text: None,
horizontal_content_list: Vec::new(),
jump_list: Vec::new(),
card_action,
}
}
#[must_use]
pub fn with_source(mut self, source: WeComCardSource) -> Self {
self.source = Some(source);
self
}
#[must_use]
pub fn with_emphasis(mut self, emphasis: WeComEmphasisContent) -> Self {
self.emphasis_content = Some(emphasis);
self
}
#[must_use]
pub fn with_quote(mut self, quote: WeComQuoteArea) -> Self {
self.quote_area = Some(quote);
self
}
#[must_use]
pub fn with_subtitle(mut self, subtitle: impl Into<String>) -> Self {
self.sub_title_text = some_non_empty(subtitle.into());
self
}
#[must_use]
pub fn with_horizontal_content(mut self, content: WeComHorizontalContent) -> Self {
self.horizontal_content_list.push(content);
self
}
#[must_use]
pub fn with_jump(mut self, jump: WeComJumpItem) -> Self {
self.jump_list.push(jump);
self
}
fn validate(&self) -> Result<(), MessagingError> {
if self.main_title.title.trim().is_empty() && self.sub_title_text.is_none() {
return Err(invalid_message("文本卡片主标题和二级文本至少需要一项"));
}
self.card_action.validate("卡片整体跳转参数")?;
validate_optional_quote(self.quote_area.as_ref())?;
validate_horizontal(&self.horizontal_content_list)?;
validate_jumps(&self.jump_list)
}
}
#[derive(Clone, Serialize)]
pub struct WeComNewsNoticeCard {
card_type: &'static str,
#[serde(skip_serializing_if = "Option::is_none")]
source: Option<WeComCardSource>,
main_title: WeComMainTitle,
card_image: WeComCardImage,
#[serde(skip_serializing_if = "Option::is_none")]
image_text_area: Option<WeComImageTextArea>,
#[serde(skip_serializing_if = "Option::is_none")]
quote_area: Option<WeComQuoteArea>,
#[serde(skip_serializing_if = "Vec::is_empty")]
vertical_content_list: Vec<WeComVerticalContent>,
#[serde(skip_serializing_if = "Vec::is_empty")]
horizontal_content_list: Vec<WeComHorizontalContent>,
#[serde(skip_serializing_if = "Vec::is_empty")]
jump_list: Vec<WeComJumpItem>,
card_action: WeComCardAction,
}
impl WeComNewsNoticeCard {
#[must_use]
pub const fn new(
main_title: WeComMainTitle,
card_image: WeComCardImage,
card_action: WeComCardAction,
) -> Self {
Self {
card_type: "news_notice",
source: None,
main_title,
card_image,
image_text_area: None,
quote_area: None,
vertical_content_list: Vec::new(),
horizontal_content_list: Vec::new(),
jump_list: Vec::new(),
card_action,
}
}
#[must_use]
pub fn with_source(mut self, source: WeComCardSource) -> Self {
self.source = Some(source);
self
}
#[must_use]
pub fn with_image_text_area(mut self, area: WeComImageTextArea) -> Self {
self.image_text_area = Some(area);
self
}
#[must_use]
pub fn with_quote(mut self, quote: WeComQuoteArea) -> Self {
self.quote_area = Some(quote);
self
}
#[must_use]
pub fn with_vertical_content(mut self, content: WeComVerticalContent) -> Self {
self.vertical_content_list.push(content);
self
}
#[must_use]
pub fn with_horizontal_content(mut self, content: WeComHorizontalContent) -> Self {
self.horizontal_content_list.push(content);
self
}
#[must_use]
pub fn with_jump(mut self, jump: WeComJumpItem) -> Self {
self.jump_list.push(jump);
self
}
fn validate(&self) -> Result<(), MessagingError> {
require_non_empty("图文卡片主标题", &self.main_title.title)?;
self.card_image.validate()?;
self.card_action.validate("卡片整体跳转参数")?;
if let Some(area) = &self.image_text_area {
area.validate()?;
}
validate_optional_quote(self.quote_area.as_ref())?;
if self.vertical_content_list.len() > MAX_VERTICAL_CONTENT {
return Err(invalid_message(format!(
"卡片垂直内容不能超过 {MAX_VERTICAL_CONTENT} 条"
)));
}
self.vertical_content_list
.iter()
.try_for_each(WeComVerticalContent::validate)?;
validate_horizontal(&self.horizontal_content_list)?;
validate_jumps(&self.jump_list)
}
}
#[derive(Clone, Serialize)]
#[serde(untagged)]
#[non_exhaustive]
pub enum WeComTemplateCard {
TextNotice(WeComTextNoticeCard),
NewsNotice(WeComNewsNoticeCard),
}
impl WeComTemplateCard {
pub(crate) fn validate(&self) -> Result<(), MessagingError> {
match self {
Self::TextNotice(card) => card.validate(),
Self::NewsNotice(card) => card.validate(),
}
}
}
impl fmt::Debug for WeComTemplateCard {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
let kind = match self {
Self::TextNotice(_) => "text_notice",
Self::NewsNotice(_) => "news_notice",
};
formatter
.debug_struct("WeComTemplateCard")
.field("kind", &kind)
.finish_non_exhaustive()
}
}
impl From<WeComTextNoticeCard> for WeComTemplateCard {
fn from(card: WeComTextNoticeCard) -> Self {
Self::TextNotice(card)
}
}
impl From<WeComNewsNoticeCard> for WeComTemplateCard {
fn from(card: WeComNewsNoticeCard) -> Self {
Self::NewsNotice(card)
}
}
fn validate_optional_quote(quote: Option<&WeComQuoteArea>) -> Result<(), MessagingError> {
if let Some(quote) = quote {
quote.validate()?;
}
Ok(())
}
fn validate_horizontal(values: &[WeComHorizontalContent]) -> Result<(), MessagingError> {
if values.len() > MAX_HORIZONTAL_CONTENT {
return Err(invalid_message(format!(
"卡片水平内容不能超过 {MAX_HORIZONTAL_CONTENT} 条"
)));
}
values.iter().try_for_each(WeComHorizontalContent::validate)
}
fn validate_jumps(values: &[WeComJumpItem]) -> Result<(), MessagingError> {
if values.len() > MAX_JUMP_ITEMS {
return Err(invalid_message(format!(
"卡片跳转指引不能超过 {MAX_JUMP_ITEMS} 条"
)));
}
values.iter().try_for_each(WeComJumpItem::validate)
}
fn some_non_empty(value: String) -> Option<String> {
let trimmed = value.trim();
if trimmed.is_empty() {
None
} else if trimmed.len() == value.len() {
Some(value)
} else {
Some(trimmed.to_owned())
}
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
#[test]
fn text_notice_card_matches_protocol_shape() {
let card = WeComTemplateCard::from(
WeComTextNoticeCard::new(
WeComMainTitle::new("发布完成").with_description("生产环境"),
WeComCardAction::url("https://example.com/releases/1"),
)
.with_horizontal_content(WeComHorizontalContent::text("版本", "1.0.0")),
);
assert_eq!(
serde_json::to_value(card).unwrap(),
json!({
"card_type": "text_notice",
"main_title": { "title": "发布完成", "desc": "生产环境" },
"horizontal_content_list": [{ "keyname": "版本", "value": "1.0.0" }],
"card_action": { "type": 1, "url": "https://example.com/releases/1" }
})
);
}
#[test]
fn news_card_rejects_invalid_aspect_ratio() {
let card = WeComTemplateCard::from(WeComNewsNoticeCard::new(
WeComMainTitle::new("日报"),
WeComCardImage::new("https://example.com/image.png").with_aspect_ratio(3.0),
WeComCardAction::url("https://example.com"),
));
let error = card.validate().unwrap_err();
assert!(error.to_string().contains("宽高比必须在 1.3 至 2.25"));
}
}