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.

169 lines
5.3 KiB

  1. # imports {{{ #
  2. from django.shortcuts import render, redirect
  3. from django.http import HttpResponse, HttpResponseBadRequest
  4. import math
  5. import random
  6. import requests
  7. import os
  8. import urllib
  9. import json
  10. import pprint
  11. from datetime import datetime
  12. from .utils import parse_library, process_library_stats
  13. from .models import User, Track, AudioFeatures, Artist
  14. # }}} imports #
  15. TIME_FORMAT = '%Y-%m-%d-%H-%M-%S'
  16. TRACKS_TO_QUERY = 5
  17. # generate_random_string {{{ #
  18. def generate_random_string(length):
  19. """Generates a random string of a certain length
  20. Args:
  21. length: the desired length of the randomized string
  22. Returns:
  23. A random string
  24. """
  25. rand_str = ""
  26. possible_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
  27. for _ in range(length):
  28. rand_str += possible_chars[random.randint(0, len(possible_chars) - 1)]
  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. user = User.objects.get_or_create(user_id=user_data_response['id'])[0]
  109. context = {
  110. 'user_name': user_data_response['display_name'],
  111. 'id': user_data_response['id'],
  112. }
  113. library_stats = {
  114. "audio_features":{},
  115. "genres":{},
  116. "year_released":{},
  117. "artists":{},
  118. "num_songs": 0,
  119. "popularity": {
  120. "average": 0,
  121. "std_dev": 0,
  122. },
  123. "total_runtime": 0
  124. }
  125. parse_library(headers, TRACKS_TO_QUERY, library_stats, user)
  126. processed_library_stats = process_library_stats(library_stats)
  127. # print("================================================")
  128. # print("Processed data follows\n")
  129. # pprint.pprint(processed_library_stats)
  130. return render(request, 'spotifyvis/user_data.html', context)
  131. # }}} user_data #