2018-06-25 15:52:10 -04:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
"""
|
|
|
|
Miscellaneous tools and help functions.
|
|
|
|
"""
|
|
|
|
import os
|
|
|
|
import re
|
2018-06-28 13:54:04 -04:00
|
|
|
import urllib
|
2018-06-25 15:52:10 -04:00
|
|
|
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)
|
2018-06-26 00:29:10 -04:00
|
|
|
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
|