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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
#![feature(proc_macro_hygiene, decl_macro)]

#[macro_use]
extern crate rocket;

use std::net::SocketAddr;

use log::{debug, LevelFilter};
use parking_lot::RwLock;
use rocket::Data;
use rocket::State;
use saigon_core::content::Content;
use saigon_core::{Adapter, HelpText, Plugin, PluginResponse};

pub type BoxedAdapter = Box<dyn Adapter + Send + Sync>;

pub type BoxedPlugin = Box<dyn Plugin + Send + Sync>;

pub struct Config {
    log_level: LevelFilter,
    addr: SocketAddr,
}

pub struct Bot {
    config: Config,
    adapters: Vec<BoxedAdapter>,
    plugins: Vec<BoxedPlugin>,
}

impl Bot {
    pub fn start(self) {
        self.configure_logger()
            .expect("Failed to configure logging");

        std::env::set_var("ROCKET_ADDRESS", format!("{}", self.config.addr.ip()));
        std::env::set_var("ROCKET_PORT", format!("{}", self.config.addr.port()));

        rocket::ignite()
            .manage(RwLock::new(self))
            .mount("/", routes![index, adapters, plugins])
            .launch();
    }

    fn configure_logger(&self) -> Result<(), log::SetLoggerError> {
        use fern::colors::{Color, ColoredLevelConfig};

        let colors = ColoredLevelConfig::new()
            .error(Color::Magenta)
            .warn(Color::Yellow)
            .info(Color::Blue)
            .debug(Color::Cyan)
            .trace(Color::Green);

        fern::Dispatch::new()
            .format(move |out, message, record| {
                out.finish(format_args!(
                    "[{}][{}] {}",
                    record.target(),
                    colors.color(record.level()),
                    message
                ))
            })
            .level(self.config.log_level)
            .chain(std::io::stdout())
            .apply()
    }
}

pub struct BotBuilder {
    log_level: LevelFilter,
    addr: SocketAddr,
    adapters: Vec<BoxedAdapter>,
    plugins: Vec<BoxedPlugin>,
}

impl BotBuilder {
    pub fn new<A: Into<SocketAddr>>(addr: A) -> Self {
        Self {
            addr: addr.into(),
            ..Default::default()
        }
    }

    pub fn log_level(mut self, level: LevelFilter) -> Self {
        self.log_level = level;
        self
    }

    pub fn add_adapter(mut self, source: BoxedAdapter) -> Self {
        self.adapters.push(source);
        self
    }

    pub fn add_plugin(mut self, plugin: BoxedPlugin) -> Self {
        self.plugins.push(plugin);
        self
    }

    pub fn build(self) -> Result<Bot, &'static str> {
        Ok(Bot {
            config: Config {
                log_level: self.log_level,
                addr: self.addr,
            },
            adapters: self.adapters,
            plugins: self.plugins,
        })
    }
}

impl Default for BotBuilder {
    fn default() -> Self {
        Self {
            log_level: LevelFilter::Info,
            addr: ([127, 0, 0, 1], 3000).into(),
            adapters: Vec::new(),
            plugins: Vec::new(),
        }
    }
}

#[post("/", data = "<payload>")]
fn index(bot: State<RwLock<Bot>>, payload: Data) -> String {
    let mut buffer = Vec::new();
    payload.stream_to(&mut buffer).unwrap();
    let payload = std::str::from_utf8(&buffer).unwrap();
    debug!(target: "saigon", "Payload is {}", payload);

    let command = {
        let mut bot = bot.write();

        bot.adapters
            .iter_mut()
            .find_map(|source| source.handle(&payload))
    };

    debug!(target: "saigon", "Command is {:?}", &command);

    if let Some(command) = command {
        if command.value.to_lowercase() == "help" {
            let mut help_texts = bot
                .read()
                .plugins
                .iter()
                .filter_map(|plugin| plugin.help())
                .collect::<Vec<HelpText>>();

            help_texts.insert(
                0,
                HelpText {
                    command: "help".into(),
                    text: "Displays help information".into(),
                },
            );

            use saigon_core::content::{Content, Table, TableColumn, TableRow};

            let mut table = Table::new();

            table.header.add_row(TableRow {
                columns: vec![
                    TableColumn::new(Content::Text("Command".into())),
                    TableColumn::new(Content::Text("Description".into())),
                ],
            });

            for help in help_texts {
                table.body.add_row(TableRow {
                    columns: vec![
                        TableColumn::new(Content::Text(format!("<code>{}</code>", help.command))),
                        TableColumn::new(Content::Text(help.text)),
                    ],
                });
            }

            return to_html_string(Content::Table(Box::new(table)));
        }

        let mut bot = bot.write();

        bot.plugins
            .iter_mut()
            .filter_map(|plugin| plugin.receive(&command).ok())
            .filter_map(display_response)
            .collect::<String>()
    } else {
        "NO COMMAND".into()
    }
}

fn to_html_string(content: Content) -> String {
    match content {
        Content::Fragment(contents) => contents.into_iter().map(to_html_string).collect::<String>(),
        Content::Text(value) => value,
        Content::Bold(content) => format!("<strong>{}</strong>", to_html_string(*content)),
        Content::Italic(content) => format!("<em>{}</em>", to_html_string(*content)),
        Content::Link(link) => format!(
            "<a href=\"{}\">{}</a>",
            link.url.clone(),
            to_html_string(link.text)
        ),
        Content::Table(table) => {
            let mut parts: Vec<String> = Vec::new();

            parts.push("<table>".into());

            parts.push("<thead>".into());

            for row in table.header.rows {
                parts.push("<tr>".into());

                for column in row.columns {
                    parts.push("<th>".into());
                    parts.push(to_html_string(column.value));
                    parts.push("</th>".into());
                }

                parts.push("</tr>".into());
            }

            parts.push("</thead>".into());

            parts.push("<tbody>".into());

            for row in table.body.rows {
                parts.push("<tr>".into());

                for column in row.columns {
                    parts.push("<td>".into());
                    parts.push(to_html_string(column.value));
                    parts.push("</td>".into());
                }

                parts.push("</tr>".into());
            }

            parts.push("</tbody>".into());

            parts.push("</table>".into());

            parts.into_iter().collect::<String>()
        }
    }
}

fn display_response(response: PluginResponse) -> Option<String> {
    match response {
        PluginResponse::Success(content) => Some(to_html_string(content)),
        PluginResponse::Ignore => None,
    }
}

#[get("/adapters")]
fn adapters(bot: State<RwLock<Bot>>) -> String {
    bot.read()
        .adapters
        .iter()
        .map(|source| format!("{}: v{}\n", source.name(), source.version()))
        .collect::<String>()
}

#[get("/plugins")]
fn plugins(bot: State<RwLock<Bot>>) -> String {
    bot.read()
        .plugins
        .iter()
        .map(|plugin| format!("{}: v{}\n", plugin.name(), plugin.version()))
        .collect::<String>()
}