Commit e0949fb2 authored by Matthieu Boileau's avatar Matthieu Boileau
Browse files

Add pelican-deadlinks plugin #110

parent 84aa6e7e
Pipeline #3626 passed with stages
in 1 minute and 8 seconds
......@@ -49,10 +49,20 @@ MARKUP = ('md', 'ipynb')
PLUGIN_PATHS = ['./plugins']
PLUGINS = ['ipynb.markup', 'pelican_dynamic', 'rst_directives', 'extract_toc', 'calcul_reader', 'calcul_filters',
'rst_include', 'sitemap']
'rst_include', 'sitemap', 'pelican-deadlinks']
# Useful for 'rst_include' plugin (elative to content directory)
RST_GLOBAL_INCLUDES = ['../plugins/rst_include/include.rst']
# For pelican-deadlinks plugin
DEADLINK_VALIDATION = False
DEADLINK_OPTS = {
'archive': True,
'classes': ['custom-class1', 'disabled'],
'labels': True,
'timeout_duration_ms': 1000,
'timeout_is_error': False,
}
MENUITEMS = [('Le groupe', '/pages/presentation_groupe.html'),
('Paysage du calcul', '/pages/paysage_du_calcul.html'),
('Nos journées', '/category/journee.html'),
......
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*,cover
.hypothesis/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# IPython Notebook
.ipynb_checkpoints
# pyenv
.python-version
# celery beat schedule file
celerybeat-schedule
# dotenv
.env
# virtualenv
.venv/
venv/
ENV/
# Spyder project settings
.spyderproject
# Rope project settings
.ropeproject
*.swp
*.orig
MIT License
Copyright (c) 2016 Marcin Glinski
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# Dead Links
This plugin scans for links and checks status code of requested url.
For responses such as 403 or 404, the plugin adds a "disabled" class
to the anchor, extends anchor with a span label and dumps warning to
the logger.
# Requirements
BeautifulSoup4, requests
To install them using pip, type: `pip install bs4 requests`
# Installation
Clone repository somewhere (let's assume destination is ./plugins/custom/deadlinks)
and edit configuration file:
```python
PLUGINS_PATH = [
# [...]
'plugins/custom'
]
PLUGINS = [
# [...]
'deadlinks'
]
```
# Settings
To enable dead link checker, set the `DEADLINK_VALIDATION` option in your
Pelican configuration file to True.
Additionally following options might be changed:
```python
DEADLINK_OPTS = {
'archive': True,
'classes': ['custom-class1', 'disabled'],
'labels': True,
'timeout_duration_ms': 1000,
'timeout_is_error': False,
}
```
Options:
| Name | Description | Default value |
| ------ | ----------- | ------------- |
| `archive` | True/False. When enabled invalid links will be replaced with proper archive.org entry | True |
| `classes` | List of classes to be add to anchor element | Empty list |
| `labels` | Insert bootstrap's label after the anchor element | False |
| `timeout_duration_ms` | Time in ms after which request is considered as timed out | 1000 |
| `timeout_is_error` | True/False. When enabled every time out is considered as dead link | False |
# -*- coding: utf8 -*-
from .deadlinks import *
# -*- coding: utf8 -*-
from logging import info, debug, warn
from bs4 import BeautifulSoup
from pelican import signals
import requests
from requests.exceptions import Timeout, RequestException
UNKNOWN = None
MS_IN_SECOND = 1000.0
DEFAULT_OPTS = {
'archive': True,
'classes': [],
'labels': False,
'timeout_duration_ms': 1000,
'timeout_is_error': False,
}
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
:return: (availibility, success, HTTP code)
"""
availibility, success, code = (False, False, None)
timeout_duration_seconds = get_opt(opts, 'timeout_duration_ms') / MS_IN_SECOND
try:
r = requests.get(url, timeout=timeout_duration_seconds)
code = r.status_code
availibility = True
success = code == requests.codes.ok
except Timeout:
availibility = False
success = UNKNOWN
except RequestException:
availibility = UNKNOWN
success = False
return (availibility, success, code)
def user_enabled(inst, opt):
"""
Check whether the option is enabled.
:param inst: instance from content object init
:param url: Option to be checked
: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
"""
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:
warn('Dead link: %s (not available)', url)
on_connection_error(anchor, opts)
else:
warn('Skipping: %s (not available)', url)
continue
elif not success:
if code >= 400 and code < 500:
warn('Dead link: %s (error code: %d)', url, code)
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)
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment