Files
muzak/playlist/views.py
T
mark aad9343569 Refactor
Moves from_json to utils and splits the models to files in a module
2024-02-06 15:31:05 +01:00

68 lines
2.3 KiB
Python

from django.shortcuts import render
from django.views import View
from django.http import HttpResponse
from django.template.response import TemplateResponse
import re
from .models import Track, Artist, Album
from .models.utils import from_json
from . import spotify
spt = spotify.Spotify()
# TODO auth mixins
class TrackListView(View):
def get(self, request):
return HttpResponse("..")
class TrackDetailView(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 NominateView(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(Artist.objects.from_json(artist))
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(Artist.objects.from_json(artist))
track_artists.append(from_json(Artist, artist))
del json["artists"]
# Track
#track = Track.objects.from_json(json)
track = from_json(Track, json)
for artist in track_artists:
track.artists.add(artist)
track.album = album
track.save()
return HttpResponse(str(track))