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
|
extern crate htmlescape;
use irc::client::prelude::*;
use regex::Regex;
use plugin::*;
use utils::Url;
use self::error::*;
use error::ErrorKind as FrippyErrorKind;
use error::FrippyError;
use failure::Fail;
use failure::ResultExt;
lazy_static! {
static ref URL_RE: Regex = Regex::new(r"(^|\s)(https?://\S+)").unwrap();
static ref WORD_RE: Regex = Regex::new(r"(\w+)").unwrap();
}
#[derive(PluginName, Debug)]
pub struct UrlTitles {
max_kib: usize,
}
#[derive(Clone, Debug)]
struct Title(String);
impl From<String> for Title {
fn from(title: String) -> Self {
Title(title)
}
}
impl From<Title> for String {
fn from(title: Title) -> Self {
title.0
}
}
impl Title {
fn find_by_delimiters(body: &str, delimiters: [&str; 3]) -> Result<Self, UrlError> {
let title = body.find(delimiters[0])
.map(|tag| {
body[tag..]
.find(delimiters[1])
.map(|offset| tag + offset + delimiters[1].len())
.map(|start| {
body[start..]
.find(delimiters[2])
.map(|offset| start + offset)
.map(|end| &body[start..end])
})
})
.and_then(|s| s.and_then(|s| s))
.ok_or(ErrorKind::MissingTitle)?;
debug!("delimiters: {:?}", delimiters);
debug!("title: {:?}", title);
htmlescape::decode_html(title)
.map(|t| t.into())
.map_err(|_| ErrorKind::HtmlDecoding.into())
}
fn find_ogtitle<'a>(body: &str) -> Result<Self, UrlError> {
Self::find_by_delimiters(body, ["property=\"og:title\"", "content=\"", "\""])
}
fn find_title<'a>(body: &str) -> Result<Self, UrlError> {
Self::find_by_delimiters(body, ["<title", ">", "</title>"])
}
// TODO Improve logic
fn is_useful(&self, url: &str) -> bool {
for word in WORD_RE.find_iter(&self.0) {
let w = word.as_str().to_lowercase();
if w.len() > 2 && !url.to_lowercase().contains(&w) {
return true;
}
}
return false;
}
fn into_useful_title<'a>(self, url: &str) -> Result<Self, UrlError> {
if self.is_useful(url) {
Ok(self)
} else {
Err(ErrorKind::UselessTitle)?
}
}
fn clean_up(self) -> Self {
self.0.trim().replace('\n', "|").replace('\r', "|").into()
}
pub fn find_useful_ogtitle<'a>(body: &str, url: &str) -> Result<Self, UrlError> {
Self::find_ogtitle(body)
.and_then(|t| t.into_useful_title(url))
.map(|t| t.clean_up())
}
pub fn find_useful_title<'a>(body: &str, url: &str) -> Result<Self, UrlError> {
Self::find_title(body)
.and_then(|t| t.into_useful_title(url))
.map(|t| t.clean_up())
}
}
impl UrlTitles {
/// If a file is larger than `max_kib` KiB the download is stopped
pub fn new(max_kib: usize) -> Self {
UrlTitles { max_kib: max_kib }
}
fn grep_url<'a>(&self, msg: &'a str) -> Option<Url<'a>> {
let captures = URL_RE.captures(msg)?;
debug!("Url captures: {:?}", captures);
Some(captures.get(2)?.as_str().into())
}
fn url(&self, text: &str) -> Result<String, UrlError> {
let url = self.grep_url(text)
.ok_or(ErrorKind::MissingUrl)?
.max_kib(self.max_kib);
let body = url.request().context(ErrorKind::Download)?;
let title = match Title::find_useful_ogtitle(&body, url.as_str()) {
Ok(t) => t,
Err(e) => match e.kind() {
ErrorKind::MissingTitle | ErrorKind::UselessTitle => {
Title::find_useful_title(&body, url.as_str())?
}
_ => Err(e)?,
},
};
Ok(title.into())
}
}
impl Plugin for UrlTitles {
fn execute(&self, _: &IrcClient, message: &Message) -> ExecutionStatus {
match message.command {
Command::PRIVMSG(_, ref msg) => if URL_RE.is_match(msg) {
ExecutionStatus::RequiresThread
} else {
ExecutionStatus::Done
},
_ => ExecutionStatus::Done,
}
}
fn execute_threaded(&self, client: &IrcClient, message: &Message) -> Result<(), FrippyError> {
Ok(match message.command {
Command::PRIVMSG(_, ref content) => match self.url(content) {
Ok(title) => client
.send_privmsg(message.response_target().unwrap(), &title)
.context(FrippyErrorKind::Connection)?,
Err(e) => Err(e).context(FrippyErrorKind::Url)?,
},
_ => (),
})
}
fn command(&self, client: &IrcClient, command: PluginCommand) -> Result<(), FrippyError> {
Ok(client
.send_notice(
&command.source,
"This Plugin does not implement any commands.",
)
.context(FrippyErrorKind::Connection)?)
}
fn evaluate(&self, _: &IrcClient, command: PluginCommand) -> Result<String, String> {
self.url(&command.tokens[0])
.map_err(|e| e.cause().unwrap().to_string())
}
}
pub mod error {
/// A URL plugin error
#[derive(Copy, Clone, Eq, PartialEq, Debug, Fail, Error)]
#[error = "UrlError"]
pub enum ErrorKind {
/// A download error
#[fail(display = "A download error occured")]
Download,
/// Missing URL error
#[fail(display = "No URL was found")]
MissingUrl,
/// Missing title error
#[fail(display = "No title was found")]
MissingTitle,
/// Useless title error
#[fail(display = "Title was not helpful")]
UselessTitle,
/// Html decoding error
#[fail(display = "Failed to decode Html characters")]
HtmlDecoding,
}
}
|