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.

преди 10 месеца
преди 5 години
преди 1 година
преди 9 месеца
преди 1 година
преди 9 месеца
преди 4 години
преди 1 година
преди 4 години
преди 5 години
преди 2 години
преди 5 години
преди 10 месеца
преди 4 години
преди 2 години
преди 10 месеца
преди 4 години
преди 10 месеца
преди 10 месеца
преди 1 година
преди 10 месеца
преди 10 месеца
преди 1 година
преди 10 месеца
преди 10 месеца
преди 9 месеца
преди 9 месеца
преди 10 месеца
преди 10 месеца
преди 10 месеца
преди 9 месеца
преди 10 месеца
преди 10 месеца
преди 10 месеца
преди 1 година
преди 1 година
преди 1 година
преди 1 година
преди 1 година
преди 3 години
преди 1 година
преди 3 години
преди 10 месеца
преди 4 години
преди 4 години
преди 4 години
преди 10 месеца
преди 4 години
преди 10 месеца
преди 1 година
преди 1 година
преди 4 години
преди 10 месеца
преди 4 години
преди 5 години
преди 4 години
преди 4 години
преди 3 години
преди 10 месеца
преди 4 години
преди 4 години
преди 8 месеца
преди 4 години
преди 4 години
преди 4 години
преди 10 месеца
преди 4 години
преди 10 месеца
преди 1 година
преди 4 години
преди 8 месеца
преди 9 месеца
преди 4 години
преди 4 години
преди 4 години
преди 3 години
преди 4 години
преди 4 години
преди 10 месеца
преди 4 години
преди 2 години
преди 4 години
преди 10 месеца
преди 4 години
преди 4 години
преди 10 месеца
преди 4 години
преди 4 години
преди 10 месеца
преди 2 години
преди 4 години
преди 2 години
преди 10 месеца
преди 10 месеца
преди 10 месеца
преди 5 години
преди 10 месеца
преди 2 години
преди 1 година
преди 8 месеца
преди 5 години
преди 1 година
преди 9 месеца
преди 1 година
преди 1 година
преди 10 месеца
преди 1 година
преди 1 година
преди 1 година
преди 1 година
преди 1 година
преди 1 година
преди 10 месеца
преди 1 година
преди 1 година
преди 1 година
преди 1 година
преди 1 година
преди 1 година
преди 1 година
преди 10 месеца
преди 10 месеца
преди 10 месеца
преди 10 месеца
преди 1 година
преди 10 месеца
преди 1 година
преди 10 месеца
преди 1 година
преди 10 месеца
преди 10 месеца
преди 10 месеца
преди 1 година
преди 5 години
преди 10 месеца
преди 4 години
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825
  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. # Extract (and remove) the title from the generated page.
  348. title, content = result.split("</h1>", 1)
  349. h1_opening_size = len("<h1>")
  350. title = title[h1_opening_size:]
  351. extra_file = file_path.with_suffix(".html")
  352. content = widont(content, html=True)
  353. if extra_file.exists():
  354. content = content.replace(
  355. "<p>{{ extra&nbsp;}}</p>", extra_file.read_text()
  356. )
  357. tags = {}
  358. if "<nav><p>" in content:
  359. # Extract the tags from the generated page.
  360. content, tags_links = content.split("<nav><p>", 1)
  361. nav_closing_size = len("</p></nav>\n")
  362. tags_links = tags_links[:-nav_closing_size]
  363. try:
  364. tags = sorted(
  365. {
  366. tag.strip().split("#", 1)[1]
  367. for tag in tags_links.split("</a>")
  368. if tag.strip()
  369. },
  370. key=lambda tag: slugify(tag),
  371. )
  372. except IndexError:
  373. # It happens for old contents, parsed for the search index.
  374. pass
  375. try:
  376. page = Page(title, content, tags, file_path.name)
  377. except ValueError:
  378. print(f"{title} has no date(?), see {file_path.name}")
  379. continue
  380. pages_by_url[page.url] = page
  381. if not page.is_draft:
  382. all_tags.update(tags)
  383. for tag in tags:
  384. if page not in pages_by_tags[tag]:
  385. pages_by_tags[tag].append(page)
  386. if only_published and page.is_draft:
  387. continue
  388. page_list.append(page)
  389. return sorted(page_list, reverse=True)
  390. @property
  391. def is_draft(self):
  392. return (
  393. datetime(year=self.date.year, month=self.date.month, day=self.date.day)
  394. > PUBLICATION_BUFFER
  395. )
  396. @cli
  397. def pages():
  398. """Build article pages."""
  399. root_path = DAVID / "2024"
  400. for previous, page, next_ in neighborhood(
  401. reversed(Page.all(source=SOURCES_PATH, only_published=False)),
  402. first={
  403. "url": "/david/2023/",
  404. "title": "Publications 2023",
  405. "is_draft": False,
  406. },
  407. ):
  408. template = environment.get_template("article_2024.html")
  409. content = template.render(page=page, prev=previous, next=next_, slugify=slugify)
  410. target_path = Path(page.url[1:])
  411. target_path.mkdir(parents=True, exist_ok=True)
  412. (target_path / "index.html").write_text(content)
  413. if page.is_draft:
  414. print(f"Draft: {LOCAL_DOMAIN}{page.url} ({page.title})")
  415. def group_by_month_year(item):
  416. return item.date.strftime("%B %Y").title()
  417. template = environment.get_template("archives_2024.html")
  418. page_list = reversed(Page.all(source=SOURCES_PATH))
  419. tags = sorted((slugify(tag), tag, len(pages_by_tags[tag])) for tag in all_tags)
  420. content = template.render(
  421. page_list=groupby(page_list, key=group_by_month_year), tags=tags
  422. )
  423. (root_path / "index.html").write_text(content)
  424. @cli
  425. def tags():
  426. """Build tags pages."""
  427. # Parse all pages to collect tags.
  428. Page.all(source=SOURCES_PATH, only_published=True)
  429. for tag in all_tags:
  430. template = environment.get_template("tag_2024.html")
  431. content = template.render(
  432. page_list=sorted(pages_by_tags[tag], reverse=True),
  433. tag_name=tag,
  434. slugify=slugify,
  435. )
  436. target_path = DAVID / "2024" / slugify(tag)
  437. target_path.mkdir(parents=True, exist_ok=True)
  438. (target_path / "index.html").write_text(content)
  439. @cli
  440. def home():
  441. """Build the home page with last published items."""
  442. template = environment.get_template("profil_2024.html")
  443. page_list = Page.all(source=SOURCES_PATH, only_published=True)
  444. tags = sorted((slugify(tag), tag, len(pages_by_tags[tag])) for tag in all_tags)
  445. content = template.render(page_list=page_list, tags=tags, slugify=slugify)
  446. (DAVID / "index.html").write_text(content)
  447. @dataclass
  448. class Website:
  449. name: str
  450. url: str
  451. feed: str
  452. def __post_init__(self):
  453. start = perf_counter()
  454. print(f"Fetching {self.feed}…")
  455. content = feedparser.parse(self.feed)
  456. elapsed = perf_counter() - start
  457. entries = content.get("entries")
  458. print(f"Fetched {self.feed} in {elapsed:.5f} seconds.")
  459. print(f"{len(entries)} entries.")
  460. date_key_parsed = (
  461. "published_parsed" if "published_parsed" in entries[0] else "updated_parsed"
  462. )
  463. try:
  464. entries = sorted(entries, key=attrgetter(date_key_parsed), reverse=True)[:2]
  465. except AttributeError:
  466. print("No `{date_key_parsed}` in", entries)
  467. for entry in entries:
  468. entry.website = self
  469. entry.date_parsed = entry[date_key_parsed]
  470. self.entries = entries
  471. @cli
  472. def blogroll():
  473. """Build the blogroll with last published items from people."""
  474. template = environment.get_template("blogroll.html")
  475. website_list = [
  476. # Invalid feed, date not standard.
  477. # Website(
  478. # name="Alex Sirac",
  479. # url="https://alexsirac.com/",
  480. # feed="https://alexsirac.com/feed",
  481. # ),
  482. Website(
  483. name="Maïtané Lenoir",
  484. url="https://www.maiwann.net/",
  485. feed="https://www.maiwann.net/feed.xml",
  486. ),
  487. Website(
  488. name="Fanny Cheung",
  489. url="https://ynote.hk/",
  490. feed="https://ynote.hk/feed.xml",
  491. ),
  492. Website(
  493. name="La Lune Mauve",
  494. url="https://lalunemauve.fr/",
  495. feed="https://lalunemauve.fr/feed/",
  496. ),
  497. Website(
  498. name="Eliness",
  499. url="https://www.hypothermia.fr/",
  500. feed="https://www.hypothermia.fr/rss",
  501. ),
  502. Website(
  503. name="Luce Carević",
  504. url="https://luce.carevic.eu/fr",
  505. feed="https://luce.carevic.eu/fr/flux",
  506. ),
  507. Website(
  508. name="Emma",
  509. url="https://emmaclit.com/",
  510. feed="https://emmaclit.com/feed/",
  511. ),
  512. Website(
  513. name="Karl Dubost",
  514. url="https://www.la-grange.net/",
  515. feed="https://www.la-grange.net/feed.atom",
  516. ),
  517. Website(
  518. name="Thomas Parisot",
  519. url="https://thom4.net/",
  520. feed="https://thom4.net/feed/",
  521. ),
  522. Website(
  523. name="Arthur Perret",
  524. url="https://www.arthurperret.fr/",
  525. feed="https://www.arthurperret.fr/feed.xml",
  526. ),
  527. Website(
  528. name="Antoine Fauchié",
  529. url="https://www.quaternum.net/",
  530. feed="https://www.quaternum.net/atom.xml",
  531. ),
  532. Website(
  533. name="Éric D.",
  534. url="https://n.survol.fr/",
  535. feed="https://n.survol.fr/feed",
  536. ),
  537. Website(
  538. name="Aude",
  539. url="https://blog.ecologie-politique.eu/",
  540. feed="https://blog.ecologie-politique.eu/feed/atom",
  541. ),
  542. # Site en maintenance.
  543. # Website(
  544. # name="Llu",
  545. # url="https://bribesdereel.net/",
  546. # feed="https://bribesdereel.net/feed/rss2",
  547. # ),
  548. Website(
  549. name="Winnie Lim (en)",
  550. url="https://winnielim.org/",
  551. feed="https://winnielim.org/feed/",
  552. ),
  553. Website(
  554. name="brr (en)",
  555. url="https://brr.fyi/",
  556. feed="https://brr.fyi/feed.xml",
  557. ),
  558. ]
  559. entry_list = sorted(
  560. chain(*[website.entries for website in website_list]),
  561. key=attrgetter("date_parsed"),
  562. reverse=True,
  563. )
  564. content = template.render(website_list=website_list, entry_list=entry_list)
  565. (DAVID / "blogroll" / "index.html").write_text(content)
  566. @cli
  567. def toot():
  568. """Pre-write the Mastodon message."""
  569. page_list = Page.all(source=SOURCES_PATH, only_published=True)
  570. last_published = page_list[0]
  571. print(f"✍️ QUOTE? — {last_published.title}, {last_published.full_url}")
  572. print()
  573. print("#blog #larletfr #rss")
  574. print(" ".join([f"#{tag}" for tag in last_published.tags]))
  575. @cli
  576. def search():
  577. """Build the static search page with custom index."""
  578. template = environment.get_template("recherche_2024.html")
  579. page_list_2024 = Page.all(
  580. source=SOURCES_PATH, only_published=True, with_anchors=False
  581. )
  582. page_list_2023 = Page.all(
  583. source=SOURCES_PATH, only_published=True, with_anchors=False
  584. )
  585. page_list_2022 = Page.all(
  586. source=DAVID / "2022" / "_sources", only_published=True, with_anchors=False
  587. )
  588. page_list_2021 = Page.all(
  589. source=DAVID / "2021" / "sources", only_published=True, with_anchors=False
  590. )
  591. page_list_2020 = Page.all(
  592. source=DAVID / "2020", only_published=True, with_anchors=False
  593. )
  594. blog_page_list_2019 = BlogPage.all(source=DAVID / "blog" / "2019")
  595. blog_page_list_2018 = BlogPage.all(source=DAVID / "blog" / "2018")
  596. blog_page_list_2017 = BlogPage.all(source=DAVID / "blog" / "2017")
  597. stream_page_list_2019 = StreamPage.all(source=DAVID / "stream" / "2019")
  598. stream_page_list_2018 = StreamPage.all(source=DAVID / "stream" / "2018")
  599. page_list = (
  600. page_list_2024
  601. + page_list_2023
  602. + page_list_2022
  603. + page_list_2021
  604. + page_list_2020
  605. + blog_page_list_2019
  606. + blog_page_list_2018
  607. + blog_page_list_2017
  608. + stream_page_list_2019
  609. + stream_page_list_2018
  610. )
  611. search_index = json.dumps([page.search_data for page in page_list], indent=2)
  612. content = template.render(search_index=search_index)
  613. (DAVID / "recherche" / "index.html").write_text(content)
  614. @cli
  615. def feed():
  616. """Generate a feed from last published items."""
  617. template = environment.get_template("feed.xml")
  618. page_list = Page.all(source=SOURCES_PATH, with_anchors=False)
  619. content = template.render(
  620. page_list=page_list[:NB_ITEMS_IN_FEED],
  621. current_dt=TODAY.strftime(NORMALIZED_STRFTIME),
  622. BASE_URL=f"{DOMAIN}/david/",
  623. )
  624. (DAVID / "log" / "index.xml").write_text(content)
  625. @wrap
  626. def perf_wrapper():
  627. start = perf_counter()
  628. yield
  629. elapsed = perf_counter() - start
  630. print(f"Done in {elapsed:.5f} seconds.")
  631. # Below are legacy blog contents, still useful for search indexation.
  632. @dataclass
  633. class BlogPage:
  634. title: str
  635. content: str
  636. file_path: str
  637. date_str: str
  638. def __post_init__(self):
  639. self.date = datetime.strptime(self.date_str, "%Y-%m-%d").date()
  640. self.url = f"/{self.file_path}/"
  641. # Create the index for the search.
  642. self.search_data = {
  643. "title": self.title,
  644. "url": self.url,
  645. "date": self.date_str,
  646. "content": do_striptags(self.content)
  647. .replace("\u00a0(cache)", " ")
  648. .replace("'", " ")
  649. .replace("<", "&lt;")
  650. .replace(">", "&gt;"),
  651. }
  652. def __eq__(self, other):
  653. return self.url == other.url
  654. def __lt__(self, other: "BlogPage"):
  655. if not isinstance(other, self.__class__):
  656. return NotImplemented
  657. return self.date < other.date
  658. @staticmethod
  659. def all(source: Path):
  660. """Retrieve all pages sorted by desc."""
  661. page_list = []
  662. for folder in each_folder_from(source):
  663. for path in each_file_from(folder, pattern="*.md"):
  664. metadata, content = path.read_text().split("\n\n", 1)
  665. if "lang:" in metadata:
  666. title, slug, date_, chapo, lang = metadata.split("\n")
  667. else:
  668. title, slug, date_, chapo = metadata.split("\n")
  669. title = title[len("title: ") :].strip()
  670. date_str = date_[len("date: ") :].strip()
  671. content = markdown_with_img_sizes(content)
  672. page = BlogPage(title, content, path.parent, date_str)
  673. page_list.append(page)
  674. return sorted(page_list, reverse=True)
  675. @dataclass
  676. class StreamPage:
  677. title: str
  678. content: str
  679. file_path: str
  680. date_str: str
  681. def __post_init__(self):
  682. self.date = datetime.strptime(self.date_str, "%Y/%m/%d").date()
  683. self.url = f"/{self.file_path}/"
  684. # Create the index for the search.
  685. self.search_data = {
  686. "title": self.title,
  687. "url": self.url,
  688. "date": self.date.isoformat(),
  689. "content": do_striptags(self.content)
  690. .replace("\u00a0(cache)", " ")
  691. .replace("'", " ")
  692. .replace("<", "&lt;")
  693. .replace(">", "&gt;"),
  694. }
  695. def __eq__(self, other):
  696. return self.url == other.url
  697. def __lt__(self, other: "StreamPage"):
  698. if not isinstance(other, self.__class__):
  699. return NotImplemented
  700. return self.date < other.date
  701. @staticmethod
  702. def all(source: Path):
  703. """Retrieve all pages sorted by desc."""
  704. page_list = []
  705. for folder in each_folder_from(source):
  706. for subfolder in each_folder_from(folder):
  707. for path in each_file_from(subfolder, pattern="*.md"):
  708. metadata, content = path.read_text().split("\n\n", 1)
  709. if "lang:" in metadata:
  710. title, lang = metadata.split("\n")
  711. else:
  712. title = metadata.strip()
  713. title = title[len("title: ") :].strip()
  714. date_str = str(path.parent)[-len("YYYY/MM/DD") :]
  715. content = markdown_with_img_sizes(content)
  716. page = StreamPage(title, content, path.parent, date_str)
  717. page_list.append(page)
  718. return sorted(page_list, reverse=True)
  719. if __name__ == "__main__":
  720. run()