Adjust blank lines to match Code Style Guide (see #103)

This commit is contained in:
coderkun 2024-05-26 18:29:10 +02:00
parent 75b99e5820
commit d2e1f6f5d8
14 changed files with 14 additions and 413 deletions

View file

@ -1,6 +1,5 @@
#!/usr/bin/env python3
import concurrent.futures
import configparser
import dateutil.parser
@ -15,14 +14,12 @@ from mcg.utils import SortOrder
from mcg.utils import Utils
class MPDException(Exception):
def __init__(self, error):
super(MPDException, self).__init__(self._parse_error(error))
self._error = error
def _parse_error(self, error):
if error:
parts = re.match("\[(\d+)@(\d+)\]\s\{(\w+)\}\s(.*)", error)
@ -33,19 +30,15 @@ class MPDException(Exception):
return parts.group(4)
return error
def get_error(self):
return self._error
def get_error_number(self):
return self._error_number
def get_command_number(self):
return self._command_number
def get_command_name(self):
return self._command_name
@ -62,53 +55,43 @@ class CommandException(MPDException):
pass
class Future(concurrent.futures.Future):
def __init__(self, signal):
concurrent.futures.Future.__init__(self)
self._signal = signal
def get_signal(self):
return self._signal
class Base():
def __init__(self):
self._callbacks = {}
def connect_signal(self, signal, callback):
"""Connect a callback function to a signal (event)."""
self._callbacks[signal] = callback
def disconnect_signal(self, signal):
"""Disconnect a callback function from a signal (event)."""
if self._has_callback(signal):
del self._callbacks[signal]
def _has_callback(self, signal):
"""Check if there is a registered callback function for a signal."""
return signal in self._callbacks
def _callback(self, signal, *data):
if signal in self._callbacks:
callback = self._callbacks[signal]
callback(*data)
def _callback_future(self, future):
self._callback(future.get_signal(), *future.result())
class Client(Base):
"""Client library for handling the connection to the Music Player Daemon.
@ -148,8 +131,6 @@ class Client(Base):
# Buffer size for reading from socket
SOCKET_BUFSIZE = 4096
def __init__(self):
"""Set class variables and instantiates the Client."""
Base.__init__(self)
@ -166,11 +147,9 @@ class Client(Base):
self._playlist = []
self._state = None
def get_logger(self):
return self._logger
# Client commands
def connect(self, host, port, password=None):
@ -183,132 +162,108 @@ class Client(Base):
self._stop.clear()
self._start_worker()
def is_connected(self):
"""Return the connection status."""
return self._worker is not None and self._worker.is_alive()
def disconnect(self):
"""Disconnect from the connected MPD."""
self._logger.info("disconnect")
self._stop.set()
self._add_action(self._disconnect)
def join(self):
self._actions.join()
def get_status(self):
"""Determine the current status."""
self._logger.info("get status")
self._add_action_signal(Client.SIGNAL_STATUS, self._get_status)
def get_stats(self):
"""Load statistics."""
self._logger.info("get stats")
self._add_action_signal(Client.SIGNAL_STATS, self._get_stats)
def get_output_devices(self):
"""Determine the list of audio output devices."""
self._logger.info("get output devices")
self._add_action_signal(Client.SIGNAL_LOAD_OUTPUT_DEVICES, self._get_output_devices)
def enable_output_device(self, device, enabled):
"""Enable/disable an audio output device."""
self._logger.info("enable output device")
self._add_action(self._enable_output_device, device, enabled)
def load_albums(self):
self._logger.info("load albums")
self._add_action_signal(Client.SIGNAL_LOAD_ALBUMS, self._load_albums)
def update(self):
self._logger.info("update")
self._add_action(self._update)
def load_playlist(self):
self._logger.info("load playlist")
self._add_action_signal(Client.SIGNAL_LOAD_PLAYLIST, self._load_playlist)
def clear_playlist(self):
"""Clear the current playlist"""
self._logger.info("clear playlist")
self._add_action(self._clear_playlist)
def remove_album_from_playlist(self, album):
"""Remove the given album from the playlist."""
self._logger.info("remove album from playlist")
self._add_action(self._remove_album_from_playlist, album)
def remove_albums_from_playlist(self, albums):
"""Remove multiple albums from the playlist in one step."""
self._logger.info("remove multiple albums from playlist")
self._add_action(self._remove_albums_from_playlist, albums)
def play_album_from_playlist(self, album):
"""Play the given album from the playlist."""
self._logger.info("play album from playlist")
self._add_action(self._play_album_from_playlist, album)
def playpause(self):
"""Play or pauses the current state."""
self._logger.info("playpause")
self._add_action(self._playpause)
def play_album(self, album):
"""Add the given album to the queue and play it immediately."""
self._logger.info("play album")
self._add_action(self._play_album, album)
def queue_album(self, album):
"""Add the given album to the queue."""
self._logger.info("play album")
self._add_action(self._queue_album, album)
def queue_albums(self, albums):
"""Add the given albums to the queue."""
self._logger.info("play albums")
self._add_action(self._queue_albums, albums)
def seek(self, pos, time):
"""Seeks to a song at a position"""
self._logger.info("seek")
self._add_action(self._seek, pos, time)
def stop(self):
self._logger.info("stop")
self._add_action(self._stop)
def set_volume(self, volume):
self._logger.info("set volume")
self._add_action(self._set_volume, volume)
def get_albumart(self, album):
self._logger.info("get albumart")
self._add_action_signal(Client.SIGNAL_LOAD_ALBUMART, self._get_albumart, album)
def get_albumart_now(self, album):
self._logger.info("get albumart now")
future = concurrent.futures.Future()
@ -316,7 +271,6 @@ class Client(Base):
(_, albumart) = future.result()
return albumart
# Private methods
def _connect(self, host, port, password):
@ -335,7 +289,6 @@ class Client(Base):
except OSError as e:
raise ConnectionException("connection failed: {}".format(e))
def _connect_socket(self, host, port):
sock = None
error = None
@ -356,7 +309,6 @@ class Client(Base):
else:
raise ConnectionException("no suitable socket")
def _greet(self):
greeting = self._read_line()
self._logger.debug("greeting: %s", greeting.strip())
@ -366,12 +318,10 @@ class Client(Base):
self._protocol_version = greeting[len(Client.PROTOCOL_GREETING):].strip()
self._logger.debug("protocol version: %s", self._protocol_version)
def _disconnect(self):
self._logger.info("disconnecting")
self._disconnect_socket()
def _disconnect_socket(self):
if self._sock_write is not None:
self._sock_write.close()
@ -382,7 +332,6 @@ class Client(Base):
self._logger.info("disconnected")
self._set_connection_status(False)
def _idle(self):
"""React to idle events from MPD."""
self._logger.info("idle")
@ -410,13 +359,11 @@ class Client(Base):
self.get_output_devices()
self.get_status()
def _noidle(self):
if self._idling:
self._logger.debug("noidle")
self._write("noidle")
def _get_status(self):
"""Action: Perform the real status determination."""
self._logger.info("getting status")
@ -471,7 +418,6 @@ class Client(Base):
bitrate = status['bitrate']
return (state, album, pos, time, volume, file, audio, bitrate, error)
def _get_stats(self):
"""Action: Perform the real statistics gathering."""
self._logger.info("getting statistics")
@ -504,7 +450,6 @@ class Client(Base):
uptime = stats['uptime']
return (artists, albums, songs, dbplaytime, playtime, uptime)
def _get_output_devices(self):
"""Action: Perform the real loading of output devices."""
devices = []
@ -514,7 +459,6 @@ class Client(Base):
devices.append(device)
return (devices, )
def _enable_output_device(self, device, enabled):
"""Action: Perform the real enabling/disabling of an output device."""
if enabled:
@ -522,7 +466,6 @@ class Client(Base):
else:
self._call('disableoutput ', device.get_id())
def _load_albums(self):
"""Action: Perform the real update."""
self._callback(Client.SIGNAL_INIT_ALBUMS)
@ -542,11 +485,9 @@ class Client(Base):
album.add_track(track)
return (self._albums, )
def _update(self):
self._call('update')
def _load_playlist(self):
self._playlist = []
for song in self._parse_list(self._call('playlistinfo'), ['file', 'playlist']):
@ -565,19 +506,16 @@ class Client(Base):
album.add_track(track)
return (self._playlist, )
def _clear_playlist(self):
"""Action: Perform the real clearing of the current playlist."""
self._call('clear')
def _remove_album_from_playlist(self, album):
self._call_list('command_list_begin')
for track in album.get_tracks():
self._call_list('deleteid', track.get_id())
self._call('command_list_end')
def _remove_albums_from_playlist(self, albums):
self._call_list('command_list_begin')
for album in albums:
@ -585,12 +523,10 @@ class Client(Base):
self._call_list('deleteid', track.get_id())
self._call('command_list_end')
def _play_album_from_playlist(self, album):
if album.get_tracks():
self._call('playid', album.get_tracks()[0].get_id())
def _playpause(self):
"""Action: Perform the real play/pause command."""
#status = self._parse_dict(self._call('status'))
@ -600,14 +536,12 @@ class Client(Base):
else:
self._call('play')
def _play_album(self, album):
track_ids = self._queue_album(album)
if track_ids:
self._logger.info("play track %d", track_ids[0])
self._call('playid', track_ids[0])
def _queue_album(self, album):
track_ids = []
if album in self._albums:
@ -623,25 +557,20 @@ class Client(Base):
track_ids.append(track_id)
return track_ids
def _queue_albums(self, albums):
track_ids = []
for album in albums:
track_ids.extend(self._queue_album(album))
def _seek(self, pos, time):
self._call('seek', pos, time)
def _stop(self):
self._call('stop')
def _set_volume(self, volume):
self._call('setvol', volume)
def _get_albumart(self, album):
if album in self._albums:
album = self._albums[album]
@ -663,7 +592,6 @@ class Client(Base):
return (album, None)
def _start_worker(self):
"""Start the worker thread which waits for action to be performed."""
self._logger.debug("start worker")
@ -672,7 +600,6 @@ class Client(Base):
self._worker.start()
self._logger.debug("worker started")
def _run(self):
while not self._stop.is_set() or not self._actions.empty():
if self._sock is not None and self._actions.empty():
@ -684,7 +611,6 @@ class Client(Base):
self._logger.debug("action done")
self._logger.debug("worker finished")
def _add_action(self, method, *args):
"""Add an action to the action list."""
self._logger.debug("add action %r (%r)", method.__name__, args)
@ -695,7 +621,6 @@ class Client(Base):
return future
def _add_action_signal(self, signal, method, *args):
"""Add an action to the action list that triggers a callback."""
self._logger.debug("add action signal %r: %r (%r)", signal, method.__name__, args)
@ -705,7 +630,6 @@ class Client(Base):
return future
def _add_action_future(self, future, method, *args):
"""Add an action to the action list based on a futre."""
self._logger.debug("add action future %r (%r)", method.__name__, args)
@ -713,7 +637,6 @@ class Client(Base):
self._actions.put(action)
self._noidle()
def _work(self, action):
(future, method, args) = action
self._logger.debug("work: %r", method.__name__)
@ -730,7 +653,6 @@ class Client(Base):
future.set_exception(e)
self._callback(Client.SIGNAL_ERROR, e)
def _call(self, command, *args):
try:
self._write(command, args)
@ -740,7 +662,6 @@ class Client(Base):
self.disconnect()
self._callback(Client.SIGNAL_ERROR, e)
def _call_list(self, command, *args):
try:
self._write(command, args)
@ -749,7 +670,6 @@ class Client(Base):
self.disconnect()
self._callback(Client.SIGNAL_ERROR, e)
def _write(self, command, args=None):
if args is not None and len(args) > 0:
line = '{} "{}"\n'.format(command, '" "'.join(str(x).replace('"', '\\\"') for x in args))
@ -759,7 +679,6 @@ class Client(Base):
self._sock_write.write(line)
self._sock_write.flush()
def _read(self):
self._logger.debug("reading response")
response = []
@ -776,7 +695,6 @@ class Client(Base):
self._logger.debug("response: %r", response)
return response
def _read_line(self):
self._logger.debug("reading line")
@ -800,7 +718,6 @@ class Client(Base):
return data.decode('utf-8')
return None
def _read_binary(self, command, filename, has_mimetype):
data = None
size = 1
@ -849,7 +766,6 @@ class Client(Base):
break
return data
def _read_bytes(self, buf, nbytes):
self._logger.debug("reading bytes")
# Use already buffered data
@ -863,7 +779,6 @@ class Client(Base):
nbytes_read += self._sock.recv_into(buf_view, nbytes)
return nbytes_read
def _buffer_get_char(self, char):
pos = self._buffer.find(char)
if pos < 0:
@ -872,7 +787,6 @@ class Client(Base):
self._buffer = self._buffer[pos+1:]
return buf
def _buffer_get_size(self, size):
buf = self._buffer[0:size]
self._logger.debug("get %d bytes from buffer", len(buf))
@ -880,12 +794,10 @@ class Client(Base):
self._logger.debug("leaving %d in the buffer", len(self._buffer))
return buf
def _buffer_set(self, buf):
self._logger.debug("set %d %s as buffer", len(buf), type(buf))
self._buffer = buf
def _parse_dict(self, response):
dict = {}
if response:
@ -894,7 +806,6 @@ class Client(Base):
dict[key] = value
return dict
def _parse_list(self, response, delimiters):
entry = {}
if response:
@ -912,12 +823,10 @@ class Client(Base):
if entry:
yield entry
def _split_line(self, line):
parts = line.split(':')
return parts[0].lower(), ':'.join(parts[1:]).lstrip()
def _extract_album(self, song, lookup=True):
album = None
if 'album' not in song:
@ -931,7 +840,6 @@ class Client(Base):
self._albums[id] = album
return album
def _extract_track(self, song):
track = None
if 'artist' in song and 'title' in song and 'file' in song:
@ -948,54 +856,42 @@ class Client(Base):
track.set_last_modified(song['last-modified'])
return track
def _extract_playlist_track(self, song):
track = self._extract_track(song)
if track and 'id' in song and 'pos' in song:
track = MCGPlaylistTrack(track, song['id'], song['pos'])
return track
def _set_connection_status(self, status):
self._callback(Client.SIGNAL_CONNECTION, status)
class OutputDevice:
def __init__(self, id, name):
self._id = id
self._name = name
self._enabled = None
def get_id(self):
return self._id
def get_name(self):
return self._name
def set_enabled(self, enabled):
self._enabled = enabled
def is_enabled(self):
return self._enabled
class MCGAlbum:
DEFAULT_ALBUM = 'Various'
_FILE_NAMES = ['cover', 'folder']
_FILE_EXTS = ['jpg', 'png', 'jpeg']
_FILTER_DELIMITER = ' '
def __init__(self, title, host):
self._artists = []
self._albumartists = []
@ -1010,49 +906,39 @@ class MCGAlbum:
self._last_modified = None
self._id = Utils.generate_id(title)
def __eq__(self, other):
return (other and self.get_id() == other.get_id())
def __hash__(self):
return hash(self._title)
def get_id(self):
return self._id
def get_artists(self):
if self._albumartists:
return [artist for artist in self._artists if artist not in self._albumartists]
return self._artists
def get_albumartists(self):
if self._albumartists:
return self._albumartists
return self._artists
def get_title(self):
return self._title
def get_dates(self):
return self._dates
def get_date(self):
if len(self._dates) == 0:
return None
return self._dates[0]
def get_path(self):
return self._path
def add_track(self, track):
self._tracks.append(track)
self._length = self._length + track.get_length()
@ -1071,19 +957,15 @@ class MCGAlbum:
if not self._last_modified or track.get_last_modified() > self._last_modified:
self._last_modified = track.get_last_modified()
def get_tracks(self):
return self._tracks
def get_length(self):
return self._length
def get_last_modified(self):
return self._last_modified
def filter(self, filter_string):
if len(filter_string) == 0:
return True
@ -1109,7 +991,6 @@ class MCGAlbum:
return False
return True
def compare(album1, album2, criterion=None, reverse=False):
if criterion == None:
criterion = SortOrder.TITLE
@ -1140,9 +1021,8 @@ class MCGAlbum:
return 1 * reverseMultiplier
class MCGTrack:
def __init__(self, artists, title, file):
if type(artists) is not list:
artists = [artists]
@ -1160,41 +1040,33 @@ class MCGTrack:
self._date = None
self._last_modified = None
def __eq__(self, other):
return self._file == other.get_file()
def __hash__(self):
return hash(self._file)
def get_artists(self):
if self._albumartists:
return [artist for artist in self._artists if artist not in self._albumartists]
return self._artists
def set_albumartists(self, artists):
if type(artists) is not list:
artists = [artists]
self._albumartists = artists
def get_albumartists(self):
if self._albumartists:
return self._albumartists
return self._artists
def get_title(self):
return self._title
def get_track(self):
return self._track
def set_track(self, track):
if type(track) is list:
track = track[0]
@ -1207,29 +1079,23 @@ class MCGTrack:
track = 0
self._track = track
def get_length(self):
return self._length
def set_length(self, length):
self._length = int(length)
def get_date(self):
return self._date
def set_date(self, date):
if type(date) is list:
date = date[0]
self._date = date
def get_file(self):
return self._file
def set_last_modified(self, date_string):
if date_string:
try:
@ -1237,13 +1103,10 @@ class MCGTrack:
except ValueError as e:
self._logger.debug("Invalid date format: %s", date_string)
def get_last_modified(self):
return self._last_modified
class MCGPlaylistTrack(MCGTrack):
def __init__(self, track, id, pos):
MCGTrack.__init__(
@ -1259,51 +1122,40 @@ class MCGPlaylistTrack(MCGTrack):
self._id = int(id)
self._pos = int(pos)
def get_id(self):
return self._id
def get_pos(self):
return self._pos
class MCGConfig(configparser.ConfigParser):
CONFIG_DIR = '~/.config/mcg/'
def __init__(self, filename):
configparser.ConfigParser.__init__(self)
self._filename = os.path.expanduser(os.path.join(MCGConfig.CONFIG_DIR, filename))
self._create_dir()
def load(self):
if os.path.isfile(self._filename):
self.read(self._filename)
def save(self):
with open(self._filename, 'w') as configfile:
self.write(configfile)
def _create_dir(self):
dirname = os.path.dirname(self._filename)
if not os.path.exists(dirname):
os.makedirs(dirname)
class MCGCache():
DIRNAME = '~/.cache/mcg/'
SIZE_FILENAME = 'size'
_lock = threading.Lock()
def __init__(self, host, size):
self._logger = logging.getLogger(__name__)
self._host = host
@ -1313,11 +1165,9 @@ class MCGCache():
os.makedirs(self._dirname)
self._read_size()
def create_filename(self, album):
return os.path.join(self._dirname, '-'.join([album.get_id()]))
def _read_size(self):
size = 100
MCGCache._lock.acquire()
@ -1338,7 +1188,6 @@ class MCGCache():
f.write(str(self._size))
MCGCache._lock.release()
def _clear(self):
for filename in os.listdir(self._dirname):
path = os.path.join(self._dirname, filename)