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
363
364
365
366
367
368
369
370
use crate::black_list::contains;
use crate::configuration::Configuration;
use crate::page::Page;
use crate::utils::{log, Client};
use rayon::ThreadPool;
use rayon::ThreadPoolBuilder;
use robotparser_fork::RobotFileParser;
use hashbrown::HashSet;
use std::{sync, time::{Duration}};
use reqwest::header::CONNECTION;
use reqwest::header;
use sync::mpsc::{channel, Sender, Receiver};
use tokio::time::sleep;
#[derive(Debug)]
pub struct Website<'a> {
pub configuration: Configuration,
pub domain: String,
links: HashSet<String>,
links_visited: HashSet<String>,
pub on_link_find_callback: fn(String) -> String,
robot_file_parser: RobotFileParser<'a>,
}
type Message = HashSet<String>;
impl<'a> Website<'a> {
pub fn new(domain: &str) -> Self {
Self {
configuration: Configuration::new(),
links_visited: HashSet::new(),
robot_file_parser: RobotFileParser::new(&format!("{}/robots.txt", domain)),
links: HashSet::from([format!("{}/", domain)]),
on_link_find_callback: |s| s,
domain: domain.to_owned(),
}
}
pub fn get_pages(&self) -> Vec<Page> {
self.links_visited.iter().map(|l| Page::build(l, "")).collect()
}
pub fn get_links(&self) -> &HashSet<String> {
&self.links_visited
}
fn get_delay(&self) -> Duration {
Duration::from_millis(self.configuration.delay)
}
pub fn configure_robots_parser(&mut self) {
if self.configuration.respect_robots_txt && self.robot_file_parser.mtime() == 0 {
self.robot_file_parser.user_agent = self.configuration.user_agent.to_string();
self.robot_file_parser.read();
self.configuration.delay = self
.robot_file_parser
.get_crawl_delay(&self.robot_file_parser.user_agent)
.unwrap_or(self.get_delay())
.as_millis() as u64;
}
}
fn configure_http_client(&mut self, user_agent: Option<String>) -> Client {
let mut headers = header::HeaderMap::new();
headers.insert(CONNECTION, header::HeaderValue::from_static("keep-alive"));
Client::builder()
.default_headers(headers)
.user_agent(user_agent.unwrap_or(self.configuration.user_agent.to_string()))
.build()
.expect("Failed building client.")
}
fn create_thread_pool(&mut self) -> ThreadPool {
ThreadPoolBuilder::new()
.num_threads(self.configuration.concurrency)
.build()
.expect("Failed building thread pool.")
}
fn setup(&mut self) -> Client {
self.configure_robots_parser();
let client = self.configure_http_client(None);
client
}
pub fn crawl(&mut self) {
let client = self.setup();
self.crawl_concurrent(&client);
}
pub fn crawl_sync(&mut self) {
let client = self.setup();
self.crawl_sequential(&client);
}
fn crawl_concurrent(&mut self, client: &Client) {
let delay = self.configuration.delay;
let delay_enabled = delay > 0;
let on_link_find_callback = self.on_link_find_callback;
let pool = self.create_thread_pool();
while !self.links.is_empty() {
let (tx, rx): (Sender<Message>, Receiver<Message>) = channel();
for link in self.links.iter() {
if !self.is_allowed(link) {
continue;
}
log("fetch", link);
self.links_visited.insert(link.into());
let link = link.clone();
let tx = tx.clone();
let cx = client.clone();
pool.spawn(move || {
if delay_enabled {
tokio_sleep(&Duration::from_millis(delay));
}
let link_result = on_link_find_callback(link);
let mut page = Page::new(&link_result, &cx);
let links = page.links();
page.clear_html();
tx.send(links).unwrap();
});
}
drop(tx);
let mut new_links: HashSet<String> = HashSet::new();
rx.into_iter().for_each(|links| {
new_links.extend(links);
});
self.links = &new_links - &self.links_visited;
}
}
fn crawl_sequential(&mut self, client: &Client) {
let delay = self.configuration.delay;
let delay_enabled = delay > 0;
let on_link_find_callback = self.on_link_find_callback;
while !self.links.is_empty() {
let mut new_links: HashSet<String> = HashSet::new();
for link in self.links.iter() {
if !self.is_allowed(link) {
continue;
}
log("fetch", link);
self.links_visited.insert(link.into());
if delay_enabled {
tokio_sleep(&Duration::from_millis(delay));
}
let link = link.clone();
let cx = client.clone();
let link_result = on_link_find_callback(link);
let page = Page::new(&link_result, &cx);
let links = page.links();
new_links.extend(links);
}
self.links = &new_links - &self.links_visited;
}
}
pub fn is_allowed(&self, link: &String) -> bool {
if self.links_visited.contains(link) {
return false;
}
if contains(&self.configuration.blacklist_url, link) {
return false;
}
if self.configuration.respect_robots_txt && !self.is_allowed_robots(link) {
return false;
}
true
}
pub fn is_allowed_robots(&self, link: &String) -> bool {
self.robot_file_parser.can_fetch("*", link)
}
}
impl<'a> Drop for Website<'a> {
fn drop(&mut self) {}
}
#[tokio::main]
async fn tokio_sleep(delay: &Duration){
sleep(*delay).await;
}
#[test]
fn crawl() {
let mut website: Website = Website::new("https://choosealicense.com");
website.crawl();
assert!(
website
.links_visited
.contains(&"https://choosealicense.com/licenses/".to_string()),
"{:?}",
website.links_visited
);
}
#[test]
fn crawl_subsequential() {
let mut website: Website = Website::new("https://choosealicense.com");
website.configuration.delay = 250;
website.crawl_sync();
assert!(
website
.links_visited
.contains(&"https://choosealicense.com/licenses/".to_string()),
"{:?}",
website.links_visited
);
}
#[test]
fn crawl_invalid() {
let url = "https://w.com";
let mut website: Website = Website::new(url);
website.crawl();
let mut uniq = HashSet::new();
uniq.insert(format!("{}/", url.to_string()));
assert_eq!(website.links_visited, uniq);
}
#[test]
fn crawl_link_callback() {
let mut website: Website = Website::new("https://choosealicense.com");
website.on_link_find_callback = |s| {
log("callback link target: {}", &s);
s
};
website.crawl();
assert!(
website
.links_visited
.contains(&"https://choosealicense.com/licenses/".to_string()),
"{:?}",
website.links_visited
);
}
#[test]
fn not_crawl_blacklist() {
let mut website: Website = Website::new("https://choosealicense.com");
website
.configuration
.blacklist_url
.push("https://choosealicense.com/licenses/".to_string());
website.crawl();
assert!(
!website
.links_visited
.contains(&"https://choosealicense.com/licenses/".to_string()),
"{:?}",
website.links_visited
);
}
#[test]
#[cfg(feature = "regex")]
fn not_crawl_blacklist_regex() {
let mut website: Website = Website::new("https://choosealicense.com");
website
.configuration
.blacklist_url
.push("/choosealicense.com/".to_string());
website.crawl();
assert_eq!(website.links_visited.len(), 0);
}
#[test]
fn test_respect_robots_txt() {
let mut website: Website = Website::new("https://stackoverflow.com");
website.configuration.respect_robots_txt = true;
assert_eq!(website.configuration.delay, 250);
assert!(!website.is_allowed(&"https://stackoverflow.com/posts/".to_string()));
let mut website_second: Website = Website::new("https://www.mongodb.com");
website_second.configuration.respect_robots_txt = true;
website_second.configuration.user_agent = "bingbot";
website_second.configure_robots_parser();
assert_eq!(
website_second.configuration.user_agent,
website_second.robot_file_parser.user_agent
);
assert_eq!(website_second.configuration.delay, 60000);
let mut website_third: Website = Website::new("https://www.mongodb.com");
website_third.configuration.respect_robots_txt = true;
website_third.configure_robots_parser();
assert_eq!(website_third.configuration.delay, 10000);
}
#[test]
fn test_link_duplicates() {
fn has_unique_elements<T>(iter: T) -> bool
where
T: IntoIterator,
T::Item: Eq + std::hash::Hash,
{
let mut uniq = HashSet::new();
iter.into_iter().all(move |x| uniq.insert(x))
}
let mut website: Website = Website::new("http://0.0.0.0:8000");
website.crawl();
assert!(has_unique_elements(&website.links_visited));
}