loveyu-kit 0.2.0

面向 Axum 项目的可组合 API 工具库
Documentation
//! 图片、文件和语音消息。

use std::fmt;

use base64::{Engine, engine::general_purpose::STANDARD};
use md5::{Digest, Md5};
use serde::Serialize;

use crate::messaging::MessagingError;

use super::{invalid_message, require_non_empty};

const MIN_MEDIA_BYTES: u64 = 6;
const MAX_FILE_BYTES: u64 = 20 * 1024 * 1024;
const MAX_VOICE_BYTES: u64 = 2 * 1024 * 1024;
const MAX_IMAGE_BYTES: usize = 2 * 1024 * 1024;
const MAX_IMAGE_BASE64_BYTES: usize = MAX_IMAGE_BYTES.div_ceil(3) * 4;

/// 企业微信媒体上传类型。
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum WeComMediaType {
    /// 普通文件,限制为 5 字节以上且不超过 20 MiB。
    File,
    /// AMR 语音,限制为 5 字节以上且不超过 2 MiB。
    Voice,
}

impl WeComMediaType {
    /// 返回企业微信协议使用的媒体类型名称。
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::File => "file",
            Self::Voice => "voice",
        }
    }

    pub(crate) const fn content_type(self) -> &'static str {
        match self {
            Self::File => "application/octet-stream",
            Self::Voice => "audio/amr",
        }
    }

    /// 返回该媒体类型允许的最大字节数。
    #[must_use]
    pub const fn max_bytes(self) -> u64 {
        match self {
            Self::File => MAX_FILE_BYTES,
            Self::Voice => MAX_VOICE_BYTES,
        }
    }

    pub(crate) fn validate_size(self, size: u64) -> Result<(), MessagingError> {
        if size < MIN_MEDIA_BYTES {
            return Err(invalid_message("上传文件必须大于 5 字节"));
        }
        if size > self.max_bytes() {
            return Err(invalid_message(format!(
                "{} 文件不能超过 {} MiB,当前为 {size} 字节",
                if self == Self::Voice {
                    "语音"
                } else {
                    "普通"
                },
                self.max_bytes() / 1024 / 1024
            )));
        }
        Ok(())
    }

    pub(crate) fn validate_file_name(self, file_name: &str) -> Result<(), MessagingError> {
        require_non_empty("上传文件名", file_name)?;
        if file_name
            .chars()
            .any(|character| character.is_control() || matches!(character, '/' | '\\'))
        {
            return Err(invalid_message("上传文件名不能包含路径分隔符或控制字符"));
        }
        if self == Self::Voice && !file_name.to_ascii_lowercase().ends_with(".amr") {
            return Err(invalid_message("语音上传仅支持 .amr 文件"));
        }
        Ok(())
    }

    pub(crate) fn validate_bytes(self, bytes: &[u8]) -> Result<(), MessagingError> {
        self.validate_size(bytes.len() as u64)?;
        if self == Self::Voice && !is_amr(bytes) {
            return Err(invalid_message("语音文件内容不是有效的 AMR 格式"));
        }
        Ok(())
    }
}

/// Base64 图片消息体。
///
/// 构造时自动计算 Base64 和 MD5,避免两者与原始图片不一致。
#[derive(Clone, Serialize)]
pub struct WeComImageContent {
    base64: String,
    md5: String,
}

impl WeComImageContent {
    /// 从 JPG 或 PNG 原始字节创建图片消息。
    ///
    /// # Errors
    ///
    /// 字节为空、超过 2 MiB 或不是 JPG/PNG 文件时返回消息校验错误。
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, MessagingError> {
        validate_image(bytes)?;
        Ok(Self {
            base64: STANDARD.encode(bytes),
            md5: md5_hex(bytes),
        })
    }

    /// 从已编码的 Base64 和 MD5 创建图片消息。
    ///
    /// 该方法会解码并重新校验 MD5、图片格式和大小。
    ///
    /// # Errors
    ///
    /// Base64 或 MD5 无效、两者不匹配,或图片格式与大小不符合约束时返回错误。
    pub fn from_base64_and_md5(
        base64: impl Into<String>,
        md5: impl Into<String>,
    ) -> Result<Self, MessagingError> {
        let base64 = base64.into();
        let md5 = md5.into();
        let base64 = base64.trim();
        if base64.len() > MAX_IMAGE_BASE64_BYTES {
            return Err(invalid_message("图片 Base64 内容超过 2 MiB 图片上限"));
        }
        let bytes = STANDARD
            .decode(base64)
            .map_err(|_| invalid_message("图片 Base64 内容无效"))?;
        validate_image(&bytes)?;
        let actual_md5 = md5_hex(&bytes);
        if !actual_md5.eq_ignore_ascii_case(md5.trim()) {
            return Err(invalid_message("图片 MD5 与 Base64 内容不一致"));
        }
        Ok(Self {
            base64: base64.to_owned(),
            md5: actual_md5,
        })
    }

    pub(crate) fn validate(&self) -> Result<(), MessagingError> {
        require_non_empty("图片 Base64", &self.base64)?;
        require_non_empty("图片 MD5", &self.md5)
    }
}

fn md5_hex(bytes: &[u8]) -> String {
    const HEX: &[u8; 16] = b"0123456789abcdef";
    let digest = Md5::digest(bytes);
    let mut encoded = String::with_capacity(digest.len() * 2);
    for byte in digest {
        encoded.push(char::from(HEX[usize::from(byte >> 4)]));
        encoded.push(char::from(HEX[usize::from(byte & 0x0f)]));
    }
    encoded
}

impl fmt::Debug for WeComImageContent {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("WeComImageContent")
            .field("base64_bytes", &self.base64.len())
            .field("md5", &"[已隐藏]")
            .finish()
    }
}

/// 已上传文件或语音的消息体。
#[derive(Clone, Serialize)]
pub struct WeComMediaContent {
    media_id: String,
}

impl WeComMediaContent {
    /// 使用同一 Webhook 上传后返回的 `media_id` 创建消息体。
    #[must_use]
    pub fn new(media_id: impl Into<String>) -> Self {
        Self {
            media_id: media_id.into(),
        }
    }

    /// 返回媒体 ID。
    #[must_use]
    pub fn media_id(&self) -> &str {
        &self.media_id
    }

    pub(crate) fn validate(&self) -> Result<(), MessagingError> {
        require_non_empty("媒体 ID", &self.media_id)
    }
}

impl fmt::Debug for WeComMediaContent {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("WeComMediaContent")
            .field("media_id", &"[已隐藏]")
            .finish()
    }
}

pub(in crate::messaging::wecom) fn is_amr(bytes: &[u8]) -> bool {
    bytes.starts_with(b"#!AMR\n") || bytes.starts_with(b"#!AMR-WB\n")
}

fn validate_image(bytes: &[u8]) -> Result<(), MessagingError> {
    if bytes.is_empty() {
        return Err(invalid_message("图片内容不能为空"));
    }
    if bytes.len() > MAX_IMAGE_BYTES {
        return Err(invalid_message(format!(
            "图片不能超过 2 MiB,当前为 {} 字节",
            bytes.len()
        )));
    }
    let is_png = bytes.starts_with(b"\x89PNG\r\n\x1a\n");
    let is_jpeg = bytes.starts_with(&[0xff, 0xd8, 0xff]);
    if !is_png && !is_jpeg {
        return Err(invalid_message("图片仅支持 JPG 或 PNG 格式"));
    }
    Ok(())
}

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

    #[test]
    fn image_content_calculates_matching_base64_and_md5() {
        let mut png = b"\x89PNG\r\n\x1a\n".to_vec();
        png.extend_from_slice(b"test-image");
        let image = WeComImageContent::from_bytes(&png).unwrap();

        assert_eq!(STANDARD.decode(&image.base64).unwrap(), png);
        assert_eq!(image.md5, md5_hex(&png));
    }

    #[test]
    fn image_rejects_unsupported_content() {
        let error = WeComImageContent::from_bytes(b"GIF89a").unwrap_err();
        assert!(error.to_string().contains("仅支持 JPG 或 PNG"));
    }

    #[test]
    fn image_rejects_oversized_base64_before_decoding() {
        let error = WeComImageContent::from_base64_and_md5(
            "A".repeat(MAX_IMAGE_BASE64_BYTES + 1),
            "ignored",
        )
        .unwrap_err();
        assert!(error.to_string().contains("超过 2 MiB"));
    }

    #[test]
    fn voice_requires_amr_header_and_extension() {
        WeComMediaType::Voice
            .validate_file_name("notice.amr")
            .unwrap();
        WeComMediaType::Voice
            .validate_bytes(b"#!AMR\nvoice")
            .unwrap();

        assert!(
            WeComMediaType::Voice
                .validate_file_name("notice.mp3")
                .is_err()
        );
        assert!(WeComMediaType::Voice.validate_bytes(b"not-amr").is_err());
    }
}