From 0d92d6b24411063932e84159e023f1f3eccea92f Mon Sep 17 00:00:00 2001 From: aj Date: Fri, 2 Aug 2019 12:54:18 +0100 Subject: [PATCH] added new spotify playlist on new and redirect --- spotify/api/api.py | 35 +++++++++++++++++++++++--- spotify/api/spotify.py | 43 ++++++++++++++++++++++++++++++++ src/js/Playlist/NewPlaylist.js | 7 ++++-- src/js/Playlist/PlaylistsView.js | 7 +++++- 4 files changed, 86 insertions(+), 6 deletions(-) create mode 100644 spotify/api/spotify.py diff --git a/spotify/api/api.py b/spotify/api/api.py index 6c42ac3..8138514 100644 --- a/spotify/api/api.py +++ b/spotify/api/api.py @@ -1,11 +1,15 @@ from flask import Blueprint, session, request, jsonify from google.cloud import firestore +from google.cloud import pubsub_v1 from werkzeug.security import check_password_hash, generate_password_hash import spotify.api.database as database blueprint = Blueprint('api', __name__) db = firestore.Client() +publisher = pubsub_v1.PublisherClient() + +run_playlist_topic_path = publisher.topic_path('sarsooxyz', 'run_user_playlist') @blueprint.route('/playlists', methods=['GET']) @@ -82,10 +86,14 @@ def playlist(): # if playlist_id is None or playlist_shuffle is None: # return jsonify({'error': 'parts and id required'}), 400 + from spotify.api.spotify import create_playlist as create_playlist + + new_playlist_id = create_playlist(session['username'], playlist_name) + playlists.add({ 'name': playlist_name, 'parts': playlist_parts, - 'playlist_id': playlist_id, + 'playlist_id': new_playlist_id, 'shuffle': playlist_shuffle }) @@ -119,8 +127,6 @@ def playlist(): return jsonify({"message": 'playlist updated', "status": "success"}), 200 - - else: return jsonify({'error': 'not logged in'}), 401 @@ -177,3 +183,26 @@ def change_password(): else: return jsonify({'error': 'not logged in'}), 401 + + +@blueprint.route('/playlist/run', methods=['GET']) +def run_playlist(): + + if 'username' in session: + + playlist_name = request.args.get('name', None) + + if playlist_name: + + data = u'{}'.format(playlist_name) + data = data.encode('utf-8') + + publisher.publish(run_playlist_topic_path, data=data, username=session['username']) + + return jsonify({'message': 'execution requested', 'status': 'success'}), 200 + + else: + return jsonify({"error": 'no name requested'}), 400 + + else: + return jsonify({'error': 'not logged in'}), 401 diff --git a/spotify/api/spotify.py b/spotify/api/spotify.py new file mode 100644 index 0000000..9bd3f33 --- /dev/null +++ b/spotify/api/spotify.py @@ -0,0 +1,43 @@ +import requests +from base64 import b64encode +from google.cloud import firestore + +db = firestore.Client() + + +def create_playlist(username, name): + + users = [i for i in db.collection(u'spotify_users').where(u'username', u'==', username).stream()] + + if len(users) == 1: + + user_dict = users[0].to_dict() + spotify_keys = db.document('key/spotify').get().to_dict() + + idsecret = b64encode(bytes(spotify_keys['clientid'] + ':' + spotify_keys['clientsecret'], "utf-8")).decode("ascii") + + token_headers = {'Authorization': 'Basic %s' % idsecret} + headers = {"Content-Type": "application/json"} + + data = {"grant_type": "refresh_token", "refresh_token": user_dict['refresh_token']} + + token_req = requests.post('https://accounts.spotify.com/api/token', data=data, headers=token_headers) + + if 200 <= token_req.status_code < 300: + accesstoken = token_req.json()['access_token'] + + json = {"name": name, "public": True, "collaborative": False} + + headers['Authorization'] = 'Bearer ' + accesstoken + + info_id = requests.get('https://api.spotify.com/v1/me', headers=headers).json()['id'] + + play_req = requests.post(f'https://api.spotify.com/v1/users/{info_id}/playlists', json=json, headers=headers) + + resp = play_req.json() + + return resp["id"] + + else: + print(token_req.status_code) + raise Exception('failed to get access token') diff --git a/src/js/Playlist/NewPlaylist.js b/src/js/Playlist/NewPlaylist.js index b71bf67..5840cb0 100644 --- a/src/js/Playlist/NewPlaylist.js +++ b/src/js/Playlist/NewPlaylist.js @@ -1,4 +1,5 @@ import React, { Component } from "react"; +import { BrowserRouter as Redirect } from "react-router-dom"; const axios = require('axios'); class NewPlaylist extends Component { @@ -33,7 +34,9 @@ class NewPlaylist extends Component { type: this.state.type, }).catch((error) => { console.log(error); - }) + }).finally(() => { + window.location.href = "/app/playlists"; + }); }else{ this.setState({ error: true, @@ -74,7 +77,7 @@ class NewPlaylist extends Component { - + { this.state.error && diff --git a/src/js/Playlist/PlaylistsView.js b/src/js/Playlist/PlaylistsView.js index ca3f0ea..2a12e02 100644 --- a/src/js/Playlist/PlaylistsView.js +++ b/src/js/Playlist/PlaylistsView.js @@ -26,7 +26,12 @@ class PlaylistsView extends Component { } handleRunPlaylist(name, event){ - + axios.get('/api/playlist/run', {params: {name: name}}) + .then((response) => { + console.log(response); + }).catch((error) => { + console.log(error); + }); } handleDeletePlaylist(name, event){