| 1 |
"""Checks that links are viable. |
| 2 |
|
| 3 |
--- |
| 4 |
layout: post |
| 5 |
source: SublimeLinter-annotations |
| 6 |
source_url: http://bit.ly/16Q7H41 |
| 7 |
title: broken links |
| 8 |
date: 2014-06-10 12:31:19 |
| 9 |
categories: writing |
| 10 |
--- |
| 11 |
|
| 12 |
Check that links are not broken. |
| 13 |
|
| 14 |
""" |
| 15 |
import re |
| 16 |
import urllib.request as urllib_request # for Python 3 |
| 17 |
from socket import error as SocketError |
| 18 |
|
| 19 |
from proselint.tools import memoize |
| 20 |
|
| 21 |
|
| 22 |
@memoize |
| 23 |
def check(text): |
| 24 |
"""Check the text.""" |
| 25 |
err = "links.valid" |
| 26 |
msg = "Broken link: {}" |
| 27 |
|
| 28 |
regex = re.compile( |
| 29 |
r"""(?i)\b((?:https?://|www\d{0,3}[.] |
| 30 |
|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+ |
| 31 |
|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\) |
| 32 |
|[^\s`!()\[\]{};:\'".,<>?\xab\xbb\u201c\u201d\u2018\u2019\u21a9]))""", |
| 33 |
re.U | re.X) |
| 34 |
|
| 35 |
errors = [] |
| 36 |
for m in re.finditer(regex, text): |
| 37 |
url = m.group(0).strip() |
| 38 |
|
| 39 |
if "http://" not in url and "https://" not in url: |
| 40 |
url = "http://" + url |
| 41 |
|
| 42 |
if is_broken_link(url): |
| 43 |
errors.append((m.start(), m.end(), err, msg.format(url), None)) |
| 44 |
|
| 45 |
return errors |
| 46 |
|
| 47 |
|
| 48 |
@memoize |
| 49 |
def is_broken_link(url): |
| 50 |
"""Determine whether the link returns a 404 error.""" |
| 51 |
try: |
| 52 |
request = urllib_request.Request( |
| 53 |
url, headers={'User-Agent': 'Mozilla/5.0'}) |
| 54 |
urllib_request.urlopen(request).read() |
| 55 |
return False |
| 56 |
except urllib_request.URLError: |
| 57 |
return True |
| 58 |
except SocketError: |
| 59 |
return True |