AzuraCast: format code

This commit is contained in:
oddluck 2020-06-13 12:12:42 +00:00
parent 771d7d8e07
commit 805baaecb2
4 changed files with 109 additions and 87 deletions

View File

@ -25,10 +25,11 @@ __author__ = supybot.authors.unknown
__contributors__ = {} __contributors__ = {}
# This is a url where the most recent plugin package can be downloaded. # This is a url where the most recent plugin package can be downloaded.
__url__ = '' __url__ = ""
from . import config from . import config
from . import plugin from . import plugin
if sys.version_info >= (3, 4): if sys.version_info >= (3, 4):
from importlib import reload from importlib import reload
else: else:

View File

@ -6,9 +6,11 @@
### ###
from supybot import conf, registry from supybot import conf, registry
try: try:
from supybot.i18n import PluginInternationalization from supybot.i18n import PluginInternationalization
_ = PluginInternationalization('AzuraCast')
_ = PluginInternationalization("AzuraCast")
except: except:
# Placeholder that allows to run the plugin on a bot # Placeholder that allows to run the plugin on a bot
# without the i18n module # without the i18n module
@ -21,16 +23,19 @@ def configure(advanced):
# user or not. You should effect your configuration by manipulating the # user or not. You should effect your configuration by manipulating the
# registry as appropriate. # registry as appropriate.
from supybot.questions import expect, anything, something, yn from supybot.questions import expect, anything, something, yn
conf.registerPlugin('AzuraCast', True)
conf.registerPlugin("AzuraCast", True)
AzuraCast = conf.registerPlugin('AzuraCast') AzuraCast = conf.registerPlugin("AzuraCast")
# This is where your configuration variables (if any) should go. For example: # This is where your configuration variables (if any) should go. For example:
# conf.registerGlobalValue(AzuraCast, 'someConfigVariableName', # conf.registerGlobalValue(AzuraCast, 'someConfigVariableName',
# registry.Boolean(False, _("""Help for someConfigVariableName."""))) # registry.Boolean(False, _("""Help for someConfigVariableName.""")))
conf.registerGlobalValue(AzuraCast, 'AzuraAPI', conf.registerGlobalValue(
registry.String('', _("""AzuraCast local API URL"""))) AzuraCast, "AzuraAPI", registry.String("", _("""AzuraCast local API URL"""))
conf.registerGlobalValue(AzuraCast, 'PublicURL', )
registry.String('', _("""Public URL for your radio"""))) conf.registerGlobalValue(
AzuraCast, "PublicURL", registry.String("", _("""Public URL for your radio"""))
)
# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79: # vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:

View File

@ -9,9 +9,11 @@ import requests
from supybot import utils, plugins, ircutils, callbacks from supybot import utils, plugins, ircutils, callbacks
from supybot.commands import * from supybot.commands import *
try: try:
from supybot.i18n import PluginInternationalization from supybot.i18n import PluginInternationalization
_ = PluginInternationalization('AzuraCast')
_ = PluginInternationalization("AzuraCast")
except ImportError: except ImportError:
# Placeholder that allows to run the plugin on a bot # Placeholder that allows to run the plugin on a bot
# without the i18n module # without the i18n module
@ -20,14 +22,15 @@ except ImportError:
class AzuraCast(callbacks.Plugin): class AzuraCast(callbacks.Plugin):
"""Plugin for the AzuraCast API""" """Plugin for the AzuraCast API"""
threaded = True threaded = True
def __init__(self, irc): def __init__(self, irc):
self.__parent = super(AzuraCast, self) self.__parent = super(AzuraCast, self)
self.__parent.__init__(irc) self.__parent.__init__(irc)
self.BASE_API = self.registryValue('AzuraAPI') self.BASE_API = self.registryValue("AzuraAPI")
self.PUB_URL = self.registryValue('PublicURL') + '#{name}' self.PUB_URL = self.registryValue("PublicURL") + "#{name}"
def _fetchURL(self, url, headers=None): def _fetchURL(self, url, headers=None):
return requests.get(url, headers=headers).json() return requests.get(url, headers=headers).json()
@ -36,32 +39,38 @@ class AzuraCast(callbacks.Plugin):
stations = {} stations = {}
for station in data: for station in data:
tmp_dict = {} tmp_dict = {}
code = station['station']['shortcode'] code = station["station"]["shortcode"]
tmp_dict['id'] = station['station']['id'] tmp_dict["id"] = station["station"]["id"]
tmp_dict['name'] = station['station']['name'] tmp_dict["name"] = station["station"]["name"]
tmp_dict['description'] = station['station']['description'] tmp_dict["description"] = station["station"]["description"]
tmp_dict['player_url'] = station['station']['listen_url'].split('?')[0] \ tmp_dict["player_url"] = (
if station['station']['is_public'] else '' station["station"]["listen_url"].split("?")[0]
tmp_dict['public_url'] = self.PUB_URL.format( if station["station"]["is_public"]
name=code) if station['station']['is_public'] else '' else ""
tmp_dict['listeners'] = station['listeners'] )
tmp_dict['nowplaying'] = station['now_playing'] tmp_dict["public_url"] = (
self.PUB_URL.format(name=code)
if station["station"]["is_public"]
else ""
)
tmp_dict["listeners"] = station["listeners"]
tmp_dict["nowplaying"] = station["now_playing"]
stations[code] = tmp_dict stations[code] = tmp_dict
return stations return stations
@wrap([getopts({'station': 'somethingWithoutSpaces'})]) @wrap([getopts({"station": "somethingWithoutSpaces"})])
def nowplaying(self, irc, msg, args, options): def nowplaying(self, irc, msg, args, options):
""" """
Fetches what is now playing Fetches what is now playing
""" """
options = dict(options) options = dict(options)
station = options.get('station') station = options.get("station")
url = self.BASE_API + 'nowplaying' url = self.BASE_API + "nowplaying"
data = self._fetchURL(url) data = self._fetchURL(url)
if not data: if not data:
irc.reply('ERROR: Something went wrong fetching data @ {}'.format(url)) irc.reply("ERROR: Something went wrong fetching data @ {}".format(url))
return return
data = self._parseData(data) data = self._parseData(data)
@ -70,26 +79,38 @@ class AzuraCast(callbacks.Plugin):
if station: if station:
# one station only # one station only
d = data.get(station.lower()) d = data.get(station.lower())
prefix = ircutils.bold('Now Playing on {}:'.format(d['name'])) prefix = ircutils.bold("Now Playing on {}:".format(d["name"]))
album = ' [{}]'.format(d['nowplaying']['song']['album']) \ album = (
if d['nowplaying']['song']['album'] else '' " [{}]".format(d["nowplaying"]["song"]["album"])
url = ' | {}'.format(d['public_url']) if d['public_url'] else '' if d["nowplaying"]["song"]["album"]
np = '{}'.format(d['nowplaying']['song']['text']) else ""
listeners = " | Listeners: {}".format(d['listeners']['current']) )
listen = " | Audio player link: {}/public/{}/playlist/pls".format(self.BASE_API.replace("/api/", ""), d['id']) url = " | {}".format(d["public_url"]) if d["public_url"] else ""
string = '{} {}{}{}{}{}'.format(prefix, np, album, listeners, url, listen) np = "{}".format(d["nowplaying"]["song"]["text"])
listeners = " | Listeners: {}".format(d["listeners"]["current"])
listen = " | Audio player link: {}/public/{}/playlist/pls".format(
self.BASE_API.replace("/api/", ""), d["id"]
)
string = "{} {}{}{}{}{}".format(prefix, np, album, listeners, url, listen)
output.append(string) output.append(string)
else: else:
# all stations? # all stations?
for s, d in data.items(): for s, d in data.items():
prefix = ircutils.bold('Now Playing on {}:'.format(d['name'])) prefix = ircutils.bold("Now Playing on {}:".format(d["name"]))
album = ' [{}]'.format(d['nowplaying']['song']['album']) \ album = (
if d['nowplaying']['song']['album'] else '' " [{}]".format(d["nowplaying"]["song"]["album"])
url = ' | {}'.format(d['public_url']) if d['public_url'] else '' if d["nowplaying"]["song"]["album"]
np = '{}'.format(d['nowplaying']['song']['text']) else ""
listeners = " | Listeners: {}".format(d['listeners']['current']) )
listen = " | Audio player link: {}/public/{}/playlist/pls".format(self.BASE_API.replace("/api/", ""), d['id']) url = " | {}".format(d["public_url"]) if d["public_url"] else ""
string = '{} {}{}{}{}{}'.format(prefix, np, album, listeners, url, listen) np = "{}".format(d["nowplaying"]["song"]["text"])
listeners = " | Listeners: {}".format(d["listeners"]["current"])
listen = " | Audio player link: {}/public/{}/playlist/pls".format(
self.BASE_API.replace("/api/", ""), d["id"]
)
string = "{} {}{}{}{}{}".format(
prefix, np, album, listeners, url, listen
)
output.append(string) output.append(string)
for string in output: for string in output:
@ -97,19 +118,19 @@ class AzuraCast(callbacks.Plugin):
return return
@wrap([getopts({'station': 'somethingWithoutSpaces'})]) @wrap([getopts({"station": "somethingWithoutSpaces"})])
def listeners(self, irc, msg, args, options): def listeners(self, irc, msg, args, options):
""" """
Fetches listeners Fetches listeners
""" """
options = dict(options) options = dict(options)
station = options.get('station') station = options.get("station")
url = self.BASE_API + 'nowplaying' url = self.BASE_API + "nowplaying"
data = self._fetchURL(url) data = self._fetchURL(url)
if not data: if not data:
irc.reply('ERROR: Something went wrong fetching data @ {}'.format(url)) irc.reply("ERROR: Something went wrong fetching data @ {}".format(url))
return return
data = self._parseData(data) data = self._parseData(data)
@ -118,39 +139,34 @@ class AzuraCast(callbacks.Plugin):
if station: if station:
# one station only # one station only
d = data.get(station.lower()) d = data.get(station.lower())
count = d['listeners']['current'] count = d["listeners"]["current"]
if count > 1 and count != 0: if count > 1 and count != 0:
cur = 'are currently' cur = "are currently"
plr = ' {} listeners '.format(ircutils.bold(count)) plr = " {} listeners ".format(ircutils.bold(count))
elif count == 1: elif count == 1:
cur = 'is currently' cur = "is currently"
plr = ' {} listener '.format(ircutils.bold(count)) plr = " {} listener ".format(ircutils.bold(count))
else: else:
cur = 'are no listeners' cur = "are no listeners"
plr = ' ' plr = " "
string = 'There {}{}on {}'.format( string = "There {}{}on {}".format(cur, plr, ircutils.bold(d["name"]))
cur, plr,
ircutils.bold(d['name']))
output.append(string) output.append(string)
else: else:
# all stations? # all stations?
for s, d in data.items(): for s, d in data.items():
count = d['listeners']['current'] count = d["listeners"]["current"]
if count > 1 and count != 0: if count > 1 and count != 0:
cur = 'are currently' cur = "are currently"
plr = ' {} listeners '.format(ircutils.bold(count)) plr = " {} listeners ".format(ircutils.bold(count))
elif count == 1: elif count == 1:
cur = 'is currently' cur = "is currently"
plr = ' {} listener '.format(ircutils.bold(count)) plr = " {} listener ".format(ircutils.bold(count))
else: else:
cur = 'are no listeners' cur = "are no listeners"
plr = ' ' plr = " "
string = 'There {}{}on {}'.format( string = "There {}{}on {}".format(cur, plr, ircutils.bold(d["name"]))
cur, plr,
ircutils.bold(d['name']))
output.append(string) output.append(string)
for string in output: for string in output:
irc.reply(string) irc.reply(string)

View File

@ -9,7 +9,7 @@ from supybot.test import *
class AzuraCastTestCase(PluginTestCase): class AzuraCastTestCase(PluginTestCase):
plugins = ('AzuraCast',) plugins = ("AzuraCast",)
# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79: # vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79: