Commit f8f388ed authored by Benoit Fabrèges's avatar Benoit Fabrèges

Removing 'pelican-deadlink' plugin. Setting 'check-deadlinks' plugin to not...

Removing 'pelican-deadlink' plugin. Setting 'check-deadlinks' plugin to not run by default. Change the variable 'DEADLINK_VALIDATION' to 'True' in pelicanconf.py and run 'make html' to check for deadlinks.
parent ce5229c8
Pipeline #6068 passed with stages
in 1 minute and 54 seconds
......@@ -52,19 +52,15 @@ MARKUP = ('md', 'ipynb')
PLUGIN_PATHS = ['./plugins']
PLUGINS = ['ipynb.markup', 'pelican_dynamic', 'rst_directives', 'extract_toc', 'calcul_reader', 'calcul_filters',
'rst_include', 'sitemap', 'pelican-deadlinks', 'tipue_search', 'check_deadlinks']
'rst_include', 'sitemap', 'tipue_search', 'check_deadlinks']
# Useful for 'rst_include' plugin (elative to content directory)
RST_GLOBAL_INCLUDES = ['../plugins/rst_include/include.rst']
# For pelican-deadlinks plugin
# For check-deadlinks plugin
DEADLINK_VALIDATION = False
DEADLINK_OPTS = {
'archive': True,
'classes': ['custom-class1', 'disabled'],
'labels': True,
'timeout_duration_ms': 4000,
'timeout_is_error': False,
'request_verify': False
'timeout_duration_ms': 5000,
'request_verify': True
}
MENUITEMS = [('Le groupe', '/pages/presentation_groupe.html'),
......
......@@ -5,6 +5,7 @@ from requests.exceptions import Timeout, RequestException, HTTPError, SSLError,
import os
from pathlib import Path
import logging
import urllib3
error_codes = {0 : "Good",
......@@ -12,7 +13,13 @@ error_codes = {0 : "Good",
2 : "Certificate validation error - check them with https://www.ssllabs.com/ssltest/analyze.html",
3 : "Connection error",
4 : "HTTP error code received (4XX or 5XX)",
5 : "File missing"}
5 : "File missing (or url not starting with http)"}
DEFAULT_OPTS = {
'timeout_duration_ms': 5000,
'request_verify': True
}
def check_file(filename):
......@@ -28,7 +35,7 @@ def check_file(filename):
return error_code
def check_url(url, timeout_ms):
def check_url(url, opts):
"""
Open connection to the given url and check status code.
......@@ -37,13 +44,17 @@ def check_url(url, timeout_ms):
:return: (success, HTTP code, message)
"""
error_code = 0
timeout_s = timeout_ms * 1e-3
timeout_s = opts['timeout_duration_ms'] * 1e-3
try:
# verify:
# - True: checks certificates
# - False: bypasses certificate validation completely
r = requests.get(url, timeout=timeout_s, verify=True)
if not opts['request_verify']:
urllib3.disable_warnings()
r = requests.get(url, timeout=timeout_s, verify=opts['request_verify'])
except Timeout:
error_code = 1
except SSLError:
......@@ -74,22 +85,25 @@ def all_generators_finalized(generators):
Pelican callback
"""
timeout_duration_ms = 8000
settings = generators[-1].settings
if not settings.get('DEADLINK_VALIDATION'):
return
output_path = Path(settings.get('OUTPUT_PATH'))
opts = settings.get('DEADLINK_OPTS', DEFAULT_OPTS)
all_pages = generators[-1].context['articles'] + \
generators[-1].context['pages'] + \
generators[-1].context['hidden_pages']
#all_pages = generators[-1].context['pages']
cache = {}
tags = {'a' : 'href', 'img' : 'src', 'link' : 'href'}
num_pages = len(all_pages)
print("Checking deadlinks in all pages")
print(f"Progression: 0 pages / {num_pages}", end="\r")
for count_pages, page in enumerate(all_pages):
print(f"{count_pages} / {num_pages}", end="\r")
soup_doc = BeautifulSoup(page.content, 'html.parser')
for tag, attr in tags.items():
......@@ -115,7 +129,7 @@ def all_generators_finalized(generators):
cache[url][1].add((page.url, page.get_relative_source_path()))
else:
if url.startswith('http'):
error_code = check_url(url, timeout_duration_ms)
error_code = check_url(url, opts)
else:
if url.startswith('/'):
internal_filename = output_path.joinpath(*(url.split(os.sep)))
......@@ -125,6 +139,9 @@ def all_generators_finalized(generators):
error_code = check_file(internal_filename.resolve())
cache[url] = (error_code, {(page.url, page.get_relative_source_path())})
print(f"Progression: {count_pages} pages / {num_pages}", end="\r")
# prints the results
results_by_code = {}
......@@ -146,3 +163,4 @@ def all_generators_finalized(generators):
msg += "\n"
logging.error(msg)
print()
# 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 *
#!/usr/bin/env python3
"""Check URL for deadlink"""
from deadlinks import get_status_code
import argparse
opts = {
'archive': True,
'classes': [],
'labels': False,
'timeout_duration_ms': 3000,
'timeout_is_error': False,
'request_verify': False
}
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Check that URL is not a dead link")
parser.add_argument('--url', nargs=1, metavar='URL', required=True, help='url to check')
parser.add_argument('--timeout', nargs=1, metavar='time', type=int, help='Timeout duration [ms]')
args = parser.parse_args()
if args.timeout:
opts['timeout_duration_ms'] = args.timeout[0]
url = args.url[0]
print("Checking URL:", url)
avail, success, code = get_status_code(url, opts)
print("available :", avail)
print("success :", success)
print("code :", code)
# -*- coding: utf8 -*-
from logging import info, debug, warning
from bs4 import BeautifulSoup
from pelican import signals
import requests
from requests.exceptions import Timeout, RequestException
import os
import urllib3
UNKNOWN = None
MS_IN_SECOND = 1000.0
DEFAULT_OPTS = {
'archive': True,
'classes': [],
'labels': False,
'timeout_duration_ms': 1000,
'timeout_is_error': False,
'request_verify': True
}
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
:param opts: Option 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
verify = get_opt(opts, 'request_verify')
if not verify:
urllib3.disable_warnings()
try:
r = requests.get(url, timeout=timeout_duration_seconds, verify=verify)
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 opt: 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
"""
def get_markdown_formatted_msg():
filepath = os.path.join('content', instance.get_relative_source_path())
return "- [ ] {msg}: [{filepath}]({filepath})".format(msg=msg, filepath=filepath)
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:
msg = 'Dead link: {} (not available)'.format(url)
on_connection_error(anchor, opts)
else:
msg = 'Skipping: {} (not available)'.format(url)
warning(get_markdown_formatted_msg())
continue
elif not success:
if 400 <= code < 500:
msg = 'Dead link: {} (error code: {})'.format(url, code)
warning(get_markdown_formatted_msg())
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)
Markdown is supported
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