Graphs and tables for your Spotify account.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

245 lines
7.4 KiB

  1. # imports {{{ #
  2. import math
  3. import random
  4. import requests
  5. import os
  6. import urllib
  7. import secrets
  8. import pprint
  9. import string
  10. from datetime import datetime
  11. from django.shortcuts import render, redirect
  12. from django.http import HttpResponse, HttpResponseBadRequest, JsonResponse
  13. from django.db.models import Count, Q
  14. from .utils import parse_library, process_library_stats, get_artists_in_genre
  15. from .models import User, Track, AudioFeatures, Artist
  16. # }}} imports #
  17. TIME_FORMAT = '%Y-%m-%d-%H-%M-%S'
  18. TRACKS_TO_QUERY = 15
  19. # generate_random_string {{{ #
  20. def generate_random_string(length):
  21. """Generates a random string of a certain length
  22. Args:
  23. length: the desired length of the randomized string
  24. Returns:
  25. A random string
  26. """
  27. all_chars = string.ascii_letters + string.digits
  28. rand_str = "".join(random.choice(all_chars) for _ in range(length))
  29. return rand_str
  30. # }}} generate_random_string #
  31. # token_expired {{{ #
  32. def token_expired(token_obtained_at, valid_for):
  33. """Returns True if token expired, False if otherwise
  34. Args:
  35. token_obtained_at: datetime object representing the date and time when the token was obtained
  36. valid_for: the time duration for which the token is valid, in seconds
  37. """
  38. time_elapsed = (datetime.today() - token_obtained_at).total_seconds()
  39. return time_elapsed >= valid_for
  40. # }}} token_expired #
  41. # index {{{ #
  42. # Create your views here.
  43. def index(request):
  44. return render(request, 'spotifyvis/index.html')
  45. # }}} index #
  46. # login {{{ #
  47. def login(request):
  48. # use a randomly generated state string to prevent cross-site request forgery attacks
  49. state_str = generate_random_string(16)
  50. request.session['state_string'] = state_str
  51. payload = {
  52. 'client_id': os.environ['SPOTIFY_CLIENT_ID'],
  53. 'response_type': 'code',
  54. 'redirect_uri': 'http://localhost:8000/callback',
  55. 'state': state_str,
  56. 'scope': 'user-library-read',
  57. 'show_dialog': False
  58. }
  59. params = urllib.parse.urlencode(payload) # turn the payload dict into a query string
  60. authorize_url = "https://accounts.spotify.com/authorize/?{}".format(params)
  61. return redirect(authorize_url)
  62. # }}} login #
  63. # callback {{{ #
  64. def callback(request):
  65. # Attempt to retrieve the authorization code from the query string
  66. try:
  67. code = request.GET['code']
  68. except KeyError:
  69. return HttpResponseBadRequest("<h1>Problem with login</h1>")
  70. payload = {
  71. 'grant_type': 'authorization_code',
  72. 'code': code,
  73. 'redirect_uri': 'http://localhost:8000/callback',
  74. 'client_id': os.environ['SPOTIFY_CLIENT_ID'],
  75. 'client_secret': os.environ['SPOTIFY_CLIENT_SECRET'],
  76. }
  77. response = requests.post('https://accounts.spotify.com/api/token', data=payload).json()
  78. # despite its name, datetime.today() returns a datetime object, not a date object
  79. # use datetime.strptime() to get a datetime object from a string
  80. request.session['token_obtained_at'] = datetime.strftime(datetime.today(), TIME_FORMAT)
  81. request.session['access_token'] = response['access_token']
  82. request.session['refresh_token'] = response['refresh_token']
  83. request.session['valid_for'] = response['expires_in']
  84. # print(response)
  85. return redirect('user_data')
  86. # }}} callback #
  87. # user_data {{{ #
  88. def user_data(request):
  89. token_obtained_at = datetime.strptime(request.session['token_obtained_at'], TIME_FORMAT)
  90. valid_for = int(request.session['valid_for'])
  91. if token_expired(token_obtained_at, valid_for):
  92. req_body = {
  93. 'grant_type': 'refresh_token',
  94. 'refresh_token': request.session['refresh_token'],
  95. 'client_id': os.environ['SPOTIFY_CLIENT_ID'],
  96. 'client_secret': os.environ['SPOTIFY_CLIENT_SECRET']
  97. }
  98. refresh_token_response = requests.post('https://accounts.spotify.com/api/token', data=req_body).json()
  99. request.session['access_token'] = refresh_token_response['access_token']
  100. request.session['valid_for'] = refresh_token_response['expires_in']
  101. auth_token_str = "Bearer " + request.session['access_token']
  102. headers = {
  103. 'Authorization': auth_token_str
  104. }
  105. user_data_response = requests.get('https://api.spotify.com/v1/me', headers=headers).json()
  106. request.session['user_id'] = user_data_response['id'] # store the user_id so it may be used to create model
  107. # request.session['user_name'] = user_data_response['display_name']
  108. try:
  109. user = User.objects.get(user_id=user_data_response['id'])
  110. except User.DoesNotExist:
  111. # Python docs recommends 32 bytes of randomness against brute force attacks
  112. user = User(user_id=user_data_response['id'], user_secret=secrets.token_urlsafe(32))
  113. request.session['user_secret'] = user.user_secret
  114. user.save()
  115. context = {
  116. 'user_secret': user.user_secret,
  117. }
  118. parse_library(headers, TRACKS_TO_QUERY, user)
  119. return render(request, 'spotifyvis/logged_in.html', context)
  120. # }}} user_data #
  121. # test_db {{{ #
  122. def test_db(request):
  123. """TODO
  124. """
  125. # user_id = "polarbier"
  126. user_id = "chrisshyi13"
  127. context = {
  128. 'user_secret': User.objects.get(user_id=user_id).user_secret,
  129. }
  130. return render(request, 'spotifyvis/test_db.html', context)
  131. # }}} test_db #
  132. # get_artist_data {{{ #
  133. def get_artist_data(request, user_secret):
  134. """TODO
  135. """
  136. user = User.objects.get(user_id=user_secret)
  137. artist_counts = Artist.objects.annotate(num_songs=Count('track',
  138. filter=Q(track__users=user)))
  139. processed_artist_counts = [{'name': artist.name,
  140. 'num_songs': artist.num_songs} for artist in artist_counts]
  141. return JsonResponse(data=processed_artist_counts, safe=False)
  142. # }}} get_artist_data #
  143. def audio_features(request, client_secret):
  144. user = User.objects.get(user_secret=client_secret)
  145. context = {
  146. 'user_id': user.user_id,
  147. 'user_secret': client_secret,
  148. }
  149. return render(request, "spotifyvis/audio_features.html", context)
  150. # get_audio_feature_data {{{ #
  151. def get_audio_feature_data(request, audio_feature, client_secret):
  152. """Returns all data points for a given audio feature
  153. Args:
  154. request: the HTTP request
  155. audio_feature: The audio feature to be queried
  156. client_secret: client secret, used to identify the user
  157. """
  158. user = User.objects.get(user_secret=client_secret)
  159. user_tracks = Track.objects.filter(users=user)
  160. response_payload = {
  161. 'data_points': [],
  162. }
  163. for track in user_tracks:
  164. try:
  165. audio_feature_obj = AudioFeatures.objects.get(track=track)
  166. response_payload['data_points'].append(getattr(audio_feature_obj, audio_feature))
  167. except AudioFeatures.DoesNotExist:
  168. continue
  169. return JsonResponse(response_payload)
  170. # }}} get_audio_feature_data #
  171. # get_genre_data {{{ #
  172. def get_genre_data(request, user_secret):
  173. """Return genre data needed to create the graph user.
  174. TODO
  175. """
  176. user = User.objects.get(user_secret=user_secret)
  177. genre_counts = (Track.objects.filter(users__exact=user)
  178. .values('genre')
  179. .order_by('genre')
  180. .annotate(num_songs=Count('genre'))
  181. )
  182. for genre_dict in genre_counts:
  183. genre_dict['artists'] = get_artists_in_genre(user, genre_dict['genre'])
  184. pprint.pprint(list(genre_counts))
  185. return JsonResponse(data=list(genre_counts), safe=False)
  186. # }}} get_genre_data #