dragonfly_plugin/server/
server.rs

1//! Lightweight handle for sending actions and subscriptions to the host.
2//!
3//! Plugin authors receive a [`Server`] reference in every event handler.
4//! It can be cloned freely and used to send actions like `send_chat`,
5//! `teleport`, or `world_set_block` back to the Dragonfly host.
6
7use tokio::sync::mpsc;
8
9use crate::types::{self, PluginToHost};
10
11#[derive(Clone)]
12pub struct Server {
13    pub plugin_id: String,
14    pub sender: mpsc::Sender<PluginToHost>,
15}
16
17impl Server {
18    /// Helper to build and send a single action.
19    pub async fn send_action(
20        &self,
21        kind: types::action::Kind,
22    ) -> Result<(), mpsc::error::SendError<PluginToHost>> {
23        let action = types::Action {
24            correlation_id: None,
25            kind: Some(kind),
26        };
27        let batch = types::ActionBatch {
28            actions: vec![action],
29        };
30        let msg = PluginToHost {
31            plugin_id: self.plugin_id.clone(),
32            payload: Some(types::PluginPayload::Actions(batch)),
33        };
34        self.sender.send(msg).await
35    }
36
37    /// Helper to send a batch of actions.
38    pub async fn send_actions(
39        &self,
40        actions: Vec<types::Action>,
41    ) -> Result<(), mpsc::error::SendError<PluginToHost>> {
42        let batch = types::ActionBatch { actions };
43        let msg = PluginToHost {
44            plugin_id: self.plugin_id.clone(),
45            payload: Some(types::PluginPayload::Actions(batch)),
46        };
47        self.sender.send(msg).await
48    }
49
50    /// Subscribe to a list of game events.
51    pub async fn subscribe(
52        &self,
53        events: Vec<types::EventType>,
54    ) -> Result<(), mpsc::error::SendError<PluginToHost>> {
55        let sub = types::EventSubscribe {
56            events: events.into_iter().map(|e| e.into()).collect(),
57        };
58        let msg = PluginToHost {
59            plugin_id: self.plugin_id.clone(),
60            payload: Some(types::PluginPayload::Subscribe(sub)),
61        };
62        self.sender.send(msg).await
63    }
64}
65
66mod helpers;