1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
//! Types used for creating plugins.

use std::any::Any;

use async_trait::async_trait;

use crate::{plugins::manager::PluginsManager, server::Client};

/// A main plugin trait.
#[async_trait]
pub trait Plugin: Any + Send + Sync {
    /// Name of the plugin.
    fn name(&self) -> &'static str;
    /// A function that will be executed when the plugin is loaded.
    async fn on_load(&self);
}

/// Add a command to the plugin.
#[async_trait]
pub trait Command: Any + Send + Sync {
    /// Name of the command.
    fn name(&self) -> &'static str;
    /// Aliases for the command.
    fn aliases(&self) -> Vec<&'static str>;
    /// Help message of the command.
    fn help(&self) -> &'static str;
    /// Usage message of the command.
    fn usage(&self) -> &'static str;
    /// Command function.
    async fn execute(&self, client: &Client, args: Vec<&str>) -> anyhow::Result<()>;
}

/// All possible to run events.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EventType {
    /// On client connected.
    OnConnect,
    /// On client sent message.
    OnSend,
    /// Event executed before command execute (e.g. for disable command).
    OnCommand,
}

/// All possible to run events.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EventData {
    /// for `onCommand` event
    Command(String),
    /// No data
    None,
}

/// Add a event to the plugin.
#[async_trait]
pub trait Event: Any + Send + Sync {
    /// Type of the event.
    fn event(&self) -> EventType;
    /// Event function.
    async fn execute(&self, client: &Client, data: EventData) -> anyhow::Result<()>;
}

/// A plugin registrar trait.
pub trait Registrar {
    /// Function to register plugins.
    fn register_plugins(&mut self, plugin: Box<dyn Plugin>);
    /// Function to register commands.
    fn register_commands(&mut self, command: Box<dyn Command>);
    /// Function to register events.
    fn register_events(&mut self, event: Box<dyn Event>);
}

impl Registrar for PluginsManager {
    fn register_plugins(&mut self, plugin: Box<dyn Plugin>) {
        self.plugins.push(plugin)
    }

    fn register_commands(&mut self, command: Box<dyn Command>) {
        self.commands.push(command)
    }

    fn register_events(&mut self, event: Box<dyn Event>) {
        self.events.push(event)
    }
}