Merge branch 'develop' into feature/webhooks

This commit is contained in:
Aarni Halinen
2022-01-13 22:18:59 +02:00
7 changed files with 207 additions and 200 deletions
+70 -61
View File
@@ -25,28 +25,38 @@ from webapp.models import processHooks
def list_view(request, *args, **kwargs):
"""Kaehmy application list"""
role_filter = request.GET.get('role', None)
if role_filter is not None and str(role_filter) != '-1':
applications = Application.objects.filter(custom_roles__id=role_filter) | Application.objects.filter(preset_roles__id=role_filter)
role_filter = request.GET.get("role", None)
if role_filter is not None and str(role_filter) != "-1":
applications = Application.objects.filter(
custom_roles__id=role_filter
) | Application.objects.filter(preset_roles__id=role_filter)
else:
applications = Application.objects.all()
applications = applications.order_by('-timestamp')
filter_options_preset = PresetRole.objects.annotate(form_count=Count('forms')).filter(form_count__gt=0)
filter_options_preset_list = [(r.id, r.name, r.form_count) for r in filter_options_preset]
filter_options_custom = CustomRole.objects.annotate(form_count=Count('forms')).filter(form_count__gt=0)
filter_options_custom_list = [(r.id, r.name, r.form_count) for r in filter_options_custom]
applications = applications.order_by("-timestamp")
filter_options_preset = PresetRole.objects.annotate(
form_count=Count("forms")
).filter(form_count__gt=0)
filter_options_preset_list = [
(r.id, r.name, r.form_count) for r in filter_options_preset
]
filter_options_custom = CustomRole.objects.annotate(
form_count=Count("forms")
).filter(form_count__gt=0)
filter_options_custom_list = [
(r.id, r.name, r.form_count) for r in filter_options_custom
]
filter_options = filter_options_preset_list + filter_options_custom_list
filter_options.sort(key=lambda f: f[1])
context = {
'applications': applications,
'application_count': len(applications),
'filter_options': filter_options
"applications": applications,
"application_count": len(applications),
"filter_options": filter_options,
}
return render(request, 'kaehmy:list.html', context)
return render(request, "kaehmy:list.html", context)
@ensure_csrf_cookie
@@ -57,23 +67,21 @@ def comment(request, *args, **kwargs):
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save()
email = comment.parent.email
name = comment.name
subject = 'Kaehmyysi tai kommenttiisi on vastattu!'
body = (f'{name.capitalize()} on vastannut kaehmyhakemukseesi tai kommenttiisi kaehmypalvelussa.\r\n\r\n'
'Käy lukemassa viesti osoitteessa https://{URL}/kaehmy')
to_email = comment.parent.email
subject = "Kaehmyysi tai kommenttiisi on vastattu!"
email_body = (
f"{name.capitalize()} on vastannut kaehmyhakemukseesi tai kommenttiisi kaehmypalvelussa.\r\n\r\n"
"Käy lukemassa viesti osoitteessa https://{URL}/kaehmy"
)
send_email(to=to_email, subject=subject, body=email_body)
logging.debug(f"Sent kaehmy comment email to recipient <{to_email}>")
send_email(email, subject, body)
logging.debug(
f'Sent kaehmy comment email to recipient <{email}>')
return redirect('/kaehmy')
return redirect("/kaehmy")
else:
context = {
'error': form.errors
}
return render(request, 'kaehmy:error.html', context)
context = {"error": form.errors}
return render(request, "kaehmy:error.html", context)
@require_http_methods(["GET"])
@@ -88,24 +96,24 @@ def statistics_view(request, *args, **kwargs):
for preset in preset_roles:
people = [form.name for form in preset.forms.all()]
role_list.append((preset.name, len(people), ', '.join(people)))
role_list.append((preset.name, len(people), ", ".join(people)))
for custom in custom_roles:
people = [form.name for form in custom.forms.all()]
role_list.append((custom.name, len(people), ', '.join(people)))
role_list.append((custom.name, len(people), ", ".join(people)))
context = {
'applications': applications,
'application_count': len(applications),
'role_list': role_list
"applications": applications,
"application_count": len(applications),
"role_list": role_list,
}
return render(request, 'kaehmy:statistics.html', context)
return render(request, "kaehmy:statistics.html", context)
@require_http_methods(["GET"])
def view(request, *args, **kwargs):
"""Render Kaehmy form page."""
form = ApplicationForm()
return render(request, 'kaehmy:kaehmy.html', {'form': form})
return render(request, "kaehmy:kaehmy.html", {"form": form})
@ensure_csrf_cookie
@@ -115,46 +123,47 @@ def submit(request, *args, **kwargs):
form = ApplicationForm(request.POST)
if form.is_valid():
application = form.save()
custom_name = form.cleaned_data.get('custom_role_name')
custom_is_board = form.cleaned_data.get('custom_role_is_board')
custom_name = form.cleaned_data.get("custom_role_name")
custom_is_board = form.cleaned_data.get("custom_role_is_board")
if len(custom_name) > 0:
custom_role = CustomRole(
name=custom_name, is_board=custom_is_board)
custom_role = CustomRole(name=custom_name, is_board=custom_is_board)
custom_role.save()
application.custom_roles.add(custom_role)
url = f'https://{URL}/kaehmy'
url = f"https://{URL}/kaehmy"
name = form.cleaned_data.get("name", "Anonymous")
email_body = (
f"Moikka {name}!\r\n\r\nHienoa, että kilta kiinnostaa! Kaehmysi on vastaanotettu.\r\n"
"Mahdollisista kommenteista tulee ilmoitus sähköpostitse.\r\n\r\n"
"Käy katsomassa kaehmytilanne osoitteessa {url}"
)
email = form.cleaned_data.get('email', '')
name = form.cleaned_data.get('name', 'Anonymous')
subject = 'Arwokas kirjattu kirje mahdolliselle tulewalle kiltahenkilölle'
body = ('Moikka {}!\r\n\r\nHienoa, että kilta kiinnostaa! Kaehmysi on vastaanotettu.\r\n'
'Mahdollisista kommenteista tulee ilmoitus sähköpostitse.\r\n\r\n'
'Käy katsomassa kaehmytilanne osoitteessa {}').format(name, url)
to_email = form.cleaned_data.get("email", "")
subject = "Arwokas kirjattu kirje mahdolliselle tulewalle kiltahenkilölle"
send_email(email, subject, body)
logging.debug('Sent kaehmy email to recipient <{}>'.format(email))
send_email(to_email, subject, email_body)
logging.debug(f"Sent kaehmy email to recipient <{to_email}>")
processHooks(message=f'Uusi New kaehmy! {name} -> {url}', eventType="kaehmy")
processHooks(message=f"Uusi New kaehmy! {name} -> {url}", eventType="kaehmy")
else:
context = {
'error': form.errors
}
return render(request, 'kaehmy:error.html', context)
return HttpResponseRedirect('/kaehmy')
context = {"error": form.errors}
return render(request, "kaehmy:error.html", context)
return HttpResponseRedirect("/kaehmy")
@require_http_methods(['GET'])
@login_required(login_url='/admin/login')
@require_http_methods(["GET"])
@login_required(login_url="/admin/login")
def export_view(request, *args, **kwargs):
def make_table(queryset):
table = ExportTable(queryset,
request=request,
exclude=['id'],
attrs={'class': 'table table-bordered table-hover'})
table = ExportTable(
queryset,
request=request,
exclude=["id"],
attrs={"class": "table table-bordered table-hover"},
)
table.paginate(page=request.GET.get('page', 1), per_page=9999)
table.paginate(page=request.GET.get("page", 1), per_page=9999)
table_html = convert_table_to_html(table, request)
return table_html
@@ -163,7 +172,7 @@ def export_view(request, *args, **kwargs):
board = filter(lambda q: q.has_any_board_role(), kaehmys)
context = {
'non_board_table': make_table(non_board),
'board_table': make_table(board),
"non_board_table": make_table(non_board),
"board_table": make_table(board),
}
return render(request, 'kaehmy:export.html', context)
return render(request, "kaehmy:export.html", context)
Binary file not shown.
+37 -50
View File
@@ -7,7 +7,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2022-01-13 00:07+0200\n"
"POT-Creation-Date: 2022-01-13 22:18+0200\n"
"PO-Revision-Date: 2017-11-02 23:09+0200\n"
"Last-Translator: \n"
"Language-Team: \n"
@@ -37,7 +37,7 @@ msgstr "Sössö articles"
msgid "Today's lunch"
msgstr ""
#: infoscreen/models.py:212 webapp/models.py:73
#: infoscreen/models.py:212 webapp/models.py:93
msgid "Events"
msgstr "Events"
@@ -113,7 +113,7 @@ msgid "Delete"
msgstr "Delete"
#: infoscreen/templates/tabs/add_remove.html:23 kaehmy/models.py:57
#: kaehmy/templates/list.html:36 webapp/models.py:147 webapp/models.py:176
#: kaehmy/templates/list.html:36 webapp/models.py:188 webapp/models.py:223
msgid "Name"
msgstr "Name"
@@ -327,7 +327,7 @@ msgstr ""
msgid "Custom role name"
msgstr ""
#: kaehmy/models.py:105 webapp/models.py:177
#: kaehmy/models.py:105 webapp/models.py:224
msgid "Board member"
msgstr "Board member"
@@ -419,8 +419,6 @@ msgid "Päivämääriä & deadlineja"
msgstr "Dates and deadlines"
#: kaehmy/templates/kaehmy.html:31
#, fuzzy
#| msgid "Vaalikokous, osa 1 (puheenjohtajan valinta)"
msgid "Vaalikokous, osa 1 (puheenjohtajan valinta) ja hallitustyrkkypaneeli"
msgstr "Election meeting, part 1 (chairman election)"
@@ -437,14 +435,7 @@ msgid "Vaalikokous, osa 3 (toimarien valinta)"
msgstr "Election meeting, part 3 (non-board election)"
#: kaehmy/templates/kaehmy.html:77
#, fuzzy, python-format
#| msgid ""
#| "\n"
#| " Hyväksyn <a href=\"https://sik.ayy.fi/files/official/"
#| "Tietosuojaseloste%%20%%E2%%80%%93%%20Toimihenkil%%C3%%B6ksi%%20hakemisen"
#| "%%20rekisteri.pdf\" target=\"_blank\">tietosuojaselosteen</a> ja "
#| "tietojeni tallentamisen.\n"
#| " "
#, python-format
msgid ""
"\n"
" Hyväksyn <a href=\"https://static.sahkoinsinoorikilta.fi/"
@@ -1100,10 +1091,6 @@ msgstr ""
msgid "Challenge"
msgstr "Challenge"
#: ohlhafv/views.py:44
msgid "You have been challenged at Ohlhafv!"
msgstr ""
#: templates/admin/base_site.html:44
msgid "Go"
msgstr "Go"
@@ -1113,132 +1100,132 @@ msgstr "Go"
msgid "Aalto-yliopiston Sähköinsinöörikilta ry"
msgstr "Aalto-yliopiston Sähköinsinöörikilta ry"
#: webapp/models.py:21
#: webapp/models.py:20
msgid "Webapp"
msgstr "Webapp"
#: webapp/models.py:29
#: webapp/models.py:28
msgid "Tag"
msgstr "Tag"
#: webapp/models.py:30
#: webapp/models.py:29
msgid "Tags"
msgstr "Tags"
#: webapp/models.py:37
#: webapp/models.py:36
msgid "Tag: {}"
msgstr "Tag: {}"
#: webapp/models.py:55
#: webapp/models.py:54
msgid "Feed"
msgstr ""
#: webapp/models.py:56
#: webapp/models.py:55
msgid "Feeds"
msgstr ""
#: webapp/models.py:64 webapp/models.py:83 webapp/models.py:122
#: webapp/models.py:155 webapp/models.py:201
#: webapp/models.py:63 webapp/models.py:102 webapp/models.py:162
#: webapp/models.py:196 webapp/models.py:248
msgid "Deleted: "
msgstr "Deleted: "
#: webapp/models.py:65
#: webapp/models.py:64
msgid "{}Feed: {}"
msgstr ""
#: webapp/models.py:72
#: webapp/models.py:92
msgid "Event"
msgstr ""
#: webapp/models.py:84
#: webapp/models.py:103
msgid "{}Event: {}"
msgstr ""
#: webapp/models.py:93
#: webapp/models.py:133
msgid "Template question"
msgstr ""
#: webapp/models.py:94
#: webapp/models.py:134
msgid "Template questions"
msgstr ""
#: webapp/models.py:101
#: webapp/models.py:141
msgid "Template questions: {}"
msgstr ""
#: webapp/models.py:108
#: webapp/models.py:148
msgid "Signup form"
msgstr ""
#: webapp/models.py:109
#: webapp/models.py:149
msgid "Signup forms"
msgstr ""
#: webapp/models.py:123
#: webapp/models.py:163
msgid "#{} {}{}"
msgstr ""
#: webapp/models.py:141
#: webapp/models.py:181
msgid "Sign-up"
msgstr ""
#: webapp/models.py:142
#: webapp/models.py:182
msgid "Sign-ups"
msgstr ""
#: webapp/models.py:181
#: webapp/models.py:228
msgid "board member"
msgstr "board member"
#: webapp/models.py:188
#: webapp/models.py:235
msgid "JobAd"
msgstr ""
#: webapp/models.py:189
#: webapp/models.py:236
msgid "JobAds"
msgstr ""
#: webapp/models.py:211
#: webapp/models.py:295
#, fuzzy
#| msgid "Kaehmy"
msgid "Hook Kaehmys"
msgstr "Kaehmy"
#: webapp/models.py:212
#: webapp/models.py:296
#, fuzzy
#| msgid "Total challenges:"
msgid "Hook Ohlhafv challenges"
msgstr "Total challenges:"
#: webapp/models.py:213
#: webapp/models.py:297
msgid "Hook published news"
msgstr ""
#: webapp/models.py:214
#: webapp/models.py:298
msgid "Hook published Job Ads"
msgstr ""
#: webapp/models.py:215
#: webapp/models.py:299
msgid "Hook published events"
msgstr ""
#: webapp/models.py:216
#: webapp/models.py:300
msgid "Hook opened signups"
msgstr ""
#: webapp/models.py:241
#: webapp/models.py:325
msgid "Webhook"
msgstr ""
#: webapp/models.py:242
#: webapp/models.py:326
msgid "Webhooks"
msgstr ""
#: webapp/models.py:256
#: webapp/models.py:339
msgid "Telegram channel"
msgstr ""
#: webapp/models.py:257
#: webapp/models.py:340
msgid "Telegram channels"
msgstr ""
Binary file not shown.
+37 -41
View File
@@ -7,7 +7,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2022-01-13 00:07+0200\n"
"POT-Creation-Date: 2022-01-13 22:18+0200\n"
"PO-Revision-Date: 2017-11-02 23:04+0200\n"
"Last-Translator: \n"
"Language-Team: \n"
@@ -38,7 +38,7 @@ msgstr "Sössön artikkelit"
msgid "Today's lunch"
msgstr "Päivän lounas"
#: infoscreen/models.py:212 webapp/models.py:73
#: infoscreen/models.py:212 webapp/models.py:93
msgid "Events"
msgstr "Tapahtumat"
@@ -114,7 +114,7 @@ msgid "Delete"
msgstr "Poista"
#: infoscreen/templates/tabs/add_remove.html:23 kaehmy/models.py:57
#: kaehmy/templates/list.html:36 webapp/models.py:147 webapp/models.py:176
#: kaehmy/templates/list.html:36 webapp/models.py:188 webapp/models.py:223
msgid "Name"
msgstr "Nimi"
@@ -328,7 +328,7 @@ msgstr "Teksti"
msgid "Custom role name"
msgstr "Uusi virka"
#: kaehmy/models.py:105 webapp/models.py:177
#: kaehmy/models.py:105 webapp/models.py:224
msgid "Board member"
msgstr "Hallituksen jäsen"
@@ -423,7 +423,7 @@ msgstr "Päivämääriä & deadlineja"
#: kaehmy/templates/kaehmy.html:31
msgid "Vaalikokous, osa 1 (puheenjohtajan valinta) ja hallitustyrkkypaneeli"
msgstr "Vaalikokous, osa 1 (puheenjohtajan valinta)"
msgstr "Vaalikokous, osa 1 (puheenjohtajan valinta) ja hallitustyrkkypaneeli"
#: kaehmy/templates/kaehmy.html:32
msgid "Vaalikokous, osa 2 (hallituksen valinta)"
@@ -1076,10 +1076,6 @@ msgstr "Haasta kaverisi mittelöön!"
msgid "Challenge"
msgstr "Haasta"
#: ohlhafv/views.py:44
msgid "You have been challenged at Ohlhafv!"
msgstr "Sinut on haastettu Øhlhäfviin!"
#: templates/admin/base_site.html:44
msgid "Go"
msgstr "Vaihda"
@@ -1089,128 +1085,128 @@ msgstr "Vaihda"
msgid "Aalto-yliopiston Sähköinsinöörikilta ry"
msgstr "Aalto-yliopiston Sähköinsinöörikilta ry"
#: webapp/models.py:21
#: webapp/models.py:20
msgid "Webapp"
msgstr "Nettisivut"
#: webapp/models.py:29
#: webapp/models.py:28
msgid "Tag"
msgstr "Tunniste"
#: webapp/models.py:30
#: webapp/models.py:29
msgid "Tags"
msgstr "Tunnisteet"
#: webapp/models.py:37
#: webapp/models.py:36
msgid "Tag: {}"
msgstr "Tunniste: {}"
#: webapp/models.py:55
#: webapp/models.py:54
msgid "Feed"
msgstr "Uutinen"
#: webapp/models.py:56
#: webapp/models.py:55
msgid "Feeds"
msgstr "Uutiset"
#: webapp/models.py:64 webapp/models.py:83 webapp/models.py:122
#: webapp/models.py:155 webapp/models.py:201
#: webapp/models.py:63 webapp/models.py:102 webapp/models.py:162
#: webapp/models.py:196 webapp/models.py:248
msgid "Deleted: "
msgstr "Poistettu: "
#: webapp/models.py:65
#: webapp/models.py:64
msgid "{}Feed: {}"
msgstr "{}Uutinen: {}"
#: webapp/models.py:72
#: webapp/models.py:92
msgid "Event"
msgstr "Tapahtuma"
#: webapp/models.py:84
#: webapp/models.py:103
msgid "{}Event: {}"
msgstr "{}Tapahtuma: {}"
#: webapp/models.py:93
#: webapp/models.py:133
msgid "Template question"
msgstr "Vakiokysymys"
#: webapp/models.py:94
#: webapp/models.py:134
msgid "Template questions"
msgstr "Vakiokysymykset"
#: webapp/models.py:101
#: webapp/models.py:141
msgid "Template questions: {}"
msgstr "Vakiokysymykset: {}"
#: webapp/models.py:108
#: webapp/models.py:148
msgid "Signup form"
msgstr "Ilmoittautumislomake"
#: webapp/models.py:109
#: webapp/models.py:149
msgid "Signup forms"
msgstr "Ilmoittautumislomakkeet"
#: webapp/models.py:123
#: webapp/models.py:163
msgid "#{} {}{}"
msgstr ""
#: webapp/models.py:141
#: webapp/models.py:181
msgid "Sign-up"
msgstr "Ilmoittautuminen"
#: webapp/models.py:142
#: webapp/models.py:182
msgid "Sign-ups"
msgstr "Ilmoittautumiset"
#: webapp/models.py:181
#: webapp/models.py:228
msgid "board member"
msgstr "hallituksen jäsen"
#: webapp/models.py:188
#: webapp/models.py:235
msgid "JobAd"
msgstr "Työpaikkailmoitus"
#: webapp/models.py:189
#: webapp/models.py:236
msgid "JobAds"
msgstr "Työpaikkailmoitukset"
#: webapp/models.py:211
#: webapp/models.py:295
msgid "Hook Kaehmys"
msgstr "Lähetä Kähmyt"
#: webapp/models.py:212
#: webapp/models.py:296
msgid "Hook Ohlhafv challenges"
msgstr "Lähetä Øhlhäfv-haasteet"
#: webapp/models.py:213
#: webapp/models.py:297
msgid "Hook published news"
msgstr "Lähetä julkaistut uutiset"
#: webapp/models.py:214
#: webapp/models.py:298
msgid "Hook published Job Ads"
msgstr "Lähetä työpaikkailmoitukset"
#: webapp/models.py:215
#: webapp/models.py:299
msgid "Hook published events"
msgstr "Lähetä julkaistut tapahtumat"
#: webapp/models.py:216
#: webapp/models.py:300
msgid "Hook opened signups"
msgstr "Lähetä auenneet ilmot"
#: webapp/models.py:241
#: webapp/models.py:325
msgid "Webhook"
msgstr "Webhook"
#: webapp/models.py:242
#: webapp/models.py:326
msgid "Webhooks"
msgstr "Webhookit"
#: webapp/models.py:256
#: webapp/models.py:339
msgid "Telegram channel"
msgstr "Telegram-kanava"
#: webapp/models.py:257
#: webapp/models.py:340
msgid "Telegram channels"
msgstr "Telegram-kanavat"
+19 -20
View File
@@ -18,7 +18,7 @@ from webapp.models import processHooks
def ohlhafv_view(request, *args, **kwargs):
"""Render Ohlhafv form page."""
form = OhlhafvForm()
return render(request, 'ohlhafv:new.html', {'form': form})
return render(request, "ohlhafv:new.html", {"form": form})
@ensure_csrf_cookie
@@ -29,33 +29,32 @@ def ohlhafv_submit(request, *args, **kwargs):
if form.is_valid():
form.save()
challenge = form.instance
email = form.cleaned_data.get('victim_email', '')
url = f'https://{URL}/ohlhafv/list'
subject = _('You have been challenged at Ohlhafv!')
url = f"https://{URL}/ohlhafv/list"
email_body = render_to_string(
'ohlhafv:email.html', {
'challenge': challenge,
'url': url,
}
"ohlhafv:email.html",
{
"challenge": challenge,
"url": url,
},
)
send_email(email, subject, email_body)
to_email = form.cleaned_data.get("victim_email", "")
subject = "Sinut on haastettu Øhlhäfviin!"
send_email(to=to_email, subject=subject, body=email_body)
logging.debug(f"Sent ohlhafv email to recipient <{to_email}>")
try:
webhook_message = render_to_string(
'ohlhafv:tgmsg.tpl', {
'challenge': challenge,
'url': url})
"ohlhafv:tgmsg.tpl", {"challenge": challenge, "url": url}
)
processHooks(message=webhook_message, eventType="ohlhafv")
except Exception:
pass
logging.debug(
'Sent ohlhafv email to recipient <{}>'.format(email))
else:
pass
return HttpResponseRedirect('/ohlhafv/list/')
return HttpResponseRedirect("/ohlhafv/list/")
@ensure_csrf_cookie
@@ -63,9 +62,9 @@ def ohlhafv_submit(request, *args, **kwargs):
def ohlhafv_list(request, *args, **kwargs):
"""Present Ohlhafv challenges list."""
challenges = OhlhafvChallenge.objects.all()
challenges = challenges.order_by('-id')
challenges = challenges.order_by("-id")
context = {
'challenges': challenges,
'challenge_count': len(challenges),
"challenges": challenges,
"challenge_count": len(challenges),
}
return render(request, 'ohlhafv:list.html', context)
return render(request, "ohlhafv:list.html", context)
+44 -28
View File
@@ -1,18 +1,30 @@
"""Webapp utils."""
from django.utils import timezone
import sendgrid
from sendgrid.helpers.mail import *
from datetime import timedelta
import logging
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, EMAIL_API_KEY, DEFAULT_EMAIL_FROM_ADDR, ENABLE_AUTOMATIC_EMAILS
import imghdr
import markdown
import sendgrid
from django.utils import timezone
from sendgrid.helpers.mail import (
Email,
To,
Subject,
Mail,
HtmlContent,
PlainTextContent,
)
from django.template.loader import render_to_string
from django.core.files.base import ContentFile
from sikweb.settings import (
FRONTEND_URL,
EMAIL_API_KEY,
DEFAULT_EMAIL_FROM,
DEFAULT_EMAIL_FROM_ADDR,
ENABLE_AUTOMATIC_EMAILS,
)
from datetime import timedelta
def get_file_extension(file_name, decoded_file):
@@ -25,15 +37,15 @@ 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:
if "data:" in data and ";base64," in data:
# Break out the header from the base64 content
header, data = data.split(';base64,')
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')
TypeError("invalid_image")
# Generate file name:
file_name = str(uuid.uuid4())
@@ -41,7 +53,10 @@ def decode_base64_file(data):
# Get the file name extension:
file_extension = get_file_extension(file_name, decoded_file)
complete_file_name = "%s.%s" % (file_name, file_extension, )
complete_file_name = "%s.%s" % (
file_name,
file_extension,
)
return ContentFile(decoded_file, name=complete_file_name)
@@ -51,50 +66,51 @@ def month_from_now():
return timezone.now() + timedelta(days=30)
def send_email(to, subject, body, html=False):
if not ENABLE_AUTOMATIC_EMAILS:
def send_email(to: str, subject: str, body: str, html: bool = False):
if ENABLE_AUTOMATIC_EMAILS is False:
logging.debug("Skipping email")
logging.debug(f"to: {to}")
logging.debug(f"subject: {subject}")
logging.debug(f"body: {body}")
return
from_email = DEFAULT_EMAIL_FROM_ADDR
to_email = to
sub = subject
from_email = Email(email=DEFAULT_EMAIL_FROM_ADDR, name=DEFAULT_EMAIL_FROM)
to_email = To(email=to)
sub = Subject(subject=subject)
html_content = None
plain_text_content = None
if (html):
html_content = HtmlContent(body)
if html:
html_content = HtmlContent(content=body)
else:
plain_text_content = PlainTextContent(body)
plain_text_content = PlainTextContent(content=body)
mail = Mail(
from_email=from_email,
to_emails=to_email,
subject=sub,
html_content=html_content,
plain_text_content=plain_text_content
plain_text_content=plain_text_content,
)
try:
sg = sendgrid.SendGridAPIClient(EMAIL_API_KEY)
sg = sendgrid.SendGridAPIClient(api_key=EMAIL_API_KEY)
response = sg.send(mail)
if response.status_code != 202:
raise Exception(f'Failed to send email: {response.body}')
raise Exception(f"Failed to send email: {response.body}")
except Exception as ex:
logging.exception('Failed to send email.')
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),
}
"webapp:signup_email.html",
{
"url": f"https://{FRONTEND_URL}/signup/edit/{id}/{uuid}",
"content": markdown.markdown(content),
},
)
return send_email(to, subject, message, True)