formatting updates

This commit is contained in:
evilchili 2024-03-05 22:15:51 -08:00
parent ddeb91f77d
commit c9eab2d2c0
5 changed files with 37 additions and 44 deletions

View File

@ -11,9 +11,9 @@ from dotenv import load_dotenv
from typing_extensions import Annotated from typing_extensions import Annotated
import croaker.path import croaker.path
from croaker.server import server
from croaker.exceptions import ConfigurationError from croaker.exceptions import ConfigurationError
from croaker.playlist import Playlist from croaker.playlist import Playlist
from croaker.server import server
SETUP_HELP = """ SETUP_HELP = """
# Root directory for croaker configuration and logs. See also croaker --root. # Root directory for croaker configuration and logs. See also croaker --root.
@ -77,12 +77,12 @@ def main(
load_dotenv(stream=io.StringIO(SETUP_HELP)) load_dotenv(stream=io.StringIO(SETUP_HELP))
if debug is not None: if debug is not None:
if debug: if debug:
os.environ["DEBUG"] = '1' os.environ["DEBUG"] = "1"
else: else:
del os.environ["DEBUG"] del os.environ["DEBUG"]
logging.basicConfig( logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
level=logging.DEBUG if debug else logging.INFO, level=logging.DEBUG if debug else logging.INFO,
) )

View File

@ -1,6 +1,7 @@
import logging import logging
import threading
import queue import queue
import threading
from croaker.playlist import load_playlist from croaker.playlist import load_playlist
from croaker.streamer import AudioStreamer from croaker.streamer import AudioStreamer
@ -24,14 +25,14 @@ class Controller(threading.Thread):
def run(self): def run(self):
logging.debug("Starting AudioStreamer...") logging.debug("Starting AudioStreamer...")
self.streamer.start() self.streamer.start()
self.load('session_start') self.load("session_start")
while True: while True:
data = self._control_queue.get() data = self._control_queue.get()
logging.debug(f"{data = }") logging.debug(f"{data = }")
self.process_request(data) self.process_request(data)
def process_request(self, data): def process_request(self, data):
cmd, *args = data.split(' ') cmd, *args = data.split(" ")
cmd = cmd.strip() cmd = cmd.strip()
if not cmd: if not cmd:
return return

View File

@ -1,6 +1,6 @@
import logging import logging
from bottle import route, abort from bottle import abort, route
from croaker import streamer from croaker import streamer
@ -27,5 +27,5 @@ def next_in_queue():
abort() abort()
track1 = pl.current track1 = pl.current
controller.play_next() controller.play_next()
tracke2 = controller.now_playing().current controller.now_playing().current
return '\n'.join([str(track1), str(track2)]) return "\n".join([str(track1), str(track2)])

View File

@ -1,5 +1,5 @@
import os
import logging import logging
import os
import queue import queue
import socketserver import socketserver
from pathlib import Path from pathlib import Path
@ -7,17 +7,17 @@ from pathlib import Path
import daemon import daemon
from croaker import path from croaker import path
from croaker.pidfile import pidfile
from croaker.controller import Controller from croaker.controller import Controller
from croaker.pidfile import pidfile
class RequestHandler(socketserver.StreamRequestHandler): class RequestHandler(socketserver.StreamRequestHandler):
supported_commands = { supported_commands = {
'PLAY': "$PLAYLIST_NAME - Switch to the specified playlist.", "PLAY": "$PLAYLIST_NAME - Switch to the specified playlist.",
'FFWD': " - Skip to the next track in the playlist.", "FFWD": " - Skip to the next track in the playlist.",
'HELP': " - Display command help.", "HELP": " - Display command help.",
'KTHX': " - Close the current connection.", "KTHX": " - Close the current connection.",
'STOP': " - Stop Croaker.", "STOP": " - Stop Croaker.",
} }
def handle(self): def handle(self):
@ -33,8 +33,8 @@ class RequestHandler(socketserver.StreamRequestHandler):
if cmd not in self.supported_commands: if cmd not in self.supported_commands:
self.send(f"ERR Unknown Command '{cmd}'") self.send(f"ERR Unknown Command '{cmd}'")
if cmd == 'KTHX': if cmd == "KTHX":
return self.send('KBAI') return self.send("KBAI")
handler = getattr(self, f"handle_{cmd}", None) handler = getattr(self, f"handle_{cmd}", None)
if handler: if handler:
@ -43,16 +43,14 @@ class RequestHandler(socketserver.StreamRequestHandler):
self.default_handler(cmd, args) self.default_handler(cmd, args)
def send(self, msg): def send(self, msg):
return self.wfile.write(msg.encode() + b'\n') return self.wfile.write(msg.encode() + b"\n")
def default_handler(self, cmd, args): def default_handler(self, cmd, args):
self.server.tell_controller(f"{cmd} {args}") self.server.tell_controller(f"{cmd} {args}")
return self.send('OK') return self.send("OK")
def handle_HELP(self, args): def handle_HELP(self, args):
return self.send('\n'.join( return self.send("\n".join(f"{cmd} {txt}" for cmd, txt in self.supported_commands.items()))
f"{cmd} {txt}" for cmd, txt in self.supported_commands.items()
))
def handle_STOP(self, args): def handle_STOP(self, args):
self.send("Shutting down.") self.send("Shutting down.")
@ -75,7 +73,7 @@ class CroakerServer(socketserver.TCPServer):
def daemonize(self) -> None: def daemonize(self) -> None:
logging.info(f"Daemonizing controller; pidfile and output in {path.root()}") logging.info(f"Daemonizing controller; pidfile and output in {path.root()}")
super().__init__((os.environ['HOST'], int(os.environ['PORT'])), RequestHandler) super().__init__((os.environ["HOST"], int(os.environ["PORT"])), RequestHandler)
self._context.pidfile = self._pidfile() self._context.pidfile = self._pidfile()
self._context.stdout = open(path.root() / Path("croaker.out"), "wb") self._context.stdout = open(path.root() / Path("croaker.out"), "wb")

View File

@ -1,14 +1,12 @@
import os
import logging import logging
import os
import threading import threading
from pathlib import Path
from functools import cached_property from functools import cached_property
from pathlib import Path
from time import sleep
import shout import shout
from time import sleep
class AudioStreamer(threading.Thread): class AudioStreamer(threading.Thread):
def __init__(self, queue, skip_event, stop_event): def __init__(self, queue, skip_event, stop_event):
@ -20,19 +18,15 @@ class AudioStreamer(threading.Thread):
@cached_property @cached_property
def _shout(self): def _shout(self):
s = shout.Shout() s = shout.Shout()
s.name = 'Croaker Radio' s.name = "Croaker Radio"
s.url = os.environ['ICECAST_URL'] s.url = os.environ["ICECAST_URL"]
s.mount = os.environ['ICECAST_MOUNT'] s.mount = os.environ["ICECAST_MOUNT"]
s.host = os.environ['ICECAST_HOST'] s.host = os.environ["ICECAST_HOST"]
s.port = int(os.environ['ICECAST_PORT']) s.port = int(os.environ["ICECAST_PORT"])
s.password = os.environ['ICECAST_PASSWORD'] s.password = os.environ["ICECAST_PASSWORD"]
s.protocol = 'http' s.protocol = "http"
s.format = 'mp3' s.format = "mp3"
s.audio_info = { s.audio_info = {shout.SHOUT_AI_BITRATE: "192", shout.SHOUT_AI_SAMPLERATE: "44100", shout.SHOUT_AI_CHANNELS: "5"}
shout.SHOUT_AI_BITRATE: '192',
shout.SHOUT_AI_SAMPLERATE: '44100',
shout.SHOUT_AI_CHANNELS: '5'
}
return s return s
def run(self): def run(self):
@ -49,10 +43,10 @@ class AudioStreamer(threading.Thread):
self._shout.close() self._shout.close()
def play(self, track: Path): def play(self, track: Path):
with track.open('rb') as fh: with track.open("rb") as fh:
self._shout.get_connected() self._shout.get_connected()
logging.debug(f"Streaming {track.stem = }") logging.debug(f"Streaming {track.stem = }")
self._shout.set_metadata({'song': track.stem}) self._shout.set_metadata({"song": track.stem})
input_buffer = fh.read(4096) input_buffer = fh.read(4096)
while not self.skip_requested.is_set(): while not self.skip_requested.is_set():
if self.stop_requested.is_set(): if self.stop_requested.is_set():