deadlinks.py 6.25 KB
Newer Older
1
2
# -*- coding: utf8 -*-

Matthieu Boileau's avatar
Matthieu Boileau committed
3
from logging import info, debug, warning
4
5
6
7
from bs4 import BeautifulSoup
from pelican import signals
import requests
from requests.exceptions import Timeout, RequestException
Matthieu Boileau's avatar
Matthieu Boileau committed
8
9
import os
import urllib3
10
11
12
13
14
15
16
17
18
19

UNKNOWN = None
MS_IN_SECOND = 1000.0

DEFAULT_OPTS = {
    'archive':  True,
    'classes':  [],
    'labels':   False,
    'timeout_duration_ms': 1000,
    'timeout_is_error':    False,
Matthieu Boileau's avatar
Matthieu Boileau committed
20
    'request_verify': True
21
22
23
24
25
26
27
28
29
30
31
32
}

SPAN_WARNING = u'<span class="label label-warning"></span>'
SPAN_DANGER = u'<span class="label label-danger"></span>'
ARCHIVE_URL = u'http://web.archive.org/web/*/{url}'


def get_status_code(url, opts):
    """
    Open connection to the given url and check status code.

    :param url: URL of the website to be checked
Matthieu Boileau's avatar
Matthieu Boileau committed
33
    :param opts: Option to be checked
34
35
36
37
    :return: (availibility, success, HTTP code)
    """
    availibility, success, code = (False, False, None)
    timeout_duration_seconds = get_opt(opts, 'timeout_duration_ms') / MS_IN_SECOND
Matthieu Boileau's avatar
Matthieu Boileau committed
38
39
40
41
    verify = get_opt(opts, 'request_verify')
    if not verify:
        urllib3.disable_warnings()

42
    try:
Matthieu Boileau's avatar
Matthieu Boileau committed
43
        r = requests.get(url, timeout=timeout_duration_seconds, verify=verify)
44
45
46
47
48
49
50
51
52
        code = r.status_code
        availibility = True
        success = code == requests.codes.ok
    except Timeout:
        availibility = False
        success = UNKNOWN
    except RequestException:
        availibility = UNKNOWN
        success = False
Matthieu Boileau's avatar
Matthieu Boileau committed
53
    return availibility, success, code
54
55
56
57
58
59
60


def user_enabled(inst, opt):
    """
    Check whether the option is enabled.

    :param inst: instance from content object init
Matthieu Boileau's avatar
Matthieu Boileau committed
61
    :param opt: Option to be checked
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
    :return: True if enabled, False if disabled or non present
    """
    return opt in inst.settings and inst.settings[opt]


def get_opt(opts, name):
    """
    Get value of the given option

    :param opts:    Table with options
    :param name:    Name of option
    :return:        Option of a given name from given table or default value
    """
    return opts[name] if name in opts else DEFAULT_OPTS[name]


def add_class(node, name):
    """
    Add class value to a given tag

    :param node:    HTML tag
    :param name:    class attribute value to add
    """
    node['class'] = node.get('class', []) + [name, ]


def change_to_archive(anchor):
    """
    Modify href attribute to point to archive.org instead of url directly.
    """
    src = anchor['href']
    dst = ARCHIVE_URL.format(url=src)
    anchor['href'] = dst


def on_connection_error(anchor, opts):
    """
    Called on connection error (URLError being thrown)

    :param anchor:  Anchor element (<a/>)
    :param opts:    Dict with user options
    """
    classes = get_opt(opts, 'classes')
    for cls in classes:
        add_class(anchor, cls)
    labels = get_opt(opts, 'labels')
    if labels:
        soup = BeautifulSoup(SPAN_DANGER, 'html.parser')
        soup.span.append('not available')
        idx = anchor.parent.contents.index(anchor) + 1
        anchor.parent.insert(idx, soup)
    archive = get_opt(opts, 'archive')
    if archive:
        change_to_archive(anchor)


def on_access_error(anchor, code, opts):
    """
    Called on access error (such as 403, 404)

    :param anchor:  Anchor element (<a/>)
    :param code:    Error code (403, 404, ...)
    :param opts:    Dict with user options
    """
    classes = get_opt(opts, 'classes')
    for cls in classes:
        add_class(anchor, cls)
    labels = get_opt(opts, 'labels')
    if labels:
        soup = BeautifulSoup(SPAN_WARNING, 'html.parser')
        soup.span.append(str(code))
        idx = anchor.parent.contents.index(anchor) + 1
        anchor.parent.insert(idx, soup)
    archive = get_opt(opts, 'archive')
    if archive:
        change_to_archive(anchor)


def content_object_init(instance):
    """
    Pelican callback
    """
Matthieu Boileau's avatar
Matthieu Boileau committed
144
145
146
147
    def get_markdown_formatted_msg():
        filepath = os.path.join('content', instance.get_relative_source_path())
        return "- [ ] {msg}: [{filepath}]({filepath})".format(msg=msg, filepath=filepath)

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
    if instance._content is None:
        return
    if not user_enabled(instance, 'DEADLINK_VALIDATION'):
        debug("Configured not to validate links")
        return

    settings = instance.settings
    siteurl = settings.get('SITEURL', '')
    opts = settings.get('DEADLINK_OPTS', DEFAULT_OPTS)

    cache = {}
    soup_doc = BeautifulSoup(instance._content, 'html.parser')

    for anchor in soup_doc(['a', 'object']):
        if 'href' not in anchor.attrs:
            continue
        url = anchor['href']

        # local files and other links are not really intresting
        if not url.startswith('http'):
            continue

        # Previous case works also for debugging environment (with SITEURL
        # being empty) This case resolves publish environment with all links
        # starting with http.
        if siteurl and url.startswith(siteurl):
            info("Url %s skipped because is starts with %s", url, siteurl)
            continue

        # No reason to query for the same link again
        if url in cache:
            avail, success, code = cache[url]
        else:
            # TODO: No reason to query for sites from already timed-out domain
            avail, success, code = get_status_code(url, opts)
            cache[url] = (avail, success, code)

        if not avail:
            timeout_is_error = get_opt(opts, 'timeout_is_error')
            if timeout_is_error:
Matthieu Boileau's avatar
Matthieu Boileau committed
188
                msg = 'Dead link: {} (not available)'.format(url)
189
190
                on_connection_error(anchor, opts)
            else:
Matthieu Boileau's avatar
Matthieu Boileau committed
191
192
                msg = 'Skipping: {} (not available)'.format(url)
            warning(get_markdown_formatted_msg())
193
194
195
            continue

        elif not success:
Matthieu Boileau's avatar
Matthieu Boileau committed
196
197
198
            if 400 <= code < 500:
                msg = 'Dead link: {} (error code: {})'.format(url, code)
                warning(get_markdown_formatted_msg())
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
                on_access_error(anchor, code, opts)
                continue
            else:
                # Codes other than [400, 500) are ignored
                pass

        # Error codes from out of range [400, 500) are considered good too
        debug('Good link: %s (%d)', url, code)

    instance._content = soup_doc.decode()


def register():
    """
    Part of Pelican API
    """
    signals.content_object_init.connect(content_object_init)