Skip to content

Commit

Permalink
Add extra fields and more
Browse files Browse the repository at this point in the history
Add extra fields, device model, software version and book name and a
description text for users.

Also read the server and port from .env, clean up the imports a bit,
move away from user and password based auth.

Refs EKIR-193
  • Loading branch information
natlibfi-max-grasbeck committed May 22, 2024
1 parent 4f5b46c commit b53d9e3
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 48 deletions.
10 changes: 4 additions & 6 deletions .env
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,7 @@ BACKUP_FILE="feedback.backup"
# Location of the csv file that contains emails and municipality names.
EMAILS_CSV="emails.csv"

MAIL_SERVER="smtp-mail.outlook.com"
MAIL_PORT="587"
MAIL_USERNAME=${MAIL_USERNAME}
MAIL_PASSWORD=${MAIL_PASSWORD}
MAIL_USE_TLS=True
MAIL_USE_SSL=True
MAIL_SERVER=${MAIL_SERVER}
MAIL_PORT=${MAIL_PORT}
MAIL_USE_TLS=False
MAIL_USE_SSL=True
74 changes: 35 additions & 39 deletions app.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,18 @@
import secrets
import re
import sys
import smtplib
import ssl
import os

from datetime import datetime

from flask import Flask
from flask import render_template
from flask import request
from flask import Flask, render_template, request, render_template, redirect, url_for

from flask import Flask, render_template, redirect, url_for
from flask_bootstrap import Bootstrap5

from flask_wtf import FlaskForm, CSRFProtect
from wtforms import (
StringField,
HiddenField,
TextAreaField,
EmailField,
SelectField,
Expand All @@ -30,8 +26,6 @@

from municipalities import indexed_municipalities, index_to_email, index_to_name

from flask import Flask

from email.message import EmailMessage
import nh3

Expand All @@ -41,7 +35,6 @@
# If not set, it defaults to /
root_path = os.environ.get("ROOT_PATH", "/")

bootstrap = Bootstrap5(app)
from config import app


Expand Down Expand Up @@ -70,8 +63,14 @@ class FeedbackForm(FlaskForm):
(_("Other")),
],
)
device_model = HiddenField(_("Device model"), [validators.Optional()])
software_version = HiddenField(_("Software version"), [validators.Optional()])
book_name = StringField(
_("Book name"), [validators.Optional(), validators.Length(1, 128)]
)
message = TextAreaField(
_("Message"), [validators.DataRequired(), validators.Length(1, 2048)]
_("Message"),
[validators.DataRequired(), validators.Length(1, 2048)],
)
municipality = SelectField(
_("My home municipality that receives this feedback"),
Expand Down Expand Up @@ -101,21 +100,26 @@ def feedback(name=None):
municipality_name = index_to_name(municipality_id)
municipality_email = index_to_email(municipality_id)

body = nh3.clean(form.message.data)
reply_to = nh3.clean(form.email.data)

subject = f"E-Kirjasto palaute - {municipality_name}: {subject}"
recipients = [
municipality_email,
app.config["ALWAYS_RECIPIENT"],
]

sent = send_email(
subject,
body,
recipients,
reply_to,
)
body = nh3.clean(form.message.data)
reply_to = nh3.clean(form.email.data)
book_name = nh3.clean(form.book_name.data)
device_model = nh3.clean(form.device_model.data)
software_version = nh3.clean(form.software_version.data)
user_agent = request.headers.get("User-Agent")

body += f"\n\nHaluan vastauksen osoitteeseen: {reply_to}"
body += f"\n\nKirjan nimi: {book_name}"
body += f"\n\nLaitteen malli: {device_model}"
body += f"\n\nOhjelmistoversio: {software_version}"
body += f"\n\nUser agent: {user_agent}"

sent = send_email(subject, body, recipients)

if sent:
return redirect(url_for("success"))
Expand All @@ -130,31 +134,22 @@ def feedback(name=None):
"sv": _("Swedish"),
}

form.device_model.data = request.args.get('device_model')
form.software_version.data = request.args.get('software_version')

return render_template(
"feedback.html",
form=FeedbackForm(),
form=form,
languages=languages,
selected_language=get_locale(),
)


def send_email(subject, body, recipients, reply_to):
if type(subject) is not str:
raise ValueError("subject must be a string")

if type(body) is not str:
raise ValueError("body must be a string")

if type(recipients) is not list:
raise ValueError("recipients must be a list")

def send_email(subject, body, recipients):
# Prevents duplicates
recipients = list(set(recipients))
message = EmailMessage()

if reply_to:
body += f"\n\nHaluan vastauksen osoitteeseen: {reply_to}"

message.set_content(body)
message["To"] = ",".join(recipients)
message["From"] = app.config["MAIL_SENDER"]
Expand All @@ -164,14 +159,11 @@ def send_email(subject, body, recipients, reply_to):
server = app.config["MAIL_SERVER"]
port = app.config["MAIL_PORT"]
sender_email = app.config["MAIL_SENDER"]
username = app.config["MAIL_USERNAME"]
password = app.config["MAIL_PASSWORD"]

try:
with smtplib.SMTP(server, port) as server:
server.starttls(context=context)
server.login(username, password)
server.sendmail(sender_email, recipients, message.as_string())
server.close()
except Exception as exception:
time = datetime.now()
save_message(
Expand All @@ -185,8 +177,12 @@ def save_message(message):
"""
If sending the email fails for any reason, this is used to save the message to disk as a backup
"""
f = open(app.config["BACKUP_FILE"], "a", encoding="utf-8")
f.write(message)
try:
f = open(app.config["BACKUP_FILE"], "a", encoding="utf-8")
f.write(message)
except Exception as exception:
return False
return True


@app.route(root_path + "/success")
Expand Down
7 changes: 4 additions & 3 deletions municipalities.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,13 +44,14 @@ def get_emails():
emails = sorted(emails, key=lambda x: x[1])

# Decorate the emails with some custom values that aren't municipalities
emails.append(
emails.insert(
0,
(
app.config["DEFAULT_RECEIVER"],
_("My home municipality is missing from this list"),
)
),
)
emails.append((app.config["DEFAULT_RECEIVER"], _("I don't want to say")))
emails.insert(0, (app.config["DEFAULT_RECEIVER"], _("I don't want to say")))

return emails

Expand Down
3 changes: 3 additions & 0 deletions templates/feedback.html
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
{% extends "header.html" %}

{% block content %}
<div class="alert alert-light" role="alert">
Voit jättää palautetta E-kirjastosta tai ehdottaa hankittavia aineistoja. Aineistoehdotuksiin ei vastata
</div>
<p>{{ message|safe }}</p>
{{ render_form(form) }}
{% endblock %}
Expand Down

0 comments on commit b53d9e3

Please sign in to comment.