from django.shortcuts import render from django.views import View from django.http import HttpResponse from django.template.response import TemplateResponse from django.contrib.auth.mixins import LoginRequiredMixin import re from random import choice from .models import Track, Artist, Album from .models.utils import from_json from . import spotify spt = spotify.Spotify() # TODO auth mixins class AuthView(View): def get(self, request): return TemplateResponse(request, "Login.html", {}) class TrackListView(View): def get(self, request): return HttpResponse("..") class TrackDetailView(LoginRequiredMixin, View): def get(self, request, spotify_id): try: track = Track.objects.get(pk=spotify_id) return HttpResponse(str(track)) except Track.DoesNotExist: return HttpResponse("No track") class VoteView(LoginRequiredMixin, View): def get(self, request): songs = Track.objects.all() return TemplateResponse(request, "Vote.html", {"songs": songs}) class VoteTrackView(LoginRequiredMixin, View): def get(self, request): pks = Track.objects.values_list('pk', flat=True) track = Track.objects.get(pk=choice(pks)) return TemplateResponse(request, "SpotifyEmbed.html", {"id": track.id}) class NominateView(LoginRequiredMixin, View): def get(self, request): return TemplateResponse(request, "Nominate.html", {}) def post(self, request): spotify_link = self.request.POST['spotify_link'] m = re.match(r"^https:\/\/open.spotify.com\/track\/(\w+)\??", spotify_link) spotify_id = m.group(1) try: track = Track.all_tracks.get(pk=spotify_id) if track.old: return HttpResponse("Deze was vorig jaar al genomineerd: " + str(track)) return HttpResponse("Maat, dat bestaat al: " + str(track)) except Track.DoesNotExist: json = spt.get_song_info(spotify_id) # 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"]) 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.album = album track.save() return HttpResponse(str(track))