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.

277 lines
8.2 KiB

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