forked from wepublic/backend
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathviews.py
320 lines (277 loc) · 11.3 KB
/
views.py
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
from django.http import HttpResponse
from rest_framework import viewsets
from rest_framework import status
from rest_framework import filters
from rest_framework.permissions import (
IsAuthenticatedOrReadOnly,
IsAuthenticated,
)
from rest_framework.reverse import reverse_lazy
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.exceptions import NotFound, PermissionDenied
from rest_framework.throttling import UserRateThrottle
from django.db.models import Sum, When, Case, IntegerField, Value, Subquery
from django.db.models.functions import Coalesce
from users.utils import slack_notify_report
from random import randint
from wepublic_backend.settings import NOREPLY_ADDRESS
from wp_core.models import (
Question,
Tag, VoteQuestion,
)
from wp_core.serializers import (
QuestionSerializer,
TagSerializer,
AnswerSerializer,
VoteQuestionSerializer,
)
from wp_core.permissions import OnlyStaffCanModify, StaffOrOwnerCanModify
from wp_core.pagination import NewestQuestionsSetPagination
from django.template.loader import render_to_string
from django.core.mail import send_mail
from django.conf import settings
from django.db.models import Q
from django.core.serializers.json import DjangoJSONEncoder
class TagViewSet(viewsets.ModelViewSet):
permission_classes = [OnlyStaffCanModify]
queryset = Tag.objects.all()
serializer_class = TagSerializer
@action(detail=True,
methods=['get'],
pagination_class=NewestQuestionsSetPagination,
throttle_classes=[UserRateThrottle]
)
def Questions(self, request, pk=None):
questions = Question.objects.filter(tags__pk=pk).annotate(
upvotes=Coalesce(Sum(
Case(
When(votequestion__up=True, then=1),
When(votequestion__up=False, then=0),
output_field=IntegerField()
)
), 0)
)
ser = QuestionSerializer(
questions,
many=True,
context={'request': request}
)
return Response(ser.data)
class QuestionsViewSet(viewsets.ModelViewSet):
permission_classes = [IsAuthenticatedOrReadOnly, StaffOrOwnerCanModify]
serializer_class = QuestionSerializer
pagination_class = NewestQuestionsSetPagination
filter_backends = (filters.OrderingFilter, filters.SearchFilter,)
search_fields = ['text', 'tags__text']
ordering_fields = ('time_created', 'upvotes', 'closed_date')
ordering = ('-time_created')
def get_queryset(self):
request = self.request
qs = self.get_annotated_questions()
if 'answered' in request.GET and request.GET['answered'] is not None:
answered = request.GET['answered']
if answered == 'true':
return qs.exclude(answers=None)
if answered == 'false':
return qs.filter(answers=None)
return qs
def get_annotated_questions(self):
qs = Question.objects.annotate(
upvotes=Coalesce(Sum(
Case(
When(votequestion__up=True, then=1),
When(votequestion__up=False, then=0),
output_field=IntegerField()
)
), 0)
)
return qs
def create(self, request):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
if not request.user.update_reputation('CREATE_QUESTION'):
return Response({"detail": "Not enough reputation"}, status=420)
question = serializer.save()
# self.perform_create(serializer)
question.vote_by(request.user, True, update_rep=False)
headers = self.get_success_headers(serializer.data)
return Response(
serializer.data,
status=status.HTTP_201_CREATED,
headers=headers
)
@action(
detail=False,
methods=['get'],
permission_classes=[IsAuthenticated],
throttle_classes=[UserRateThrottle],
pagination_class=NewestQuestionsSetPagination,
)
def my(self, request):
"""Gets all own and voted for questions."""
subquery = Subquery(
VoteQuestion.objects.filter(
user=request.user,
up=True
).values('question_id')
)
questions = self.get_queryset().filter(
Q(user=request.user) | Q(id__in=subquery)
).annotate(
own=Value(True)
)
if request.version == 'v2':
page = self.paginate_queryset(questions)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
else:
serializer = self.get_serializer(questions, many=True)
data = serializer.data
return Response(data)
@action(detail=True, methods=['get'], permission_classes=[IsAuthenticated], throttle_classes=[UserRateThrottle])
def answers(self, request, pk=None) -> HttpResponse:
try:
question = Question.objects.all().get(pk=pk)
except Question.DoesNotExist:
raise NotFound(
detail='Question with the id %s does not exist' % pk
)
return Response(
AnswerSerializer(
question.answers.all(),
many=True,
context={'request': request}
).data
)
@action(detail=True, methods=['get'])
def tags(self, request, pk=None) -> HttpResponse:
try:
question = Question.objects.all().get(pk=pk)
except Question.DoesNotExist:
raise NotFound(
detail='Question with the id %s does not exist' % pk
)
serializer = TagSerializer(question.tags, many=True)
return Response(serializer.data)
@action(detail=False, methods=['get'], throttle_classes=[UserRateThrottle])
def random(self, request) -> HttpResponse:
questions = self.get_annotated_questions().filter(
closed=False
)
if request.user.is_anonymous is not True:
questions = questions.exclude(
votequestion__user=request.user
)
questions = questions.order_by('?')[:1]
questions_length = questions.count()
if questions_length == 0:
return Response({"detail": "No Questions Left"}, status=204)
return Response(
self.get_serializer(
questions.get()
).data
)
@action(detail=True, methods=['post'], permission_classes=[IsAuthenticated], throttle_classes=[UserRateThrottle])
def upvote(self, request, pk=None) -> HttpResponse:
try:
question = self.get_queryset().get(pk=pk)
except Question.DoesNotExist:
raise NotFound(
detail='Question with the id %s does not exist' % pk
)
if question.closed:
raise PermissionDenied(
detail='Question {} is already closed'.format(question.id))
question.vote_by(request.user, True)
# get the question again, so the upvote count updates
question = self.get_queryset().get(pk=pk)
return Response(self.get_serializer(question).data)
@action(detail=False, methods=['get'], permission_classes=[IsAuthenticated], throttle_classes=[UserRateThrottle])
def myvotes(self, request) -> HttpResponse:
user = request.user
votes = VoteQuestion.objects.filter(user=user)
return Response(VoteQuestionSerializer(votes, many=True).data)
@action(detail=False, methods=['get'], permission_classes=[IsAuthenticated], throttle_classes=[UserRateThrottle])
def upvotes(self, request) -> HttpResponse:
user = request.user
questions = self.get_queryset().filter(
votequestion__up=True,
votequestion__user=user
)
questions = filters.OrderingFilter().filter_queryset(
self.request,
questions,
self
)
answered = request.GET.get('answered')
if answered is not None:
if answered == 'true':
questions = questions.exclude(answers=None)
if answered == 'false':
questions = questions.filter(answers=None)
return Response(self.get_serializer(questions, many=True).data)
@action(
detail=False,
methods=['get'],
permission_classes=[IsAuthenticated],
throttle_classes=[UserRateThrottle],
pagination_class=NewestQuestionsSetPagination,
)
def downvotes(self, request) -> HttpResponse:
user = request.user
questions = self.get_queryset().filter(
votequestion__up=False,
votequestion__user=user
)
page = self.paginate_queryset(questions)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
@action(detail=True, methods=['post'], permission_classes=[IsAuthenticated], throttle_classes=[UserRateThrottle])
def downvote(self, request, pk=None) -> HttpResponse:
try:
question = self.get_queryset().get(pk=pk)
except Question.DoesNotExist:
raise NotFound(detail='Question id %s does not exist' % pk)
if question.closed:
raise PermissionDenied(
detail='Question {} is already closed'.format(question.id))
question.vote_by(request.user, False)
question = self.get_queryset().get(pk=pk)
return Response(
self.get_serializer(question).data,
status=status.HTTP_201_CREATED
)
@action(detail=True, methods=['post'], permission_classes=[IsAuthenticated], throttle_classes=[UserRateThrottle])
def report(self, request, pk=None) -> HttpResponse:
user = request.user
url = reverse_lazy(
'admin:wp_core_question_change',
args=([pk]),
request=request
)
question = self.get_object()
reason = request.data.get('reason', 'nichts angegeben')
params = {
'question': question.text,
'link': url,
'reason': reason,
'reporter': user,
}
plain = render_to_string(
'wp_core/mails/report_question_email.txt', params)
html = render_to_string(
'wp_core/mails/report_question_email.html', params)
if settings.REPORT_MAILS_ACTIVE:
emails = settings.REPORT_MAILS
send_mail(
'Eine Frage wurde gemeldet',
plain,
NOREPLY_ADDRESS,
emails,
html_message=html
)
slack_notify_report(question.text, reason, url, user)
return Response({'success': True})