Passed
Push — master ( f1fa6b...b933ea )
by Jochen
02:27
created

blueprints/api/tourney/match/comments/views.py (2 issues)

1
"""
2
byceps.blueprints.api.tourney.match.views
3
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4
5
:Copyright: 2006-2019 Jochen Kupperschmidt
6
:License: Modified BSD, see LICENSE for details.
7
"""
8
9
from flask import abort, jsonify, request, url_for
10
from marshmallow import ValidationError
11
12
from ......services.tourney import match_comment_service, match_service
13
from ......services.user import service as user_service
14
from ......util.framework.blueprint import create_blueprint
15
from ......util.framework.templating import templated
16
from ......util.views import respond_created, respond_no_content
17
18
from ....decorators import api_token_required
19
20
from ... import signals
21
22
from .schemas import CreateMatchCommentRequest, ModerateMatchCommentRequest
23
24
25
blueprint = create_blueprint('api_tourney_match_comments', __name__)
26
27
28
@blueprint.route('/matches/<uuid:match_id>/comments')
29
@api_token_required
30
@templated
31
def view_for_match(match_id):
32
    """Render the comments on a match."""
33
    match = _get_match_or_404(match_id)
34
35
    party_id = request.args.get('party_id')
36
37
    comments = match_comment_service.get_comments(
38
        match.id, party_id=party_id, include_hidden=False
39
    )
40
41
    return {
42
        'comments': comments,
43
    }
44
45
46
@blueprint.route('/matches/<uuid:match_id>/comments.json')
47
@api_token_required
48
def view_for_match_as_json(match_id):
49
    """Render the comments on a match as JSON."""
50
    match = _get_match_or_404(match_id)
51
52
    party_id = request.args.get('party_id')
53
54
    comments = match_comment_service.get_comments(
55
        match.id, party_id=party_id, include_hidden=True
56
    )
57
58
    comment_dtos = list(map(_comment_to_json, comments))
59
60
    return jsonify({
61
        'comments': comment_dtos,
62
    })
63
64
65
def _comment_to_json(comment):
66
    creator = comment.creator
67
68
    return {
69
        'comment_id': str(comment.id),
70
        'match_id': str(comment.match_id),
71
        'created_at': comment.created_at.isoformat(),
72
        'creator': {
73
            'user_id': str(creator.id),
74
            'screen_name': creator.screen_name,
75
            'suspended': creator.suspended,
76
            'deleted': creator.deleted,
77
            'avatar_url': creator.avatar_url,
78
            'is_orga': creator.is_orga,
79
        },
80
        'body': comment.body_rendered,
81
        'hidden': comment.hidden,
82
        'hidden_at': comment.hidden_at.isoformat() \
83
                     if (comment.hidden_at is not None) else None,
84
        'hidden_by_id': comment.hidden_by_id,
85
    }
86
87
88
blueprint.add_url_rule(
89
    '/match_comments/<uuid:comment_id>',
90
    endpoint='view',
91
    build_only=True,
92
)
93
94
95
@blueprint.route('/match_comments', methods=['POST'])
96
@api_token_required
97
@respond_created
98
def create():
99
    """Create a comment on a match."""
100
    schema = CreateMatchCommentRequest()
101
    try:
102
        req = schema.load(request.get_json())
103
    except ValidationError as e:
104
        abort(400, str(e.normalized_messages()))
105
106
    match = match_service.find_match(req['match_id'])
107
    if not match:
108
        abort(400, 'Unknown match ID')
109
110
    creator = user_service.find_active_user(req['creator_id'])
111
    if not creator:
112
        abort(400, 'Creator ID does not reference an active user.')
113
114
    body = req['body'].strip()
115
116
    comment = match_comment_service.create_comment(match.id, creator.id, body)
117
118
    signals.match_comment_created.send(None, comment_id=comment.id)
119
120
    return url_for('.view', comment_id=comment.id)
121
122
123
@blueprint.route(
1 ignored issue
show
This code seems to be duplicated in your project.
Loading history...
124
    '/match_comments/<uuid:comment_id>/flags/hidden', methods=['POST']
125
)
126
@api_token_required
127
@respond_no_content
128
def hide(comment_id):
129
    """Hide the match comment."""
130
    schema = ModerateMatchCommentRequest()
131
    try:
132
        req = schema.load(request.get_json())
133
    except ValidationError as e:
134
        abort(400, str(e.normalized_messages()))
135
136
    initiator = user_service.find_active_user(req['initiator_id'])
137
    if not initiator:
138
        abort(400, 'Initiator ID does not reference an active user.')
139
140
    match_comment_service.hide_comment(comment_id, initiator.id)
141
142
143
@blueprint.route(
1 ignored issue
show
This code seems to be duplicated in your project.
Loading history...
144
    '/match_comments/<uuid:comment_id>/flags/hidden',
145
    methods=['DELETE'],
146
)
147
@api_token_required
148
@respond_no_content
149
def unhide(comment_id):
150
    """Un-hide the match comment."""
151
    schema = ModerateMatchCommentRequest()
152
    try:
153
        req = schema.load(request.get_json())
154
    except ValidationError as e:
155
        abort(400, str(e.normalized_messages()))
156
157
    initiator = user_service.find_active_user(req['initiator_id'])
158
    if not initiator:
159
        abort(400, 'Initiator ID does not reference an active user.')
160
161
    match_comment_service.unhide_comment(comment_id, initiator.id)
162
163
164
def _get_match_or_404(match_id):
165
    match = match_service.find_match(match_id)
166
167
    if match is None:
168
        abort(404)
169
170
    return match
171