~homeworkprod/byceps

ref: 4237b3ec9496efe95dcce82bea3207ab9de4d520 byceps/byceps/blueprints/user_message/views.py -rw-r--r-- 2.0 KiB
4237b3ec — Jochen Kupperschmidt Move ticketing blueprint into `site` subpackage 1 year, 10 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
"""
byceps.blueprints.user_message.views
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Send messages from one user to another.

:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""

from flask import abort, g, request, url_for

from ...services.user import service as user_service
from ...services.user_message import service as user_message_service
from ...util.framework.blueprint import create_blueprint
from ...util.framework.flash import flash_success
from ...util.framework.templating import templated
from ...util.views import redirect_to

from ..authentication.decorators import login_required

from .forms import CreateForm


blueprint = create_blueprint('user_message', __name__)


@blueprint.route('/to/<uuid:recipient_id>/create')
@login_required
@templated
def create_form(recipient_id, erroneous_form=None):
    """Show a form to create a message to send to the user."""
    recipient = _get_user_or_404(recipient_id)

    form = erroneous_form if erroneous_form else CreateForm()

    return {
        'recipient': recipient,
        'form': form,
    }


@blueprint.route('/to/<uuid:recipient_id>/create', methods=['POST'])
@login_required
def create(recipient_id):
    """Create a message to send to the user."""
    recipient = _get_user_or_404(recipient_id)

    form = CreateForm(request.form)
    if not form.validate():
        return create_form(recipient.id, form)

    sender = g.current_user
    body = form.body.data.strip()
    sender_contact_url = url_for(
        '.create_form', recipient_id=sender.id, _external=True
    )

    user_message_service.send_message(
        sender.id, recipient.id, body, sender_contact_url, g.site_id
    )

    flash_success(
        f'Deine Nachricht an {recipient.screen_name} wurde versendet.'
    )

    return redirect_to('user_profile.view', user_id=recipient.id)


def _get_user_or_404(user_id):
    user = user_service.find_active_user(user_id, include_avatar=True)

    if user is None:
        abort(404)

    return user