moved request to separate message, added logging

This commit is contained in:
aj 2019-05-14 12:39:17 +01:00
parent dce90e1ccc
commit a12fc26a4f
10 changed files with 133 additions and 63 deletions

1
.gitignore vendored
View File

@ -2,3 +2,4 @@ env
__pycache__ __pycache__
*.csv *.csv
.idea .idea
.spot

View File

@ -1,7 +1,9 @@
import spotframework.net.user as userclass import spotframework.net.user as userclass
import spotframework.net.network as networkclass import spotframework.net.network as networkclass
import spotframework.log.log as log
import os, datetime import os
import datetime
def checkPhone(): def checkPhone():
@ -35,3 +37,5 @@ if __name__ == '__main__':
network.setShuffle(True) network.setShuffle(True)
network.setVolume(os.environ['SPOTALARMVOLUME']) network.setVolume(os.environ['SPOTALARMVOLUME'])
network.next() network.next()
log.dumpLog()

View File

@ -1,8 +1,11 @@
import spotframework.net.user as userclass import spotframework.net.user as userclass
import spotframework.net.network as networkclass import spotframework.net.network as networkclass
import spotframework.io.csv as csvwrite import spotframework.io.csv as csvwrite
import spotframework.log.log as log
import sys, datetime, os import sys
import datetime
import os
if __name__ == '__main__': if __name__ == '__main__':
@ -23,4 +26,5 @@ if __name__ == '__main__':
for play in playlists: for play in playlists:
csvwrite.exportPlaylist(play, totalpath) csvwrite.exportPlaylist(play, totalpath)
print(play.name + ' exported')
log.dumpLog()

10
main.py
View File

@ -7,10 +7,12 @@ if __name__ == '__main__':
network = networkclass.network(userclass.User()) network = networkclass.network(userclass.User())
#network.getPlaylist('000Eh2vXzYGgrEFlgcWZj3') # network.setVolume(105)
network.getPlaylist('000Eh2vXzYGgrEFlgcWZj3')
#network.getPlayer() #network.getPlayer()
playlists = network.getUserPlaylists() # playlists = network.getUserPlaylists()
for playlist in playlists: # for playlist in playlists:
print(playlist.name + ' ' + playlist.playlistid) # print(playlist.name + ' ' + playlist.playlistid)

View File

@ -1,10 +1,14 @@
import csv import csv
import datetime import datetime
import spotframework.log.log as log
headers = ['name', 'artist', 'album', 'album artist', 'added', 'track id', 'album id', 'added by'] headers = ['name', 'artist', 'album', 'album artist', 'added', 'track id', 'album id', 'added by']
def exportPlaylist(playlist, path, name=None): def exportPlaylist(playlist, path, name=None):
log.log('exportPlaylist', playlist.name, path, name)
date = str(datetime.datetime.now()) date = str(datetime.datetime.now())
if name is None: if name is None:

View File

26
spotframework/log/log.py Normal file
View File

@ -0,0 +1,26 @@
import os
import datetime
import spotframework.net.const as const
logentries = []
def log(entry, *args):
timestamp = datetime.datetime.now()
output = str(timestamp) + ' ' + entry + ' ' + ' '.join([str(i) for i in args])
logentries.append(output)
print(output)
def dumpLog():
if not os.path.exists(os.path.join(const.config_path, 'log')):
os.makedirs(os.path.join(const.config_path, 'log'))
with open(os.path.join(const.config_path, 'log', '{}_log'.format(datetime.datetime.now().strftime('%m_%y'))), 'a+') as file_obj:
for entry in logentries:
file_obj.write(entry + '\n')

View File

@ -2,7 +2,7 @@
class playlist: class playlist:
def __init__(self, playlistid, uri, name=None, userid=None): def __init__(self, playlistid, uri=None, name=None, userid=None):
self.tracks = [] self.tracks = []
self.name = name self.name = name
self.playlistid = playlistid self.playlistid = playlistid

View File

@ -1,3 +1,4 @@
api_url = 'https://api.spotify.com/v1/' api_url = 'https://api.spotify.com/v1/'
config_path = '.spot'

View File

@ -1,6 +1,7 @@
import requests import requests
from . import const from . import const
from spotframework.model.playlist import playlist as playlistclass from spotframework.model.playlist import playlist as playlistclass
import spotframework.log.log as log
limit = 50 limit = 50
@ -10,8 +11,47 @@ class network:
def __init__(self, user): def __init__(self, user):
self.user = user self.user = user
def _makeGetRequest(self, method, url, params=None, headers=None):
req = requests.get(const.api_url + url, params=params, headers=headers)
if 200 <= req.status_code < 300:
log.log(method, 'get', str(req.status_code))
return req.json()
else:
log.log(method, 'get', str(req.status_code), req.text)
return None
def _makePostRequest(self, method, url, params=None, headers=None):
req = requests.post(const.api_url + url, params=params, headers=headers)
if 200 <= req.status_code < 300:
log.log(method, 'post', str(req.status_code))
return req.text
else:
log.log(method, 'post', str(req.status_code), req.text)
return None
def _makePutRequest(self, method, url, params=None, json=None, headers=None):
req = requests.put(const.api_url + url, params=params, json=json, headers=headers)
if 200 <= req.status_code < 300:
log.log(method, 'put', str(req.status_code))
return req.text
else:
log.log(method, 'put', str(req.status_code), req.text)
return None
def getPlaylist(self, playlistid, tracksonly=False): def getPlaylist(self, playlistid, tracksonly=False):
print('getting ' + playlistid)
log.log("getPlaylist", playlistid)
# print('getting ' + playlistid)
tracks = self.getPlaylistTracks(playlistid) tracks = self.getPlaylistTracks(playlistid)
@ -24,22 +64,19 @@ class network:
return playlist return playlist
def getPlaylists(self, offset=0): def getPlaylists(self, offset=0):
print('getting user playlists {}'.format(offset))
log.log("getPlaylists", offset)
# print('getting user playlists {}'.format(offset))
headers = {'Authorization': 'Bearer ' + self.user.access_token} headers = {'Authorization': 'Bearer ' + self.user.access_token}
playlists = [] playlists = []
params = {'offset': offset, 'limit': limit} params = {'offset': offset, 'limit': limit}
req = requests.get(const.api_url + 'me/playlists', params=params, headers=headers)
#print(req.text) resp = self._makeGetRequest('getPlaylists', 'me/playlists', params=params, headers=headers)
if req.status_code == 200: if resp:
#print(req.text)
resp = req.json()
for responseplaylist in resp['items']: for responseplaylist in resp['items']:
@ -54,8 +91,6 @@ class network:
if resp['next']: if resp['next']:
playlists += self.getPlaylists(offset + limit) playlists += self.getPlaylists(offset + limit)
#print(req.text)
return playlists return playlists
else: else:
@ -63,66 +98,58 @@ class network:
def getUserPlaylists(self): def getUserPlaylists(self):
log.log("getUserPlaylists")
return list(filter(lambda x: x.userid == self.user.username, self.getPlaylists())) return list(filter(lambda x: x.userid == self.user.username, self.getPlaylists()))
def getPlaylistTracks(self, playlistid, offset=0): def getPlaylistTracks(self, playlistid, offset=0):
headers = {'Authorization': 'Bearer ' + self.user.access_token} log.log("getPlaylistTracks", playlistid, offset)
print('getting playlist tracks {} {}'.format(playlistid, offset)) headers = {'Authorization': 'Bearer ' + self.user.access_token}
tracks = [] tracks = []
params = {'offset': offset, 'limit': limit} params = {'offset': offset, 'limit': limit}
req = requests.get(const.api_url + 'playlists/{}/tracks'.format(playlistid), params=params, headers=headers)
#print(req.text) resp = self._makeGetRequest('getPlaylistTracks', 'playlists/{}/tracks'.format(playlistid), params, headers)
if req.status_code == 200: tracks += resp['items']
#print(req.text) if resp['next']:
resp = req.json() tracks += self.getPlaylistTracks(playlistid, offset + limit)
tracks += resp['items'] return tracks
if resp['next']:
tracks += self.getPlaylistTracks(playlistid, offset + limit)
#print(req.text)
return tracks
else:
raise ValueError("Couldn't Pull Playlist " + str(playlistid) + ' ' + str(req.status_code))
def getAvailableDevices(self): def getAvailableDevices(self):
log.log("getAvailableDevices")
headers = {'Authorization': 'Bearer ' + self.user.access_token} headers = {'Authorization': 'Bearer ' + self.user.access_token}
req = requests.get(const.api_url + 'me/player/devices', headers=headers) return self._makeGetRequest('getAvailableDevices', 'me/player/devices', headers=headers)
if req.status_code == 200:
return req.json()
else:
return None
def getPlayer(self): def getPlayer(self):
log.log("getPlayer")
headers = {'Authorization': 'Bearer ' + self.user.access_token} headers = {'Authorization': 'Bearer ' + self.user.access_token}
req = requests.get(const.api_url + 'me/player', headers=headers) return self._makeGetRequest('getPlayer', 'me/player', headers=headers)
if req.status_code == 200:
return req.json()
else:
return None
def getDeviceID(self, devicename): def getDeviceID(self, devicename):
log.log("getDeviceID", devicename)
return next((i for i in self.getAvailableDevices()['devices'] if i['name'] == devicename), None)['id'] return next((i for i in self.getAvailableDevices()['devices'] if i['name'] == devicename), None)['id']
def play(self, uri, deviceid=None): def play(self, uri, deviceid=None):
log.log("play", uri, deviceid)
headers = {'Authorization': 'Bearer ' + self.user.access_token} headers = {'Authorization': 'Bearer ' + self.user.access_token}
if deviceid is not None: if deviceid is not None:
@ -132,13 +159,13 @@ class network:
payload = {'context_uri': uri} payload = {'context_uri': uri}
req = requests.put(const.api_url + 'me/player/play', params=params, json=payload, headers=headers) req = self._makePutRequest('play', 'me/player/play', params=params, json=payload, headers=headers)
print(req.status_code)
print(req.text)
def next(self, deviceid=None): def next(self, deviceid=None):
log.log("next", deviceid)
headers = {'Authorization': 'Bearer ' + self.user.access_token} headers = {'Authorization': 'Bearer ' + self.user.access_token}
if deviceid is not None: if deviceid is not None:
@ -146,13 +173,13 @@ class network:
else: else:
params = None params = None
req = requests.post(const.api_url + 'me/player/next', params=params, headers=headers) req = self._makePostRequest('next', 'me/player/next', params=params, headers=headers)
print(req.status_code)
print(req.text)
def setShuffle(self, state, deviceid=None): def setShuffle(self, state, deviceid=None):
log.log("setShuffle", state, deviceid)
headers = {'Authorization': 'Bearer ' + self.user.access_token} headers = {'Authorization': 'Bearer ' + self.user.access_token}
params = {'state': str(state).lower()} params = {'state': str(state).lower()}
@ -160,21 +187,22 @@ class network:
if deviceid is not None: if deviceid is not None:
params['device_id'] = deviceid params['device_id'] = deviceid
req = requests.put(const.api_url + 'me/player/shuffle', params=params, headers=headers) req = self._makePutRequest('setShuffle', 'me/player/shuffle', params=params, headers=headers)
print(req.status_code)
print(req.text)
def setVolume(self, volume, deviceid=None): def setVolume(self, volume, deviceid=None):
headers = {'Authorization': 'Bearer ' + self.user.access_token} log.log("setVolume", volume, deviceid)
params = {'volume_percent': volume} if 0 <= int(volume) <= 100:
headers = {'Authorization': 'Bearer ' + self.user.access_token}
if deviceid is not None: params = {'volume_percent': volume}
params['device_id'] = deviceid
req = requests.put(const.api_url + 'me/player/volume', params=params, headers=headers) if deviceid is not None:
params['device_id'] = deviceid
print(req.status_code) req = self._makePutRequest('setVolume', 'me/player/volume', params=params, headers=headers)
print(req.text)
else:
log.log("setVolume", volume, "not allowed")