integrated cloud function, removed implied environment variables

This commit is contained in:
aj 2019-08-02 12:02:24 +01:00
parent 5aa8e47ddf
commit c221025c5f
11 changed files with 143 additions and 53 deletions

21
.gcloudignore Normal file
View File

@ -0,0 +1,21 @@
# This file specifies files that are *not* uploaded to Google Cloud Platform
# using gcloud. It follows the same syntax as .gitignore, with the addition of
# "#!include" directives (which insert the entries of the given .gitignore-style
# file at that point).
#
# For more information, run:
# $ gcloud topic gcloudignore
#
.gcloudignore
# If you would like to upload your .git directory, .gitignore file or files
# from your .gitignore file, remove the corresponding line
# below:
.git
.gitignore
env
.idea
.spot
node_modules
#!include:.gitignore

View File

@ -22,7 +22,10 @@ if __name__ == '__main__':
try: try:
network = Network(User()) network = Network(User(os.environ['SPOTCLIENT'],
os.environ['SPOTSECRET'],
os.environ['SPOTACCESS'],
os.environ['SPOTREFRESH']))
found = False found = False

View File

@ -11,7 +11,10 @@ if __name__ == '__main__':
try: try:
network = Network(User()) network = Network(User(os.environ['SPOTCLIENT'],
os.environ['SPOTSECRET'],
os.environ['SPOTACCESS'],
os.environ['SPOTREFRESH']))
playlists = network.get_user_playlists() playlists = network.get_user_playlists()
for playlist in playlists: for playlist in playlists:

View File

@ -104,7 +104,10 @@ def go():
log.log('none to execute, terminating') log.log('none to execute, terminating')
return return
net = Network(User()) net = Network(User(os.environ['SPOTCLIENT'],
os.environ['SPOTSECRET'],
os.environ['SPOTACCESS'],
os.environ['SPOTREFRESH']))
engine = PlaylistEngine(net) engine = PlaylistEngine(net)
engine.load_user_playlists() engine.load_user_playlists()

View File

@ -1,8 +1,13 @@
from spotframework.net.user import User from spotframework.net.user import User
from spotframework.net.network import Network from spotframework.net.network import Network
import os
if __name__ == '__main__': if __name__ == '__main__':
network = Network(User()) network = Network(User(os.environ['SPOTCLIENT'],
os.environ['SPOTSECRET'],
os.environ['SPOTACCESS'],
os.environ['SPOTREFRESH']))
print(network.user.access_token) print(network.user.access_token)

36
main.py
View File

@ -1,36 +1,14 @@
import spotframework.net.user as userclass
import spotframework.net.network as networkclass
import spotframework.net.network as playlist
import spotframework.io.json as json
if __name__ == '__main__': def run_user_playlist(event, context):
print('hello world')
# data = json.loadJson('.spot/config.json') import base64
# print(data) name = base64.b64decode(event['data']).decode('utf-8')
username = event['attributes']['username']
network = networkclass.Network(userclass.User()) print(f'{username} - {name}')
# tracks = network.getPlaylistTracks("76ynkbkyc4uq11u1FcpOyG") from spotframework.google.run_user_playlist import run_user_playlist as run
# print(tracks[0]) run(username, name)
# network.setVolume(105)
# network.getPlaylist('000Eh2vXzYGgrEFlgcWZj3')
#
# playlist = network.makePlaylist('new playlist')
#
# network.addPlaylistTracks(playlist.playlistid, ["spotify:track:78lC4VmDVSSsCUQ0VNdQva"]*149)
#
# network.replacePlaylistTracks(playlist.playlistid, ["spotify:track:78lC4VmDVSSsCUQ0VNdQva"] * 160)
#
# network.pause()
#network.getPlayer()
# playlists = network.getUserPlaylists()
# for playlist in playlists:
# print(playlist.name + ' ' + playlist.playlistid)

18
requirements.txt Normal file
View File

@ -0,0 +1,18 @@
cachetools==3.1.1
certifi==2019.3.9
chardet==3.0.4
google-api-core==1.14.2
google-auth==1.6.3
google-cloud-core==1.0.3
google-cloud-firestore==1.3.0
googleapis-common-protos==1.6.0
grpcio==1.22.0
idna==2.8
protobuf==3.9.0
pyasn1==0.4.6
pyasn1-modules==0.2.5
pytz==2019.2
requests==2.21.0
rsa==4.0
six==1.12.0
urllib3==1.24.3

View File

View File

@ -0,0 +1,65 @@
from google.cloud import firestore
from spotframework.engine.playlistengine import PlaylistEngine
from spotframework.engine.filter.shuffle import Shuffle
from spotframework.engine.filter.sortreversereleasedate import SortReverseReleaseDate
from spotframework.engine.filter.deduplicatebyid import DeduplicateByID
from spotframework.net.network import Network
from spotframework.net.user import User
db = firestore.Client()
def run_user_playlist(username, playlist_name):
users = db.collection(u'spotify_users').where(u'username', u'==', username).stream()
users = [i for i in users]
if len(users) == 1:
user_dict = users[0].to_dict()
playlist_collection = db.collection(u'spotify_users', u'{}'.format(users[0].id), 'playlists')
print(user_dict['access_token'], user_dict['refresh_token'])
playlists = [i for i in playlist_collection.where(u'name', u'==', playlist_name).stream()]
if len(playlists) == 1:
playlist_dict = playlists[0].to_dict()
if playlist_dict['playlist_id'] is None:
raise Exception('no playlist id to populate')
if len(playlist_dict['parts']) == 0:
raise Exception('no playlists to use for creation')
spotify_keys = db.document('key/spotify').get().to_dict()
net = Network(User(spotify_keys['clientid'],
spotify_keys['clientsecret'],
user_dict['access_token'],
user_dict['refresh_token']))
engine = PlaylistEngine(net)
engine.load_user_playlists()
processors = [DeduplicateByID()]
if playlist_dict['shuffle'] is True:
processors.append(Shuffle())
else:
processors.append(SortReverseReleaseDate())
tracks = engine.make_playlist(playlist_dict['parts'], processors)
engine.execute_playlist(tracks, playlist_dict['playlist_id'])
engine.change_description(playlist_dict['parts'], playlist_dict['playlist_id'])
else:
raise Exception('multiple playlists found')
else:
raise Exception('more than one user found')

View File

@ -111,7 +111,7 @@ class Network:
params = {'offset': offset, 'limit': limit} params = {'offset': offset, 'limit': limit}
resp = self._make_get_request('getPlaylistTracks', 'playlists/{}/tracks'.format(playlistid), params=params) resp = self._make_get_request('getPlaylistTracks', f'playlists/{playlistid}/tracks', params=params)
tracks += resp['items'] tracks += resp['items']
@ -202,8 +202,7 @@ class Network:
def make_playlist(self, name, description=None, public=True, collaborative=False): def make_playlist(self, name, description=None, public=True, collaborative=False):
log.log("makePlaylist", name, 'description:{}'.format(description), 'public:{}'.format(public), log.log("makePlaylist", name, f'description:{description}', f'public:{public}', f'collaborative:{collaborative}')
'collaborative:{}'.format(collaborative))
headers = {"Content-Type": "application/json"} headers = {"Content-Type": "application/json"}
@ -212,8 +211,7 @@ class Network:
if description is not None: if description is not None:
json["description"] = description json["description"] = description
req = self._make_post_request('makePlaylist', 'users/{}/playlists'.format(self.user.username), json=json, req = self._make_post_request('makePlaylist', f'users/{self.user.username}/playlists', json=json, headers=headers)
headers=headers)
if req is not None: if req is not None:
resp = req.json() resp = req.json()
@ -232,8 +230,7 @@ class Network:
json = {"uris": uris[:100]} json = {"uris": uris[:100]}
req = self._make_put_request('replacePlaylistTracks', 'playlists/{}/tracks'.format(playlistid), json=json, req = self._make_put_request('replacePlaylistTracks', f'playlists/{playlistid}/tracks', json=json, headers=headers)
headers=headers)
if req is not None: if req is not None:
resp = req.json() resp = req.json()
@ -261,8 +258,7 @@ class Network:
if description is not None: if description is not None:
json['description'] = description json['description'] = description
req = self._make_put_request('changePlaylistDetails', 'playlists/{}'.format(playlistid), json=json, req = self._make_put_request('changePlaylistDetails', f'playlists/{playlistid}', json=json, headers=headers)
headers=headers)
return req return req
def add_playlist_tracks(self, playlistid, uris): def add_playlist_tracks(self, playlistid, uris):
@ -273,8 +269,7 @@ class Network:
json = {"uris": uris[:100]} json = {"uris": uris[:100]}
req = self._make_post_request('addPlaylistTracks', 'playlists/{}/tracks'.format(playlistid), json=json, req = self._make_post_request('addPlaylistTracks', f'playlists/{playlistid}/tracks', json=json, headers=headers)
headers=headers)
if req is not None: if req is not None:
resp = req.json() resp = req.json()

View File

@ -1,16 +1,15 @@
import os
import requests import requests
from base64 import b64encode from base64 import b64encode
client_id = os.environ['SPOTCLIENT']
client_secret = os.environ['SPOTSECRET']
class User: class User:
def __init__(self): def __init__(self, client_id, client_secret, access_token, refresh_token):
self.accesstoken = os.environ['SPOTACCESS'] self.accesstoken = access_token
self.refreshtoken = os.environ['SPOTREFRESH'] self.refreshtoken = refresh_token
self.client_id = client_id
self.client_secret = client_secret
self.refresh_token() self.refresh_token()
@ -18,7 +17,7 @@ class User:
def refresh_token(self): def refresh_token(self):
idsecret = b64encode(bytes(client_id + ':' + client_secret, "utf-8")).decode("ascii") idsecret = b64encode(bytes(self.client_id + ':' + self.client_secret, "utf-8")).decode("ascii")
headers = {'Authorization': 'Basic %s' % idsecret} headers = {'Authorization': 'Basic %s' % idsecret}
data = {"grant_type": "refresh_token", "refresh_token": self.refreshtoken} data = {"grant_type": "refresh_token", "refresh_token": self.refreshtoken}