summaryrefslogtreecommitdiffstats
path: root/src/plugins/url.rs
blob: b980d3ea8b2783b2095d92fc1f25215bc7c865a6 (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
extern crate regex;
extern crate reqwest;
extern crate select;

use irc::client::prelude::*;
use irc::error::IrcError;

use self::regex::Regex;

use std::str;
use std::io::{self, Read};
use self::reqwest::Client;
use self::reqwest::header::Connection;

use self::select::document::Document;
use self::select::predicate::Name;

use plugin::*;

lazy_static! {
    static ref RE: Regex = Regex::new(r"(^|\s)(https?://\S+)").unwrap();
}

#[derive(PluginName, Debug)]
pub struct Url {
    max_kib: usize,
}

impl Url {
    /// If a file is larger than `max_kib` KiB the download is stopped
    pub fn new(max_kib: usize) -> Url {
        Url {max_kib: max_kib}
    }

    fn grep_url(&self, msg: &str) -> Option<String> {
        match RE.captures(msg) {
            Some(captures) => {
                debug!("Url captures: {:?}", captures);

                Some(captures.get(2).unwrap().as_str().to_string())
            }
            None => None,
        }
    }

    fn download(&self, url: &str) -> Option<String> {
        let response = Client::new()
            .get(url)
            .header(Connection::close())
            .send();

        match response {
            Ok(mut response) => {
                let mut body = String::new();

                // 500 kilobyte buffer
                let mut buf = [0; 500 * 1000];
                let mut written = 0;
                // Read until we reach EOF or max_kib KiB
                loop {
                    let len = match response.read(&mut buf) {
                        Ok(0) => break,
                        Ok(len) => len,
                        Err(ref e) if e.kind() == io::ErrorKind::Interrupted => continue,
                        Err(e) => {
                            debug!("Download from {:?} failed: {}", url, e);
                            return None;
                        }
                    };

                    let slice = match str::from_utf8(&buf[..len]) {
                        Ok(slice) => slice,
                        Err(e) => {
                            debug!("Failed to read bytes from {:?} as UTF8: {}", url, e);
                            return None;
                        }
                    };

                    body.push_str(slice);
                    written += len;

                    // Check if the file is too large to download
                    if written > self.max_kib * 1024 {
                        debug!("Stopping download - File from {:?} is larger than {} KiB", url, self.max_kib);
                        return None;
                    }

                }
                Some(body) // once told me
            }
            Err(e) => {
                debug!("Bad response from {:?}: ({})", url, e);
                return None;
            }
        }
    }

    fn url(&self, text: &str) -> Result<String, &str> {
        let url = match self.grep_url(text) {
            Some(url) => url,
            None => {
                return Err("No Url was found.")
            }
        };


        match self.download(&url) {
            Some(body) => {

                let doc = Document::from(body.as_ref());
                if let Some(title) = doc.find(Name("title")).next() {
                    let title = title.children().next().unwrap();
                    let title_text = title.as_text().unwrap().trim().replace("\n", "|");
                    debug!("Title: {:?}", title);
                    debug!("Text: {:?}", title_text);

                    Ok(title_text)

                } else {
                    Err("No title was found.")
                }
            }
            None => Err("Failed to download document.")
        }
    }
}

impl Plugin for Url {
    fn is_allowed(&self, _: &IrcClient, message: &Message) -> bool {
        match message.command {
            Command::PRIVMSG(_, ref msg) => RE.is_match(msg),
            _ => false,
        }
    }

    fn execute(&self, server: &IrcClient, message: &Message) -> Result<(), IrcError> {
        match message.command {
            Command::PRIVMSG(_, ref content) => {
                match self.url(content) {
                    Ok(title) => server.send_privmsg(&message.response_target().unwrap(), &title),
                    Err(_) => Ok(()),
                }
            }
            _ => Ok(()),
        }
    }

    fn command(&self, server: &IrcClient, command: PluginCommand) -> Result<(), IrcError> {
        server.send_notice(&command.source,
                           "This Plugin does not implement any commands.")
    }

    fn evaluate(&self, _: &IrcClient, command: PluginCommand) -> Result<String, String> {
        self.url(&command.tokens[0]).map_err(|e| String::from(e))
    }
}

#[cfg(test)]
mod tests {}