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.

260 lines
8.6 KiB

  1. # imports {{{ #
  2. import math
  3. import random
  4. import requests
  5. import urllib
  6. import secrets
  7. import pprint
  8. import string
  9. from django.shortcuts import render, redirect
  10. from django.http import JsonResponse
  11. from django.db.models import Count, Q, Max
  12. from .utils import *
  13. from .models import *
  14. from login.models import User
  15. from login.utils import get_user_context
  16. from dateutil.parser import parse
  17. # }}} imports #
  18. # constants {{{ #
  19. USER_TRACKS_LIMIT = 50
  20. HISTORY_LIMIT = 50
  21. ARTIST_LIMIT = 50
  22. FEATURES_LIMIT = 100
  23. # ARTIST_LIMIT = 25
  24. # FEATURES_LIMIT = 25
  25. TRACKS_TO_QUERY = 100
  26. HISTORY_ENDPOINT = 'https://api.spotify.com/v1/me/player/recently-played'
  27. console_logging = True
  28. # console_logging = False
  29. # }}} constants #
  30. # parse_library {{{ #
  31. def parse_library(request, user_secret):
  32. """Scans user's library for num_tracks and store the information in a
  33. database.
  34. :user_secret: secret for User object who's library is being scanned.
  35. :returns: None
  36. """
  37. offset = 0
  38. payload = {'limit': str(USER_TRACKS_LIMIT)}
  39. artist_genre_queue = []
  40. features_queue = []
  41. user_obj = User.objects.get(secret=user_secret)
  42. user_headers = get_user_header(user_obj)
  43. # create this obj so loop runs at least once
  44. saved_tracks_response = [0]
  45. # scan until reach num_tracks or no tracks left if scanning entire library
  46. while (TRACKS_TO_QUERY == 0 or offset < TRACKS_TO_QUERY) and len(saved_tracks_response) > 0:
  47. payload['offset'] = str(offset)
  48. saved_tracks_response = requests.get('https://api.spotify.com/v1/me/tracks',
  49. headers=user_headers,
  50. params=payload).json()['items']
  51. if console_logging:
  52. tracks_processed = 0
  53. for track_dict in saved_tracks_response:
  54. # add artists {{{ #
  55. # update artist info before track so that Track object can reference
  56. # Artist object
  57. track_artists = []
  58. for artist_dict in track_dict['track']['artists']:
  59. artist_obj, artist_created = Artist.objects.get_or_create(
  60. id=artist_dict['id'],
  61. name=artist_dict['name'],)
  62. # only add/tally up artist genres if new
  63. if artist_created:
  64. artist_genre_queue.append(artist_obj)
  65. if len(artist_genre_queue) == ARTIST_LIMIT:
  66. add_artist_genres(user_headers, artist_genre_queue)
  67. artist_genre_queue = []
  68. track_artists.append(artist_obj)
  69. # }}} add artists #
  70. track_obj, track_created = save_track_obj(track_dict['track'],
  71. track_artists, user_obj)
  72. # add audio features {{{ #
  73. # if a new track is not created, the associated audio feature does
  74. # not need to be created again
  75. if track_created:
  76. features_queue.append(track_obj)
  77. if len(features_queue) == FEATURES_LIMIT:
  78. get_audio_features(user_headers, features_queue)
  79. features_queue = []
  80. # }}} add audio features #
  81. if console_logging:
  82. tracks_processed += 1
  83. print("Added track #{}: {} - {}".format(
  84. offset + tracks_processed,
  85. track_obj.artists.first(),
  86. track_obj.name,
  87. ))
  88. # calculates num_songs with offset + songs retrieved
  89. offset += USER_TRACKS_LIMIT
  90. # clean-up {{{ #
  91. # update remaining artists without genres and songs without features if
  92. # there are any
  93. if len(artist_genre_queue) > 0:
  94. add_artist_genres(user_headers, artist_genre_queue)
  95. if len(features_queue) > 0:
  96. get_audio_features(user_headers, features_queue)
  97. # }}} clean-up #
  98. update_track_genres(user_obj)
  99. return render(request, 'graphs/logged_in.html', get_user_context(user_obj))
  100. # }}} parse_library #
  101. # parse_history {{{ #
  102. def parse_history(request, user_secret):
  103. """Scans user's listening history and stores the information in a
  104. database.
  105. :user_secret: secret for User object who's library is being scanned.
  106. :returns: None
  107. """
  108. user_obj = User.objects.get(secret=user_secret)
  109. last_time_played = History.objects.filter(user=user_obj).aggregate(Max('timestamp'))['timestamp__max']
  110. payload = {'limit': str(USER_TRACKS_LIMIT), 'after': last_time_played.isoformat()}
  111. artist_genre_queue = []
  112. user_headers = get_user_header(user_obj)
  113. history_response = requests.get(HISTORY_ENDPOINT,
  114. headers=user_headers,
  115. params=payload).json()['items']
  116. if console_logging:
  117. tracks_processed = 0
  118. for track_dict in history_response:
  119. # add artists {{{ #
  120. # update artist info before track so that Track object can reference
  121. # Artist object
  122. track_artists = []
  123. for artist_dict in track_dict['track']['artists']:
  124. artist_obj, artist_created = Artist.objects.get_or_create(
  125. id=artist_dict['id'],
  126. name=artist_dict['name'],)
  127. # only add/tally up artist genres if new
  128. if artist_created:
  129. artist_genre_queue.append(artist_obj)
  130. if len(artist_genre_queue) == ARTIST_LIMIT:
  131. add_artist_genres(user_headers, artist_genre_queue)
  132. artist_genre_queue = []
  133. track_artists.append(artist_obj)
  134. # }}} add artists #
  135. # don't associate history track with User, not necessarily in their
  136. # library
  137. track_obj, track_created = save_track_obj(track_dict['track'],
  138. track_artists, None)
  139. history_obj, history_created = History.objects.get_or_create(
  140. user=user_obj,
  141. timestamp=parse(track_dict['played_at']),
  142. track=track_obj,)
  143. if console_logging:
  144. tracks_processed += 1
  145. print("Added history track #{}: {}".format(
  146. tracks_processed, history_obj,))
  147. if len(artist_genre_queue) > 0:
  148. add_artist_genres(user_headers, artist_genre_queue)
  149. # TODO: update track genres from History relation
  150. # update_track_genres(user_obj)
  151. return render(request, 'graphs/logged_in.html', get_user_context(user_obj))
  152. # }}} get_history #
  153. # get_artist_data {{{ #
  154. def get_artist_data(request, user_secret):
  155. """Returns artist data as a JSON serialized list of dictionaries
  156. The (key, value) pairs are (artist name, song count for said artist)
  157. :param request: the HTTP request
  158. :param user_secret: the user secret used for identification
  159. :return: a JsonResponse
  160. """
  161. user = User.objects.get(secret=user_secret)
  162. artist_counts = Artist.objects.annotate(num_songs=Count('track',
  163. filter=Q(track__users=user)))
  164. processed_artist_counts = [{'name': artist.name, 'num_songs': artist.num_songs}
  165. for artist in artist_counts]
  166. pprint.pprint(processed_artist_counts)
  167. return JsonResponse(data=processed_artist_counts, safe=False)
  168. # }}} get_artist_data #
  169. # get_audio_feature_data {{{ #
  170. def get_audio_feature_data(request, audio_feature, user_secret):
  171. """Returns all data points for a given audio feature
  172. Args:
  173. request: the HTTP request
  174. audio_feature: The audio feature to be queried
  175. user_secret: client secret, used to identify the user
  176. """
  177. user = User.objects.get(secret=user_secret)
  178. user_tracks = Track.objects.filter(users=user)
  179. response_payload = {
  180. 'data_points': [],
  181. }
  182. for track in user_tracks:
  183. try:
  184. audio_feature_obj = AudioFeatures.objects.get(track=track)
  185. response_payload['data_points'].append(getattr(audio_feature_obj, audio_feature))
  186. except AudioFeatures.DoesNotExist:
  187. continue
  188. return JsonResponse(response_payload)
  189. # }}} get_audio_feature_data #
  190. # get_genre_data {{{ #
  191. def get_genre_data(request, user_secret):
  192. """Return genre data needed to create the graph user.
  193. TODO
  194. """
  195. user = User.objects.get(secret=user_secret)
  196. genre_counts = (Track.objects.filter(users__exact=user)
  197. .values('genre')
  198. .order_by('genre')
  199. .annotate(num_songs=Count('genre'))
  200. )
  201. for genre_dict in genre_counts:
  202. genre_dict['artists'] = get_artists_in_genre(user, genre_dict['genre'],
  203. genre_dict['num_songs'])
  204. print("*** Genre Breakdown ***")
  205. pprint.pprint(list(genre_counts))
  206. return JsonResponse(data=list(genre_counts), safe=False)
  207. # }}} get_genre_data #