Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

clean server #39

Merged
merged 4 commits into from
Aug 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ pycairo==1.26.0
Pygments==2.18.0
PyGObject==3.48.2
pyradios==2.1.0
python-mpv==1.0.6
python-vlc==3.0.20123
setuptools==70.0.0
sniffio==1.3.1
streamscrobbler3==0.0.4
tinydb==4.8.0
wcwidth==0.2.13
mpv==1.0.7
21 changes: 15 additions & 6 deletions xradios/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import os
import logging
import logging.config
from logging.handlers import RotatingFileHandler

from appdirs import user_log_dir
from appdirs import user_data_dir
Expand All @@ -13,22 +15,29 @@

xradios_config_dir = Path(user_config_dir(appname=app_name))
xradios_config_dir.mkdir(parents=True, exist_ok=True)

xradios_data_dir = Path(user_data_dir(appname=app_name))
xradios_data_dir.mkdir(parents=True, exist_ok=True)

xradios_log_dir = Path(user_log_dir(appname=app_name))
xradios_log_dir.mkdir(parents=True, exist_ok=True)

log_level = getattr(logging, os.environ.get("XRADIOS_LOG_LEVEL", "INFO"))

if log_level == logging.DEBUG:
log_format = "%(levelname)s - %(name)s - %(module)s - %(funcName)s - %(message)s"
log_format = "%(levelname)s - %(name)s - %(filename)s -%(module)s - %(funcName)s - %(message)s"
else:
log_format = "%(levelname)s - %(name)s - %(message)s"

log_file = "xradios.log"

logging.basicConfig(
filename=xradios_log_dir / log_file, level=log_level, format=log_format
# logging.config.dictConfig(config={"level": log_level, "handlers": [], "version": 1})
logging.basicConfig(level=log_level, format=log_format)

logging.getLogger().handlers = []
handler = RotatingFileHandler(
filename=xradios_log_dir / log_file,
maxBytes=5 * 1024 * 1024,
backupCount=2
)
# handler.setLevel(log_level)
# handler.setFormatter(logging.Formatter(log_format))
logging.getLogger("xradiosd").addHandler(handler)
logging.getLogger("xradios").addHandler(handler)
20 changes: 17 additions & 3 deletions xradios/core/player.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@


class PlayerBase(ABC):

state = False

@abstractmethod
Expand All @@ -35,9 +34,24 @@ def playing(self):
return self.state


class MPVPlayer(PlayerBase):
def log_handler(level, prefix, message):
func = getattr(log, level.lower(), log.info) # getattr default -> log.info
func(f"{prefix}: {message}")

player = MPV()

class MPVPlayer(PlayerBase):
extra_mpv_opts = {
"cache": True,
"cache_secs": 10,
}

player = MPV(
log_handler=log_handler,
loglevel=logging.getLevelName(log.root.level).lower(),
**extra_mpv_opts,
)
log.debug(f"mpv --cache ---> {player['cache']}")
log.debug(f"mpv --cache-secs ---> {player.cache_secs}")

def play(self, stationuuid):
url = self._click_counter(stationuuid)
Expand Down
28 changes: 9 additions & 19 deletions xradios/core/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,38 +70,31 @@ def now_playing():
return


@cmd('favorites')
@cmd("favorites")
def favorites():

stations = [dict(s) for s in db.all()]

if stations:
return stations
else:
return rb.stations_by_votes(limit=100)


@cmd('add_favorite')
@cmd("add_favorite")
def add_favorite(**station):
# Check if the station has already been added to favorites
if not db.search(Query().stationuuid == station['stationuuid']):
if not db.search(Query().stationuuid == station["stationuuid"]):
db.insert(station)
log.debug(f'Adding a new station to favorites {station=}')
log.debug(f"Adding a new station to favorites {station=}")


@cmd('remove_favorite')
@cmd("remove_favorite")
def remove_favorite(**station):
db.remove(Query().stationuuid == station['stationuuid'])
log.debug(f'Removing a station from favorites {station=}')
db.remove(Query().stationuuid == station["stationuuid"])
log.debug(f"Removing a station from favorites {station=}")


class RequestHandler(SimpleXMLRPCRequestHandler):
rpc_paths = ("/", "/RPC2")
# def log_request(self, code="-", size="-"):
# from xradios.logger import log
# log.info(f'RPC status code {code}')
# BaseHTTPRequestHandler.log_message = lambda *args: print(*args)
# BaseHTTPRequestHandler.log_request(self, code, size)


class RPCServer:
Expand All @@ -112,15 +105,13 @@ def __init__(self, address):
requestHandler=RequestHandler,
use_builtin_types=True,
)
self._serv.rpc_paths = ("/", "/RPC2") # default
self._serv.register_introspection_functions()

for key, value in command_handlers.items():
setattr(self, key, value)
self.register_function(getattr(self, key))

def register_function(self, function, name=None):
# https://stackoverflow.com/questions/119802/using-kwargs-with-simplexmlrpcserver-in-python
def _function(args, kwargs):
return function(*args, **kwargs)

Expand All @@ -136,15 +127,14 @@ def stop(self):

def sigterm_handler(signo, frame, server):
server.stop()
log.info('Shutdown server...')
log.info("Shutdown server...")
raise SystemExit(0)


def run(host="", port=10000):
server = RPCServer((host, port))
signal.signal(
signal.SIGTERM,
lambda signo, frame: sigterm_handler(signo, frame, server)
signal.SIGTERM, lambda signo, frame: sigterm_handler(signo, frame, server)
)
log.info(f"Serving XML-RPC port: {port}")
server.serve_forever()
Expand Down
2 changes: 1 addition & 1 deletion xradios/tui/buffers/display.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ async def run(self):
except Exception:
pass
else:
if all(result.values()):
if result and all(result.values()):
self.metadata = result
await asyncio.sleep(30)

Expand Down