aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/factoids/mod.rs
blob: 5f9f99af6d7d20a01e4b061e474ef893b8dcbe6c (plain) (blame)
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
extern crate rlua;

use std::fmt;
use self::rlua::prelude::*;
use irc::client::prelude::*;
use irc::error::Error as IrcError;

use std::sync::Mutex;

use plugin::*;
mod database;
use self::database::Database;

static LUA_SANDBOX: &'static str = include_str!("sandbox.lua");

#[derive(PluginName)]
pub struct Factoids<T: Database> {
    factoids: Mutex<T>,
}

macro_rules! try_lock {
    ( $m:expr ) => {
        match $m.lock() {
            Ok(guard) => guard,
            Err(poisoned) => poisoned.into_inner(),
        }
    }
}

impl<T: Database> Factoids<T> {
    pub fn new(db: T) -> Factoids<T> {
        Factoids { factoids: Mutex::new(db) }
    }

    fn add(&self, server: &IrcServer, command: &mut PluginCommand) -> Result<(), IrcError> {

        if command.tokens.len() < 2 {
            return self.invalid_command(server, command);
        }

        let name = command.tokens.remove(0);

        try_lock!(self.factoids)
            .insert(&name, &command.tokens.join(" "));

        server.send_notice(&command.source, "Successfully added")
    }

    fn get(&self, server: &IrcServer, command: &PluginCommand) -> Result<(), IrcError> {

        if command.tokens.len() < 1 {
            self.invalid_command(server, command)

        } else {
            let name = &command.tokens[0];
            let factoids = try_lock!(self.factoids);
            let factoid = match factoids.get(name) {
                Some(v) => v,
                None => return self.invalid_command(server, command),
            };

            server.send_privmsg(&command.target, &format!("{}: {}", name, factoid))
        }
    }

    fn exec(&self, server: &IrcServer, mut command: PluginCommand) -> Result<(), IrcError> {
        if command.tokens.len() < 1 {
            self.invalid_command(server, &command)

        } else {
            let name = command.tokens.remove(0);

            let factoids = try_lock!(self.factoids);
            let factoid = match factoids.get(&name) {
                Some(v) => v,
                None => return self.invalid_command(server, &command),
            };

            let value = if factoid.starts_with(">") {
                let factoid = String::from(&factoid[1..]);

                if factoid.starts_with(">") {
                    factoid
                } else {
                    match self.run_lua(&name, &factoid, &command) {
                        Ok(v) => v,
                        Err(e) => format!("{}", e),
                    }
                }
            } else {
                factoid
            };

            server.send_privmsg(&command.target, &value)
        }
    }

    fn run_lua(&self,
               name: &str,
               code: &str,
               command: &PluginCommand)
               -> Result<String, rlua::Error> {

        let args = command
            .tokens
            .iter()
            .filter(|x| !x.is_empty())
            .map(ToOwned::to_owned)
            .collect::<Vec<String>>();

        let lua = Lua::new();
        let globals = lua.globals();

        globals.set("factoid", lua.load(code, Some(name))?)?;
        globals.set("args", args)?;
        globals.set("input", command.tokens.join(" "))?;
        globals.set("user", command.source.clone())?;
        globals.set("channel", command.target.clone())?;
        globals.set("output", lua.create_table())?;

        lua.exec::<()>(LUA_SANDBOX, Some(name))?;
        let output: Vec<String> = globals.get::<_, Vec<String>>("output")?;

        Ok(output.join("|").replace("\n", "|"))
    }

    fn invalid_command(&self, server: &IrcServer, command: &PluginCommand) -> Result<(), IrcError> {
        server.send_notice(&command.source, "Invalid Command")
    }
}

impl<T: Database> Plugin for Factoids<T> {
    fn is_allowed(&self, _: &IrcServer, message: &Message) -> bool {
        match message.command {
            Command::PRIVMSG(_, ref content) => content.starts_with('!'),
            _ => false,
        }
    }

    fn execute(&self, server: &IrcServer, message: &Message) -> Result<(), IrcError> {
        if let Command::PRIVMSG(_, mut content) = message.command.clone() {
            content.remove(0);

            let t: Vec<String> = content.split(' ').map(ToOwned::to_owned).collect();

            let c = PluginCommand {
                source: message.source_nickname().unwrap().to_string(),
                target: message.response_target().unwrap().to_string(),
                tokens: t,
            };

            self.exec(server, c)

        } else {
            Ok(())
        }
    }

    fn command(&self, server: &IrcServer, mut command: PluginCommand) -> Result<(), IrcError> {
        if command.tokens.is_empty() {
            return self.invalid_command(server, &command);
        }

        let sub_command = command.tokens.remove(0);
        match sub_command.as_ref() {
            "add" => self.add(server, &mut command),
            "get" => self.get(server, &command),
            "exec" => self.exec(server, command),
            _ => self.invalid_command(server, &command),
        }
    }
}

impl<T: Database> fmt::Debug for Factoids<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Factoids {{ ... }}")
    }
}