anonkun/tools.py

44 lines
1.1 KiB
Python
Raw Permalink Normal View History

2018-06-25 15:52:10 -04:00
#!/usr/bin/env python3
"""
Miscellaneous tools and help functions.
"""
import os
import re
import hashlib
import magic
import requests
IMG_DIR = "/usr/local/www/html/img"
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}" />'
2018-06-25 15:52:10 -04:00
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