Browse Source

Retrieve audio feature data from frontend

Added user_secret field to User. Set up a basic JavaScript function for
querying audio feature data from the frontend.
master
Chris Shyi 7 years ago
parent
commit
3e35e52f45
  1. 2
      .gitignore
  2. 2
      spotifyvis/models.py
  3. 28
      spotifyvis/static/spotifyvis/scripts/user_data.js
  4. 11
      spotifyvis/templates/spotifyvis/user_data.html
  5. 2
      spotifyvis/urls.py
  6. 29
      spotifyvis/views.py

2
.gitignore

@ -3,7 +3,7 @@ db.sqlite3
*.bak *.bak
.idea/ .idea/
.vscode/* .vscode/*
spotifyvis/migrations/*
api-keys.sh api-keys.sh
Pipfile Pipfile
*.txt *.txt

2
spotifyvis/models.py

@ -28,7 +28,7 @@ class User(models.Model):
verbose_name_plural = "Users" verbose_name_plural = "Users"
user_id = models.CharField(primary_key=True, max_length=MAX_ID) # the user's Spotify ID user_id = models.CharField(primary_key=True, max_length=MAX_ID) # the user's Spotify ID
# username = models.CharField(max_length=30) # User's Spotify user name, if set
user_secret = models.CharField(max_length=30, default='')
def __str__(self): def __str__(self):
return self.user_id return self.user_id

28
spotifyvis/static/spotifyvis/scripts/user_data.js

@ -0,0 +1,28 @@
/**
* Retrieves data for a specific audio feature for a certain user
* @param audioFeature: the audio feature for which data will be retrieved
* @param clientSecret: the client secret, needed for security
*/
function getAudioFeatureData(audioFeature, userSecret) {
let httpRequest = new XMLHttpRequest();
/*
* Handler for the response
*/
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
let responseData = JSON.parse(httpRequest.responseText);
// TODO: The data points need to be plotted instead
for (let data of responseData.data_points) {
console.log(data);
}
} else {
alert("There was a problem with the login request, please try again!");
}
}
};
let queryString = `/audio_features/${audioFeature}/${userSecret}`;
httpRequest.open('GET', queryString, true);
httpRequest.send();
}

11
spotifyvis/templates/spotifyvis/user_data.html

@ -16,11 +16,10 @@
<p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="#">upgrade your browser</a> to improve your experience.</p> <p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="#">upgrade your browser</a> to improve your experience.</p>
<![endif]--> <![endif]-->
<p>Logged in as {{ id }}</p> <p>Logged in as {{ id }}</p>
<h2>Display name {{ user_name }}</h2>
<ul>
{% for genre_name, genre_count in genre_dict.items %}
<li>{{ genre_name }} - {{ genre_count }}</li>
{% endfor %}
</ul>
<script src="{% static "spotifyvis/scripts/user_data.js" %}"></script>
<script>
sessionStorage.setItem('user_secret', "{{ user_secret }}");
getAudioFeatureData('instrumentalness', sessionStorage.getItem('user_secret'));
</script>
</body> </body>
</html> </html>

2
spotifyvis/urls.py

@ -10,4 +10,6 @@ urlpatterns = [
path('user_data', user_data, name='user_data'), path('user_data', user_data, name='user_data'),
path('test_db', test_db, name='test_db'), path('test_db', test_db, name='test_db'),
path('user_artists/<str:user_id>', get_artist_data, name='get_artist_data'), path('user_artists/<str:user_id>', get_artist_data, name='get_artist_data'),
path('audio_features/<str:audio_feature>/<str:client_secret>', get_audio_feature_data, name='get_audio_feature_data'),
] ]

29
spotifyvis/views.py

@ -145,12 +145,15 @@ def user_data(request):
request.session['user_id'] = user_data_response['id'] # store the user_id so it may be used to create model request.session['user_id'] = user_data_response['id'] # store the user_id so it may be used to create model
# request.session['user_name'] = user_data_response['display_name'] # request.session['user_name'] = user_data_response['display_name']
# get_or_create() returns a tuple (obj, created)
user = User.objects.get_or_create(user_id=user_data_response['id'])[0]
try:
user = User.objects.get(user_id=user_data_response['id'])
except User.DoesNotExist:
user = User(user_id=user_data_response['id'], user_secret=generate_random_string(30))
user.save()
context = { context = {
'user_name': user_data_response['display_name'],
'id': user_data_response['id'], 'id': user_data_response['id'],
'user_secret': user.user_secret,
} }
parse_library(headers, TRACKS_TO_QUERY, user) parse_library(headers, TRACKS_TO_QUERY, user)
@ -178,3 +181,23 @@ def get_artist_data(request, user_id):
processed_artist_data = [{'name': artist.name, 'num_songs': artist.num_songs} for artist in artist_counts] processed_artist_data = [{'name': artist.name, 'num_songs': artist.num_songs} for artist in artist_counts]
return JsonResponse(data=processed_artist_data, safe=False) return JsonResponse(data=processed_artist_data, safe=False)
def get_audio_feature_data(request, audio_feature, client_secret):
"""Returns all data points for a given audio feature
Args:
request: the HTTP request
audio_feature: The audio feature to be queried
client_secret: client secret, used to identify the user
"""
user = User.objects.get(user_secret=client_secret)
user_tracks = Track.objects.filter(users=user)
response_payload = {
'data_points': [],
}
for track in user_tracks:
audio_feature_obj = AudioFeatures.objects.get(track=track)
response_payload['data_points'].append(getattr(audio_feature_obj, audio_feature))
return JsonResponse(response_payload)
Loading…
Cancel
Save