Files
muzak/playlist/views.py
T
2024-02-26 22:51:35 +01:00

186 lines
7.3 KiB
Python

from django.shortcuts import render
from django.views import View
from django.http import HttpResponse, HttpResponseRedirect
from django.template.response import TemplateResponse
from django.contrib.auth.mixins import LoginRequiredMixin
import re
from collections import OrderedDict
from .models import Track, Artist, Album, Vote, Background, Profile
from .utils import from_json, get_unvoted
from . import spotify
from .tasks import get_banter, get_and_dither_image
spt = spotify.Spotify()
class AuthView(View):
def get(self, request):
if request.user.is_authenticated:
return HttpResponseRedirect('/vote/')
else:
return TemplateResponse(request, "Login.html", {})
class VoteView(LoginRequiredMixin, View):
def get(self, request, undo=None):
track = get_unvoted(request.user)
if track and not track.album.image:
get_and_dither_image(track.album.image_url, track.album, "image")
return TemplateResponse(request, "Vote.html", {"track": track, "undo": undo})
def post(self, request):
try:
spotify_id = self.request.POST['spotify_id']
score = int(self.request.POST['vote'])
score = min(max(-2, score), 2)
track = Track.objects.get(pk=spotify_id)
try:
Vote.objects.get(user=request.user, track=track)
except Vote.DoesNotExist:
pass
else:
raise Exception(f"{request.user} already voted for {track}")
vote = Vote.objects.create(track=track, user=request.user, points=score)
(profile,_) = Profile.objects.get_or_create(user=request.user)
profile.last_voted = track
profile.save()
return self.get(request, undo=vote)
except Exception as e:
print(e)
class NominateView(LoginRequiredMixin, View):
def get(self, request):
(profile,_) = Profile.objects.get_or_create(user=request.user)
profile.update_quota()
return TemplateResponse(request, "Nominate.html", {})
def post(self, request):
(profile,_) = Profile.objects.get_or_create(user=request.user)
if profile.quota < 1:
return TemplateResponse(request, "Nominate.html", {"error": "Nee nee nee, dat gaan we dus even niet doen."})
try:
spotify_link = self.request.POST['spotify_link']
# Short url?
if re.match(r"^https:\/\/spotify.link.*", spotify_link):
spotify_link = spt.unshort(spotify_link)
m = re.match(r"^https:\/\/open.spotify.com\/track\/([a-zA-Z0-9]+)\??", spotify_link)
spotify_id = m.group(1)
except:
return TemplateResponse(request, "Nominate.html", {"error": "Geef een geldige spotify link op!"})
try:
track = Track.all_tracks.get(pk=spotify_id)
if track.old:
track.old = False
track.save()
return TemplateResponse(request, "Nominate.html", {
"warning": "Hey een klassieker.",
"nominated": track
})
return TemplateResponse(request, "Nominate.html", {
"error": "Deze is al genomineerd dit jaar, probeer eens iets anders.",
"nominated": track
})
except Track.DoesNotExist:
try:
json = spt.get_song_info(spotify_id)
except:
return TemplateResponse(request, "Nominate.html", {"error": "Fout bij het ophalen van het liedje."})
# Album artists
album_artists = []
for artist in json["album"]["artists"]:
album_artists.append(from_json(Artist, artist))
del json["album"]["artists"]
# Album
album = from_json(Album, json["album"])
album.image_url = json["album"]["images"][0]["url"]
album.save()
del json["album"]
for artist in album_artists:
album.artists.add(artist)
# Track artists
track_artists = []
for artist in json["artists"]:
track_artists.append(from_json(Artist, artist))
del json["artists"]
# Track
track = from_json(Track, json)
for artist in track_artists:
track.artists.add(artist)
track.save()
dup = track.is_duplicate_of()
if dup:
track.delete()
return TemplateResponse(request, "Nominate.html", {
"error": f"Die hadden we al knul.",
"nominated": dup
})
track.album = album
track.save()
get_banter.delay(track.id)
profile.quota -= 1
profile.save()
return TemplateResponse(request, "Nominate.html", {"nominated": track})
class SettingsView(LoginRequiredMixin, View):
def get(self, request):
backgrounds = Background.objects.all()
(profile,created) = Profile.objects.get_or_create(user=request.user)
context = {
"backgrounds": backgrounds,
"currentBackground": (profile.background.id if profile.background else 1)
}
return TemplateResponse(request, "Settings.html", context)
def post(self, request):
try:
bg = Background.objects.get(pk=request.POST['background'])
(profile,_) = Profile.objects.get_or_create(user=request.user)
profile.background = bg
profile.save()
except:
pass
finally:
return self.get(request)
class UndoView(LoginRequiredMixin, View):
def get(self, request):
return HttpResponseRedirect('/vote/')
def post(self, request):
spotify_id = self.request.POST['spotify_id']
track = Track.objects.get(pk=spotify_id)
(profile,_) = Profile.objects.get_or_create(user=request.user)
if profile.last_voted != track:
raise Exception(f"{request.user} is not allowed to undo vote for {track}")
vote = None
try:
vote = Vote.objects.get(user=request.user, track=track)
except Vote.DoesNotExist:
raise Exception(f"{request.user} did not vote for {track}")
profile.last_voted = None
profile.save()
vote.delete()
return HttpResponseRedirect('/vote/')
class OverView(LoginRequiredMixin, View):
def get(self, request):
votes = Vote.objects.select_related().distinct()
artists = {}
for vote in votes:
for artist in vote.track.artists.all():
if not artists.get(artist.name):
artists[artist.name] = {}
for artist in vote.track.album.artists.all():
if not artists.get(artist.name):
artists[artist.name] = {}
if not artists[artist.name].get(vote.track.album.name):
artists[artist.name][vote.track.album.name] = []
artists[artist.name][vote.track.album.name] += [vote.track]
artists_ordered = OrderedDict(sorted(artists.items()))
context = {
"artists": artists_ordered
}
return TemplateResponse(request, "Overview.html", context)