Repository with sources and generator of https://larlet.fr/david/ https://larlet.fr/david/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

site.py 28KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820
  1. #!/usr/bin/env python3
  2. import hashlib
  3. import json
  4. import locale
  5. import time
  6. from collections import defaultdict
  7. from dataclasses import dataclass
  8. from datetime import datetime, timedelta
  9. from html import escape
  10. from itertools import chain, groupby
  11. from operator import attrgetter
  12. from pathlib import Path
  13. from string import Template
  14. from textwrap import dedent
  15. from time import perf_counter
  16. from urllib.parse import unquote, urlparse
  17. import feedparser
  18. import markdown
  19. import mistune
  20. from jinja2 import Environment as Env
  21. from jinja2 import FileSystemLoader
  22. from jinja2.filters import do_striptags
  23. from minicli import cli, run, wrap
  24. from mistune.plugins.formatting import mark, strikethrough
  25. from mistune.util import safe_entity
  26. from PIL import Image
  27. from slugify import slugify
  28. from typography import typographie
  29. from widont import widont
  30. # Useful for dates rendering within Jinja2.
  31. locale.setlocale(locale.LC_ALL, "fr_FR.UTF-8")
  32. VERSION = "2024.01.01"
  33. HERE = Path(".")
  34. DAVID = HERE / "david"
  35. STATIC = HERE / ".." / "larlet-fr-static"
  36. DOMAIN = "https://larlet.fr"
  37. LOCAL_DOMAIN = "http://larlet.test:3579"
  38. # Hardcoding publication at 12 in Paris timezone.
  39. NORMALIZED_STRFTIME = "%Y-%m-%dT12:00:00+01:00"
  40. TODAY = datetime.today() + timedelta(hours=6)
  41. PUBLICATION_BUFFER = TODAY - timedelta(days=0)
  42. NB_ITEMS_IN_FEED = 30
  43. SOURCES_PATH = DAVID / "2024" / "_sources"
  44. all_tags = set()
  45. pages_by_tags = defaultdict(list)
  46. pages_by_url = {}
  47. class TagsRenderer(mistune.HTMLRenderer):
  48. """Make the asumption each line starting with a `#` is a tag."""
  49. def paragraph(self, text):
  50. if text.startswith("#"):
  51. tags = " ".join(
  52. f'<a href="/david/2024/{slugify(tag.strip())}/">#{tag.strip()}</a>'
  53. for tag in text.split("#")
  54. if tag.strip()
  55. )
  56. return f"<nav><p>{tags}</p></nav>\n"
  57. return super().paragraph(text)
  58. class FrenchTypographyRenderer(mistune.HTMLRenderer):
  59. """Apply French typographic rules to text."""
  60. def text(self, text):
  61. return typographie(super().text(text), html=True)
  62. def block_html(self, html):
  63. return typographie(super().block_html(html), html=True)
  64. class CustomLinkAttributesRenderer(mistune.HTMLRenderer):
  65. """Automatically generate the title for internal links.
  66. Also, set the domain as a data-attribute for a remote link.
  67. Also, add an archive link if it exists.
  68. Also, split that.
  69. """
  70. def link(self, text, url, title=None):
  71. attrs = {}
  72. attrs["href"] = self.safe_url(url)
  73. if not title and url.startswith("/david/2024/"):
  74. # It will not work for internal urls referencing the future.
  75. page = pages_by_url.get(url)
  76. if page:
  77. title = page.title
  78. else:
  79. hostname = urlparse(url).hostname
  80. if hostname is not None:
  81. if hostname.startswith("www."):
  82. domain = hostname[len("www.") :]
  83. else:
  84. domain = hostname
  85. if domain == "developer.mozilla.org":
  86. domain = "MDN"
  87. attrs["data-link-domain"] = unquote(domain)
  88. if title:
  89. attrs["title"] = safe_entity(title)
  90. attributes = {f'{attr}="{value}"' for attr, value in attrs.items()}
  91. initial_link = f'<a {" ".join(sorted(attributes))}>{text}</a>'
  92. hash_url = hashlib.md5(url.encode("utf-8")).hexdigest()
  93. archive_folder = (
  94. HERE.resolve().parent
  95. / "larlet-fr-david-cache"
  96. / "cache"
  97. / "2024"
  98. / hash_url
  99. ).resolve()
  100. # Regular links without archive.
  101. if not archive_folder.exists():
  102. return initial_link
  103. archive_path_md = archive_folder / "index.md"
  104. parser = markdown.Markdown(extensions=["meta"])
  105. parser.convert(archive_path_md.read_text())
  106. metadata = parser.Meta if hasattr(parser, "Meta") else None
  107. archive_date = metadata.get("archive_date")[0]
  108. description = metadata.get("description")[0]
  109. favicon = metadata.get("favicon")[0]
  110. language = metadata.get("language")[0][:2]
  111. anglais = " (anglais)" if language == "en" else ""
  112. link = f"/david/cache/2024/{hash_url}/"
  113. return f"""<a {" ".join(sorted(attributes))} hreflang="{language}"
  114. title="Consultation de l’article{anglais}">{text}</a>
  115. <a href="{link}" hreflang="{language}"
  116. data-tippy data-description="{description.replace('"', ' ')}"
  117. data-source="{attrs["href"]}"
  118. data-date="{archive_date}"
  119. data-favicon="{favicon}"
  120. data-domain="{attrs["data-link-domain"]}"
  121. ><svg xmlns="http://www.w3.org/2000/svg"
  122. width="24" height="24" viewBox="0 0 24 24" fill="none"
  123. stroke="currentColor" stroke-width="2" stroke-linecap="square"
  124. stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle>
  125. <path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"></path>
  126. <line x1="12" y1="17" x2="12.01" y2="17"></line>
  127. </svg>
  128. <span class="sr-only">[archive]</span></a>"""
  129. class CustomAndBlockquoteLanguageRenderer(FrenchTypographyRenderer, TagsRenderer):
  130. """Sets the English language attribute for blockquotes with `[en]` prefix."""
  131. def _get_language(self, text):
  132. if text.startswith("<p>[en] "):
  133. return "en", text.replace("<p>[en] ", "<p>")
  134. else:
  135. return None, text
  136. def block_quote(self, text):
  137. language, text = self._get_language(text)
  138. if language:
  139. return f'\n<blockquote lang="{language}">\n{text}</blockquote>\n'
  140. else:
  141. return f"\n<blockquote>\n{text}</blockquote>\n"
  142. class ImgsWithSizesRenderer(CustomAndBlockquoteLanguageRenderer):
  143. """Renders images as <figure>s and add sizes."""
  144. def paragraph(self, text):
  145. # In case of a figure, we do not want the (non-standard) paragraph.
  146. if text.strip().startswith("<figure>"):
  147. return text
  148. return super().paragraph(text)
  149. def _generate_size(self, src, width, height):
  150. src_size = src.replace(".jpg", f"_{width}x{height}.jpg")
  151. full_path = STATIC / Path(src[1:])
  152. full_path_size = STATIC / Path(src_size[1:])
  153. if full_path_size.exists() or "/2024/" not in src:
  154. return src_size
  155. image = Image.open(full_path)
  156. image.thumbnail((width, height), resample=Image.LANCZOS)
  157. image.save(full_path_size, icc_profile=image.info.get("icc_profile"))
  158. return src_size
  159. def _generate_webp(self, src):
  160. src_webp = src.replace(".jpg", ".webp")
  161. full_path = STATIC / Path(src[1:])
  162. full_path_webp = STATIC / Path(src_webp[1:])
  163. if full_path_webp.exists() or "/2024/" not in src:
  164. return src_webp
  165. image = Image.open(full_path)
  166. image.save(
  167. full_path_webp, format="webp", icc_profile=image.info.get("icc_profile")
  168. )
  169. # command = [
  170. # "cwebp",
  171. # "-q",
  172. # "80",
  173. # full_path,
  174. # "-o",
  175. # full_path_webp,
  176. # "-metadata",
  177. # "icc",
  178. # ]
  179. # subprocess.check_output(command, stderr=subprocess.STDOUT)
  180. return src_webp
  181. def image(self, alt, url, title=None):
  182. SIZES = [(660, 440), (990, 660), (1320, 880)]
  183. full_path = STATIC / Path(url[1:])
  184. image = Image.open(full_path)
  185. width, height = image.size
  186. jpg_srcs = [(url, width, height)]
  187. # src_webp = self._generate_webp(src)
  188. # webp_srcs = [(src_webp, width, height)]
  189. for size_width, size_height in SIZES:
  190. src_size = self._generate_size(url, size_width, size_height)
  191. jpg_srcs.append((src_size, size_width, size_height))
  192. # src_size_webp = self._generate_webp(src_size)
  193. # webp_srcs.append((src_size_webp, size_width, size_height))
  194. jpg_srcsets = ", ".join(
  195. f"{jpg_src} {jpg_width}w" for jpg_src, jpg_width, jpg_height in jpg_srcs
  196. )
  197. # webp_srcsets = ", ".join(
  198. # f"{webp_src} {webp_width}w"
  199. # for webp_src, webp_width, webp_height in webp_srcs
  200. # )
  201. return dedent(
  202. f"""\
  203. <figure>
  204. <a href="{url}"
  205. title="Cliquer pour une version haute résolution">
  206. <img
  207. src="{url}"
  208. width="{width}" height="{height}"
  209. srcset="{jpg_srcsets}"
  210. sizes="min(100vw, calc(100vh * {width} / {height}))"
  211. loading="lazy"
  212. decoding="async"
  213. alt="{alt}">
  214. </a>
  215. <figcaption>{title}</figcaption>
  216. </figure>
  217. """
  218. )
  219. class AnchorsRenderer(CustomLinkAttributesRenderer, ImgsWithSizesRenderer):
  220. """Custom renderer for H2 titles and HR with anchors."""
  221. # This is fragile to say the least…
  222. global_counter = 0
  223. def heading(self, text, level):
  224. if level == 2:
  225. slug = slugify(text)
  226. return (
  227. f'<h2 id="{slug}">'
  228. f"{text} "
  229. f'<a href="#{slug}" title="Ancre vers cette partie">#</a>'
  230. f"</h2>"
  231. )
  232. else:
  233. return super().heading(text, level)
  234. def thematic_break(self) -> str:
  235. self.global_counter += 1
  236. id = f"hr-{self.global_counter}"
  237. return (
  238. f'<a href="#{id}" title="Lien vers cette section de la page">'
  239. f'<hr id="{id}" />'
  240. "</a>\n"
  241. )
  242. # We want a custom renderer to create a hash/link for each H2 headings.
  243. markdown_with_anchors = mistune.Markdown(
  244. renderer=AnchorsRenderer(escape=False),
  245. plugins=[mark, strikethrough],
  246. )
  247. # The second markdown is pertinent to generate articles for the feed,
  248. # we do not need anchors in that case.
  249. markdown_with_img_sizes = mistune.Markdown(
  250. renderer=ImgsWithSizesRenderer(escape=False),
  251. plugins=[mark, strikethrough],
  252. )
  253. # This is the jinja2 configuration to locate templates.
  254. environment = Env(loader=FileSystemLoader(str(DAVID / "templates")))
  255. def format_struct_time(value, format="%d-%m-%Y"):
  256. return time.strftime(format, value)
  257. environment.filters["format_struct_time"] = format_struct_time
  258. def format_date(value, format="%-d %B %Y"):
  259. return value.strftime(format)
  260. environment.filters["format_date"] = format_date
  261. def neighborhood(iterable, first=None, last=None):
  262. """
  263. Yield the (previous, current, next) items given an iterable.
  264. You can specify a `first` and/or `last` item for bounds.
  265. """
  266. iterator = iter(iterable)
  267. previous = first
  268. current = next(iterator) # Throws StopIteration if empty.
  269. for next_ in iterator:
  270. yield (previous, current, next_)
  271. previous = current
  272. current = next_
  273. yield (previous, current, last)
  274. def each_file_from(source_dir, pattern="*", exclude=None):
  275. """Walk across the `source_dir` and return the `pattern` file paths."""
  276. for path in _each_path_from(source_dir, pattern=pattern, exclude=exclude):
  277. if path.is_file():
  278. yield path
  279. def each_folder_from(source_dir, exclude=None):
  280. """Walk across the `source_dir` and return the folder paths."""
  281. for path in _each_path_from(source_dir, exclude=exclude):
  282. if path.is_dir():
  283. yield path
  284. def _each_path_from(source_dir, pattern="*", exclude=None):
  285. for path in sorted(Path(source_dir).glob(pattern)):
  286. if exclude is not None and path.name in exclude:
  287. continue
  288. yield path
  289. @dataclass
  290. class Page:
  291. title: str
  292. content: str
  293. tags: list
  294. file_path: str
  295. lang: str = "fr"
  296. def __post_init__(self):
  297. try:
  298. date_str, _ = self.file_path.split(" - ", 1)
  299. except ValueError:
  300. # Fallback for 2020 contents (search index)
  301. suffix = len(".md")
  302. prefix = len("YYYY/MM-DD") + suffix
  303. date_str = "2020-" + self.file_path[-prefix:-suffix]
  304. self.url = f"/david/{date_str.replace('-', '/')}/"
  305. self.date = datetime.strptime(date_str, "%Y-%m-%d").date()
  306. self.full_url = f"{DOMAIN}{self.url}"
  307. self.normalized_date = self.date.strftime(NORMALIZED_STRFTIME)
  308. self.escaped_title = escape(self.title)
  309. tag_template = Template(
  310. f'<a href="{DOMAIN}/david/2024/$tag_slug/">#$tag_name</a>'
  311. )
  312. tag_links = " ".join(
  313. tag_template.substitute(tag_slug=slugify(tag), tag_name=tag)
  314. for tag in self.tags
  315. )
  316. self.escaped_content = escape(
  317. self.content.replace('href="/', f'href="{DOMAIN}/')
  318. .replace('src="/', f'src="{DOMAIN}/')
  319. .replace('href="#', f'href="{self.full_url}#')
  320. + f"<nav><p>{tag_links}</p></nav>"
  321. + '<hr/><p><a href="mailto:david@larlet.fr">Réagir ?</a></p>'
  322. )
  323. # Extract first paragraph.
  324. self.extract = do_striptags(self.content.split("</p>", 1)[0] + "</p>")
  325. # Create the index for the search.
  326. self.search_data = {
  327. "title": self.title,
  328. "url": self.url,
  329. "date": date_str,
  330. "content": do_striptags(self.content)
  331. .replace("\u00a0(cache)", " ")
  332. .replace("'", " "),
  333. }
  334. def __eq__(self, other):
  335. return self.url == other.url
  336. def __lt__(self, other: "Page"):
  337. if not isinstance(other, Page):
  338. return NotImplemented
  339. return self.date < other.date
  340. @staticmethod
  341. def all(source: Path, only_published=True, with_anchors=True):
  342. """Retrieve all pages sorted by desc."""
  343. page_list = []
  344. md = markdown_with_anchors if with_anchors else markdown_with_img_sizes
  345. for file_path in sorted(each_file_from(source, pattern="*.md")):
  346. result, state = md.read(file_path)
  347. result = widont(result, html=True)
  348. # Extract (and remove) the title from the generated page.
  349. title, content = result.split("</h1>", 1)
  350. h1_opening_size = len("<h1>")
  351. title = title[h1_opening_size:]
  352. tags = {}
  353. if "<nav><p>" in content:
  354. # Extract the tags from the generated page.
  355. content, tags_links = content.split("<nav><p>", 1)
  356. nav_closing_size = len("</p></nav>\n")
  357. tags_links = tags_links[:-nav_closing_size]
  358. try:
  359. tags = sorted(
  360. {
  361. tag.strip().split("#", 1)[1]
  362. for tag in tags_links.split("</a>")
  363. if tag.strip()
  364. },
  365. key=lambda tag: slugify(tag),
  366. )
  367. except IndexError:
  368. # It happens for old contents, parsed for the search index.
  369. pass
  370. try:
  371. page = Page(title, content, tags, file_path.name)
  372. except ValueError:
  373. print(f"{title} has no date(?), see {file_path.name}")
  374. continue
  375. pages_by_url[page.url] = page
  376. if not page.is_draft:
  377. all_tags.update(tags)
  378. for tag in tags:
  379. if page not in pages_by_tags[tag]:
  380. pages_by_tags[tag].append(page)
  381. if only_published and page.is_draft:
  382. continue
  383. page_list.append(page)
  384. return sorted(page_list, reverse=True)
  385. @property
  386. def is_draft(self):
  387. return (
  388. datetime(year=self.date.year, month=self.date.month, day=self.date.day)
  389. > PUBLICATION_BUFFER
  390. )
  391. @cli
  392. def pages():
  393. """Build article pages."""
  394. root_path = DAVID / "2024"
  395. for previous, page, next_ in neighborhood(
  396. reversed(Page.all(source=SOURCES_PATH, only_published=False)),
  397. first={
  398. "url": "/david/2023/",
  399. "title": "Publications 2023",
  400. "is_draft": False,
  401. },
  402. ):
  403. template = environment.get_template("article_2024.html")
  404. content = template.render(page=page, prev=previous, next=next_, slugify=slugify)
  405. target_path = Path(page.url[1:])
  406. target_path.mkdir(parents=True, exist_ok=True)
  407. (target_path / "index.html").write_text(content)
  408. if page.is_draft:
  409. print(f"Draft: {LOCAL_DOMAIN}{page.url} ({page.title})")
  410. def group_by_month_year(item):
  411. return item.date.strftime("%B %Y").title()
  412. template = environment.get_template("archives_2024.html")
  413. page_list = reversed(Page.all(source=SOURCES_PATH))
  414. tags = sorted((slugify(tag), tag, len(pages_by_tags[tag])) for tag in all_tags)
  415. content = template.render(
  416. page_list=groupby(page_list, key=group_by_month_year), tags=tags
  417. )
  418. (root_path / "index.html").write_text(content)
  419. @cli
  420. def tags():
  421. """Build tags pages."""
  422. # Parse all pages to collect tags.
  423. Page.all(source=SOURCES_PATH, only_published=True)
  424. for tag in all_tags:
  425. template = environment.get_template("tag_2024.html")
  426. content = template.render(
  427. page_list=sorted(pages_by_tags[tag], reverse=True),
  428. tag_name=tag,
  429. slugify=slugify,
  430. )
  431. target_path = DAVID / "2024" / slugify(tag)
  432. target_path.mkdir(parents=True, exist_ok=True)
  433. (target_path / "index.html").write_text(content)
  434. @cli
  435. def home():
  436. """Build the home page with last published items."""
  437. template = environment.get_template("profil_2024.html")
  438. page_list = Page.all(source=SOURCES_PATH, only_published=True)
  439. tags = sorted((slugify(tag), tag, len(pages_by_tags[tag])) for tag in all_tags)
  440. content = template.render(page_list=page_list, tags=tags, slugify=slugify)
  441. (DAVID / "index.html").write_text(content)
  442. @dataclass
  443. class Website:
  444. name: str
  445. url: str
  446. feed: str
  447. def __post_init__(self):
  448. start = perf_counter()
  449. print(f"Fetching {self.feed}…")
  450. content = feedparser.parse(self.feed)
  451. elapsed = perf_counter() - start
  452. entries = content.get("entries")
  453. print(f"Fetched {self.feed} in {elapsed:.5f} seconds.")
  454. print(f"{len(entries)} entries.")
  455. date_key_parsed = (
  456. "published_parsed" if "published_parsed" in entries[0] else "updated_parsed"
  457. )
  458. try:
  459. entries = sorted(entries, key=attrgetter(date_key_parsed), reverse=True)[:2]
  460. except AttributeError:
  461. print("No `{date_key_parsed}` in", entries)
  462. for entry in entries:
  463. entry.website = self
  464. entry.date_parsed = entry[date_key_parsed]
  465. self.entries = entries
  466. @cli
  467. def blogroll():
  468. """Build the blogroll with last published items from people."""
  469. template = environment.get_template("blogroll.html")
  470. website_list = [
  471. # Invalid feed, date not standard.
  472. # Website(
  473. # name="Alex Sirac",
  474. # url="https://alexsirac.com/",
  475. # feed="https://alexsirac.com/feed",
  476. # ),
  477. Website(
  478. name="Maïtané Lenoir",
  479. url="https://www.maiwann.net/",
  480. feed="https://www.maiwann.net/feed.xml",
  481. ),
  482. Website(
  483. name="Fanny Cheung",
  484. url="https://ynote.hk/",
  485. feed="https://ynote.hk/feed.xml",
  486. ),
  487. Website(
  488. name="La Lune Mauve",
  489. url="https://lalunemauve.fr/",
  490. feed="https://lalunemauve.fr/feed/",
  491. ),
  492. Website(
  493. name="Eliness",
  494. url="https://www.hypothermia.fr/",
  495. feed="https://www.hypothermia.fr/rss",
  496. ),
  497. Website(
  498. name="Luce Carević",
  499. url="https://luce.carevic.eu/fr",
  500. feed="https://luce.carevic.eu/fr/flux",
  501. ),
  502. Website(
  503. name="Emma",
  504. url="https://emmaclit.com/",
  505. feed="https://emmaclit.com/feed/",
  506. ),
  507. Website(
  508. name="Karl Dubost",
  509. url="https://www.la-grange.net/",
  510. feed="https://www.la-grange.net/feed.atom",
  511. ),
  512. Website(
  513. name="Thomas Parisot",
  514. url="https://thom4.net/",
  515. feed="https://thom4.net/feed/",
  516. ),
  517. Website(
  518. name="Arthur Perret",
  519. url="https://www.arthurperret.fr/",
  520. feed="https://www.arthurperret.fr/feed.xml",
  521. ),
  522. Website(
  523. name="Antoine Fauchié",
  524. url="https://www.quaternum.net/",
  525. feed="https://www.quaternum.net/atom.xml",
  526. ),
  527. Website(
  528. name="Éric D.",
  529. url="https://n.survol.fr/",
  530. feed="https://n.survol.fr/feed",
  531. ),
  532. Website(
  533. name="Aude",
  534. url="https://blog.ecologie-politique.eu/",
  535. feed="https://blog.ecologie-politique.eu/feed/atom",
  536. ),
  537. # Site en maintenance.
  538. # Website(
  539. # name="Llu",
  540. # url="https://bribesdereel.net/",
  541. # feed="https://bribesdereel.net/feed/rss2",
  542. # ),
  543. Website(
  544. name="Winnie Lim (en)",
  545. url="https://winnielim.org/",
  546. feed="https://winnielim.org/feed/",
  547. ),
  548. Website(
  549. name="brr (en)",
  550. url="https://brr.fyi/",
  551. feed="https://brr.fyi/feed.xml",
  552. ),
  553. ]
  554. entry_list = sorted(
  555. chain(*[website.entries for website in website_list]),
  556. key=attrgetter("date_parsed"),
  557. reverse=True,
  558. )
  559. content = template.render(website_list=website_list, entry_list=entry_list)
  560. (DAVID / "blogroll" / "index.html").write_text(content)
  561. @cli
  562. def toot():
  563. """Pre-write the Mastodon message."""
  564. page_list = Page.all(source=SOURCES_PATH, only_published=True)
  565. last_published = page_list[0]
  566. print(f"✍️ QUOTE? — {last_published.title}, {last_published.full_url}")
  567. print()
  568. print("#blog #larletfr #rss")
  569. print(" ".join([f"#{tag}" for tag in last_published.tags]))
  570. @cli
  571. def search():
  572. """Build the static search page with custom index."""
  573. template = environment.get_template("recherche_2024.html")
  574. page_list_2024 = Page.all(
  575. source=SOURCES_PATH, only_published=True, with_anchors=False
  576. )
  577. page_list_2023 = Page.all(
  578. source=SOURCES_PATH, only_published=True, with_anchors=False
  579. )
  580. page_list_2022 = Page.all(
  581. source=DAVID / "2022" / "_sources", only_published=True, with_anchors=False
  582. )
  583. page_list_2021 = Page.all(
  584. source=DAVID / "2021" / "sources", only_published=True, with_anchors=False
  585. )
  586. page_list_2020 = Page.all(
  587. source=DAVID / "2020", only_published=True, with_anchors=False
  588. )
  589. blog_page_list_2019 = BlogPage.all(source=DAVID / "blog" / "2019")
  590. blog_page_list_2018 = BlogPage.all(source=DAVID / "blog" / "2018")
  591. blog_page_list_2017 = BlogPage.all(source=DAVID / "blog" / "2017")
  592. stream_page_list_2019 = StreamPage.all(source=DAVID / "stream" / "2019")
  593. stream_page_list_2018 = StreamPage.all(source=DAVID / "stream" / "2018")
  594. page_list = (
  595. page_list_2024
  596. + page_list_2023
  597. + page_list_2022
  598. + page_list_2021
  599. + page_list_2020
  600. + blog_page_list_2019
  601. + blog_page_list_2018
  602. + blog_page_list_2017
  603. + stream_page_list_2019
  604. + stream_page_list_2018
  605. )
  606. search_index = json.dumps([page.search_data for page in page_list], indent=2)
  607. content = template.render(search_index=search_index)
  608. (DAVID / "recherche" / "index.html").write_text(content)
  609. @cli
  610. def feed():
  611. """Generate a feed from last published items."""
  612. template = environment.get_template("feed.xml")
  613. page_list = Page.all(source=SOURCES_PATH, with_anchors=False)
  614. content = template.render(
  615. page_list=page_list[:NB_ITEMS_IN_FEED],
  616. current_dt=TODAY.strftime(NORMALIZED_STRFTIME),
  617. BASE_URL=f"{DOMAIN}/david/",
  618. )
  619. (DAVID / "log" / "index.xml").write_text(content)
  620. @wrap
  621. def perf_wrapper():
  622. start = perf_counter()
  623. yield
  624. elapsed = perf_counter() - start
  625. print(f"Done in {elapsed:.5f} seconds.")
  626. # Below are legacy blog contents, still useful for search indexation.
  627. @dataclass
  628. class BlogPage:
  629. title: str
  630. content: str
  631. file_path: str
  632. date_str: str
  633. def __post_init__(self):
  634. self.date = datetime.strptime(self.date_str, "%Y-%m-%d").date()
  635. self.url = f"/{self.file_path}/"
  636. # Create the index for the search.
  637. self.search_data = {
  638. "title": self.title,
  639. "url": self.url,
  640. "date": self.date_str,
  641. "content": do_striptags(self.content)
  642. .replace("\u00a0(cache)", " ")
  643. .replace("'", " ")
  644. .replace("<", "&lt;")
  645. .replace(">", "&gt;"),
  646. }
  647. def __eq__(self, other):
  648. return self.url == other.url
  649. def __lt__(self, other: "BlogPage"):
  650. if not isinstance(other, self.__class__):
  651. return NotImplemented
  652. return self.date < other.date
  653. @staticmethod
  654. def all(source: Path):
  655. """Retrieve all pages sorted by desc."""
  656. page_list = []
  657. for folder in each_folder_from(source):
  658. for path in each_file_from(folder, pattern="*.md"):
  659. metadata, content = path.read_text().split("\n\n", 1)
  660. if "lang:" in metadata:
  661. title, slug, date_, chapo, lang = metadata.split("\n")
  662. else:
  663. title, slug, date_, chapo = metadata.split("\n")
  664. title = title[len("title: ") :].strip()
  665. date_str = date_[len("date: ") :].strip()
  666. content = markdown_with_img_sizes(content)
  667. page = BlogPage(title, content, path.parent, date_str)
  668. page_list.append(page)
  669. return sorted(page_list, reverse=True)
  670. @dataclass
  671. class StreamPage:
  672. title: str
  673. content: str
  674. file_path: str
  675. date_str: str
  676. def __post_init__(self):
  677. self.date = datetime.strptime(self.date_str, "%Y/%m/%d").date()
  678. self.url = f"/{self.file_path}/"
  679. # Create the index for the search.
  680. self.search_data = {
  681. "title": self.title,
  682. "url": self.url,
  683. "date": self.date.isoformat(),
  684. "content": do_striptags(self.content)
  685. .replace("\u00a0(cache)", " ")
  686. .replace("'", " ")
  687. .replace("<", "&lt;")
  688. .replace(">", "&gt;"),
  689. }
  690. def __eq__(self, other):
  691. return self.url == other.url
  692. def __lt__(self, other: "StreamPage"):
  693. if not isinstance(other, self.__class__):
  694. return NotImplemented
  695. return self.date < other.date
  696. @staticmethod
  697. def all(source: Path):
  698. """Retrieve all pages sorted by desc."""
  699. page_list = []
  700. for folder in each_folder_from(source):
  701. for subfolder in each_folder_from(folder):
  702. for path in each_file_from(subfolder, pattern="*.md"):
  703. metadata, content = path.read_text().split("\n\n", 1)
  704. if "lang:" in metadata:
  705. title, lang = metadata.split("\n")
  706. else:
  707. title = metadata.strip()
  708. title = title[len("title: ") :].strip()
  709. date_str = str(path.parent)[-len("YYYY/MM/DD") :]
  710. content = markdown_with_img_sizes(content)
  711. page = StreamPage(title, content, path.parent, date_str)
  712. page_list.append(page)
  713. return sorted(page_list, reverse=True)
  714. if __name__ == "__main__":
  715. run()