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
|
extern crate regex;
extern crate select;
use irc::client::prelude::*;
use irc::error::IrcError;
use self::regex::Regex;
use self::select::document::Document;
use self::select::predicate::Name;
use plugin::*;
use utils;
use error::FrippyError;
use error::UrlError;
use failure::Fail;
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> {
let captures = RE.captures(msg)?;
debug!("Url captures: {:?}", captures);
Some(captures.get(2)?.as_str().to_owned())
}
fn get_title(&self, body: &str) -> Option<String> {
let doc = Document::from(body.as_ref());
let title = doc.find(Name("title")).next()?;
let title = title.children().next()?;
let title_text = title.as_text()?.trim().replace("\n", "|");
debug!("Title: {:?}", title);
debug!("Text: {:?}", title_text);
Some(title_text)
}
fn url(&self, text: &str) -> Result<String, FrippyError> {
let url = self.grep_url(text).ok_or(UrlError::MissingUrl)?;
let body = utils::download(self.max_kib, &url)?;
Ok(self.get_title(&body).ok_or(UrlError::MissingTitle)?)
}
}
impl Plugin for Url {
fn execute(&self, _: &IrcClient, message: &Message) -> ExecutionStatus {
match message.command {
Command::PRIVMSG(_, ref msg) => if RE.is_match(msg) {
ExecutionStatus::RequiresThread
} else {
ExecutionStatus::Done
},
_ => ExecutionStatus::Done,
}
}
fn execute_threaded(&self, client: &IrcClient, message: &Message) -> Result<(), IrcError> {
match message.command {
Command::PRIVMSG(_, ref content) => match self.url(content) {
Ok(title) => client.send_privmsg(message.response_target().unwrap(), &title),
Err(e) => {
error!("Url plugin error: {}", e);
Ok(())
}
},
_ => Ok(()),
}
}
fn command(&self, client: &IrcClient, command: PluginCommand) -> Result<(), IrcError> {
client.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| e.cause().unwrap().to_string())
}
}
#[cfg(test)]
mod tests {}
|