A place to cache linked articles (think custom and personal wayback machine)
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

cache.py 8.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. #!/usr/bin/env python3
  2. import codecs
  3. import fnmatch
  4. import hashlib
  5. import os
  6. from dataclasses import dataclass
  7. from datetime import date
  8. from pathlib import Path
  9. from time import perf_counter
  10. from urllib.parse import urlparse
  11. import httpx
  12. import lassie
  13. import lxml
  14. import markdown
  15. from jinja2 import Environment as Env
  16. from jinja2 import FileSystemLoader
  17. from minicli import cli, run, wrap
  18. from readability.readability import Document
  19. HERE = Path(".")
  20. YEAR = "2024"
  21. CACHE_PATH = HERE / "cache" / YEAR
  22. LOCAL_DOMAIN = "http://larlet.test:3579"
  23. environment = Env(loader=FileSystemLoader(str(HERE / "templates")))
  24. def parse_markdown(file_path):
  25. """Extract title, (HTML) content and metadata from a markdown file."""
  26. parser = markdown.Markdown(extensions=["meta"])
  27. with codecs.open(file_path, "r") as source:
  28. content = parser.convert(source.read())
  29. metadata = parser.Meta if hasattr(parser, "Meta") else None
  30. title = metadata["title"][0] if metadata is not None else ""
  31. return title, content, metadata
  32. def each_markdown_from(source_dir, file_name="index.md"):
  33. """Walk across the `source_dir` and return the md file paths."""
  34. for root, dirnames, filenames in os.walk(source_dir):
  35. for filename in fnmatch.filter(filenames, file_name):
  36. yield os.path.join(root, filename)
  37. @dataclass
  38. class Cache:
  39. title: str
  40. content: str
  41. url: str
  42. hash_url: str
  43. archive_date: str
  44. og_image: str
  45. description: str
  46. favicon: str
  47. @staticmethod
  48. def all(source_dir=CACHE_PATH):
  49. for file_path in each_markdown_from(source_dir):
  50. title, content, metadata = parse_markdown(file_path)
  51. url = metadata["url"][0]
  52. hash_url = metadata["hash_url"][0]
  53. archive_date = metadata["archive_date"][0]
  54. og_image = metadata.get("og_image", [""])[0]
  55. description = metadata.get("description", [""])[0]
  56. favicon = metadata.get("favicon", [""])[0]
  57. yield Cache(
  58. title,
  59. content,
  60. url,
  61. hash_url,
  62. archive_date,
  63. og_image,
  64. description,
  65. favicon,
  66. )
  67. @staticmethod
  68. def one(hash_url):
  69. return next(Cache.all(source_dir=CACHE_PATH / hash_url))
  70. def extract_page(url):
  71. """From an URL, extract title and content using Readability.
  72. The title is shortened through the `short_title` native method.
  73. The content doesn't contain `<body>` tags to be directly
  74. embeddable in the template and rendered as is.
  75. """
  76. # Retrieves the resource and turns it into a Readability doc.
  77. response = httpx.get(url)
  78. document = Document(response.text)
  79. # The short title is more concise and readable.
  80. title = document.short_title()
  81. content = document.summary(html_partial=True)
  82. # Removing the added <div> and spaces.
  83. content = content[5:-6].strip()
  84. return title, content
  85. def create(hash_url):
  86. """Turn new MD file into HTML file."""
  87. template = environment.get_template("cache_article.html")
  88. cache = Cache.one(hash_url)
  89. page = template.render(cache=cache)
  90. cache_target = CACHE_PATH / hash_url
  91. if not os.path.exists(cache_target):
  92. os.makedirs(cache_target)
  93. open(cache_target / "index.html", "w").write(page)
  94. print(f"Done: {LOCAL_DOMAIN}/david/cache/{YEAR}/{hash_url}/")
  95. def save(
  96. title,
  97. content,
  98. url,
  99. hash_url,
  100. archive_date,
  101. cache_path,
  102. og_image,
  103. description,
  104. favicon,
  105. ):
  106. template = environment.get_template("cache_article.md")
  107. page = template.render(
  108. title=title,
  109. content=content,
  110. url=url,
  111. hash_url=hash_url,
  112. archive_date=archive_date,
  113. og_image=og_image,
  114. description=description,
  115. favicon=favicon,
  116. )
  117. result_path = os.path.join(cache_path, "index.md")
  118. open(result_path, "w").write(page)
  119. return result_path
  120. @cli
  121. def generate():
  122. """Generate caches MD files into HTML files."""
  123. cache_list = []
  124. template = environment.get_template("cache_article.html")
  125. for cache in Cache.all():
  126. page = template.render(cache=cache)
  127. open(CACHE_PATH / cache.hash_url / "index.html", "w").write(page)
  128. cache_list.append(cache)
  129. template = environment.get_template("cache_archives.html")
  130. page = template.render(cache_list=cache_list)
  131. open(CACHE_PATH / "index.html", "w").write(page)
  132. print(f"Done: {LOCAL_DOMAIN}/david/cache/{YEAR}/")
  133. def fetch_metadata(title, url, description):
  134. """Fetch additional metadata."""
  135. parsed_url = urlparse(url)
  136. root_url = f"{parsed_url.scheme}://{parsed_url.netloc}/"
  137. data = lassie.fetch(url)
  138. og_image = ""
  139. favicon = ""
  140. for image in data.get("images"):
  141. image_type = image.get("type")
  142. image_src = image.get("src")
  143. if image_src == root_url:
  144. og_image = ""
  145. continue
  146. elif image_type == "og:image" and not og_image:
  147. og_image = image_src
  148. continue
  149. elif image_type == "twitter:image" and not og_image:
  150. og_image = image_src
  151. continue
  152. elif image_type == "favicon":
  153. if not favicon:
  154. favicon = image_src
  155. elif ".ico" in favicon and ".ico" not in image_src:
  156. favicon = image_src
  157. # Fallback on server's default.
  158. if not favicon:
  159. favico_url = f"{root_url}favicon.ico"
  160. response = httpx.get(favico_url)
  161. if response.status_code == 200:
  162. favicon = favico_url
  163. if data.get("title") != title:
  164. print(data.get("title"), "vs.", title, url)
  165. description = description or data.get("description", "")
  166. return og_image, description, favicon
  167. @cli
  168. def metadata():
  169. """Fetch additional metadata for existing archives."""
  170. for cache in Cache.all():
  171. # That one is takin way too long.
  172. if cache.url.startswith("https://tw5.immateriel.fr"):
  173. print("Skipping", cache.url)
  174. continue
  175. # if cache.description or cache.url.startswith(
  176. # (
  177. # "https://www.la-grange.net",
  178. # "https://gilest.org",
  179. # "https://vasilis.nl",
  180. # "https://www.danmcquillan.org",
  181. # "https://public-inbox.org",
  182. # )
  183. # ):
  184. # print("Skipping", cache.url)
  185. # continue
  186. print("Fetching metadata for", cache.url, cache.title)
  187. og_image, description, favicon = fetch_metadata(
  188. cache.title, cache.url, cache.description
  189. )
  190. save(
  191. cache.title,
  192. cache.content,
  193. cache.url,
  194. cache.hash_url,
  195. cache.archive_date,
  196. os.path.join(CACHE_PATH, cache.hash_url),
  197. og_image,
  198. description,
  199. favicon,
  200. )
  201. @cli
  202. def new(url):
  203. """Turn the given URL into a MD and a HTML files.
  204. :url: The URL of the page to put into cache.
  205. """
  206. hash_url = hashlib.md5(url.encode("utf-8")).hexdigest()
  207. try:
  208. title, content = extract_page(url)
  209. except (
  210. lxml.etree.XMLSyntaxError,
  211. httpx.HTTPError,
  212. httpx.ReadTimeout,
  213. ) as e:
  214. print(f"WARNING: {e}")
  215. title, content = "", ""
  216. cache_path = os.path.join(CACHE_PATH, hash_url)
  217. if not os.path.exists(cache_path):
  218. os.makedirs(cache_path)
  219. archive_date = date.today()
  220. # Caching a markdown file.
  221. og_image, description, favicon = fetch_metadata(title, url, "")
  222. result_path = save(
  223. title,
  224. content,
  225. url,
  226. hash_url,
  227. archive_date,
  228. cache_path,
  229. og_image,
  230. description,
  231. favicon,
  232. )
  233. # Generating the HTML file.
  234. create(hash_url)
  235. md_line = f"> <cite>*[{title}]({url})*</cite>"
  236. print(md_line)
  237. os.popen(f'subl "{result_path}"')
  238. @wrap
  239. def perf_wrapper():
  240. start = perf_counter()
  241. yield
  242. elapsed = perf_counter() - start
  243. print(f"Done in {elapsed:.5f} seconds.")
  244. if __name__ == "__main__":
  245. run()