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.

84 lines
2.8 KiB

  1. from django.shortcuts import render, redirect
  2. from django.http import HttpResponse, HttpResponseBadRequest
  3. import math
  4. import random
  5. import requests
  6. import os
  7. import urllib
  8. import datetime
  9. def generate_random_string(length):
  10. """Generates a random string of a certain length
  11. Args:
  12. length: the desired length of the randomized string
  13. Returns:
  14. A random string
  15. """
  16. rand_str = ""
  17. possible_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
  18. for _ in range(length):
  19. rand_str += possible_chars[random.randint(0, len(possible_chars) - 1)]
  20. return rand_str
  21. def token_expired(token_obtained_at, valid_for):
  22. """Returns True if token expired, False if otherwise
  23. Args:
  24. token_obtained_at: datetime object representing the date and time when the token was obtained
  25. valid_for: the time duration for which the token is valid, in seconds
  26. """
  27. time_elapsed = (datetime.datetime.today() - token_obtained_at).seconds
  28. return time_elapsed >= valid_for
  29. # Create your views here.
  30. def index(request):
  31. return render(request, 'spotifyvis/index.html')
  32. def login(request):
  33. # use a randomly generated state string to prevent cross-site request forgery attacks
  34. state_str = generate_random_string(16)
  35. request.session['state_string'] = state_str
  36. payload = {
  37. 'client_id': os.environ['SPOTIFY_CLIENT_ID'],
  38. 'response_type': 'code',
  39. 'redirect_uri': 'http://localhost:8000/callback',
  40. 'state': state_str,
  41. 'scope': 'user-library-read',
  42. 'show_dialog': False
  43. }
  44. params = urllib.parse.urlencode(payload) # turn the payload dict into a query string
  45. authorize_url = "https://accounts.spotify.com/authorize/?{}".format(params)
  46. return redirect(authorize_url)
  47. def callback(request):
  48. # Attempt to retrieve the authorization code from the query string
  49. try:
  50. code = request.GET['code']
  51. except KeyError:
  52. return HttpResponseBadRequest("<h1>Problem with login</h1>")
  53. payload = {
  54. 'grant_type': 'authorization_code',
  55. 'code': code,
  56. 'redirect_uri': 'http://localhost:8000/callback',
  57. 'client_id': os.environ['SPOTIFY_CLIENT_ID'],
  58. 'client_secret': os.environ['SPOTIFY_CLIENT_SECRET'],
  59. }
  60. response = requests.post('https://accounts.spotify.com/api/token', data = payload).json()
  61. # despite its name, datetime.today() returns a datetime object, not a date object
  62. request.session['token_obtained_at'] = str(datetime.datetime.today())
  63. request.session['access_token'] = response['access_token']
  64. request.session['refresh_token'] = response['refresh_token']
  65. request.session['valid_for'] = response['expires_in']
  66. print(response)
  67. return HttpResponse("At callback")