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.9KB

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