aboutsummaryrefslogtreecommitdiff
path: root/azalea/src/lib.rs
blob: 8ef02e7c0a48c8627ca5be3e0f15215bb801aa7e (plain)
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
mod bot;
pub mod prelude;

use async_trait::async_trait;
pub use azalea_client::*;
use azalea_protocol::ServerAddress;
use parking_lot::Mutex;
use std::{future::Future, sync::Arc};
use thiserror::Error;

/// Plugins can keep their own personal state, listen to events, and add new functions to Client.
#[async_trait]
pub trait Plugin: Send + Sync {
    async fn handle(self: Arc<Self>, bot: Client, event: Arc<Event>);
}

// pub type HeuristicFn<N, W> = fn(start: &Vertex<N, W>, current: &Vertex<N, W>) -> W;
pub type HandleFn<Fut, S> = fn(Client, Arc<Event>, Arc<Mutex<S>>) -> Fut;

pub struct Options<S, A, Fut>
where
    A: TryInto<ServerAddress>,
    Fut: Future<Output = Result<(), anyhow::Error>>,
{
    pub address: A,
    pub account: Account,
    pub plugins: Vec<Arc<dyn Plugin>>,
    pub state: Arc<Mutex<S>>,
    pub handle: HandleFn<Fut, S>,
}

#[derive(Error, Debug)]
pub enum Error {
    #[error("Invalid address")]
    InvalidAddress,
}

/// Join a Minecraft server.
///
/// ```no_run
/// azalea::start(azalea::Options {
///     account,
///     address: "localhost",
///     state: Arc::new(Mutex::new(State::default())),
///     plugins: vec![&autoeat::Plugin::default()],
///     handle: Box::new(handle),
/// }).await.unwrap();
/// ```
pub async fn start<
    S: Send + 'static,
    A: Send + TryInto<ServerAddress>,
    Fut: Future<Output = Result<(), anyhow::Error>> + Send + 'static,
>(
    options: Options<S, A, Fut>,
) -> Result<(), Error> {
    let address = match options.address.try_into() {
        Ok(address) => address,
        Err(_) => return Err(Error::InvalidAddress),
    };

    let (bot, mut rx) = options.account.join(&address).await.unwrap();

    let state = options.state;
    let bot_plugin = Arc::new(bot::Plugin::default());

    while let Some(event) = rx.recv().await {
        // we put it into an Arc so it's cheaper to clone
        let event = Arc::new(event);

        for plugin in &options.plugins {
            tokio::spawn(plugin.clone().handle(bot.clone(), event.clone()));
        }

        {
            let bot_plugin = bot_plugin.clone();
            let bot = bot.clone();
            let event = event.clone();
            tokio::spawn(bot::Plugin::handle(bot_plugin, bot, event));
        };
        tokio::spawn((options.handle)(bot.clone(), event.clone(), state.clone()));
    }

    Ok(())
}