added new spotify playlist on new and redirect

This commit is contained in:
aj 2019-08-02 12:54:18 +01:00
parent 84bbcc21fc
commit 0d92d6b244
4 changed files with 86 additions and 6 deletions

View File

@ -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

43
spotify/api/spotify.py Normal file
View File

@ -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')

View File

@ -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 {
</tr>
<tr>
<td colSpan="2">
<button className="button full-width" onClick={this.handleSubmit}>create</button>
<input type="submit" className="button full-width" onClick={this.handleSubmit} value="create" />
</td>
</tr>
{ this.state.error &&

View File

@ -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){