sites/tobias.raayoni-last.com/plugins/lostimages.py

56 lines
1.9 KiB
Python
Raw Normal View History

"""Drop <img> tags in article bodies whose file did not survive the recovery.
The same situation as assetcheck.py, one level down: the recovered bodies kept
their original /library/ references, and 22 of 200 point at files no archive
holds (checked against Wayback; the CDX API returns no captures for them).
Left alone they render as a broken-image box, which on a phone reads as an
unexplained 40px hole between paragraphs. The reference is still worth keeping
in the Markdown source, so this strips it only from the generated HTML and
leaves a comment naming the file, which keeps the output self-documenting for
anyone who later finds the originals on the offline drive.
"""
import os
import re
from pelican import signals
IMG = re.compile(r'<img[^>]*\bsrc="(/[^"]+)"[^>]*>')
ANCHOR = re.compile(r'<a[^>]*\bhref="(/library/[^"]+)"[^>]*>(.*?)</a>', re.S)
def _strip(content):
body = getattr(content, "_content", None)
if not body or "<img" not in body:
return
base = content.settings.get("PATH", "content")
lost = []
def anchor(m):
rel = m.group(1).lstrip("/")
if os.path.exists(os.path.join(base, rel)):
return m.group(0)
return m.group(2)
def sub(m):
rel = m.group(1).lstrip("/")
if os.path.exists(os.path.join(base, rel)):
return m.group(0)
lost.append(os.path.basename(rel))
return "<!-- lost image: %s -->" % os.path.basename(rel)
body = IMG.sub(sub, body)
# a thumbnail that linked to the full-size file leaves the <a> behind, and
# its href 404s just as the <img> did
body = ANCHOR.sub(anchor, body)
if not lost:
return
# a paragraph that held nothing but the lost image would still occupy space
body = re.sub(r"<p>\s*((?:<!-- lost image: [^>]*-->\s*)+)</p>", r"\1", body)
content._content = body
content.lost_images = lost
def register():
signals.content_object_init.connect(_strip)