NDOJ/judge/utils/opengraph.py

25 lines
850 B
Python
Raw Permalink Normal View History

2020-01-21 06:35:58 +00:00
from django.core.cache import cache
from django.template.defaultfilters import truncatewords
from judge.jinja2.markdown import markdown
from judge.jinja2.reference import reference
2022-10-25 04:59:04 +00:00
def generate_opengraph(cache_key, data):
2020-01-21 06:35:58 +00:00
metadata = cache.get(cache_key)
if metadata is None:
description = None
2022-10-25 04:59:04 +00:00
tree = reference(markdown(data)).tree
2022-05-14 17:57:27 +00:00
for p in tree.iterfind(".//p"):
2020-01-21 06:35:58 +00:00
text = p.text_content().strip()
if text:
description = text
break
if description:
2022-05-14 17:57:27 +00:00
for remove in (r"\[", r"\]", r"\(", r"\)"):
description = description.replace(remove, "")
img = tree.xpath(".//img")
metadata = truncatewords(description, 60), img[0].get("src") if img else None
2020-01-21 06:35:58 +00:00
cache.set(cache_key, metadata, 86400)
return metadata