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.

cache.py 4.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. #!/usr/bin/env python3
  2. import codecs
  3. import fnmatch
  4. import hashlib
  5. import os
  6. from dataclasses import dataclass
  7. from pathlib import Path
  8. from time import perf_counter
  9. import httpx
  10. import lxml
  11. import markdown
  12. from jinja2 import Environment as Env
  13. from jinja2 import FileSystemLoader
  14. from minicli import cli, run, wrap
  15. from readability.readability import Document
  16. HERE = Path(".")
  17. DAVID = HERE / "david"
  18. CACHE_PATH = DAVID / "cache"
  19. DOMAIN = "https://larlet.fr"
  20. environment = Env(loader=FileSystemLoader(str(DAVID / "templates")))
  21. def parse_markdown(file_path):
  22. """Extract title, (HTML) content and metadata from a markdown file."""
  23. parser = markdown.Markdown(extensions=["meta"])
  24. with codecs.open(file_path, "r") as source:
  25. content = parser.convert(source.read())
  26. metadata = parser.Meta if hasattr(parser, "Meta") else None
  27. title = metadata["title"][0] if metadata is not None else ""
  28. return title, content, metadata
  29. def each_markdown_from(source_dir, file_name="index.md"):
  30. """Walk across the `source_dir` and return the md file paths."""
  31. for root, dirnames, filenames in os.walk(source_dir):
  32. for filename in fnmatch.filter(filenames, file_name):
  33. yield os.path.join(root, filename)
  34. @dataclass
  35. class Cache:
  36. title: str
  37. content: str
  38. url: str
  39. hash_url: str
  40. @staticmethod
  41. def all(source_dir=CACHE_PATH):
  42. for file_path in each_markdown_from(source_dir):
  43. title, content, metadata = parse_markdown(file_path)
  44. url = metadata["url"][0]
  45. hash_url = metadata["hash_url"][0]
  46. yield Cache(title, content, url, hash_url)
  47. @staticmethod
  48. def one(hash_url):
  49. return next(Cache.all(source_dir=CACHE_PATH / hash_url))
  50. def extract_page(url):
  51. """From an URL, extract title and content using Readability.
  52. The title is shortened through the `short_title` native method.
  53. The content doesn't contain `<body>` tags to be directly
  54. embeddable in the template and rendered as is.
  55. """
  56. # Retrieves the resource and turns it into a Readability doc.
  57. response = httpx.get(url)
  58. document = Document(response.text)
  59. # The short title is more concise and readable.
  60. title = document.short_title()
  61. content = document.summary(html_partial=True)
  62. # Removing the added <div> and spaces.
  63. content = content[5:-6].strip()
  64. return title, content
  65. def create(hash_url):
  66. """Turn new MD file into HTML file."""
  67. template = environment.get_template("cache_article.html")
  68. cache = Cache.one(hash_url)
  69. page = template.render(cache=cache)
  70. cache_target = CACHE_PATH / hash_url
  71. if not os.path.exists(cache_target):
  72. os.makedirs(cache_target)
  73. open(cache_target / "index.html", "w").write(page)
  74. print(f"Done: http://larlet.test:8001/david/cache/{hash_url}/")
  75. @cli
  76. def generate():
  77. """Generate caches MD files into HTML files."""
  78. caches = []
  79. template = environment.get_template("cache_article.html")
  80. for cache in Cache.all():
  81. page = template.render(cache=cache)
  82. open(CACHE_PATH / cache.hash_url / "index.html", "w").write(page)
  83. caches.append(cache)
  84. template = environment.get_template("cache_archives.html")
  85. page = template.render(caches=caches)
  86. open(CACHE_PATH / "index.html", "w").write(page)
  87. print("Done: http://larlet.test:8001/david/cache/")
  88. @cli
  89. def new(url):
  90. """Turn the given URL into a MD and a HTML files.
  91. :url: The URL of the page to put into cache.
  92. """
  93. hash_url = hashlib.md5(url.encode("utf-8")).hexdigest()
  94. url_cache = f"/david/cache/{hash_url}/"
  95. link_line = f"]({url}) ([cache]({url_cache}))"
  96. print(link_line)
  97. try:
  98. title, content = extract_page(url)
  99. except (lxml.etree.XMLSyntaxError, httpx.exceptions.HTTPError,) as e:
  100. print(f"WARNING: {e}")
  101. title, content = "", ""
  102. cache_path = os.path.join(CACHE_PATH, hash_url)
  103. if not os.path.exists(cache_path):
  104. os.makedirs(cache_path)
  105. # Caching a markdown file.
  106. template = environment.get_template("cache_article.md")
  107. page = template.render(title=title, content=content, url=url, hash_url=hash_url)
  108. result_path = os.path.join(cache_path, "index.md")
  109. open(result_path, "w").write(page)
  110. # Generating the HTML file.
  111. create(hash_url)
  112. md_line = f"> <cite>*[{title}]({url})* ([cache]({url_cache}))</cite>"
  113. print(md_line)
  114. os.popen(f'subl "{result_path}"')
  115. return md_line
  116. @wrap
  117. def perf_wrapper():
  118. start = perf_counter()
  119. yield
  120. elapsed = perf_counter() - start
  121. print(f"Done in {elapsed:.5f} seconds.")
  122. if __name__ == "__main__":
  123. run()