2022-07-17 13:10:52 -05:00
|
|
|
use crate::bot::{Context, Trigger};
|
2022-07-16 17:40:58 -05:00
|
|
|
use async_trait::async_trait;
|
|
|
|
use fancy_regex::{Captures, Regex};
|
|
|
|
use htmlescape::decode_html;
|
2022-07-20 16:39:14 -05:00
|
|
|
use hyper::header::HeaderValue;
|
2022-07-17 13:10:52 -05:00
|
|
|
use reqwest::Client;
|
2022-07-16 17:40:58 -05:00
|
|
|
|
|
|
|
pub struct Title {
|
|
|
|
http: Client,
|
2022-07-17 13:10:52 -05:00
|
|
|
title_regex: Regex,
|
2022-07-16 17:40:58 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Title {
|
|
|
|
pub fn new() -> anyhow::Result<Self> {
|
|
|
|
Ok(Title {
|
|
|
|
http: Client::new(),
|
2022-07-26 17:56:00 -05:00
|
|
|
title_regex: Regex::new(r"<title[^>]*>(.*?)</title>")?,
|
2022-07-16 17:40:58 -05:00
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[async_trait]
|
|
|
|
impl Trigger for Title {
|
2022-07-17 13:10:52 -05:00
|
|
|
async fn execute<'a>(
|
|
|
|
&mut self,
|
|
|
|
_msg: Context<'a>,
|
|
|
|
captures: Captures<'a>,
|
|
|
|
) -> anyhow::Result<String> {
|
2022-07-16 17:40:58 -05:00
|
|
|
let url = captures.get(0).unwrap().as_str();
|
|
|
|
tracing::debug!("url: {}", url);
|
|
|
|
|
|
|
|
let request = self.http.get(url).build()?;
|
|
|
|
let response = self.http.execute(request).await?;
|
|
|
|
let headers = response.headers();
|
2022-07-20 16:39:14 -05:00
|
|
|
|
|
|
|
let header = headers.get("Content-Type");
|
|
|
|
let mime = header
|
|
|
|
.map(HeaderValue::to_str)
|
|
|
|
.transpose()?
|
|
|
|
.unwrap_or("text/html");
|
|
|
|
if mime.contains("text/html") {
|
|
|
|
let body = response.text().await?;
|
2022-07-26 17:56:00 -05:00
|
|
|
if let Some(tm) = self.title_regex.captures(&body)?.and_then(|c| c.get(1)) {
|
2022-07-20 16:39:14 -05:00
|
|
|
let title_match = tm.as_str();
|
|
|
|
let result = decode_html(title_match).unwrap_or_else(|_| title_match.to_string());
|
|
|
|
Ok(format!("\x039[Title]\x0311 {}", result))
|
2022-07-16 17:40:58 -05:00
|
|
|
} else {
|
2022-07-20 16:39:14 -05:00
|
|
|
Ok("\x039[Title]\x0311 No title".into())
|
2022-07-16 17:40:58 -05:00
|
|
|
}
|
|
|
|
} else {
|
2022-07-20 16:39:14 -05:00
|
|
|
let content_length = response.content_length().map(|l| (l / 1024).to_string());
|
|
|
|
let size = content_length.as_deref().unwrap_or("unknown");
|
|
|
|
Ok(format!("\x039[Title]\x0311 File: {}; {}kb", mime, size))
|
|
|
|
}
|
2022-07-16 17:40:58 -05:00
|
|
|
}
|
2022-07-17 13:10:52 -05:00
|
|
|
}
|