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

feat: use Show from nowplaypadgen project #132

Draft
wants to merge 12 commits into
base: main
Choose a base branch
from
4 changes: 1 addition & 3 deletions nowplaying/daemon.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,9 +100,7 @@ def get_input_handler(self): # pragma: no cover
klangbecken.add_track_handler(track_handler)
handler.register_observer(klangbecken)

nonklangbecken = inputObservers.NonKlangbeckenInputObserver(
self.options.currentShowUrl
)
nonklangbecken = inputObservers.NonKlangbeckenInputObserver(self.options)
nonklangbecken.add_track_handler(track_handler)
handler.register_observer(nonklangbecken)

Expand Down
20 changes: 17 additions & 3 deletions nowplaying/input/observer.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,27 @@ class InputObserver(ABC):
_SHOW_NAME_KLANGBECKEN = "Klangbecken"
_SHOW_URL_KLANGBECKEN = "http://www.rabe.ch/sendungen/musik/klangbecken.html"

def __init__(self, current_show_url):
self.current_show_url = current_show_url
class Options:
def __init__(self, current_show_url, default_show_url: str = None):
if not default_show_url:
# TODO v3 remove this fallback
logger.warning(
"No default show URL specified, using deprecated hardcoded default."
)
default_show_url = "https://www.rabe.ch/"
self.current_show_url = current_show_url
self.default_show_url = default_show_url

def __init__(self, options):
if isinstance(options, str) or options is None:
# TODO v3 remove this fallback
options = __class__.Options(options)
self.current_show_url = options.current_show_url

self.first_run = True
self.previous_saemubox_id = None
self.show = None
self.showclient = client.ShowClient(current_show_url)
self.showclient = client.ShowClient(options)
self.show = self.showclient.get_show_info()

self.previous_show_uuid = None
Expand Down
20 changes: 20 additions & 0 deletions nowplaying/options.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,18 @@ class Options:
"""Default socket of 2 minutes, to prevent endless hangs on HTTP requests."""
socketDefaultTimeout = 120

class DefaultShowURLType(str):
"""Default show URL, if we have no further info on the current show, we will use this URL.

Currently this flag is experimental and may be ignored in some cases.

Default: https://www.rabe.ch/
"""

pass

default_show_url: DefaultShowURLType = "https://www.rabe.ch/"

def __init__(self):
"""Configure configargparse."""
self.__args = configargparse.ArgParser(
Expand Down Expand Up @@ -65,6 +77,12 @@ def __init__(self):
dest="currentShowUrl",
help="Current Show URL e.g. 'https://libretime.int.example.org/api/live-info-v2/format/json'",
)
self.__args.add_argument(
"--default-show-url",
dest="default_show_url",
help=__class__.DefaultShowURLType.__doc__,
default=__class__.default_show_url,
)
self.__args.add_argument(
"--input-file",
dest="inputFile",
Expand Down Expand Up @@ -100,3 +118,5 @@ def __init__(self):
def parse_known_args(self):
"""Parse known args with configargparse."""
self.__args.parse_known_args(namespace=self)
# TODO v3 remove hack
self.current_show_url = self.currentShowUrl
26 changes: 21 additions & 5 deletions nowplaying/show/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,24 @@ class ShowClient:
__cleanup_show_name_regexp = re.compile(r"&(\w+?);")
__show_datetime_format = "%Y-%m-%d %H:%M:%S"

def __init__(self, current_show_url):
class Options:
"""Options for ShowClient."""

self.current_show_url = current_show_url
def __init__(self, current_show_url, default_show_url="https://www.rabe.ch/"):
self.current_show_url = current_show_url
self.default_show_url = default_show_url

self.show = Show()
def __init__(self, options):
if isinstance(options, str):
logger.warning(
"legacy string options passed to ShowClient, please use a ShowClient.Options object instead"
)
options = __class__.Options(current_show_url=options)

self.options = options
self.current_show_url = options.current_show_url

self.show = Show(self.options)
self.showtz = None

def get_show_info(self, force_update=False):
Expand All @@ -47,15 +60,18 @@ def get_show_info(self, force_update=False):

def lazy_update(self):
# only update the info if we expect that a new show has started
if datetime.datetime.now(pytz.timezone("UTC")) > self.show.endtime:
if (
not self.show.endtime
or datetime.datetime.now(pytz.timezone("UTC")) > self.show.endtime
):
logger.info("Show expired, going to update show info")
self.update()

else:
logger.debug("Show still running, won't update show info")

def update(self):
self.show = Show() # Create a new show object
self.show = Show(self.options) # Create a new show object

# Set the show's default end time to now + 30 seconds to prevent updates
# happening every second and hammering the web service if something
Expand Down
47 changes: 24 additions & 23 deletions nowplaying/show/show.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,41 +3,42 @@
import logging.handlers
import uuid

import pytz
from nowplaypadgen.show import Show as PadGenShow, ShowError as PadGenShowError

logger = logging.getLogger(__name__)

DEFAULT_SHOW_URL = "https://www.rabe.ch"


class ShowError(Exception):
class ShowError(PadGenShowError):
"""Show related exception."""

pass


class Show:
class Show(PadGenShow):
"""Show object which has a start and end time and an optional URL."""

def __init__(self):
self.name = ""

self.url = DEFAULT_SHOW_URL
class Options:
def __init__(self, default_show_url: str = None):
if not default_show_url:
# TODO v3 remove this fallback
logger.warning(
"No default show URL specified, using deprecated hardcoded default."
)
default_show_url = "https://www.rabe.ch/"
self.default_show_url = default_show_url

def __init__(self, options: Options = None):
"""Initialize a new Show object."""
if isinstance(options, str) or options is None:
# TODO v3 remove this fallback
options = Show.Options()
self.options = options
super().__init__()

# The show's global unique identifier
self.uuid = str(uuid.uuid4())

# Get current datetime object in UTC timezone
now = datetime.datetime.now(pytz.timezone("UTC"))

# The show's start time, initially set to now
self.starttime = now

# The show's end time, initially set to to now
self.endtime = now
self.name = ""
self.url = self.options.default_show_url
self.uuid = str(uuid.uuid4()) #: The show's global unique identifier

def set_name(self, name):
# The name of the show
"""Set the show's name."""
self.name = name

def set_url(self, url):
Expand Down
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
ConfigArgParse==1.5.3
isodate==0.6.1
lxml==4.9.0
nowplaypadgen==0.4.1
opentelemetry-api==1.11.1
opentelemetry-exporter-otlp==1.11.1
opentelemetry-sdk==1.11.1
Expand Down
7 changes: 5 additions & 2 deletions tests/test_show.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,17 @@

import pytest
import pytz
from nowplaypadgen.show import Show as PadGenShow

from nowplaying.show.show import DEFAULT_SHOW_URL, Show, ShowError
from nowplaying.show.show import Show, ShowError

DEFAULT_SHOW_URL = "https://www.rabe.ch/"


def test_init():
"""Test :class:`Show`'s :meth:`.__init__` method."""
show = Show()
assert show.starttime == show.endtime
assert isinstance(show, PadGenShow)


def test_name():
Expand Down
6 changes: 3 additions & 3 deletions tests/test_show_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ def test_update_connection_error(mock_requests_get):
show_client = ShowClient(_BASE_URL)
show_client.update()
assert show_client.show.name == ""
assert show_client.show.url == "https://www.rabe.ch"
assert show_client.show.url == "https://www.rabe.ch/"


@patch("requests.get")
Expand All @@ -120,7 +120,7 @@ def test_update_no_url(mock_requests_get):
)
show_client = ShowClient(_BASE_URL)
show_client.update()
assert show_client.show.url == "https://www.rabe.ch"
assert show_client.show.url == "https://www.rabe.ch/"


@patch("requests.get")
Expand Down Expand Up @@ -171,7 +171,7 @@ def test_update_show_empty(mock_requests_get):
show_client = ShowClient(_BASE_URL)
show_client.update()
assert show_client.show.name == ""
assert show_client.show.url == "https://www.rabe.ch"
assert show_client.show.url == "https://www.rabe.ch/"


@patch("requests.get")
Expand Down
6 changes: 6 additions & 0 deletions tests/test_track_observer_tickertrack.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
"""Tests for :class:`observer.TickerTrackObserver`."""

import os
from datetime import datetime, timedelta

import pytest
import pytz

from nowplaying.track.observers.ticker import TickerTrackObserver

Expand All @@ -27,6 +29,10 @@ def test_track_started(track_factory, show_factory):
track = track_factory()
track.show = show_factory()

now = datetime.now(pytz.timezone("UTC"))
track.show.starttime = now
track.show.endtime = now + timedelta(hours=1)

ticker_track_observer = TickerTrackObserver(
ticker_file_path="/tmp/track_started.xml"
)
Expand Down