A place to cache linked articles (think custom and personal wayback machine)
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.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  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. YEAR = "2023"
  18. CACHE_PATH = HERE / "cache" / YEAR
  19. LOCAL_DOMAIN = "http://larlet.test:3579"
  20. environment = Env(loader=FileSystemLoader(str(HERE / "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: {LOCAL_DOMAIN}/david/cache/{YEAR}/{hash_url}/")
  75. @cli
  76. def generate():
  77. """Generate caches MD files into HTML files."""
  78. cache_list = []
  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. cache_list.append(cache)
  84. template = environment.get_template("cache_archives.html")
  85. page = template.render(cache_list=cache_list)
  86. open(CACHE_PATH / "index.html", "w").write(page)
  87. print(f"Done: {LOCAL_DOMAIN}/david/cache/{YEAR}/")
  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/{YEAR}/{hash_url}/"
  95. link_line = f"]({url}) ([cache]({url_cache}))"
  96. print(link_line)
  97. try:
  98. title, content = extract_page(url)
  99. except (
  100. lxml.etree.XMLSyntaxError,
  101. httpx.HTTPError,
  102. httpx.ReadTimeout,
  103. ) as e:
  104. print(f"WARNING: {e}")
  105. title, content = "", ""
  106. cache_path = os.path.join(CACHE_PATH, hash_url)
  107. if not os.path.exists(cache_path):
  108. os.makedirs(cache_path)
  109. # Caching a markdown file.
  110. template = environment.get_template("cache_article.md")
  111. page = template.render(title=title, content=content, url=url, hash_url=hash_url)
  112. result_path = os.path.join(cache_path, "index.md")
  113. open(result_path, "w").write(page)
  114. # Generating the HTML file.
  115. create(hash_url)
  116. md_line = f"> <cite>*[{title}]({url})* ([cache]({url_cache}))</cite>"
  117. print(md_line)
  118. os.popen(f'subl "{result_path}"')
  119. return md_line
  120. @wrap
  121. def perf_wrapper():
  122. start = perf_counter()
  123. yield
  124. elapsed = perf_counter() - start
  125. print(f"Done in {elapsed:.5f} seconds.")
  126. if __name__ == "__main__":
  127. run()