loveyu-kit 0.2.0

面向 Axum 项目的可组合 API 工具库
Documentation
//! 图文消息。

use std::fmt;

use serde::Serialize;

use crate::messaging::MessagingError;

use super::{ensure_max_bytes, invalid_message, require_non_empty};

const MAX_ARTICLES: usize = 8;
const MAX_TITLE_BYTES: usize = 128;
const MAX_DESCRIPTION_BYTES: usize = 512;

/// 一条图文消息。
#[derive(Clone, Serialize)]
pub struct WeComNewsArticle {
    title: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    description: Option<String>,
    url: String,
    #[serde(rename = "picurl", skip_serializing_if = "Option::is_none")]
    picture_url: Option<String>,
}

impl WeComNewsArticle {
    /// 创建图文条目。
    #[must_use]
    pub fn new(title: impl Into<String>, url: impl Into<String>) -> Self {
        Self {
            title: title.into(),
            description: None,
            url: url.into(),
            picture_url: None,
        }
    }

    /// 设置图文描述。
    #[must_use]
    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        self.description = some_non_empty(description.into());
        self
    }

    /// 设置 JPG 或 PNG 图片链接。
    #[must_use]
    pub fn with_picture_url(mut self, picture_url: impl Into<String>) -> Self {
        self.picture_url = some_non_empty(picture_url.into());
        self
    }

    fn validate(&self) -> Result<(), MessagingError> {
        require_non_empty("图文标题", &self.title)?;
        require_non_empty("图文跳转链接", &self.url)?;
        // 官方服务端会自动截断,工具库选择提前返错,避免标题被静默改写。
        ensure_max_bytes("图文标题", &self.title, MAX_TITLE_BYTES)?;
        if let Some(description) = &self.description {
            ensure_max_bytes("图文描述", description, MAX_DESCRIPTION_BYTES)?;
        }
        Ok(())
    }
}

impl fmt::Debug for WeComNewsArticle {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("WeComNewsArticle")
            .field("title_bytes", &self.title.len())
            .field("has_description", &self.description.is_some())
            .field("has_picture", &self.picture_url.is_some())
            .finish_non_exhaustive()
    }
}

/// 图文消息体,每条消息支持 1 至 8 条图文。
#[derive(Clone, Serialize)]
pub struct WeComNewsContent {
    articles: Vec<WeComNewsArticle>,
}

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

    /// 返回图文条目。
    #[must_use]
    pub fn articles(&self) -> &[WeComNewsArticle] {
        &self.articles
    }

    pub(crate) fn validate(&self) -> Result<(), MessagingError> {
        if !(1..=MAX_ARTICLES).contains(&self.articles.len()) {
            return Err(invalid_message(format!(
                "图文消息必须包含 1 至 {MAX_ARTICLES} 条图文,当前为 {} 条",
                self.articles.len()
            )));
        }
        self.articles
            .iter()
            .try_for_each(WeComNewsArticle::validate)
    }
}

impl fmt::Debug for WeComNewsContent {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("WeComNewsContent")
            .field("article_count", &self.articles.len())
            .finish()
    }
}

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 super::*;

    #[test]
    fn news_rejects_more_than_eight_articles() {
        let articles = (0..9)
            .map(|index| WeComNewsArticle::new(format!("标题 {index}"), "https://example.com"));
        let error = WeComNewsContent::new(articles).validate().unwrap_err();

        assert!(error.to_string().contains("1 至 8 条"));
    }
}