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.

402 lines
14 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. # imports {{{ #
  2. import requests
  3. import math
  4. import os
  5. import json
  6. from django.core import serializers
  7. from django.core.exceptions import ObjectDoesNotExist
  8. from django.db import IntegrityError
  9. from django.db.models import Count, F, Max
  10. from django.db.models import FloatField
  11. from django.db.models.functions import Cast
  12. from django.http import JsonResponse
  13. from django.utils import timezone
  14. from datetime import datetime
  15. from dateutil.parser import parse
  16. from pprint import pprint
  17. from . import views
  18. from .models import *
  19. from login.models import User
  20. HISTORY_ENDPOINT = 'https://api.spotify.com/v1/me/player/recently-played'
  21. # }}} imports #
  22. # console_logging = True
  23. console_logging = False
  24. artists_genre_processed = 0
  25. features_processed = 0
  26. # update_track_genres {{{ #
  27. def update_track_genres(user_obj):
  28. """Updates user_obj's tracks with the most common genre associated with the
  29. songs' artist(s).
  30. :user_obj: User object who's tracks are being updated.
  31. :returns: None
  32. """
  33. tracks_processed = 0
  34. user_tracks = Track.objects.filter(users__exact=user_obj)
  35. for track in user_tracks:
  36. # just using this variable to save another call to db
  37. track_artists = list(track.artists.all())
  38. # TODO: Use the most popular genre of the first artist as the Track genre
  39. first_artist_genres = track_artists[0].genres.all().order_by('-num_songs')
  40. undefined_genre_obj = Genre.objects.get(name="undefined")
  41. most_common_genre = first_artist_genres.first() if first_artist_genres.first() is \
  42. not undefined_genre_obj else first_artist_genres[1]
  43. track.genre = most_common_genre if most_common_genre is not None \
  44. else undefined_genre_obj
  45. track.save()
  46. tracks_processed += 1
  47. if console_logging:
  48. print("Added '{}' as genre for song #{} - '{}'".format(
  49. track.genre,
  50. tracks_processed,
  51. track.name,
  52. ))
  53. # }}} update_track_genres #
  54. # save_track_obj {{{ #
  55. def save_track_obj(track_dict, artists, user_obj):
  56. """Make an entry in the database for this track if it doesn't exist already.
  57. :track_dict: dictionary from the API call containing track information.
  58. :artists: artists of the song, passed in as a list of Artist objects.
  59. :user_obj: User object for which this Track is to be associated with.
  60. :returns: (The created/retrieved Track object, created)
  61. """
  62. track_query = Track.objects.filter(id__exact=track_dict['id'])
  63. if len(track_query) != 0:
  64. return track_query[0], False
  65. else:
  66. # check if track is simple or full, simple Track object won't have year
  67. # if 'album' in track_dict:
  68. if 'release_date' in track_dict['album']:
  69. # try:
  70. new_track = Track.objects.create(
  71. id=track_dict['id'],
  72. year=track_dict['album']['release_date'].split('-')[0],
  73. popularity=int(track_dict['popularity']),
  74. runtime=int(float(track_dict['duration_ms']) / 1000),
  75. name=track_dict['name'],
  76. )
  77. else:
  78. # except (IntegrityError, KeyError) as e:
  79. new_track = Track.objects.create(
  80. id=track_dict['id'],
  81. popularity=int(track_dict['popularity']),
  82. runtime=int(float(track_dict['duration_ms']) / 1000),
  83. name=track_dict['name'],
  84. )
  85. # have to add artists and user_obj after saving object since track needs to
  86. # have ID before filling in m2m field
  87. for artist in artists:
  88. new_track.artists.add(artist)
  89. # print(new_track.name, artist.name)
  90. if user_obj != None:
  91. new_track.users.add(user_obj)
  92. new_track.save()
  93. return new_track, True
  94. # }}} save_track_obj #
  95. # get_audio_features {{{ #
  96. def get_audio_features(headers, track_objs):
  97. """Creates and saves a new AudioFeatures objects for the respective
  98. track_objs. track_objs should contain the API limit for a single call
  99. (FEATURES_LIMIT) for maximum efficiency.
  100. :headers: headers containing the API token
  101. :track_objs: Track objects to associate with the new AudioFeatures object
  102. :returns: None
  103. """
  104. track_ids = str.join(",", [track_obj.id for track_obj in track_objs])
  105. params = {'ids': track_ids}
  106. features_response = requests.get("https://api.spotify.com/v1/audio-features",
  107. headers=headers,
  108. params={'ids': track_ids}
  109. ).json()['audio_features']
  110. # pprint.pprint(features_response)
  111. useless_keys = [ "key", "mode", "type", "liveness", "id", "uri",
  112. "track_href", "analysis_url", "time_signature", ]
  113. for i in range(len(track_objs)):
  114. if features_response[i] is not None:
  115. # Data that we don't need
  116. cur_features_obj = AudioFeatures()
  117. cur_features_obj.track = track_objs[i]
  118. for key, val in features_response[i].items():
  119. if key not in useless_keys:
  120. setattr(cur_features_obj, key, val)
  121. cur_features_obj.save()
  122. if console_logging:
  123. global features_processed
  124. features_processed += 1
  125. print("Added features for song #{} - {}".format(
  126. features_processed, track_objs[i].name))
  127. # }}} get_audio_features #
  128. # process_artist_genre {{{ #
  129. def process_artist_genre(genre_name, artist_obj):
  130. """Increase count for corresponding Genre object to genre_name and associate that
  131. Genre object with artist_obj.
  132. :genre_name: Name of genre.
  133. :artist_obj: Artist object to associate Genre object with
  134. :returns: None
  135. """
  136. genre_obj, created = Genre.objects.get_or_create(name=genre_name, defaults={'num_songs': 1})
  137. if not created:
  138. genre_obj.num_songs = F('num_songs') + 1
  139. genre_obj.save()
  140. artist_obj.genres.add(genre_obj)
  141. artist_obj.save()
  142. # }}} process_artist_genre #
  143. # add_artist_genres {{{ #
  144. def add_artist_genres(headers, artist_objs):
  145. """Adds genres to artist_objs and increases the count the respective Genre
  146. object. artist_objs should contain the API limit for a single call
  147. (ARTIST_LIMIT) for maximum efficiency.
  148. :headers: For making the API call.
  149. :artist_objs: List of Artist objects for which to add/tally up genres for.
  150. :returns: None
  151. """
  152. artist_ids = str.join(",", [artist_obj.id for artist_obj in artist_objs])
  153. artists_response = requests.get('https://api.spotify.com/v1/artists/',
  154. headers=headers,
  155. params={'ids': artist_ids},
  156. ).json()['artists']
  157. for i in range(len(artist_objs)):
  158. if len(artists_response[i]['genres']) == 0:
  159. process_artist_genre("undefined", artist_objs[i])
  160. else:
  161. for genre in artists_response[i]['genres']:
  162. process_artist_genre(genre, artist_objs[i])
  163. # print(artist_objs[i].name, genre)
  164. if console_logging:
  165. global artists_genre_processed
  166. artists_genre_processed += 1
  167. print("Added genres for artist #{} - {}".format(
  168. artists_genre_processed, artist_objs[i].name))
  169. # }}} add_artist_genres #
  170. # get_artists_in_genre {{{ #
  171. def get_artists_in_genre(user, genre):
  172. """Return count of artists in genre.
  173. :user: User object to return data for.
  174. :genre: genre to count artists for. (string)
  175. :returns: dict of artists in the genre along with the number of songs they
  176. have.
  177. """
  178. genre_obj = Genre.objects.get(name=genre)
  179. tracks_in_genre = Track.objects.filter(genre=genre_obj, users=user)
  180. track_count = tracks_in_genre.count()
  181. user_artists = Artist.objects.filter(track__users=user) # use this variable to save on db queries
  182. total_artist_counts = tracks_in_genre.aggregate(counts=Count('artists'))['counts']
  183. processed_artist_counts = {}
  184. for artist in user_artists:
  185. # TODO: figure out collab problem #
  186. # artist_count = math.floor(artist.track_set.filter(genre=genre_obj,
  187. # users=user).count() * track_count / total_artist_counts)
  188. artist_count = artist.track_set.filter(genre=genre_obj,
  189. users=user).count()
  190. if artist_count > 0:
  191. processed_artist_counts[artist.name] = artist_count
  192. return processed_artist_counts
  193. # }}} get_artists_in_genre #
  194. # save_track_artists {{{ #
  195. def save_track_artists(track_dict, artist_genre_queue, user_headers):
  196. """ Update artist info before creating Track so that Track object can
  197. reference Artist object.
  198. :track_dict: response from Spotify API for track
  199. :returns: list of Artist objects in Track
  200. """
  201. track_artists = []
  202. for artist_dict in track_dict['artists']:
  203. try:
  204. artist_obj, artist_created = Artist.objects.get_or_create(
  205. id=artist_dict['id'],
  206. name=artist_dict['name'],)
  207. if artist_created:
  208. artist_genre_queue.append(artist_obj)
  209. if len(artist_genre_queue) == views.ARTIST_LIMIT:
  210. add_artist_genres(user_headers, artist_genre_queue)
  211. artist_genre_queue[:] = []
  212. # artist changed name but same id
  213. except IntegrityError as e:
  214. artist_obj = Artist.objects.get(id=artist_dict['id'])
  215. artist_obj.name = artist_dict['name']
  216. artist_obj.save()
  217. # only add/tally up artist genres if new
  218. track_artists.append(artist_obj)
  219. return track_artists
  220. # }}} save_track_artists #
  221. # get_user_header {{{ #
  222. def get_user_header(user_obj):
  223. """Returns the authorization string needed to make an API call.
  224. :user_obj: User to return the auth string for.
  225. :returns: the authorization string used for the header in a Spotify API
  226. call.
  227. """
  228. seconds_elapsed = (timezone.now() -
  229. user_obj.access_obtained_at).total_seconds()
  230. if seconds_elapsed >= user_obj.access_expires_in:
  231. req_body = {
  232. 'grant_type': 'refresh_token',
  233. 'refresh_token': user_obj.refresh_token,
  234. 'client_id': os.environ['SPOTIFY_CLIENT_ID'],
  235. 'client_secret': os.environ['SPOTIFY_CLIENT_SECRET']
  236. }
  237. token_response = requests.post('https://accounts.spotify.com/api/token',
  238. data=req_body).json()
  239. user_obj.access_token = token_response['access_token']
  240. user_obj.access_expires_in = token_response['expires_in']
  241. user_obj.save()
  242. return {'Authorization': "Bearer " + user_obj.access_token}
  243. # }}} get_user_header #
  244. # save_history_obj {{{ #
  245. def save_history_obj (user, timestamp, track):
  246. """Return (get/create) a History object with the specified parameters. Can't
  247. use built-in get_or_create since don't know auto PK.
  248. :user: User object History should be associated with
  249. :timestamp: time at which song was listened to
  250. :track: Track object for song
  251. :returns: History object
  252. """
  253. history_query = History.objects.filter(user__exact=user,
  254. timestamp__exact=timestamp)
  255. if len(history_query) == 0:
  256. history_obj = History.objects.create(user=user, timestamp=timestamp,
  257. track=track)
  258. else:
  259. history_obj = history_query[0]
  260. return history_obj
  261. # }}} save_history_obj #
  262. # get_next_history_row {{{ #
  263. def get_next_history_row(csv_reader, headers, prev_info):
  264. """Return formatted information from next row in history CSV file.
  265. :csv_reader: TODO
  266. :headers:
  267. :prev_info: history_obj_info of last row in case no more rows
  268. :returns: (boolean of if last row, dict with information of next row)
  269. """
  270. try:
  271. row = next(csv_reader)
  272. # if Track.objects.filter(id__exact=row[1]).exists():
  273. history_obj_info = {}
  274. for i in range(len(headers)):
  275. history_obj_info[headers[i]] = row[i]
  276. return False, history_obj_info
  277. except StopIteration:
  278. return True, prev_info
  279. # }}} get_next_history_row #
  280. # parse_history {{{ #
  281. def parse_history(user_secret):
  282. """Scans user's listening history and stores the information in a
  283. database.
  284. :user_secret: secret for User object who's library is being scanned.
  285. :returns: None
  286. """
  287. user_obj = User.objects.get(secret=user_secret)
  288. payload = {'limit': str(views.USER_TRACKS_LIMIT)}
  289. last_time_played = History.objects.filter(user=user_obj).aggregate(Max('timestamp'))['timestamp__max']
  290. if last_time_played is not None:
  291. payload['after'] = last_time_played.isoformat()
  292. artist_genre_queue = []
  293. user_headers = get_user_header(user_obj)
  294. history_response = requests.get(HISTORY_ENDPOINT,
  295. headers=user_headers,
  296. params=payload).json()['items']
  297. # pprint(history_response)
  298. tracks_processed = 0
  299. for track_dict in history_response:
  300. # don't associate history track with User, not necessarily in their
  301. # library
  302. # track_obj, track_created = save_track_obj(track_dict['track'],
  303. # track_artists, None)
  304. track_artists = save_track_artists(track_dict['track'], artist_genre_queue,
  305. user_headers)
  306. track_obj, track_created = save_track_obj(track_dict['track'],
  307. track_artists, None)
  308. history_obj = save_history_obj(user_obj, parse(track_dict['played_at']),
  309. track_obj)
  310. tracks_processed += 1
  311. if console_logging:
  312. print("Added history track #{}: {}".format(
  313. tracks_processed, history_obj,))
  314. if len(artist_genre_queue) > 0:
  315. add_artist_genres(user_headers, artist_genre_queue)
  316. # TODO: update track genres from History relation
  317. # update_track_genres(user_obj)
  318. print("Scanned {} history tracks for user {} at {}.".format(
  319. tracks_processed, user_obj.id, datetime.now()))
  320. # }}} get_history #