aboutsummaryrefslogtreecommitdiffstats
path: root/src/commands/web.rs
blob: fc44d7b4d20b979632d4e8e2d5681e5972aac2ea (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
use std::time::Duration;

use poise::serenity_prelude as serenity;
use scraper::{Html, Selector};

use crate::Data;
use crate::error::{Error, Result};
use crate::lang;

type Context<'a> = poise::Context<'a, Data, Error>;

/// Search the web via DuckDuckGo
#[poise::command(slash_command)]
pub async fn web(ctx: Context<'_>, #[description = "Search query"] query: String) -> Result<()> {
    ctx.defer().await?;

    let url = format!(
        "https://html.duckduckgo.com/html/?q={}",
        urlencoding(&query)
    );
    let html = ctx
        .data()
        .http_client
        .get(&url)
        .timeout(Duration::from_secs(15))
        .send()
        .await?
        .text()
        .await?;

    let results = {
        let document = Html::parse_document(&html);

        let result_selector = Selector::parse(".result").unwrap();
        let title_selector = Selector::parse(".result__title a").unwrap();
        let snippet_selector = Selector::parse(".result__snippet").unwrap();

        let mut results = Vec::new();
        for result in document.select(&result_selector).take(5) {
            let title = result
                .select(&title_selector)
                .next()
                .map(|a| a.text().collect::<String>())
                .unwrap_or_default();

            let url = result
                .select(&title_selector)
                .next()
                .and_then(|a| a.attr("href"))
                .unwrap_or("")
                .to_string();

            let snippet = result
                .select(&snippet_selector)
                .next()
                .map(|s| s.text().collect::<String>())
                .unwrap_or_default();

            let clean_url = if let Some(encoded) = url.split("uddg=").nth(1) {
                let encoded = encoded.split('&').next().unwrap_or(encoded);
                url_decode(encoded)
            } else {
                url.to_string()
            };

            results.push((title, clean_url, snippet));
        }
        results
    };

    if results.is_empty() {
        ctx.say(lang::L_WEB_NO_RESULTS).await?;
        return Ok(());
    }

    let mut embed = serenity::CreateEmbed::default()
        .title(lang::fmt_web_title(&query))
        .color(0x00aaff);

    for (i, (title, url, snippet)) in results.iter().enumerate() {
        embed = embed.field(
            format!("{}. {title}", i + 1),
            format!("{url}\n{snippet}"),
            false,
        );
    }

    ctx.send(poise::CreateReply::default().embed(embed)).await?;
    Ok(())
}

fn url_decode(s: &str) -> String {
    let mut result = String::new();
    let mut chars = s.chars();
    while let Some(c) = chars.next() {
        match c {
            '+' => result.push(' '),
            '%' => {
                let hi = chars.next().and_then(|c| c.to_digit(16));
                let lo = chars.next().and_then(|c| c.to_digit(16));
                if let (Some(hi), Some(lo)) = (hi, lo) {
                    result.push(char::from_u32((hi << 4) | lo).unwrap_or('�'));
                } else {
                    result.push('%');
                }
            }
            _ => result.push(c),
        }
    }
    result
}

fn urlencoding(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for byte in s.as_bytes() {
        match byte {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'_' | b'-' | b'.' | b'~' => {
                out.push(*byte as char)
            }
            b' ' => out.push('+'),
            _ => out.push_str(&format!("%{byte:02X}")),
        }
    }
    out
}

pub fn commands() -> Vec<poise::Command<Data, Error>> {
    vec![web()]
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn encodes_utf8_bytes_not_chars() {
        assert_eq!(urlencoding("ż"), "%C5%BC");
        assert_eq!(urlencoding("a b"), "a+b");
    }
}