anonkun/tools.py

55 lines
1.3 KiB
Python

#!/usr/bin/env python3
"""
Miscellaneous tools and help functions.
"""
import os
import re
import urllib
import hashlib
import magic
import requests
IMG_DIR = "/usr/local/www/html/img"
def sanitize_title(canon_title):
"""
Sanitizes the given canonical title for a quest and returns a
url-friendly version.
"""
ident_title = canon_title.lower().replace(" ", "-")
ident_title = urllib.parse.quote(ident_title)
return ident_title
def handle_img(post):
"""
Handles [img] tags within a quest post appropriately.
"""
urls = re.findall(r"\[img\](.*?)\[/img\]", post)
for url in urls:
try:
res = requests.get(url)
res.raise_for_status()
mime = magic.from_buffer(res.content, mime=True)
assert mime in ["image/jpeg", "image/png","image/gif","video/webm"]
h = hashlib.sha256()
h.update(res.content)
fname = h.hexdigest()
fname += "." + mime.partition("/")[2]
with open(os.path.join(IMG_DIR, fname), "wb") as file:
for chunk in res.iter_content(100000):
file.write(chunk)
alt_text = os.path.basename(url)
img_tag = f'<img src="/img/{fname}" alt="{alt_text}" '
img_tag += f'title="{alt_text}" />'
except requests.exceptions:
img_tag = "INVALID_IMG_URL"
except assertion:
img_tag = "INVALID_IMG_MIME_TYPE"
except:
img_tag = "UNKNOWN_ERROR"
post = post.replace("[img]" + url + "[/img]", img_tag)
return post