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
use futures::stream::StreamExt;
use rayon::prelude::*;
use reqwest::header;
use reqwest::Client;
use std::collections::HashMap;
use crate::config::{Config, SearchEngine};
use crate::error::{Error, Result};
use crate::tui::markdown;
use crate::tui::markdown::Markdown;
use super::api::{Answer, Api, Question};
use super::local_storage::LocalStorage;
use super::scraper::{DuckDuckGo, Google, ScrapedData, Scraper};
const CONCURRENT_REQUESTS_LIMIT: usize = 8;
const USER_AGENT: &str =
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:11.0) Gecko/20100101 Firefox/11.0";
#[derive(Clone)]
pub struct Search {
api: Api,
config: Config,
query: String,
sites: HashMap<String, String>,
}
impl Search {
pub fn new(config: Config, local_storage: LocalStorage, query: String) -> Self {
let api = Api::new(config.api_key.clone());
let sites = local_storage.get_urls(&config.sites);
Search {
api,
config,
query,
sites,
}
}
pub async fn search_lucky(&mut self) -> Result<String> {
let original_config = self.config.clone();
self.config.limit = 1;
if let SearchEngine::StackExchange = self.config.search_engine {
self.config.sites.truncate(1);
}
let result = self.search().await;
self.config = original_config;
Ok(result?
.into_iter()
.next()
.ok_or(Error::NoResults)?
.answers
.into_iter()
.next()
.ok_or_else(|| Error::StackExchange(String::from("Received question with no answers")))?
.body)
}
pub async fn search_md(&self) -> Result<Vec<Question<Markdown>>> {
Ok(parse_markdown(self.search().await?))
}
pub async fn search(&self) -> Result<Vec<Question<String>>> {
match self.config.search_engine {
SearchEngine::DuckDuckGo => self.search_by_scraper(DuckDuckGo).await,
SearchEngine::Google => self.search_by_scraper(Google).await,
SearchEngine::StackExchange => self.parallel_search_advanced().await,
}
.and_then(|qs| {
if qs.is_empty() {
Err(Error::NoResults)
} else {
Ok(qs)
}
})
}
async fn search_by_scraper(&self, scraper: impl Scraper) -> Result<Vec<Question<String>>> {
let url = scraper.get_url(&self.query, self.sites.values());
let html = Client::new()
.get(url)
.header(header::USER_AGENT, USER_AGENT)
.send()
.await?
.text()
.await?;
let data = scraper.parse(&html, &self.sites, self.config.limit)?;
self.parallel_questions(data).await
}
async fn parallel_questions(&self, data: ScrapedData) -> Result<Vec<Question<String>>> {
let ScrapedData {
question_ids,
ordering,
} = data;
futures::stream::iter(question_ids)
.map(|(site, ids)| {
let api = self.api.clone();
tokio::spawn(async move {
let api = &api;
api.questions(&site, ids).await
})
})
.buffer_unordered(CONCURRENT_REQUESTS_LIMIT)
.collect::<Vec<_>>()
.await
.into_iter()
.map(|r| r.map_err(Error::from).and_then(|x| x))
.collect::<Result<Vec<Vec<_>>>>()
.map(|v| {
let mut qs: Vec<Question<String>> = v.into_iter().flatten().collect();
qs.sort_unstable_by_key(|q| ordering.get(&q.id.to_string()).unwrap());
qs
})
}
async fn parallel_search_advanced(&self) -> Result<Vec<Question<String>>> {
futures::stream::iter(self.config.sites.clone())
.map(|site| {
let api = self.api.clone();
let limit = self.config.limit;
let query = self.query.clone();
tokio::spawn(async move {
let api = &api;
api.search_advanced(&query, &site, limit).await
})
})
.buffer_unordered(CONCURRENT_REQUESTS_LIMIT)
.collect::<Vec<_>>()
.await
.into_iter()
.map(|r| r.map_err(Error::from).and_then(|x| x))
.collect::<Result<Vec<Vec<_>>>>()
.map(|v| {
let mut qs: Vec<Question<String>> = v.into_iter().flatten().collect();
if self.config.sites.len() > 1 {
qs.sort_unstable_by_key(|q| -q.score);
}
qs
})
}
}
fn parse_markdown(qs: Vec<Question<String>>) -> Vec<Question<Markdown>> {
qs.into_par_iter()
.map(|q| {
let body = markdown::parse(q.body);
let answers = q
.answers
.into_par_iter()
.map(|a| {
let body = markdown::parse(a.body);
Answer {
body,
id: a.id,
score: a.score,
is_accepted: a.is_accepted,
}
})
.collect::<Vec<_>>();
Question {
body,
answers,
id: q.id,
score: q.score,
title: q.title,
}
})
.collect::<Vec<_>>()
}
#[cfg(test)]
mod tests {
#[test]
fn test_duckduckgo_response() {
}
}