summaryrefslogtreecommitdiffstats
path: root/src/stackexchange/scraper.rs
blob: e67f0f6d0885b15486de81aef06303eab22fcb3c (plain)
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
use percent_encoding::percent_decode_str;
use reqwest::Url;
use scraper::html::Html;
use scraper::selector::Selector;
use std::collections::hash_map::Entry;
use std::collections::HashMap;

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

/// DuckDuckGo URL
const DUCKDUCKGO_URL: &str = "https://duckduckgo.com";
const GOOGLE_URL: &str = "https://google.com/search";

// Is question_id unique across all sites? If not, then this edge case is
// unaccounted for when sorting.
//
// If this is ever an issue, it wouldn't be too hard to account for this; just
// keep track of site in the `ordering` field and also return site from the
// spawned per-site tasks.
#[derive(Debug, PartialEq)]
pub struct ScrapedData {
    /// Mapping of site code to question ids
    pub question_ids: HashMap<String, Vec<String>>,
    /// Mapping of question_id to its ordinal place in search results
    pub ordering: HashMap<String, usize>,
}

// TODO add this type system limitation to blog post
pub trait Scraper {
    /// Parse data from search results html
    fn parse(&self, html: &str, sites: &HashMap<String, String>, limit: u16)
        -> Result<ScrapedData>;

    /// Get the url to search query restricted to sites
    fn get_url<'a, I>(&self, query: &str, sites: I) -> Url
    where
        I: IntoIterator<Item = &'a String>;
}

pub struct DuckDuckGo;

impl Scraper for DuckDuckGo {
    /// Parse (site, question_id) pairs out of duckduckgo search results html
    fn parse(
        &self,
        html: &str,
        sites: &HashMap<String, String>,
        limit: u16,
    ) -> Result<ScrapedData> {
        let anchors = Selector::parse("a.result__a").unwrap();
        parse_with_selector(anchors, html, sites, limit).and_then(|sd| {
            // DDG seems to never have empty results, so assume this is blocked
            if sd.question_ids.is_empty() {
                Err(Error::ScrapingError(String::from(
                    "DuckDuckGo blocked this request",
                )))
            } else {
                Ok(sd)
            }
        })
    }

    /// Creates duckduckgo search url given sites and query
    /// See https://duckduckgo.com/params for more info
    fn get_url<'a, I>(&self, query: &str, sites: I) -> Url
    where
        I: IntoIterator<Item = &'a String>,
    {
        let q = make_query_arg(query, sites);
        Url::parse_with_params(
            DUCKDUCKGO_URL,
            &[("q", q.as_str()), ("kz", "-1"), ("kh", "-1")],
        )
        .unwrap()
    }
}

pub struct Google;

impl Scraper for Google {
    /// Parse SE data out of google search results html
    fn parse(
        &self,
        html: &str,
        sites: &HashMap<String, String>,
        limit: u16,
    ) -> Result<ScrapedData> {
        let anchors = Selector::parse("div.r > a").unwrap();
        parse_with_selector(anchors, html, sites, limit)
    }

    /// Creates duckduckgo search url given sites and query
    /// See https://duckduckgo.com/params for more info
    fn get_url<'a, I>(&self, query: &str, sites: I) -> Url
    where
        I: IntoIterator<Item = &'a String>,
    {
        let q = make_query_arg(query, sites);
        Url::parse_with_params(GOOGLE_URL, &[("q", q.as_str())]).unwrap()
    }
}

fn make_query_arg<'a, I>(query: &str, sites: I) -> String
where
    I: IntoIterator<Item = &'a String>,
{
    let mut q = String::new();
    //  Restrict to sites
    q.push('(');
    q.push_str(
        sites
            .into_iter()
            .map(|site| String::from("site:") + site)
            .collect::<Vec<_>>()
            .join(" OR ")
            .as_str(),
    );
    q.push_str(") ");
    //  Search terms
    q.push_str(
        query
            .trim_end_matches('?')
            .split_whitespace()
            .collect::<Vec<_>>()
            .join(" ")
            .as_str(),
    );
    q
}

fn parse_with_selector(
    anchors: Selector,
    html: &str,
    sites: &HashMap<String, String>,
    limit: u16,
) -> Result<ScrapedData> {
    let fragment = Html::parse_document(html);
    let mut question_ids: HashMap<String, Vec<String>> = HashMap::new();
    let mut ordering: HashMap<String, usize> = HashMap::new();
    let mut count = 0;
    for anchor in fragment.select(&anchors) {
        let url = anchor
            .value()
            .attr("href")
            .ok_or_else(|| Error::ScrapingError("Anchor with no href".to_string()))
            .map(|href| percent_decode_str(href).decode_utf8_lossy().into_owned())?;
        sites.iter().find_map(|(site_code, site_url)| {
            let id = question_url_to_id(site_url, &url)?;
            ordering.insert(id.to_owned(), count);
            match question_ids.entry(site_code.to_owned()) {
                Entry::Occupied(mut o) => o.get_mut().push(id),
                Entry::Vacant(o) => {
                    o.insert(vec![id]);
                }
            }
            count += 1;
            Some(())
        });
        if count >= limit as usize {
            break;
        }
    }
    Ok(ScrapedData {
        question_ids,
        ordering,
    })
}

// TODO use str_prefix once its stable
fn question_url_to_id(site_url: &str, input: &str) -> Option<String> {
    ["/questions/", "/q/"].iter().find_map(|segment| {
        let fragment = site_url.trim_end_matches('/').to_owned() + segment;
        let mut ix = input.find(&fragment)?;
        if ix > 0 && input.chars().nth(ix - 1) == Some('.') {
            return None;
        }
        ix += fragment.len();
        let input = &input[ix..];
        let id = if let Some(end) = input.find('/') {
            input[0..end].to_string()
        } else {
            input[0..].to_string()
        };
        if id.chars().all(|c| c.is_digit(10)) {
            Some(id)
        } else {
            None
        }
    })
}

// TODO  Get blocked google request html
// TODO Get google no results html
// note: this may only be possible at search.rs level (with non-200 code)
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_duckduckgo_url() {
        let q = "how do I exit vim?";
        let sites = vec![
            String::from("stackoverflow.com"),
            String::from("unix.stackexchange.com"),
        ];
        assert_eq!(
            DuckDuckGo.get_url(q, &sites).as_str(),
            String::from(
                "https://duckduckgo.com/\
                ?q=%28site%3Astackoverflow.com+OR+site%3Aunix.stackexchange.com%29\
                +how+do+I+exit+vim&kz=-1&kh=-1"
            )
        )
    }

    #[test]
    fn test_duckduckgo_parser() {
        let html = include_str!("../../test/duckduckgo/exit-vim.html");
        let sites = vec![
            ("stackoverflow", "stackoverflow.com"),
            ("askubuntu", "askubuntu.com"),
        ]
        .into_iter()
        .map(|(k, v)| (k.to_string(), v.to_string()))
        .collect::<HashMap<String, String>>();
        let expected_scraped_data = ScrapedData {
            question_ids: vec![
                ("stackoverflow", vec!["11828270", "9171356"]),
                ("askubuntu", vec!["24406"]),
            ]
            .into_iter()
            .map(|(k, v)| {
                (
                    k.to_string(),
                    v.into_iter().map(|s| s.to_string()).collect(),
                )
            })
            .collect(),
            ordering: vec![("11828270", 0),