docbox-web-scraper 0.6.1

Web scraping logic for docbox, document parsing, favicon resolution, ogp resolution
Documentation
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
//! # Document
//!
//! HTML document related logic for extracting information scraped from remote
//! HTML pages such as OGP metadata <title/> tags etc

use mime::Mime;
use std::str::FromStr;
use thiserror::Error;
use tl::{HTMLTag, Parser};
use url::Url;

use crate::{
    request::{RequestError, get_request},
    url_validation::UrlValidation,
};

/// Metadata extracted from a website
#[derive(Debug)]
pub struct WebsiteMetadata {
    pub title: Option<String>,
    pub og_title: Option<String>,
    pub og_description: Option<String>,
    pub og_image: Option<String>,
    pub favicons: Vec<Favicon>,
}

/// Favicon extracted from a website
#[derive(Debug, Clone)]
pub struct Favicon {
    /// Mime type for the favicon
    pub ty: Mime,
    /// Size if known
    pub sizes: Option<String>,
    /// URL of the favicon
    pub href: String,
}

/// State for data extracted from a website document
#[derive(Default)]
struct WebsiteDocumentState {
    title: Option<String>,
    description: Option<String>,
    og_title: Option<String>,
    og_description: Option<String>,
    og_image: Option<String>,
    favicons: Vec<Favicon>,
}

/// Errors that could occur when website metadata is loaded
#[derive(Debug, Error)]
pub enum WebsiteMetadataError {
    #[error(transparent)]
    Request(#[from] RequestError),

    #[error("failed to read response")]
    ReadResponse(reqwest::Error),

    #[error(transparent)]
    Parse(WebsiteMetadataParseError),
}

/// Errors that could occur when parsing the website metadata
#[derive(Debug, Error)]
pub enum WebsiteMetadataParseError {
    #[error("failed to parse resource response")]
    Parsing,
    #[error("failed to query page head")]
    QueryHead,
    #[error("page missing head element")]
    MissingHead,
    #[error("failed to parse head element")]
    InvalidHead,
    #[error("head element has no children")]
    EmptyHead,
}

/// Connects to a website reading the HTML contents, extracts the metadata
/// required from the <head/> element
pub async fn get_website_metadata<D: UrlValidation>(
    client: &reqwest::Client,
    url: &Url,
) -> Result<WebsiteMetadata, WebsiteMetadataError> {
    let mut url = url.clone();

    // Get the path from the URL
    let path = url.path();

    // Check if the path ends with a common HTML extension or if it is empty
    if !path.ends_with(".html") && !path.ends_with(".htm") && path.is_empty() {
        // Append /index.html if needed
        url.set_path("/index.html");
    }

    // Request page at URL
    let (response, _redirects) = get_request::<D>(client, url).await?;

    // Read response text
    let text = response
        .text()
        .await
        .map_err(WebsiteMetadataError::ReadResponse)?;

    parse_website_metadata(&text).map_err(WebsiteMetadataError::Parse)
}

/// Error's that can occur when attempting to load robots.txt
#[derive(Debug, Error)]
pub enum RobotsTxtError {
    #[error(transparent)]
    Request(#[from] RequestError),

    #[error("failed to read response")]
    ReadResponse(reqwest::Error),
}

/// Attempts to read the robots.txt file for the website to determine if
/// scraping is allowed
pub async fn is_allowed_robots_txt<D: UrlValidation>(
    client: &reqwest::Client,
    url: &Url,
) -> Result<bool, RobotsTxtError> {
    let mut url = url.clone();

    let original_url = url.to_string();

    // Change path to /robots.txt
    url.set_path("/robots.txt");

    // Request page at URL
    let (response, _redirects) = get_request::<D>(client, url).await?;

    // Read response text
    let robots_txt = response
        .text()
        .await
        .map_err(RobotsTxtError::ReadResponse)?;

    let mut matcher = robotstxt::DefaultMatcher::default();
    let is_allowed =
        matcher.one_agent_allowed_by_robots(&robots_txt, "DocboxLinkBot", &original_url);

    Ok(is_allowed)
}

/// Parse website metadata contained within the provided HTML content
pub fn parse_website_metadata(html: &str) -> Result<WebsiteMetadata, WebsiteMetadataParseError> {
    let dom = tl::parse(html, tl::ParserOptions::default())
        .map_err(|_| WebsiteMetadataParseError::Parsing)?;

    let parser = dom.parser();

    // Find the head element
    let head = dom
        .query_selector("head")
        .ok_or(WebsiteMetadataParseError::QueryHead)?
        .next()
        .ok_or(WebsiteMetadataParseError::MissingHead)?
        .get(parser)
        .ok_or(WebsiteMetadataParseError::InvalidHead)?;

    let mut state = WebsiteDocumentState::default();

    let children = head
        .children()
        .ok_or(WebsiteMetadataParseError::EmptyHead)?;
    for child in children.all(parser) {
        let tag = match child.as_tag() {
            Some(tag) => tag,
            None => continue,
        };

        match tag.name().as_bytes() {
            // Extract page title tag
            b"title" => visit_title_tag(&mut state, parser, tag),
            // Extract metadata
            b"meta" => visit_meta_tag(&mut state, tag),
            // Extract favicons
            b"link" => visit_link_tag(&mut state, tag),
            // Ignore other tags
            _ => {}
        }
    }

    // Fallback to description
    let og_description = state.og_description.or(state.description);

    Ok(WebsiteMetadata {
        title: state.title,
        og_title: state.og_title,
        og_description,
        og_image: state.og_image,
        favicons: state.favicons,
    })
}

/// Determines which favicon to use from the provided list
///
/// Prefers .ico format currently then defaulting to first
/// available. At a later date might want to check the sizes
/// field
pub fn determine_best_favicon(favicons: &[Favicon]) -> Option<&Favicon> {
    favicons
        .iter()
        // Search for an ico first
        .find(|favicon| favicon.ty.essence_str().eq("image/x-icon"))
        // Fallback to whatever is first
        .or_else(|| favicons.first())
}

/// Visit <title/> tags in the document
fn visit_title_tag<'doc>(
    state: &mut WebsiteDocumentState,
    parser: &Parser<'doc>,
    tag: &HTMLTag<'doc>,
) {
    let value = tag.inner_text(parser).to_string();
    state.title = Some(value);
}

/// Visit metadata tags in the document like:
///
/// <meta name="description" content="Website title" />
/// <meta property="og:title" content="Website title" />
/// <meta property="og:image" content="https://example.com/image.jpg" />
/// <meta property="og:description"Website description" />
fn visit_meta_tag<'doc>(state: &mut WebsiteDocumentState, tag: &HTMLTag<'doc>) {
    let attributes = tag.attributes();
    let property = match attributes.get("property").flatten() {
        Some(value) => value.as_bytes(),
        None => match attributes.get("name").flatten() {
            Some(value) => value.as_bytes(),
            None => return,
        },
    };

    fn get_content_value<'doc>(attributes: &tl::Attributes<'doc>) -> Option<String> {
        attributes
            .get("content")
            .flatten()
            .map(|value| value.as_utf8_str().to_string())
    }

    match property {
        b"description" => {
            if let Some(content) = get_content_value(attributes) {
                state.description = Some(content);
            }
        }
        b"og:title" => {
            if let Some(content) = get_content_value(attributes) {
                state.og_title = Some(content);
            }
        }
        b"og:description" => {
            if let Some(content) = get_content_value(attributes) {
                state.og_description = Some(content);
            }
        }
        b"og:image" => {
            if let Some(content) = get_content_value(attributes) {
                state.og_image = Some(content);
            }
        }
        _ => {}
    }
}

/// Visit a link tag attempt to find a favicon image file link:
///
/// <link rel="icon" type="image/x-icon" href="/images/favicon.ico">
/// <link rel="shortcut icon" type="image/x-icon" href="/images/favicon.ico">
fn visit_link_tag(state: &mut WebsiteDocumentState, tag: &HTMLTag<'_>) {
    let attributes = tag.attributes();

    let rel = attributes.get("rel").flatten().map(tl::Bytes::as_bytes);

    // Only match icon link
    if !matches!(rel, Some(b"icon" | b"shortcut icon")) {
        return;
    }

    let mime = attributes
        .get("type")
        .flatten()
        .and_then(|value| Mime::from_str(value.as_utf8_str().as_ref()).ok());

    // Ignore missing or invalid mimes
    let ty = match mime {
        Some(value) => value,
        None => return,
    };

    let href = attributes
        .get("href")
        .flatten()
        .map(|value| value.as_utf8_str().to_string());

    // Ignore missing href
    let href = match href {
        Some(value) => value,
        None => return,
    };

    let sizes = attributes
        .get("sizes")
        .flatten()
        .map(|value| value.as_utf8_str().to_string());

    state.favicons.push(Favicon { ty, sizes, href });
}

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

    #[test]
    fn test_parse_website_metadata_all_fields() {
        let html = r#"
            <html>
                <head>
                    <title>Test Title</title>
                    <meta name="description" content="Fallback description" />
                    <meta property="og:title" content="OG Title" />
                    <meta property="og:description" content="OG Description" />
                    <meta property="og:image" content="https://example.com/image.png" />
                    <link rel="icon" type="image/x-icon" href="/favicon.ico" sizes="16x16" />
                </head>
            </html>
        "#;

        let metadata = parse_website_metadata(html).expect("Failed to parse metadata");

        assert_eq!(metadata.title, Some("Test Title".to_string()));
        assert_eq!(metadata.og_title, Some("OG Title".to_string()));
        assert_eq!(metadata.og_description, Some("OG Description".to_string()));
        assert_eq!(
            metadata.og_image,
            Some("https://example.com/image.png".to_string())
        );
        assert_eq!(metadata.favicons.len(), 1);
        let favicon = &metadata.favicons[0];
        assert_eq!(favicon.ty, mime::Mime::from_str("image/x-icon").unwrap());
        assert_eq!(favicon.href, "/favicon.ico");
        assert_eq!(favicon.sizes, Some("16x16".to_string()));
    }

    #[test]
    fn test_parse_website_metadata_fallback_description() {
        let html = r#"
            <html>
                <head>
                    <title>Test Title</title>
                    <meta name="description" content="Fallback description" />
                </head>
            </html>
        "#;

        let metadata = parse_website_metadata(html).expect("Failed to parse metadata");

        assert_eq!(
            metadata.og_description,
            Some("Fallback description".to_string())
        );
    }

    #[test]
    fn test_parse_website_metadata_missing_tags() {
        let html = r"
            <html>
                <head>
                    <!-- Empty head -->
                </head>
            </html>
        ";

        let metadata = parse_website_metadata(html).expect("Failed to parse metadata");

        assert!(metadata.title.is_none());
        assert!(metadata.og_title.is_none());
        assert!(metadata.og_description.is_none());
        assert!(metadata.og_image.is_none());
        assert!(metadata.favicons.is_empty());
    }

    #[test]
    fn test_determine_best_favicon_prefers_ico() {
        let favicons = vec![
            Favicon {
                ty: mime::Mime::from_str("image/png").unwrap(),
                href: "/favicon.png".to_string(),
                sizes: Some("32x32".to_string()),
            },
            Favicon {
                ty: mime::Mime::from_str("image/x-icon").unwrap(),
                href: "/favicon.ico".to_string(),
                sizes: Some("16x16".to_string()),
            },
        ];

        let best = determine_best_favicon(&favicons);
        assert!(best.is_some());
        assert_eq!(best.unwrap().href, "/favicon.ico");
    }

    #[test]
    fn test_determine_best_favicon_fallback() {
        let favicons = vec![Favicon {
            ty: mime::Mime::from_str("image/png").unwrap(),
            href: "/favicon.png".to_string(),
            sizes: None,
        }];

        let best = determine_best_favicon(&favicons);
        assert!(best.is_some());
        assert_eq!(best.unwrap().href, "/favicon.png");
    }

    #[test]
    fn test_determine_best_favicon_none() {
        let favicons = vec![];
        let best = determine_best_favicon(&favicons);
        assert!(best.is_none());
    }
}