plugin_interfaces/message/
plugin_message.rs

1use crate::{send_to_frontend, PluginHandler};
2use serde_json::json;
3
4/// 消息类型枚举
5#[derive(Debug, Clone)]
6pub enum MessageType {
7    /// 普通消息
8    Normal,
9    /// 成功消息
10    Success,
11    /// 警告消息
12    Warning,
13    /// 错误消息
14    Error,
15    /// 信息消息
16    Info,
17}
18
19impl MessageType {
20    fn as_str(&self) -> &'static str {
21        match self {
22            MessageType::Normal => "normal",
23            MessageType::Success => "success",
24            MessageType::Warning => "warning",
25            MessageType::Error => "error",
26            MessageType::Info => "info",
27        }
28    }
29}
30
31/// 发送消息到前端(新协议)
32pub fn send_message_to_frontend(plugin_id: &str, content: &str, message_type: MessageType) -> bool {
33    let payload = json!({
34        "type": "plugin_message",
35        "plugin_id": plugin_id,
36        "content": content,
37        "message_type": message_type.as_str(),
38        "timestamp": std::time::SystemTime::now()
39            .duration_since(std::time::UNIX_EPOCH)
40            .unwrap()
41            .as_millis()
42    });
43
44    send_to_frontend("plugin-message", &payload.to_string())
45}
46
47/// 发送消息到前端(兼容旧协议)
48pub fn send_message_to_frontend_legacy(plugin_id: &str, payload: &str) -> bool {
49    send_to_frontend(
50        "plugin-message-response",
51        &format!(
52            "{{\"plugin\": \"{}\", \"response\": \"{}\"}}",
53            plugin_id, payload
54        ),
55    )
56}
57
58/// 插件消息发送器
59pub trait PluginMessage {
60    /// 向前端发送消息(新协议)
61    fn send_message_to_frontend(&self, content: &str) -> bool {
62        self.send_message_to_frontend_typed(content, MessageType::Normal)
63    }
64
65    /// 向前端发送带类型的消息
66    fn send_message_to_frontend_typed(&self, content: &str, message_type: MessageType) -> bool;
67
68    /// 向前端发送成功消息
69    fn send_success_message(&self, content: &str) -> bool {
70        self.send_message_to_frontend_typed(content, MessageType::Success)
71    }
72
73    /// 向前端发送错误消息
74    fn send_error_message(&self, content: &str) -> bool {
75        self.send_message_to_frontend_typed(content, MessageType::Error)
76    }
77
78    /// 向前端发送警告消息
79    fn send_warning_message(&self, content: &str) -> bool {
80        self.send_message_to_frontend_typed(content, MessageType::Warning)
81    }
82
83    /// 向前端发送信息消息
84    fn send_info_message(&self, content: &str) -> bool {
85        self.send_message_to_frontend_typed(content, MessageType::Info)
86    }
87}
88
89impl<T: PluginHandler> PluginMessage for T {
90    fn send_message_to_frontend_typed(&self, content: &str, message_type: MessageType) -> bool {
91        send_message_to_frontend(self.get_metadata().id.as_str(), content, message_type)
92    }
93}
94
95