#!/usr/bin/env python3
import hashlib
import json
import locale
import time
from collections import defaultdict
from dataclasses import dataclass
from datetime import datetime, timedelta
from html import escape
from itertools import chain, groupby
from operator import attrgetter
from pathlib import Path
from string import Template
from textwrap import dedent
from time import perf_counter
from urllib.parse import unquote, urlparse
import feedparser
import markdown
import mistune
from jinja2 import Environment as Env
from jinja2 import FileSystemLoader
from jinja2.filters import do_striptags
from minicli import cli, run, wrap
from mistune.plugins.formatting import mark, strikethrough
from mistune.util import safe_entity
from PIL import Image
from slugify import slugify
from typography import typographie
from widont import widont
# Useful for dates rendering within Jinja2.
locale.setlocale(locale.LC_ALL, "fr_FR.UTF-8")
VERSION = "2024.01.01"
HERE = Path(".")
DAVID = HERE / "david"
STATIC = HERE / ".." / "larlet-fr-static"
DOMAIN = "https://larlet.fr"
LOCAL_DOMAIN = "http://larlet.test:3579"
# Hardcoding publication at 12 in Paris timezone.
NORMALIZED_STRFTIME = "%Y-%m-%dT12:00:00+01:00"
TODAY = datetime.today() + timedelta(hours=6)
PUBLICATION_BUFFER = TODAY - timedelta(days=0)
NB_ITEMS_IN_FEED = 30
SOURCES_PATH = DAVID / "2024" / "_sources"
all_tags = set()
pages_by_tags = defaultdict(list)
pages_by_url = {}
class TagsRenderer(mistune.HTMLRenderer):
"""Make the asumption each line starting with a `#` is a tag."""
def paragraph(self, text):
if text.startswith("#"):
tags = " ".join(
f'#{tag.strip()}'
for tag in text.split("#")
if tag.strip()
)
return f"\n"
return super().paragraph(text)
class FrenchTypographyRenderer(mistune.HTMLRenderer):
"""Apply French typographic rules to text."""
def text(self, text):
return typographie(super().text(text), html=True)
def block_html(self, html):
return typographie(super().block_html(html), html=True)
class CustomLinkAttributesRenderer(mistune.HTMLRenderer):
"""Automatically generate the title for internal links.
Also, set the domain as a data-attribute for a remote link.
Also, add an archive link if it exists.
Also, split that.
"""
def link(self, text, url, title=None):
attrs = {}
attrs["href"] = self.safe_url(url)
if not title and url.startswith("/david/2024/"):
# It will not work for internal urls referencing the future.
page = pages_by_url.get(url)
if page:
title = page.title
else:
hostname = urlparse(url).hostname
if hostname is not None:
if hostname.startswith("www."):
domain = hostname[len("www.") :]
else:
domain = hostname
if domain == "developer.mozilla.org":
domain = "MDN"
attrs["data-link-domain"] = unquote(domain)
if title:
attrs["title"] = safe_entity(title)
attributes = {f'{attr}="{value}"' for attr, value in attrs.items()}
initial_link = f'{text}'
hash_url = hashlib.md5(url.encode("utf-8")).hexdigest()
archive_folder = (
HERE.resolve().parent
/ "larlet-fr-david-cache"
/ "cache"
/ "2024"
/ hash_url
).resolve()
# Regular links without archive.
if not archive_folder.exists():
return initial_link
archive_path_md = archive_folder / "index.md"
parser = markdown.Markdown(extensions=["meta"])
parser.convert(archive_path_md.read_text())
metadata = parser.Meta if hasattr(parser, "Meta") else None
archive_date = metadata.get("archive_date")[0]
description = metadata.get("description")[0]
favicon = metadata.get("favicon")[0]
language = metadata.get("language")[0][:2]
anglais = " (anglais)" if language == "en" else ""
link = f"/david/cache/2024/{hash_url}/"
return f"""{text}[archive]"""
class CustomAndBlockquoteLanguageRenderer(FrenchTypographyRenderer, TagsRenderer):
"""Sets the English language attribute for blockquotes with `[en]` prefix."""
def _get_language(self, text):
if text.startswith("
[en] "):
return "en", text.replace("
[en] ", "
")
else:
return None, text
def block_quote(self, text):
language, text = self._get_language(text)
if language:
return f'\n
\n{text}
\n'
else:
return f"\n
\n{text}
\n"
class ImgsWithSizesRenderer(CustomAndBlockquoteLanguageRenderer):
"""Renders images as