From f6395d4d9c37d86e4728fbbd1bb2a6a4af7a821a Mon Sep 17 00:00:00 2001 From: Matthew Wild Date: Sun, 16 Jan 2022 15:21:34 +0000 Subject: [PATCH] Complete the implementation of data import --- snikket_web/invite.py | 39 +++++++++++++++++++++++++++++++-------- 1 file changed, 31 insertions(+), 8 deletions(-) diff --git a/snikket_web/invite.py b/snikket_web/invite.py index 226b4b7..1ccda08 100644 --- a/snikket_web/invite.py +++ b/snikket_web/invite.py @@ -10,13 +10,14 @@ from quart import ( current_app, render_template, redirect, + request, url_for, session as http_session, ) import wtforms -from flask_babel import lazy_gettext as _l +from flask_babel import lazy_gettext as _l, gettext from .infra import client, selected_locale, BaseForm @@ -26,6 +27,9 @@ bp = Blueprint("invite", __name__) INVITE_SESSION_JID = "invite-session-jid" +MAX_IMPORT_DATA_SIZE = 5*1024*1024 # 5MB +SUPPORTED_IMPORT_TYPES = ["application/xml", "text/xml"] + EIMPORTTOOBIG = _l("The account data you tried to import is too large to" "upload. Please contact your Snikket operator.") @@ -250,19 +254,38 @@ class DataImportForm(BaseForm): async def success() -> str: form = DataImportForm() if form.validate_on_submit(): - client.import_account_data() - # Re-render success page, this time with no import option - return await render_template( - "invite_success.html", - jid=http_session.get(INVITE_SESSION_JID, ""), - migration_success=True, + ok = True + file_info = (await request.files).get(form.account_data_file.name) + if file_info is not None: + mimetype = file_info.mimetype + data = file_info.stream.read() + if len(data) > MAX_IMPORT_DATA_SIZE: + form.account_data_file.errors.append(EIMPORTTOOBIG) + ok = False + elif mimetype not in SUPPORTED_IMPORT_TYPES: + form.account_data_file.errors.append( + # not breaking the line here to avoid extract + # translations failing (defensive) + gettext("The account data you tried to import is in an unknown format. Please upload an XML file in XEP-0227 format (provided format: %(mimetype)s).", mimetype=mimetype), # noqa:E501 ) + ok = False + elif len(data) > 0: + await client.import_account_data(data) + + if ok: + # Re-render success page, this time with no import option + return await render_template( + "invite_success.html", + jid=http_session.get(INVITE_SESSION_JID, ""), + migration_success=True, + ) + return await render_template( "invite_success.html", jid=http_session.get(INVITE_SESSION_JID, ""), migration_success=False, form=form, - max_import_size=5*1024*1024, # 5MB + max_import_size=MAX_IMPORT_DATA_SIZE, import_too_big_warning_header=_l("Error"), import_too_big_warning=EIMPORTTOOBIG, )