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.

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