Exemple #1
0
	def __init__(self):

		self.nombre_radios_pais = []
		self.url_radios_pais = []
		self.resultado_pais_busqueda_nombre = []
		self.resultado_pais_busqueda_numero = []
		self.resultado_pais_busqueda_abreviado = []

		self.nombre_busqueda_general_radio = []
		self.url_busqueda_general_radio = []

		self.nombre_idioma = []
		self.cantidad_idioma = []
		self.busqueda_nombre_idioma = []
		self.busqueda_cantidad_idioma = []

		self.nombre_tag = []
		self.cantidad_tag = []
		self.busqueda_nombre_tag = []
		self.busqueda_cantidad_tag = []

		self.paises_radio_español = []
		self.paises_radio_abreviado = []
		self.paises_numero_emisoras = []
		self.paises_numero_total_emisoras = ""

		expire_after = timedelta(days=3)
		session = CachedSession(
			cache_name=os.path.join(globalVars.appArgs.configPath, "zRadio", "cache"),
			backend='sqlite',
			expire_after=expire_after)
		self.rb = RadioBrowser(session=session)
		self.datos_pais = self.rb.countries()
Exemple #2
0
    def __init__(self):

        self.nombre_radios_pais = []
        self.url_radios_pais = []
        self.resultado_pais_busqueda_nombre = []
        self.resultado_pais_busqueda_numero = []
        self.resultado_pais_busqueda_abreviado = []

        self.nombre_busqueda_general_radio = []
        self.url_busqueda_general_radio = []

        self.nombre_idioma = []
        self.cantidad_idioma = []
        self.busqueda_nombre_idioma = []
        self.busqueda_cantidad_idioma = []

        self.nombre_tag = []
        self.cantidad_tag = []
        self.busqueda_nombre_tag = []
        self.busqueda_cantidad_tag = []

        self.paises_radio_español = []
        self.paises_radio_abreviado = []
        self.paises_numero_emisoras = []
        self.paises_numero_total_emisoras = ""

        self.rb = RadioBrowser()
        self.datos_pais = self.rb.countries()
Exemple #3
0
def cmd_rb_play(bot, user, text, command, parameter):
    global log

    log.debug('cmd: Play a station by ID')
    if not parameter:
        log.debug('rbplay without parameter')
        msg = tr('rb_play_empty')
        bot.send_msg(msg, text)
    else:
        log.debug('cmd: Retreiving url for station ID ' + parameter)
        rb = RadioBrowser()
        rstation = rb.station_by_uuid(parameter)
        stationname = rstation[0]['name']
        country = rstation[0]['countrycode']
        codec = rstation[0]['codec']
        bitrate = rstation[0]['bitrate']
        genre = rstation[0]['tags']
        homepage = rstation[0]['homepage']
        url = rstation[0]['url']
        msg = 'Radio station added to playlist:'

        msg += '<table><tr><th>ID</th><th>Station Name</th><th>Genre</th><th>Codec/Bitrate</th><th>Country</th><th>Homepage</th></tr>' + \
               f"<tr><td>{parameter}</td><td>{stationname}</td><td>{genre}</td><td>{codec}/{bitrate}</td><td>{country}</td><td>{homepage}</td></tr></table>"
        log.debug(f'cmd: Added station to playlist {stationname}')
        bot.send_msg(msg, text)
        if url != "-1":
            log.info('cmd: Found url: ' + url)
            music_wrapper = get_cached_wrapper_from_scrap(type='radio', url=url, name=stationname, user=user)
            var.playlist.append(music_wrapper)
            log.info("cmd: add to playlist: " + music_wrapper.format_debug_string())
            bot.async_download_next()
        else:
            log.info('cmd: No playable url found.')
            msg += "No playable url found for this station, please try another station."
            bot.send_msg(msg, text)
Exemple #4
0
    def CPS_match_query_phrase(self, phrase):
        # Look for regex matches
        # Play (radio|station|stream) <data>
        match = re.search(self.translate_regex('radio'), phrase)
        try:
            data = re.sub(self.translate_regex('radio'), '', phrase)
            rb = RadioBrowser()
            stations = rb.search(name=data, bitrateMin='128')
            stations != []
            self.log.info('CPS Match (radio): ' + stations[0]['name'] + ' | ' +
                          stations[0]['url'])

            if match:
                return (stations[0]['name'], CPSMatchLevel.EXACT, {
                    "station": stations[0]["name"],
                    "url": stations[0]["url"],
                    "image": stations[0]['favicon']
                })
            else:
                return (stations[0]['name'], CPSMatchLevel.TITLE, {
                    "station": stations[0]["name"],
                    "url": stations[0]["url"],
                    "image": stations[0]['favicon']
                })
        except Exception:
            return None
Exemple #5
0
def match_genre(phrase):
    """Takes the user utterance and attempts to match a genre of station,
    returning the most popular of that genre.

    :param phrase: User utterance
    :type phrase: str

    :return: A tuple containing the original phrase, the CPS.MatchLevel,
    and a dictionary containing the resolved stream URL.
    :rtype: tuple
    """
    # Strip 'a' and 'station' from phrases like 'Play a jazz station.'.
    stripped_phrase = phrase.lower().replace("a ", "").replace(" station", "")
    try:
        rb = RadioBrowser()
    except Exception as e:
        LOG.exception("Failed to load pyradios" + repr(e))
    LOG.info(f"Searching for a {stripped_phrase} station")
    results = rb.search(tag=stripped_phrase, order="votes")
    parsed = json.loads(json.dumps(results))

    if len(parsed) > 0:
        LOG.info(f"Found {parsed[0]['name']} ({parsed[0]['url_resolved']})")
        return phrase, CPSMatchLevel.EXACT, {"url": parsed[0]["url_resolved"]}
    else:
        match_station_name(phrase)
Exemple #6
0
def cmd_rb_query(bot, user, text, command, parameter):
    global log

    log.info('cmd: Querying radio stations')
    if not parameter:
        log.debug('rbquery without parameter')
        msg = tr('rb_query_empty')
        bot.send_msg(msg, text)
    else:
        log.debug('cmd: Found query parameter: ' + parameter)
        rb = RadioBrowser()
        rb_stations = rb.search(name=parameter, name_exact=False)
        msg = tr('rb_query_result')
        msg += '\n<table><tr><th>!rbplay ID</th><th>Station Name</th><th>Genre</th><th>Codec/Bitrate</th><th>Country</th></tr>'
        if not rb_stations:
            log.debug(f"cmd: No matches found for rbquery {parameter}")
            bot.send_msg(f"Radio-Browser found no matches for {parameter}",
                         text)
        else:
            for s in rb_stations:
                station_id = s['stationuuid']
                station_name = s['name']
                country = s['countrycode']
                codec = s['codec']
                bitrate = s['bitrate']
                genre = s['tags']
                msg += f"<tr><td>{station_id}</td><td>{station_name}</td><td>{genre}</td><td>{codec}/{bitrate}</td><td>{country}</td></tr>"
            msg += '</table>'
            # Full message as html table
            if len(msg) <= 5000:
                bot.send_msg(msg, text)
            # Shorten message if message too long (stage I)
            else:
                log.debug('Result too long stage I')
                msg = tr('rb_query_result') + ' (shortened L1)'
                msg += '\n<table><tr><th>!rbplay ID</th><th>Station Name</th></tr>'
                for s in rb_stations:
                    station_id = s['stationuuid']
                    station_name = s['name']
                    msg += f'<tr><td>{station_id}</td><td>{station_name}</td>'
                msg += '</table>'
                if len(msg) <= 5000:
                    bot.send_msg(msg, text)
                # Shorten message if message too long (stage II)
                else:
                    log.debug('Result too long stage II')
                    msg = tr('rb_query_result') + ' (shortened L2)'
                    msg += '!rbplay ID - Station Name'
                    for s in rb_stations:
                        station_id = s['stationuuid']
                        station_name = s['name'][:12]
                        msg += f'{station_id} - {station_name}'
                    if len(msg) <= 5000:
                        bot.send_msg(msg, text)
                    # Message still too long
                    else:
                        bot.send_msg(
                            'Query result too long to post (> 5000 characters), please try another query.',
                            text)
Exemple #7
0
def match_station_name(phrase):
    """Takes the user utterance and attempts to match a specific station

    :param phrase: User utterance
    :type phrase: str

    :return: A tuple containing the original phrase, the CPS.MatchLevel,
    and a dictionary containing the resolved stream URL.
    :rtype: tuple
    """
    numbers_regex = r"\b(one|two|three|four|five|six|seven|eight|nine)\b"
    try:
        rb = RadioBrowser()
    except Exception as e:
        LOG.exception("Failed to load pyradios" + repr(e))
    LOG.info(f"Searching for {phrase}")
    results = rb.search(name=phrase)
    parsed = json.loads(json.dumps(results))

    if len(parsed) > 0:
        # If an exatch match has been found return.
        LOG.info(f"Found {parsed[0]['name']} ({parsed[0]['url_resolved']})")
        return phrase, CPSMatchLevel.EXACT, {"url": parsed[0]["url_resolved"]}
    elif re.search(" [0-9]+ ", phrase):
        # If no match has been found, replace any digits (1,2,3) with text
        # (one, two, three) and repeat search.
        num = re.findall("[0-9]+", phrase)
        inf_eng = inflect.engine()
        for number in num:
            phrase = phrase.replace(num, inf_eng.number_to_words(number))
        match_station_name(phrase)
    elif re.search(numbers_regex, phrase):
        # As above but reversed: change strings to ints and repeat search.
        num = re.findall(numbers_regex, phrase)
        for number in num:
            phrase = phrase.replace(number, str(w2n.word_to_num(number)))
        match_station_name(phrase)
    else:
        return None
Exemple #8
0
from pyradios import RadioBrowser
rb = RadioBrowser()


def get_radio(radio_title):
    stantions = rb.stations_by_name(radio_title)
    if stantions == []:
        return {}
    stantion = sorted(stantions, key=lambda k: k['votes'], reverse=True)[0]
    return {
        "title": stantion['name'],
        "duration": "radio",
        "file": stantion['url_resolved'],
        "cover": stantion.get("favicon")
    }
Exemple #9
0
    def __init__(self):
        self.API = None
        self.response = None
        self.target_station = None

        self.API = RadioBrowser()
Exemple #10
0
def rb():
    return RadioBrowser(base_url=BASE_URL)
Exemple #11
0
    def init(self, settings, q):
        self.module_path = os.path.dirname(os.path.abspath(__file__))

        try:
            lang = gettext.translation('pext_module_radio',
                                       localedir=os.path.join(
                                           self.module_path, 'locale'),
                                       languages=[settings['_locale']])
        except FileNotFoundError:
            lang = gettext.NullTranslations()
            print("No {} translation available for pext_module_radio".format(
                settings['_locale']))

        lang.install()

        self.rb = RadioBrowser()

        self.settings = settings
        self.q = q

        self.favourites = []
        try:
            with open(os.path.join(self.module_path, "_user_favourites.txt"),
                      "r") as favourites_file:
                for favourite in favourites_file:
                    self.favourites.append(favourite.strip())
        except IOError:
            pass

        self.cached = {
            'countries': {
                'time': 0
            },
            'codecs': {
                'time': 0
            },
            'languages': {
                'time': 0
            },
            'tags': {
                'time': 0
            }
        }

        self.cachedStations = {
            '_favourites': {
                'time': 0
            },
            'countries': {},
            'codecs': {},
            'languages': {},
            'tags': {},
            'topvote': {
                'time': 0
            },
            'topclick': {
                'time': 0
            },
            'lastclick': {
                'time': 0
            },
            'lastchange': {
                'time': 0
            }
        }

        self.nowPlaying = None

        if not which("ffplay"):
            self.q.put([
                Action.critical_error,
                _("ffplay is not installed, please install it.")
            ])
            return

        self._get_entries()
Exemple #12
0
def rb():
    _rb = RadioBrowser()
    return _rb
Exemple #13
0
def rb():
    _rb = RadioBrowser()
    _rb.base_url = BASE_URL
    return _rb