Adjust line length to match Code Style Guide (see #103)

This commit is contained in:
coderkun 2024-05-27 12:46:46 +02:00
parent d2e1f6f5d8
commit a1f8b73590
11 changed files with 436 additions and 258 deletions

View file

@ -188,7 +188,8 @@ class Client(Base):
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)
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."""
@ -205,7 +206,8 @@ class Client(Base):
def load_playlist(self):
self._logger.info("load playlist")
self._add_action_signal(Client.SIGNAL_LOAD_PLAYLIST, self._load_playlist)
self._add_action_signal(Client.SIGNAL_LOAD_PLAYLIST,
self._load_playlist)
def clear_playlist(self):
"""Clear the current playlist"""
@ -262,7 +264,8 @@ class Client(Base):
def get_albumart(self, album):
self._logger.info("get albumart")
self._add_action_signal(Client.SIGNAL_LOAD_ALBUMART, self._get_albumart, album)
self._add_action_signal(Client.SIGNAL_LOAD_ALBUMART,
self._get_albumart, album)
def get_albumart_now(self, album):
self._logger.info("get albumart now")
@ -292,7 +295,9 @@ class Client(Base):
def _connect_socket(self, host, port):
sock = None
error = None
for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.IPPROTO_TCP):
resources = socket.getaddrinfo(host, port, socket.AF_UNSPEC,
socket.SOCK_STREAM, socket.IPPROTO_TCP)
for res in resources:
af, socktype, proto, canonname, sa = res
try:
sock = socket.socket(af, socktype, proto)
@ -315,7 +320,8 @@ class Client(Base):
if not greeting.startswith(Client.PROTOCOL_GREETING):
self._disconnect_socket()
raise ProtocolException("invalid greeting: {}".format(greeting))
self._protocol_version = greeting[len(Client.PROTOCOL_GREETING):].strip()
self._protocol_version = greeting[len(Client.PROTOCOL_GREETING
):].strip()
self._logger.debug("protocol version: %s", self._protocol_version)
def _disconnect(self):
@ -428,7 +434,7 @@ class Client(Base):
artists = 0
if 'artists' in stats:
artists = int(stats['artists'])
# Albums
# Albums
albums = 0
if 'albums' in stats:
albums = int(stats['albums'])
@ -478,7 +484,9 @@ class Client(Base):
album = self._extract_album(album)
self._logger.debug("album: %r", album)
# Tracks
for song in self._parse_list(self._call('find album ', album.get_title()), ['file']):
songs = self._parse_list(
self._call('find album ', album.get_title()), ['file'])
for song in songs:
track = self._extract_track(song)
if track:
self._logger.debug("track: %r", track)
@ -490,17 +498,22 @@ class Client(Base):
def _load_playlist(self):
self._playlist = []
for song in self._parse_list(self._call('playlistinfo'), ['file', 'playlist']):
songs = self._parse_list(self._call('playlistinfo'),
['file', 'playlist'])
for song in songs:
self._logger.debug("song: %r", song)
# Track
track = self._extract_playlist_track(song)
self._logger.debug("track: %r", track)
# Album
album = self._extract_album(song, lookup=False)
if len(self._playlist) == 0 or self._playlist[len(self._playlist)-1] != album:
if (
len(self._playlist) == 0
or self._playlist[len(self._playlist) - 1] != album
):
self._playlist.append(album)
else:
album = self._playlist[len(self._playlist)-1]
album = self._playlist[len(self._playlist) - 1]
self._logger.debug("album: %r", album)
if track:
album.add_track(track)
@ -549,7 +562,8 @@ class Client(Base):
for track in self._albums[album].get_tracks():
self._logger.info("addid: %r", track.get_file())
track_id = None
track_id_response = self._parse_dict(self._call('addid', track.get_file()))
track_id_response = self._parse_dict(
self._call('addid', track.get_file()))
if 'id' in track_id_response:
track_id = track_id_response['id']
self._logger.debug("track id: %r", track_id)
@ -574,19 +588,24 @@ class Client(Base):
def _get_albumart(self, album):
if album in self._albums:
album = self._albums[album]
self._logger.debug("get albumart for album \"%s\"", album.get_title())
self._logger.debug("get albumart for album \"%s\"",
album.get_title())
# Use "albumart" command
if album.get_tracks():
try:
return (album, self._read_binary('albumart', album.get_tracks()[0].get_file(), False))
return (album,
self._read_binary('albumart',
album.get_tracks()[0].get_file(),
False))
except CommandException as e:
# The "albumart" command throws an exception if not found
if e.get_error_number() != Client.PROTOCOL_ERROR_NOEXISTS:
raise e
# If no albumart can be found, use "readpicture" command
for track in album.get_tracks():
data = self._read_binary('readpicture', track.get_file(), True)
data = self._read_binary('readpicture',
track.get_file(), True)
if data:
return (album, data)
@ -595,7 +614,9 @@ class Client(Base):
def _start_worker(self):
"""Start the worker thread which waits for action to be performed."""
self._logger.debug("start worker")
self._worker = threading.Thread(target=self._run, name='mcg-worker', args=())
self._worker = threading.Thread(target=self._run,
name='mcg-worker',
args=())
self._worker.setDaemon(True)
self._worker.start()
self._logger.debug("worker started")
@ -623,7 +644,8 @@ class Client(Base):
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)
self._logger.debug("add action signal %r: %r (%r)", signal,
method.__name__, args)
future = Future(signal)
future.add_done_callback(self._callback_future)
self._add_action_future(future, method, *args)
@ -658,7 +680,10 @@ class Client(Base):
self._write(command, args)
return self._read()
except MPDException as e:
if command == 'idle' and e.get_error_number() == Client.PROTOCOL_ERROR_PERMISSION:
if (
command == 'idle'
and e.get_error_number() == Client.PROTOCOL_ERROR_PERMISSION
):
self.disconnect()
self._callback(Client.SIGNAL_ERROR, e)
@ -666,13 +691,17 @@ class Client(Base):
try:
self._write(command, args)
except MPDException as e:
if command == 'idle' and e.get_error_number() == Client.PROTOCOL_ERROR_PERMISSION:
if (
command == 'idle'
and e.get_error_number() == Client.PROTOCOL_ERROR_PERMISSION
):
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))
line = '{} "{}"\n'.format(
command, '" "'.join(str(x).replace('"', '\\\"') for x in args))
else:
line = '{}\n'.format(command)
self._logger.debug("write: %r", line)
@ -683,7 +712,10 @@ class Client(Base):
self._logger.debug("reading response")
response = []
line = self._read_line()
while not line.startswith(Client.PROTOCOL_COMPLETION) and not line.startswith(Client.PROTOCOL_ERROR):
while (
not line.startswith(Client.PROTOCOL_COMPLETION)
and not line.startswith(Client.PROTOCOL_ERROR)
):
response.append(line.strip())
line = self._read_line()
if line.startswith(Client.PROTOCOL_COMPLETION):
@ -752,7 +784,7 @@ class Client(Base):
if not data:
data = bytearray(size)
# Create a view for the current chunk of data
data_view = memoryview(data)[offset:offset+binary]
data_view = memoryview(data)[offset:offset + binary]
# Read actual bytes
self._read_bytes(data_view, binary)
offset += binary
@ -782,9 +814,9 @@ class Client(Base):
def _buffer_get_char(self, char):
pos = self._buffer.find(char)
if pos < 0:
pos = len(self._buffer)-1
buf = self._buffer[0:pos+1]
self._buffer = self._buffer[pos+1:]
pos = len(self._buffer) - 1
buf = self._buffer[0:pos + 1]
self._buffer = self._buffer[pos + 1:]
return buf
def _buffer_get_size(self, size):
@ -917,7 +949,10 @@ class MCGAlbum:
def get_artists(self):
if self._albumartists:
return [artist for artist in self._artists if artist not in self._albumartists]
return [
artist for artist in self._artists
if artist not in self._albumartists
]
return self._artists
def get_albumartists(self):
@ -948,13 +983,19 @@ class MCGAlbum:
for artist in track.get_albumartists():
if artist not in self._albumartists:
self._albumartists.append(artist)
if track.get_date() is not None and track.get_date() not in self._dates:
if (
track.get_date() is not None
and track.get_date() not in self._dates
):
self._dates.append(track.get_date())
path = os.path.dirname(track.get_file())
if path not in self._pathes:
self._pathes.append(path)
if track.get_last_modified():
if not self._last_modified or track.get_last_modified() > self._last_modified:
if (
not self._last_modified
or track.get_last_modified() > self._last_modified
):
self._last_modified = track.get_last_modified()
def get_tracks(self):
@ -984,7 +1025,10 @@ class MCGAlbum:
continue
# Search in track data
for track in self._tracks:
if keyword in track.get_title().lower() or keyword in track.get_file().lower():
if (
keyword in track.get_title().lower()
or keyword in track.get_file().lower()
):
result = True
break
if not result:
@ -1048,7 +1092,10 @@ class MCGTrack:
def get_artists(self):
if self._albumartists:
return [artist for artist in self._artists if artist not in self._albumartists]
return [
artist for artist in self._artists
if artist not in self._albumartists
]
return self._artists
def set_albumartists(self, artists):
@ -1071,7 +1118,7 @@ class MCGTrack:
if type(track) is list:
track = track[0]
if type(track) is str and '/' in track:
track = track[0: track.index('/')]
track = track[0:track.index('/')]
if track is not None:
try:
track = int(track)
@ -1108,13 +1155,10 @@ class MCGTrack:
class MCGPlaylistTrack(MCGTrack):
def __init__(self, track, id, pos):
MCGTrack.__init__(
self,
track.get_artists(),
track.get_title(),
track.get_file()
)
MCGTrack.__init__(self, track.get_artists(), track.get_title(),
track.get_file())
self.set_albumartists(track.get_albumartists())
self.set_track(track.get_track())
self.set_length(track.get_length())
@ -1134,7 +1178,8 @@ class MCGConfig(configparser.ConfigParser):
def __init__(self, filename):
configparser.ConfigParser.__init__(self)
self._filename = os.path.expanduser(os.path.join(MCGConfig.CONFIG_DIR, filename))
self._filename = os.path.expanduser(
os.path.join(MCGConfig.CONFIG_DIR, filename))
self._create_dir()
def load(self):
@ -1160,7 +1205,8 @@ class MCGCache():
self._logger = logging.getLogger(__name__)
self._host = host
self._size = size
self._dirname = os.path.expanduser(os.path.join(MCGCache.DIRNAME, host))
self._dirname = os.path.expanduser(os.path.join(
MCGCache.DIRNAME, host))
if not os.path.exists(self._dirname):
os.makedirs(self._dirname)
self._read_size()
@ -1178,7 +1224,10 @@ class MCGCache():
try:
size = int(f.readline())
except:
self._logger.warning("invalid cache file: %s, deleting file", filename, exc_info=True)
self._logger.warning(
"invalid cache file: %s, deleting file",
filename,
exc_info=True)
size = None
# Clear cache if size has changed
if size != self._size: