pep 8 code style

This commit is contained in:
aj 2019-06-11 11:59:24 +01:00
parent cc41e949a9
commit 35633f1396
11 changed files with 104 additions and 107 deletions

View File

@ -1,11 +1,12 @@
import spotframework.net.user as userclass from spotframework.net.user import User
import spotframework.net.network as networkclass from spotframework.net.network import Network
import spotframework.log.log as log import spotframework.log.log as log
import os import os
import datetime import datetime
def checkPhone():
def check_phone():
response = os.system("ping -c 1 -w5 " + os.environ['PHONEIP'] + " > /dev/null 2>&1") response = os.system("ping -c 1 -w5 " + os.environ['PHONEIP'] + " > /dev/null 2>&1")
log.log('checking for phone') log.log('checking for phone')
@ -14,16 +15,17 @@ def checkPhone():
else: else:
return False return False
if __name__ == '__main__': if __name__ == '__main__':
try: try:
network = networkclass.network(userclass.User()) network = Network(User())
found = False found = False
for i in range(0, 36): for i in range(0, 36):
if checkPhone(): if check_phone():
found = True found = True
break break
@ -31,17 +33,17 @@ if __name__ == '__main__':
date = datetime.datetime.now() date = datetime.datetime.now()
playlists = network.getUserPlaylists() playlists = network.get_user_playlists()
playlisturi = next((i.uri for i in playlists if i.name == date.strftime("%B %-y").lower()), os.environ['SPOTALARMURI']) playlisturi = next((i.uri for i in playlists if i.name == date.strftime("%B %-y").lower()), os.environ['SPOTALARMURI'])
network.play(playlisturi, network.getDeviceID(os.environ['SPOTALARMDEVICENAME'])) network.play(playlisturi, network.get_device_id(os.environ['SPOTALARMDEVICENAME']))
network.setShuffle(True) network.set_shuffle(True)
network.setVolume(os.environ['SPOTALARMVOLUME']) network.set_volume(os.environ['SPOTALARMVOLUME'])
network.next() network.next()
log.dumpLog() log.dump_log()
except: except:
log.dumpLog() log.dump_log()

View File

@ -1,5 +1,5 @@
import spotframework.net.user as userclass from spotframework.net.user import User
import spotframework.net.network as networkclass from spotframework.net.network import Network
import spotframework.io.csv as csvwrite import spotframework.io.csv as csvwrite
import spotframework.log.log as log import spotframework.log.log as log
@ -11,11 +11,11 @@ if __name__ == '__main__':
try: try:
network = networkclass.network(userclass.User()) network = Network(User())
playlists = network.getUserPlaylists() playlists = network.get_user_playlists()
for playlist in playlists: for playlist in playlists:
playlist.tracks = network.getPlaylistTracks(playlist.playlistid) playlist.tracks = network.get_playlist_tracks(playlist.playlistid)
path = sys.argv[1] path = sys.argv[1]
@ -27,9 +27,9 @@ if __name__ == '__main__':
os.makedirs(totalpath) os.makedirs(totalpath)
for play in playlists: for play in playlists:
csvwrite.exportPlaylist(play, totalpath) csvwrite.export_playlist(play, totalpath)
log.dumpLog() log.dump_log()
except: except:
log.dumpLog() log.dump_log()

View File

@ -1,6 +1,6 @@
import spotframework.net.const as const import spotframework.net.const as const
import spotframework.net.network as network from spotframework.net.network import Network
import spotframework.net.user as user from spotframework.net.user import User
import spotframework.log.log as log import spotframework.log.log as log
import spotframework.io.json as json import spotframework.io.json as json
import spotframework.util.monthstrings as monthstrings import spotframework.util.monthstrings as monthstrings
@ -21,9 +21,9 @@ if __name__ == '__main__':
try: try:
if os.path.exists(os.path.join(const.config_path, 'playlists.json')): if os.path.exists(os.path.join(const.config_path, 'playlists.json')):
data = json.loadJson(os.path.join(const.config_path, 'playlists.json')) data = json.load_json(os.path.join(const.config_path, 'playlists.json'))
net = network.network(user.User()) net = Network(User())
engine = PlaylistEngine(net) engine = PlaylistEngine(net)
engine.load_user_playlists() engine.load_user_playlists()
@ -80,9 +80,9 @@ if __name__ == '__main__':
if 'SLACKHOOK' in os.environ: if 'SLACKHOOK' in os.environ:
requests.post(os.environ['SLACKHOOK'], json={"text": "spot playlists: config json not found"}) requests.post(os.environ['SLACKHOOK'], json={"text": "spot playlists: config json not found"})
log.dumpLog() log.dump_log()
except Exception: except:
log.log("exception occured") log.log("exception occured")
if 'SLACKHOOK' in os.environ: if 'SLACKHOOK' in os.environ:
requests.post(os.environ['SLACKHOOK'], json={"text": "spot playlists: exception occured"}) requests.post(os.environ['SLACKHOOK'], json={"text": "spot playlists: exception occured"})
log.dumpLog() log.dump_log()

View File

@ -1,8 +1,8 @@
import spotframework.net.user as userclass from spotframework.net.user import User
import spotframework.net.network as networkclass from spotframework.net.network import Network
if __name__ == '__main__': if __name__ == '__main__':
network = networkclass.network(userclass.User()) network = Network(User())
print(network.user.access_token) print(network.user.access_token)

View File

@ -11,7 +11,7 @@ if __name__ == '__main__':
# print(data) # print(data)
network = networkclass.network(userclass.User()) network = networkclass.Network(userclass.User())
# tracks = network.getPlaylistTracks("76ynkbkyc4uq11u1FcpOyG") # tracks = network.getPlaylistTracks("76ynkbkyc4uq11u1FcpOyG")

View File

@ -14,14 +14,14 @@ class PlaylistEngine:
self.net = net self.net = net
def load_user_playlists(self): def load_user_playlists(self):
self.playlists = self.net.getUserPlaylists() self.playlists = self.net.get_user_playlists()
def append_user_playlists(self): def append_user_playlists(self):
self.playlists += self.net.getUserPlaylists() self.playlists += self.net.get_user_playlists()
def get_playlist_tracks(self, playlist): def get_playlist_tracks(self, playlist):
log.log("pulling tracks for {}".format(playlist.name)) log.log("pulling tracks for {}".format(playlist.name))
playlist.tracks = self.net.getPlaylistTracks(playlist.playlistid) playlist.tracks = self.net.get_playlist_tracks(playlist.playlistid)
def make_playlist(self, playlist_parts, processors=[]): def make_playlist(self, playlist_parts, processors=[]):
@ -65,7 +65,7 @@ class PlaylistEngine:
return self.make_playlist(recent_playlist_parts + [this_month, last_month], processors) return self.make_playlist(recent_playlist_parts + [this_month, last_month], processors)
def execute_playlist(self, tracks, playlist_id): def execute_playlist(self, tracks, playlist_id):
self.net.replacePlaylistTracks(playlist_id, [i['track']['uri'] for i in tracks]) self.net.replace_playlist_tracks(playlist_id, [i['track']['uri'] for i in tracks])
def change_description(self, playlistparts, playlist_id): def change_description(self, playlistparts, playlist_id):
self.net.changePlaylistDetails(playlist_id, description=' / '.join(playlistparts)) self.net.change_playlist_details(playlist_id, description=' / '.join(playlistparts))

View File

@ -5,7 +5,8 @@ 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 export_playlist(playlist, path, name=None):
log.log('exportPlaylist', playlist.name, path, name) log.log('exportPlaylist', playlist.name, path, name)

View File

@ -3,7 +3,8 @@ import os
import spotframework.log.log as log import spotframework.log.log as log
def loadJson(path):
def load_json(path):
log.log("load json", path) log.log("load json", path)

View File

@ -5,6 +5,7 @@ import spotframework.net.const as const
logentries = [] logentries = []
def log(entry, *args): def log(entry, *args):
timestamp = datetime.datetime.now() timestamp = datetime.datetime.now()
@ -15,7 +16,8 @@ def log(entry, *args):
print(output) print(output)
def dumpLog():
def dump_log():
if not os.path.exists(os.path.join(const.config_path, 'log')): if not os.path.exists(os.path.join(const.config_path, 'log')):
os.makedirs(os.path.join(const.config_path, 'log')) os.makedirs(os.path.join(const.config_path, 'log'))

View File

@ -1,19 +1,19 @@
import requests import requests
from . import const from . import const
from spotframework.model.playlist import Playlist as playlistclass from spotframework.model.playlist import Playlist
import spotframework.log.log as log import spotframework.log.log as log
limit = 50 limit = 50
class network: class Network:
def __init__(self, user): def __init__(self, user):
self.user = user self.user = user
def _makeGetRequest(self, method, url, params=None, headers={}): def _make_get_request(self, method, url, params=None, headers={}):
headers['Authorization'] = 'Bearer ' + self.user.access_token headers['Authorization'] = 'Bearer ' + self.user.accesstoken
req = requests.get(const.api_url + url, params=params, headers=headers) req = requests.get(const.api_url + url, params=params, headers=headers)
@ -25,9 +25,9 @@ class network:
return None return None
def _makePostRequest(self, method, url, params=None, json=None, headers={}): def _make_post_request(self, method, url, params=None, json=None, headers={}):
headers['Authorization'] = 'Bearer ' + self.user.access_token headers['Authorization'] = 'Bearer ' + self.user.accesstoken
req = requests.post(const.api_url + url, params=params, json=json, headers=headers) req = requests.post(const.api_url + url, params=params, json=json, headers=headers)
@ -39,9 +39,9 @@ class network:
return None return None
def _makePutRequest(self, method, url, params=None, json=None, headers={}): def _make_put_request(self, method, url, params=None, json=None, headers={}):
headers['Authorization'] = 'Bearer ' + self.user.access_token headers['Authorization'] = 'Bearer ' + self.user.accesstoken
req = requests.put(const.api_url + url, params=params, json=json, headers=headers) req = requests.put(const.api_url + url, params=params, json=json, headers=headers)
@ -53,14 +53,13 @@ class network:
return None return None
def get_playlist(self, playlistid, tracksonly=False):
def getPlaylist(self, playlistid, tracksonly=False):
log.log("getPlaylist", playlistid) log.log("getPlaylist", playlistid)
tracks = self.getPlaylistTracks(playlistid) tracks = self.get_playlist_tracks(playlistid)
playlist = playlistclass(playlistid) playlist = Playlist(playlistid)
playlist.tracks += tracks playlist.tracks += tracks
if not tracksonly: if not tracksonly:
@ -68,7 +67,7 @@ class network:
return playlist return playlist
def getPlaylists(self, offset=0): def get_playlists(self, offset=0):
log.log("getPlaylists", offset) log.log("getPlaylists", offset)
@ -76,35 +75,35 @@ class network:
params = {'offset': offset, 'limit': limit} params = {'offset': offset, 'limit': limit}
resp = self._makeGetRequest('getPlaylists', 'me/playlists', params=params) resp = self._make_get_request('getPlaylists', 'me/playlists', params=params)
if resp: if resp:
for responseplaylist in resp['items']: for responseplaylist in resp['items']:
playlist = playlistclass(responseplaylist['id'], responseplaylist['uri']) playlist = Playlist(responseplaylist['id'], responseplaylist['uri'])
playlist.name = responseplaylist['name'] playlist.name = responseplaylist['name']
playlist.userid = responseplaylist['owner']['id'] playlist.userid = responseplaylist['owner']['id']
playlists.append(playlist) playlists.append(playlist)
#playlists = playlists + resp['items'] # playlists = playlists + resp['items']
if resp['next']: if resp['next']:
playlists += self.getPlaylists(offset + limit) playlists += self.get_playlists(offset + limit)
return playlists return playlists
else: else:
return None return None
def getUserPlaylists(self): def get_user_playlists(self):
log.log("getUserPlaylists") 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.get_playlists()))
def getPlaylistTracks(self, playlistid, offset=0): def get_playlist_tracks(self, playlistid, offset=0):
log.log("getPlaylistTracks", playlistid, offset) log.log("getPlaylistTracks", playlistid, offset)
@ -112,35 +111,32 @@ class network:
params = {'offset': offset, 'limit': limit} params = {'offset': offset, 'limit': limit}
resp = self._makeGetRequest('getPlaylistTracks', 'playlists/{}/tracks'.format(playlistid), params=params) resp = self._make_get_request('getPlaylistTracks', 'playlists/{}/tracks'.format(playlistid), params=params)
tracks += resp['items'] tracks += resp['items']
if resp['next']: if resp['next']:
tracks += self.getPlaylistTracks(playlistid, offset + limit) tracks += self.get_playlist_tracks(playlistid, offset + limit)
return tracks return tracks
def get_available_devices(self):
def getAvailableDevices(self):
log.log("getAvailableDevices") log.log("getAvailableDevices")
return self._makeGetRequest('getAvailableDevices', 'me/player/devices') return self._make_get_request('getAvailableDevices', 'me/player/devices')
def get_player(self):
def getPlayer(self):
log.log("getPlayer") log.log("getPlayer")
return self._makeGetRequest('getPlayer', 'me/player') return self._make_get_request('getPlayer', 'me/player')
def get_device_id(self, devicename):
def getDeviceID(self, devicename):
log.log("getDeviceID", 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.get_available_devices()['devices'] if i['name'] == devicename), None)['id']
def play(self, uri, deviceid=None): def play(self, uri, deviceid=None):
@ -153,7 +149,7 @@ class network:
payload = {'context_uri': uri} payload = {'context_uri': uri}
req = self._makePutRequest('play', 'me/player/play', params=params, json=payload) req = self._make_put_request('play', 'me/player/play', params=params, json=payload)
def pause(self, deviceid=None): def pause(self, deviceid=None):
@ -164,8 +160,7 @@ class network:
else: else:
params = None params = None
req = self._makePutRequest('pause', 'me/player/pause', params=params) req = self._make_put_request('pause', 'me/player/pause', params=params)
def next(self, deviceid=None): def next(self, deviceid=None):
@ -176,10 +171,9 @@ class network:
else: else:
params = None params = None
req = self._makePostRequest('next', 'me/player/next', params=params) req = self._make_post_request('next', 'me/player/next', params=params)
def set_shuffle(self, state, deviceid=None):
def setShuffle(self, state, deviceid=None):
log.log("setShuffle", state, deviceid) log.log("setShuffle", state, deviceid)
@ -188,10 +182,9 @@ class network:
if deviceid is not None: if deviceid is not None:
params['device_id'] = deviceid params['device_id'] = deviceid
req = self._makePutRequest('setShuffle', 'me/player/shuffle', params=params) req = self._make_put_request('setShuffle', 'me/player/shuffle', params=params)
def set_volume(self, volume, deviceid=None):
def setVolume(self, volume, deviceid=None):
log.log("setVolume", volume, deviceid) log.log("setVolume", volume, deviceid)
@ -202,12 +195,12 @@ class network:
if deviceid is not None: if deviceid is not None:
params['device_id'] = deviceid params['device_id'] = deviceid
req = self._makePutRequest('setVolume', 'me/player/volume', params=params) req = self._make_put_request('setVolume', 'me/player/volume', params=params)
else: else:
log.log("setVolume", volume, "not allowed") log.log("setVolume", volume, "not allowed")
def makePlaylist(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, 'description:{}'.format(description), 'public:{}'.format(public),
'collaborative:{}'.format(collaborative)) 'collaborative:{}'.format(collaborative))
@ -219,19 +212,19 @@ class network:
if description is not None: if description is not None:
json["description"] = description json["description"] = description
req = self._makePostRequest('makePlaylist', 'users/{}/playlists'.format(self.user.username), json=json, req = self._make_post_request('makePlaylist', 'users/{}/playlists'.format(self.user.username), json=json,
headers=headers) headers=headers)
if req is not None: if req is not None:
resp = req.json() resp = req.json()
if resp is not None: if resp is not None:
playlist = playlistclass(resp["id"], uri=resp['uri'], name=resp['name'], userid=resp['owner']['id']) playlist = Playlist(resp["id"], uri=resp['uri'], name=resp['name'], userid=resp['owner']['id'])
return playlist return playlist
return None return None
def replacePlaylistTracks(self, playlistid, uris): def replace_playlist_tracks(self, playlistid, uris):
log.log("replacePlaylistTracks", playlistid) log.log("replacePlaylistTracks", playlistid)
@ -239,16 +232,16 @@ class network:
json = {"uris": uris[:100]} json = {"uris": uris[:100]}
req = self._makePutRequest('replacePlaylistTracks', 'playlists/{}/tracks'.format(playlistid), json=json, req = self._make_put_request('replacePlaylistTracks', 'playlists/{}/tracks'.format(playlistid), json=json,
headers=headers) headers=headers)
if req is not None: if req is not None:
resp = req.json() resp = req.json()
if len(uris) > 100: if len(uris) > 100:
self.addPlaylistTracks(playlistid, uris[100:]) self.add_playlist_tracks(playlistid, uris[100:])
def changePlaylistDetails(self, playlistid, name=None, public=None, collaborative=None, description=None): def change_playlist_details(self, playlistid, name=None, public=None, collaborative=None, description=None):
log.log("changePlaylistDetails", playlistid) log.log("changePlaylistDetails", playlistid)
@ -268,11 +261,11 @@ class network:
if description is not None: if description is not None:
json['description'] = description json['description'] = description
req = self._makePutRequest('changePlaylistDetails', 'playlists/{}'.format(playlistid), json=json, req = self._make_put_request('changePlaylistDetails', 'playlists/{}'.format(playlistid), json=json,
headers=headers) headers=headers)
return req return req
def addPlaylistTracks(self, playlistid, uris): def add_playlist_tracks(self, playlistid, uris):
log.log("addPlaylistTracks", playlistid) log.log("addPlaylistTracks", playlistid)
@ -280,7 +273,7 @@ class network:
json = {"uris": uris[:100]} json = {"uris": uris[:100]}
req = self._makePostRequest('addPlaylistTracks', 'playlists/{}/tracks'.format(playlistid), json=json, req = self._make_post_request('addPlaylistTracks', 'playlists/{}/tracks'.format(playlistid), json=json,
headers=headers) headers=headers)
if req is not None: if req is not None:
@ -288,4 +281,4 @@ class network:
if len(uris) > 100: if len(uris) > 100:
self.addPlaylistTracks(playlistid, uris[100:]) self.add_playlist_tracks(playlistid, uris[100:])

View File

@ -5,34 +5,32 @@ from base64 import b64encode
client_id = os.environ['SPOTCLIENT'] client_id = os.environ['SPOTCLIENT']
client_secret = os.environ['SPOTSECRET'] client_secret = os.environ['SPOTSECRET']
class User: class User:
def __init__(self): def __init__(self):
self.access_token = os.environ['SPOTACCESS'] self.accesstoken = os.environ['SPOTACCESS']
self.refresh_token = os.environ['SPOTREFRESH'] self.refreshtoken = os.environ['SPOTREFRESH']
self.refreshToken() self.refresh_token()
self.username = self.getInfo()['id'] self.username = self.get_info()['id']
def refreshToken(self): def refresh_token(self):
idsecret = b64encode(bytes(client_id + ':' + client_secret, "utf-8")).decode("ascii") idsecret = b64encode(bytes(client_id + ':' + client_secret, "utf-8")).decode("ascii")
headers = { 'Authorization' : 'Basic %s' % idsecret } headers = {'Authorization': 'Basic %s' % idsecret}
data = {"grant_type": "refresh_token", "refresh_token": self.refresh_token} data = {"grant_type": "refresh_token", "refresh_token": self.refreshtoken}
req = requests.post('https://accounts.spotify.com/api/token', data = data, headers = headers ) req = requests.post('https://accounts.spotify.com/api/token', data=data, headers=headers)
#print(req.status_code)
#print(req.text)
if req.status_code is 200: if req.status_code is 200:
self.access_token = req.json()['access_token'] self.accesstoken = req.json()['access_token']
def getInfo(self): def get_info(self):
headers = { 'Authorization' : 'Bearer %s' % self.access_token } headers = {'Authorization': 'Bearer %s' % self.accesstoken}
req = requests.get('https://api.spotify.com/v1/me', headers = headers) req = requests.get('https://api.spotify.com/v1/me', headers=headers)
return req.json() return req.json()