plugin_interfaces/message/
plugin_message.rs1use crate::{send_to_frontend, PluginHandler};
2use serde_json::json;
3
4#[derive(Debug, Clone)]
6pub enum MessageType {
7 Normal,
9 Success,
11 Warning,
13 Error,
15 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
31pub 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
47pub 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
58pub trait PluginMessage {
60 fn send_message_to_frontend(&self, content: &str) -> bool {
62 self.send_message_to_frontend_typed(content, MessageType::Normal)
63 }
64
65 fn send_message_to_frontend_typed(&self, content: &str, message_type: MessageType) -> bool;
67
68 fn send_success_message(&self, content: &str) -> bool {
70 self.send_message_to_frontend_typed(content, MessageType::Success)
71 }
72
73 fn send_error_message(&self, content: &str) -> bool {
75 self.send_message_to_frontend_typed(content, MessageType::Error)
76 }
77
78 fn send_warning_message(&self, content: &str) -> bool {
80 self.send_message_to_frontend_typed(content, MessageType::Warning)
81 }
82
83 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