Files
web2.0-backend/webapp/utils.py
T
2020-11-30 20:54:31 +02:00

113 lines
3.3 KiB
Python

"""Webapp utils."""
from django.utils import timezone
# from django.core.mail import send_mail
import os
from mailjet_rest import Client
from datetime import timedelta
import logging
from django.conf import settings
from django.template.loader import render_to_string
from django.core.files.base import ContentFile
import base64
import uuid
from sikweb.settings import FRONTEND_URL, URL, EMAIL_API_KEY, EMAIL_API_SECRET, DEFAULT_EMAIL_FROM, DEFAULT_EMAIL_FROM_ADDR, ENABLE_AUTOMATIC_EMAILS
import imghdr
import markdown
def get_file_extension(file_name, decoded_file):
extension = imghdr.what(file_name, decoded_file)
extension = "jpg" if extension == "jpeg" else extension
return extension
def decode_base64_file(data):
# Check if this is a base64 string
if isinstance(data, str):
# Check if the base64 string is in the "data:" format
if 'data:' in data and ';base64,' in data:
# Break out the header from the base64 content
header, data = data.split(';base64,')
# Try to decode the file. Return validation error if it fails.
try:
decoded_file = base64.b64decode(data)
except TypeError:
TypeError('invalid_image')
# Generate file name:
file_name = str(uuid.uuid4())
# Get the file name extension:
file_extension = get_file_extension(file_name, decoded_file)
complete_file_name = "%s.%s" % (file_name, file_extension, )
return ContentFile(decoded_file, name=complete_file_name)
def month_from_now():
"""Return date one month from now."""
return timezone.now() + timedelta(days=30)
def send_email(to, subject, body, html=False):
if not ENABLE_AUTOMATIC_EMAILS:
logging.debug("Skipping email")
logging.debug(f"to: {to}")
logging.debug(f"subject: {subject}")
logging.debug(f"body: {body}")
return
try:
mailjet = Client(auth=(EMAIL_API_KEY, EMAIL_API_SECRET), version='v3.1')
data = {
'Messages': [
{
"From": {
"Email": DEFAULT_EMAIL_FROM_ADDR,
"Name": DEFAULT_EMAIL_FROM
},
"To": [
{
"Email": to,
"Name": "You"
}
],
"Subject": subject
}
]
}
if (html):
data["Messages"][0]["HTMLPart"] = body
else:
data["Messages"][0]["TextPart"] = body
success = mailjet.send.create(data=data)
# For some reason returns 200 OK instead of 201 Created...
if success.status_code != 200:
raise Exception(f'Failed to send email: {success.json()}')
except Exception as ex:
logging.exception('Failed to send email.')
def send_signup_email(to, subject, id, uuid, content):
message = render_to_string(
'webapp:signup_email.html', {
'url': f"https://{FRONTEND_URL}/signup/edit/{id}/{uuid}",
'content': markdown.markdown(content),
}
)
return send_email(to, subject, message, True)
def admin_send_email_signupees(list, subject, content):
for to in list:
send_email(to, subject, markdown.markdown(content), True)