pretalx-musicrate/pretalx_musicrate/views.py

473 lines
16 KiB
Python
Raw Permalink Normal View History

2023-12-18 01:38:35 +01:00
import csv
import re
2023-12-15 02:52:49 +01:00
from hmac import compare_digest
from urllib.parse import parse_qs, urlparse
2023-12-15 02:52:49 +01:00
2023-12-13 23:58:00 +01:00
from django.contrib import messages
2023-12-18 01:38:35 +01:00
from django.db.models import Case, FilteredRelation, Q, Value, When
from django.http import HttpResponse, JsonResponse
2023-12-16 01:05:05 +01:00
from django.shortcuts import get_object_or_404, redirect
2023-12-15 02:48:31 +01:00
from django.urls import reverse
2023-12-15 17:12:12 +01:00
from django.utils.functional import cached_property
from django.utils.html import Urlizer
2023-12-16 01:05:05 +01:00
from django.utils.translation import gettext_lazy as _, ngettext
from django.views.generic import FormView, TemplateView, View
2023-12-15 17:12:12 +01:00
from django.views.generic.detail import SingleObjectMixin
from django_context_decorator import context
2023-12-15 02:48:31 +01:00
from pretalx.common.mixins.views import EventPermissionRequired
2024-02-13 18:39:25 +01:00
from pretalx.submission.models import Submission
2023-12-15 02:48:31 +01:00
2024-02-13 18:39:25 +01:00
from .forms import AssigneeForm, MusicrateSettingsForm, RatingForm
2023-12-16 01:05:05 +01:00
from .models import Juror, Rating
2023-12-13 23:58:00 +01:00
youtube_re = re.compile(
r"(?:https?://)?(youtu\.be/|(?:(?:m|www)\.)?youtube\.com/watch\?)", re.IGNORECASE
)
2023-12-13 23:58:00 +01:00
2023-12-15 02:52:49 +01:00
class JoinView(TemplateView):
template_name = "pretalx_musicrate/join.html"
def validate_token(self, token):
2023-12-16 01:05:05 +01:00
try:
self.juror = Juror.objects.get(token=token)
return True
except Juror.DoesNotExist:
self.juror = None
2023-12-15 02:52:49 +01:00
if compare_digest(
token.encode("utf-8"),
self.request.event.pretalx_musicrate_settings.join_token.encode("utf-8"),
):
return True
messages.error(self.request, _("Invalid token"))
return False
def get_context_data(self, token_valid=False, **kwargs):
context = super().get_context_data(**kwargs)
2023-12-16 01:05:05 +01:00
context["juror"] = self.juror
2023-12-15 02:52:49 +01:00
context["token_valid"] = token_valid
return context
def get(self, request, *args, token, **kwargs):
token_valid = self.validate_token(token)
2023-12-16 01:05:05 +01:00
if self.juror is not None:
submission = (
self.juror.last_submission
or self.request.event.pretalx_musicrate_settings.last_submission
or self.request.event.submissions.filter(
submission_type__in=self.request.event.pretalx_musicrate_settings.submission_types.all()
)
.order_by("created")
.first()
)
if submission is not None:
return redirect(
"plugins:pretalx_musicrate:rating",
event=self.request.event.slug,
token=self.juror.token,
code=submission.code,
)
2023-12-15 02:52:49 +01:00
return super().get(request, *args, token_valid=token_valid, **kwargs)
def post(self, request, *args, token, **kwargs):
token_valid = self.validate_token(token)
if token_valid:
2023-12-16 01:05:05 +01:00
if self.juror is None:
self.juror = Juror.objects.create(
event=self.request.event,
last_submission=self.request.event.pretalx_musicrate_settings.last_submission,
)
submission = (
self.juror.last_submission
or self.request.event.pretalx_musicrate_settings.last_submission
or self.request.event.submissions.filter(
submission_type__in=self.request.event.pretalx_musicrate_settings.submission_types.all()
)
.order_by("created")
.first()
)
if submission is not None:
return redirect(
"plugins:pretalx_musicrate:rating",
event=self.request.event.slug,
token=self.juror.token,
code=submission.code,
)
2023-12-15 02:52:49 +01:00
return self.render_to_response(
self.get_context_data(token_valid=token_valid, **kwargs)
)
2023-12-15 02:48:31 +01:00
class MusicrateSettingsView(EventPermissionRequired, FormView):
2023-12-13 23:58:00 +01:00
permission_required = "orga.change_settings"
template_name = "pretalx_musicrate/settings.html"
form_class = MusicrateSettingsForm
def get_success_url(self):
return self.request.path
def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
kwargs["event"] = self.request.event
return kwargs
def form_valid(self, form):
form.save()
2023-12-14 00:57:15 +01:00
messages.success(
self.request, _("The pretalx-musicrate settings were updated.")
2023-12-14 00:57:15 +01:00
)
2023-12-13 23:58:00 +01:00
return super().form_valid(form)
2023-12-15 02:48:31 +01:00
class QRCodeView(EventPermissionRequired, TemplateView):
permission_required = "orga.view_submissions"
template_name = "pretalx_musicrate/qrcode.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["contents"] = self.request.build_absolute_uri(
reverse(
"plugins:pretalx_musicrate:join",
kwargs={
"event": self.request.event.slug,
"token": self.request.event.pretalx_musicrate_settings.join_token,
},
)
)
2023-12-16 01:05:05 +01:00
context["last_submission"] = (
self.request.event.pretalx_musicrate_settings.last_submission
or self.request.event.submissions.filter(
submission_type__in=self.request.event.pretalx_musicrate_settings.submission_types.all()
)
.order_by("created")
.first()
)
2023-12-15 02:48:31 +01:00
return context
2023-12-15 17:12:12 +01:00
class SubmissionMixin(SingleObjectMixin):
slug_field = "code"
slug_url_kwarg = "code"
def get_queryset(self):
return self.request.event.submissions.prefetch_related("answers").filter(
submission_type__in=self.request.event.pretalx_musicrate_settings.submission_types.all()
)
@context
@cached_property
def submission(self):
return self.get_object()
@context
@cached_property
def genre(self):
return (
self.submission.answers.filter(
question=self.request.event.pretalx_musicrate_settings.genre_question
)
.values_list("answer", flat=True)
.first()
)
@context
@cached_property
def origin(self):
return (
self.submission.answers.filter(
question=self.request.event.pretalx_musicrate_settings.origin_question
)
.values_list("answer", flat=True)
.first()
)
def get_url_kwargs(self, **kwargs):
return self.request.resolver_match.kwargs | kwargs
@cached_property
def index_queryset(self):
return (
2023-12-15 17:12:12 +01:00
self.get_queryset()
.prefetch_related(None)
.only("pk", "code")
.order_by("created")
2023-12-15 17:12:12 +01:00
)
@context
@cached_property
def prev(self):
if self.index == 1:
2023-12-15 17:12:12 +01:00
return None
return reverse(
self.request.resolver_match.view_name,
kwargs=self.get_url_kwargs(
code=self.index_queryset[self.index - 1 - 1].code
),
2023-12-15 17:12:12 +01:00
)
@context
@cached_property
def index(self):
return next(
map(
lambda s: s[0] + 1,
2023-12-15 17:12:12 +01:00
filter(
lambda s: s[1].pk == self.submission.pk,
enumerate(self.index_queryset),
2023-12-15 17:12:12 +01:00
),
)
)
@context
@cached_property
def count(self):
return self.index_queryset.count()
2023-12-15 17:12:12 +01:00
@context
@cached_property
def next(self):
if self.index == self.count:
2023-12-15 17:12:12 +01:00
return None
return reverse(
self.request.resolver_match.view_name,
kwargs=self.get_url_kwargs(
code=self.index_queryset[self.index - 1 + 1].code
),
2023-12-15 17:12:12 +01:00
)
2023-12-16 01:05:05 +01:00
class RatingView(FormView, SubmissionMixin):
template_name = "pretalx_musicrate/rating.html"
form_class = RatingForm
@cached_property
def juror(self):
return get_object_or_404(
Juror, token=self.request.resolver_match.kwargs["token"]
)
@context
@cached_property
def can_continue(self):
return self.submission.ratings.filter(juror=self.juror).exists()
def get_form(self, form_class=None):
if form_class is None:
form_class = self.get_form_class()
try:
instance = Rating.objects.get(submission=self.submission, juror=self.juror)
except Rating.DoesNotExist:
instance = None
return form_class(instance=instance, **self.get_form_kwargs())
def get_success_url(self):
return self.request.path
def form_valid(self, form):
obj = form.save(commit=False)
obj.submission = self.submission
obj.juror = self.juror
obj.save()
try:
self.juror.last_submission = self.submission
self.juror.save()
except Exception:
pass
messages.success(self.request, _("Saved!"))
return super().form_valid(form)
def get(self, request, *args, **kwargs):
self.object = self.get_object()
if (
(settings := self.request.event.pretalx_musicrate_settings).last_submission
is not None
and self.object.created > settings.last_submission.created
):
return redirect(
self.request.resolver_match.view_name,
event=self.request.event.slug,
token=self.juror.token,
code=settings.last_submission.code,
)
return super().get(request, *args, **kwargs)
2023-12-15 17:12:12 +01:00
class PresenterView(EventPermissionRequired, SubmissionMixin, TemplateView):
permission_required = "orga.view_submissions"
template_name = "pretalx_musicrate/present.html"
@context
@cached_property
def links(self):
class Extractor:
def __init__(self):
self.urls = []
def format(self, href, **kwargs):
self.urls.append(href)
return href
extractor = Extractor()
urlizer = Urlizer()
urlizer.url_template = extractor
urlizer(self.submission.abstract)
urlizer(self.submission.description)
urlizer(self.submission.notes)
urlizer(self.submission.internal_notes)
for answer in self.submission.answers.filter(
question__in=self.request.event.pretalx_musicrate_settings.link_questions.all()
).values_list("answer", flat=True):
urlizer(answer)
links = []
for url in extractor.urls:
if (m := youtube_re.search(url)) is not None:
links.append(
(
"youtube",
2024-02-13 15:38:04 +01:00
(
url.removeprefix("http")
.removeprefix("s")
.removeprefix("://")
.removeprefix("youtu.be/")[:11]
if m[1] == "youtu.be/"
else "".join(
parse_qs(urlparse(url).query).get("v", "dQw4w9WgXcQ")
)
),
)
)
else:
links.append(("other", url))
return links
2023-12-15 17:12:12 +01:00
@context
@property
def can_continue(self):
return True
def get(self, request, *args, **kwargs):
self.object = self.get_object()
2023-12-16 01:05:05 +01:00
if (
(settings := self.request.event.pretalx_musicrate_settings).last_submission
is None
or self.object.created > settings.last_submission.created
):
try:
settings.last_submission = self.object
settings.save()
except Exception:
pass
response = super().get(request, *args, **kwargs)
response._csp_update = {"frame-src": "https://www.youtube-nocookie.com"}
return response
2023-12-16 01:05:05 +01:00
class MayAdvanceView(EventPermissionRequired, SubmissionMixin, View):
permission_required = "orga.view_submissions"
def get(self, request, *args, **kwargs):
2023-12-16 01:05:05 +01:00
num_ratings = self.submission.ratings.count()
num_jurors = self.request.event.jurors.count()
return JsonResponse(
{
"mayAdvance": num_ratings
>= int(
num_jurors
* self.request.event.pretalx_musicrate_settings.advance_threshold
)
and num_jurors > 2,
2023-12-16 01:05:05 +01:00
"statusText": ngettext(
"%(num_ratings)d of %(num_jurors)d has rated this submission",
"%(num_ratings)d of %(num_jurors)d have rated this submission",
num_ratings,
)
% {"num_jurors": num_jurors, "num_ratings": num_ratings},
}
)
2023-12-18 01:38:35 +01:00
class ExportView(EventPermissionRequired, View):
permission_required = "orga.view_submissions"
def get(self, request, *args, **kwargs):
response = HttpResponse(
content_type="text/csv",
headers={
"Content-Disposition": f'attachment; filename="{request.event.slug}.csv"'
},
)
writer = csv.writer(response)
genre_question = request.event.pretalx_musicrate_settings.genre_question
origin_question = request.event.pretalx_musicrate_settings.origin_question
jurors = request.event.jurors.order_by("token")
for submission in (
request.event.submissions.prefetch_related("answers")
.select_related("submission_type")
.filter(
submission_type__in=request.event.pretalx_musicrate_settings.submission_types.all()
)
.only("title", "submission_type__name")
.order_by("created")
2023-12-18 01:38:35 +01:00
):
submission_info = [submission.title, submission.submission_type.name]
if genre_question is not None:
submission_info.append(
submission.answers.filter(question=genre_question)
.values_list("answer", flat=True)
.first()
or ""
)
if origin_question is not None:
submission_info.append(
submission.answers.filter(question=origin_question)
.values_list("answer", flat=True)
.first()
or ""
)
writer.writerow(
[
*submission_info,
*jurors.annotate(
filtered_ratings=FilteredRelation(
"ratings", condition=Q(ratings__submission=submission)
),
rating=Case(
When(filtered_ratings__rating=None, then=Value("")),
When(filtered_ratings__rating="", then=Value("E")),
default="filtered_ratings__rating",
),
).values_list("rating", flat=True),
]
)
return response
2024-02-13 18:39:25 +01:00
class AssigneeView(EventPermissionRequired, FormView, SingleObjectMixin):
form_class = AssigneeForm
model = Submission
permission_required = "orga.change_submissions"
slug_field = "code"
slug_url_kwarg = "code"
template_name = "pretalx_musicrate/assignee.html"
def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
kwargs["submission"] = self.object
return kwargs
def get_success_url(self):
return self.request.path
def form_valid(self, form):
form.save()
messages.success(self.request, _("Saved!"))
return super().form_valid(form)
def get(self, *args, **kwargs):
self.object = self.get_object()
return super().get(*args, **kwargs)
def post(self, *args, **kwargs):
self.object = self.get_object()
return super().post(*args, **kwargs)