repos

blog.bythewood.me-wagtail

mirror archived upstream

Self-hostable blog for developers built on Wagtail and Django, with webpack, Bootstrap, and CodeMirror.

blogbootstrapdjangodockerhandcodedpythonself-hostedwagtailwebpack

1.2 KB · 35 lines · Python Raw History
 1import hashlib
 2import io
 3import threading
 4
 5from django import template
 6from django.core.files.storage import default_storage
 7from django.utils.html import format_html
 8from django.utils import timezone
 9
10from blog.chromium import generate_screenshot_from_url
11
12register = template.Library()
13
14
15def og_image(url, force=False):
16    filename = hashlib.md5(url.encode("utf-8")).hexdigest()
17    filename = f"og_images/{filename}.png"
18
19    if not default_storage.exists(filename) or force:
20        # save a quick file to prevent infinite loop
21        default_storage.save(filename, io.BytesIO())
22        generate_screenshot_from_url(url, filename)
23    else:
24        # if the file exists, check it's timestamp, if it's older than a day
25        # regenerate it with threading since the old one is okay for now
26        one_day_ago = timezone.now() - timezone.timedelta(days=1)
27        if default_storage.get_modified_time(filename) < one_day_ago:
28            threading.Thread(
29                target=generate_screenshot_from_url, args=(url, filename)
30            ).start()
31
32    # get full url including domain
33    url = default_storage.url(filename)
34    return format_html('<meta property="og:image" content="{}">', url)