replace exception error logs with exception method, update model for csv export

This commit is contained in:
aj 2020-07-01 10:30:26 +01:00
parent 3e679d37ac
commit 030708e12d
9 changed files with 106 additions and 65 deletions

View File

@ -1,5 +1,5 @@
from spotframework.net.user import NetworkUser from spotframework.net.user import NetworkUser
from spotframework.net.network import Network from spotframework.net.network import Network, SpotifyNetworkException
import spotframework.io.csv as csvwrite import spotframework.io.csv as csvwrite
import sys import sys
@ -32,22 +32,30 @@ if __name__ == '__main__':
network = Network(NetworkUser(client_id=os.environ['SPOT_CLIENT'], network = Network(NetworkUser(client_id=os.environ['SPOT_CLIENT'],
client_secret=os.environ['SPOT_SECRET'], client_secret=os.environ['SPOT_SECRET'],
refresh_token=os.environ['SPOT_REFRESH'])).refresh_access_token() refresh_token=os.environ['SPOT_REFRESH'])).refresh_access_token()
playlists = network.get_user_playlists()
for playlist in playlists: try:
playlist.tracks = network.get_playlist_tracks(playlist.uri) playlists = network.get_user_playlists(response_limit=5)
path = sys.argv[1] for playlist in playlists:
try:
playlist.tracks = network.get_playlist_tracks(playlist.uri)
except SpotifyNetworkException:
logger.exception(f'error occured during {playlist.name} track retrieval')
datepath = str(datetime.datetime.now()).split(' ')[0].replace('-', '/') path = sys.argv[1]
totalpath = os.path.join(path, datepath) datepath = str(datetime.datetime.now()).split(' ')[0].replace('-', '/')
pathdir = os.path.dirname(totalpath)
if not os.path.exists(totalpath):
os.makedirs(totalpath)
for play in playlists: totalpath = os.path.join(path, datepath)
csvwrite.export_playlist(play, totalpath) pathdir = os.path.dirname(totalpath)
if not os.path.exists(totalpath):
os.makedirs(totalpath)
for play in playlists:
csvwrite.export_playlist(play, totalpath)
except SpotifyNetworkException:
logger.exception('error occured during user playlist retrieval')
# except Exception as e: # except Exception as e:
# logger.exception(f'exception occured') # logger.exception(f'exception occured')

View File

@ -1,7 +1,7 @@
certifi==2019.11.28 certifi==2020.6.20
chardet==3.0.4 chardet==3.0.4
Click==7.0 click==7.1.2
idna==2.8 idna==2.10
requests==2.22.0 requests==2.24.0
tabulate==0.8.6 tabulate==0.8.7
urllib3==1.25.7 urllib3==1.25.9

View File

@ -4,7 +4,7 @@ import logging
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
headers = ['name', 'artist', 'album', 'album artist', 'added', 'track id', 'album id', 'added by'] headers = ['name', 'artist', 'album', 'album artist', 'added', 'track id', 'album id', 'artist id', 'added by']
def export_playlist(playlist, path, name=None): def export_playlist(playlist, path, name=None):
@ -23,12 +23,13 @@ def export_playlist(playlist, path, name=None):
for track in playlist.tracks: for track in playlist.tracks:
writer.writerow({ writer.writerow({
'name': track.name, 'name': track.track.name,
'album': track.album.name, 'album': track.track.album.name,
'added': track.added_at, 'added': track.added_at,
'track id': track.uri.object_id if track.uri is not None else 'none', 'track id': track.track.uri.object_id if track.track.uri is not None else 'none',
'album id': track.album.uri.object_id if track.album.uri is not None else 'none', 'album id': track.track.album.uri.object_id if track.track.album.uri is not None else 'none',
'added by': track.added_by.username, 'artist id': ', '.join(x.uri.object_id for x in track.track.artists),
'album artist': ', '.join(x.name for x in track.album.artists), 'added by': track.added_by.id,
'artist': ', '.join(x.name for x in track.artists) 'album artist': ', '.join(x.name for x in track.track.album.artists),
'artist': ', '.join(x.name for x in track.track.artists)
}) })

View File

@ -23,8 +23,8 @@ class Listener:
self.now_playing = None self.now_playing = None
try: try:
self.now_playing: Optional[CurrentlyPlaying] = net.get_player() self.now_playing: Optional[CurrentlyPlaying] = net.get_player()
except SpotifyNetworkException as e: except SpotifyNetworkException:
logger.error(f'error occured retrieving currently playing - {e}') logger.exception(f'error occured retrieving currently playing')
self.on_playback_change = [] self.on_playback_change = []
@ -45,8 +45,8 @@ class Listener:
else: else:
self.now_playing = live_now_playing self.now_playing = live_now_playing
except SpotifyNetworkException as e: except SpotifyNetworkException:
logger.error(f'error occured retrieving currently playing - {e}') logger.exception(f'error occured retrieving currently playing')
def update_recent_tracks(self): def update_recent_tracks(self):
"""retrieve recently played tracks and merge with previously stored""" """retrieve recently played tracks and merge with previously stored"""
@ -62,5 +62,5 @@ class Listener:
if self.max_recent_tracks is not None: if self.max_recent_tracks is not None:
self.recent_tracks = self.recent_tracks[-self.max_recent_tracks:] self.recent_tracks = self.recent_tracks[-self.max_recent_tracks:]
except SpotifyNetworkException as e: except SpotifyNetworkException:
logger.error(f'error occured retrieving recent tracks - {e}') logger.exception(f'error occured retrieving recent tracks')

View File

@ -119,6 +119,23 @@ class SimplifiedPlaylist:
class FullPlaylist(SimplifiedPlaylist): class FullPlaylist(SimplifiedPlaylist):
followers: dict = None followers: dict = None
def __post_init__(self):
if isinstance(self.tracks, dict):
self.tracks = []
if isinstance(self.uri, str):
self.uri = Uri(self.uri)
if self.uri:
if self.uri.object_type != Uri.ObjectType.playlist:
raise TypeError('provided uri not for a playlist')
if all((isinstance(i, dict) for i in self.images)):
self.images = [Image(**i) for i in self.images]
if isinstance(self.owner, dict):
self.owner = PublicUser(**self.owner)
def __str__(self): def __str__(self):
prefix = f'\n==={self.name}===\n\n' if self.name is not None else '' prefix = f'\n==={self.name}===\n\n' if self.name is not None else ''
prefix += f'uri: {self.uri}\n' if self.uri is not None else '' prefix += f'uri: {self.uri}\n' if self.uri is not None else ''

View File

@ -1,5 +1,5 @@
from __future__ import annotations from __future__ import annotations
from typing import TYPE_CHECKING, Union, List from typing import Union, List
from datetime import datetime from datetime import datetime
from dataclasses import dataclass, field from dataclasses import dataclass, field
@ -9,8 +9,7 @@ from enum import Enum
import spotframework.model.album import spotframework.model.album
import spotframework.model.artist import spotframework.model.artist
import spotframework.model.service import spotframework.model.service
if TYPE_CHECKING: import spotframework.model.user
from spotframework.model.user import PublicUser
@dataclass @dataclass
@ -105,7 +104,7 @@ class LibraryTrack:
@dataclass @dataclass
class PlaylistTrack: class PlaylistTrack:
added_at: datetime added_at: datetime
added_by: PublicUser added_by: spotframework.model.user.PublicUser
is_local: bool is_local: bool
primary_color: str primary_color: str
track: TrackFull track: TrackFull
@ -115,6 +114,9 @@ class PlaylistTrack:
if isinstance(self.track, dict): if isinstance(self.track, dict):
self.track = TrackFull(**self.track) self.track = TrackFull(**self.track)
if isinstance(self.added_by, dict):
self.added_by = spotframework.model.user.PublicUser(**self.added_by)
if isinstance(self.added_at, str): if isinstance(self.added_at, str):
self.added_at = datetime.strptime(self.added_at, '%Y-%m-%dT%H:%M:%S%z') self.added_at = datetime.strptime(self.added_at, '%Y-%m-%dT%H:%M:%S%z')

View File

@ -9,10 +9,11 @@ class PublicUser:
href: str href: str
id: str id: str
uri: Union[str, Uri] uri: Union[str, Uri]
display_name: str
external_urls: dict external_urls: dict
type: str type: str
display_name: str = None
email: str = None
followers: dict = field(default_factory=dict) followers: dict = field(default_factory=dict)
images: List[Image] = field(default_factory=list) images: List[Image] = field(default_factory=list)
@ -28,7 +29,7 @@ class PublicUser:
self.images = [Image(**i) for i in self.images] self.images = [Image(**i) for i in self.images]
def __str__(self): def __str__(self):
return f'{self.display_name}' return f'{self.id}'
@dataclass @dataclass
@ -37,3 +38,14 @@ class PrivateUser(PublicUser):
email: str = None email: str = None
product: str = None product: str = None
def __post_init__(self):
if isinstance(self.uri, str):
self.uri = Uri(self.uri)
if self.uri:
if self.uri.object_type != Uri.ObjectType.user:
raise TypeError('provided uri not for a user')
if all((isinstance(i, dict) for i in self.images)):
self.images = [Image(**i) for i in self.images]

View File

@ -236,8 +236,8 @@ class Network:
self.user.last_refreshed = datetime.datetime.utcnow() self.user.last_refreshed = datetime.datetime.utcnow()
for func in self.user.on_refresh: for func in self.user.on_refresh:
func(self.user) func(self.user)
except SpotifyNetworkException as e: except SpotifyNetworkException:
logger.error(f'error refreshing user token - {e}') logger.exception(f'error refreshing user token')
return self return self
@ -373,17 +373,18 @@ class Network:
return return_items return return_items
def get_user_playlists(self) -> List[SimplifiedPlaylist]: def get_user_playlists(self, response_limit: int = None) -> List[SimplifiedPlaylist]:
"""retrieve user owned playlists """retrieve user owned playlists
:param response_limit: max playlists to return
:return: List of user owned playlists if available :return: List of user owned playlists if available
""" """
logger.info('pulling all playlists') logger.info('pulling all playlists')
playlists = self.get_playlists() playlists = self.get_playlists(response_limit=response_limit)
if self.user.user.id is None: if self.user.user is None:
logger.debug('no user info, refreshing for filter') logger.debug('no user info, refreshing for filter')
self.refresh_user_info() self.refresh_user_info()

View File

@ -15,7 +15,7 @@ class Player:
self.last_status = None self.last_status = None
def __str__(self): def __str__(self):
return f'{self.net.user.user.display_name} - {self.status}' return f'{self.net.user.user.id} - {self.status}'
def __repr__(self): def __repr__(self):
return f'Player: {self.net.user} - {self.status}' return f'Player: {self.net.user} - {self.status}'
@ -24,8 +24,8 @@ class Player:
def available_devices(self): def available_devices(self):
try: try:
return self.net.get_available_devices() return self.net.get_available_devices()
except SpotifyNetworkException as e: except SpotifyNetworkException:
logger.error(f'error retrieving current devices - {e}') logger.exception(f'error retrieving current devices')
@property @property
def status(self): def status(self):
@ -34,8 +34,8 @@ class Player:
if new_status: if new_status:
self.last_status = new_status self.last_status = new_status
return self.last_status return self.last_status
except SpotifyNetworkException as e: except SpotifyNetworkException:
logger.error(f'error retrieving current devices - {e}') logger.exception(f'error retrieving current devices')
def play(self, def play(self,
context: Union[Context, AlbumFull, FullPlaylist] = None, context: Union[Context, AlbumFull, FullPlaylist] = None,
@ -70,20 +70,20 @@ class Player:
self.net.play(uris=[i.uri for i in tracks] + uris) self.net.play(uris=[i.uri for i in tracks] + uris)
else: else:
self.net.play() self.net.play()
except SpotifyNetworkException as e: except SpotifyNetworkException:
logger.error(f'error playing - {e}') logger.exception(f'error playing')
def change_device(self, device: Device): def change_device(self, device: Device):
try: try:
self.net.change_playback_device(device.id) self.net.change_playback_device(device.id)
except SpotifyNetworkException as e: except SpotifyNetworkException:
logger.error(f'error changing device to {device.name} - {e}') logger.exception(f'error changing device to {device.name}')
def pause(self): def pause(self):
try: try:
self.net.pause() self.net.pause()
except SpotifyNetworkException as e: except SpotifyNetworkException:
logger.error(f'error pausing - {e}') logger.exception(f'error pausing')
def toggle_playback(self): def toggle_playback(self):
status = self.status status = self.status
@ -96,28 +96,28 @@ class Player:
else: else:
logger.warning('no current playback, playing') logger.warning('no current playback, playing')
self.play() self.play()
except SpotifyNetworkException as e: except SpotifyNetworkException:
logger.error(f'error toggling playback - {e}') logger.exception(f'error toggling playback')
def next(self): def next(self):
try: try:
self.net.next() self.net.next()
except SpotifyNetworkException as e: except SpotifyNetworkException:
logger.error(f'error skipping track - {e}') logger.exception(f'error skipping track')
def previous(self): def previous(self):
try: try:
self.net.previous() self.net.previous()
except SpotifyNetworkException as e: except SpotifyNetworkException:
logger.error(f'error reversing track - {e}') logger.exception(f'error reversing track')
def shuffle(self, state=None): def shuffle(self, state=None):
if state is not None: if state is not None:
if isinstance(state, bool): if isinstance(state, bool):
try: try:
self.net.set_shuffle(state) self.net.set_shuffle(state)
except SpotifyNetworkException as e: except SpotifyNetworkException:
logger.error(f'error setting shuffle - {e}') logger.exception(f'error setting shuffle')
else: else:
raise TypeError(f'{state} is not bool') raise TypeError(f'{state} is not bool')
else: else:
@ -135,7 +135,7 @@ class Player:
self.net.set_volume(value, deviceid=device.id) self.net.set_volume(value, deviceid=device.id)
else: else:
self.net.set_volume(value) self.net.set_volume(value)
except SpotifyNetworkException as e: except SpotifyNetworkException:
logger.error(f'error setting volume to {value} - {e}') logger.exception(f'error setting volume to {value}')
else: else:
logger.error(f'{value} not between 0 and 100') logger.error(f'{value} not between 0 and 100')