radio_browser.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. """Search radio stations from RadioBrowser by `Advanced station search API`_.
  4. .. _Advanced station search API:
  5. https://de1.api.radio-browser.info/#Advanced_station_search
  6. """
  7. from urllib.parse import urlencode
  8. import babel
  9. from flask_babel import gettext
  10. from searx.network import get
  11. from searx.enginelib.traits import EngineTraits
  12. from searx.locales import language_tag
  13. traits: EngineTraits
  14. about = {
  15. "website": 'https://www.radio-browser.info/',
  16. "wikidata_id": 'Q111664849',
  17. "official_api_documentation": 'https://de1.api.radio-browser.info/',
  18. "use_official_api": True,
  19. "require_api_key": False,
  20. "results": 'JSON',
  21. }
  22. paging = True
  23. categories = ['music', 'radio']
  24. base_url = "https://de1.api.radio-browser.info" # see https://api.radio-browser.info/ for all nodes
  25. number_of_results = 10
  26. station_filters = [] # ['countrycode', 'language']
  27. """A list of filters to be applied to the search of radio stations. By default
  28. none filters are applied. Valid filters are:
  29. ``language``
  30. Filter stations by selected language. For instance the ``de`` from ``:de-AU``
  31. will be translated to `german` and used in the argument ``language=``.
  32. ``countrycode``
  33. Filter stations by selected country. The 2-digit countrycode of the station
  34. comes from the region the user selected. For instance ``:de-AU`` will filter
  35. out all stations not in ``AU``.
  36. .. note::
  37. RadioBrowser has registered a lot of languages and countrycodes unknown to
  38. :py:obj:`babel` and note that when searching for radio stations, users are
  39. more likely to search by name than by region or language.
  40. """
  41. def request(query, params):
  42. args = {
  43. 'name': query,
  44. 'order': 'votes',
  45. 'offset': (params['pageno'] - 1) * number_of_results,
  46. 'limit': number_of_results,
  47. 'hidebroken': 'true',
  48. 'reverse': 'true',
  49. }
  50. if 'language' in station_filters:
  51. lang = traits.get_language(params['searxng_locale']) # type: ignore
  52. if lang:
  53. args['language'] = lang
  54. if 'countrycode' in station_filters:
  55. if len(params['searxng_locale'].split('-')) > 1:
  56. countrycode = params['searxng_locale'].split('-')[-1].upper()
  57. if countrycode in traits.custom['countrycodes']: # type: ignore
  58. args['countrycode'] = countrycode
  59. params['url'] = f"{base_url}/json/stations/search?{urlencode(args)}"
  60. return params
  61. def response(resp):
  62. results = []
  63. json_resp = resp.json()
  64. for result in json_resp:
  65. url = result['homepage']
  66. if not url:
  67. url = result['url_resolved']
  68. content = []
  69. tags = ', '.join(result.get('tags', '').split(','))
  70. if tags:
  71. content.append(tags)
  72. for x in ['state', 'country']:
  73. v = result.get(x)
  74. if v:
  75. v = str(v).strip()
  76. content.append(v)
  77. metadata = []
  78. codec = result.get('codec')
  79. if codec and codec.lower() != 'unknown':
  80. metadata.append(f'{codec} ' + gettext('radio'))
  81. for x, y in [
  82. (gettext('bitrate'), 'bitrate'),
  83. (gettext('votes'), 'votes'),
  84. (gettext('clicks'), 'clickcount'),
  85. ]:
  86. v = result.get(y)
  87. if v:
  88. v = str(v).strip()
  89. metadata.append(f"{x} {v}")
  90. results.append(
  91. {
  92. 'url': url,
  93. 'title': result['name'],
  94. 'img_src': result.get('favicon', '').replace("http://", "https://"),
  95. 'content': ' | '.join(content),
  96. 'metadata': ' | '.join(metadata),
  97. 'iframe_src': result['url_resolved'].replace("http://", "https://"),
  98. }
  99. )
  100. return results
  101. def fetch_traits(engine_traits: EngineTraits):
  102. """Fetch languages and countrycodes from RadioBrowser
  103. - ``traits.languages``: `list of languages API`_
  104. - ``traits.custom['countrycodes']``: `list of countries API`_
  105. .. _list of countries API: https://de1.api.radio-browser.info/#List_of_countries
  106. .. _list of languages API: https://de1.api.radio-browser.info/#List_of_languages
  107. """
  108. # pylint: disable=import-outside-toplevel
  109. from babel.core import get_global
  110. babel_reg_list = get_global("territory_languages").keys()
  111. language_list = get(f'{base_url}/json/languages').json() # type: ignore
  112. country_list = get(f'{base_url}/json/countries').json() # type: ignore
  113. for lang in language_list:
  114. babel_lang = lang.get('iso_639')
  115. if not babel_lang:
  116. # the language doesn't have any iso code, and hence can't be parsed
  117. # print(f"ERROR: lang - no iso code in {lang}")
  118. continue
  119. try:
  120. sxng_tag = language_tag(babel.Locale.parse(babel_lang, sep="-"))
  121. except babel.UnknownLocaleError:
  122. # print(f"ERROR: language tag {babel_lang} is unknown by babel")
  123. continue
  124. eng_tag = lang['name']
  125. conflict = engine_traits.languages.get(sxng_tag)
  126. if conflict:
  127. if conflict != eng_tag:
  128. print("CONFLICT: babel %s --> %s, %s" % (sxng_tag, conflict, eng_tag))
  129. continue
  130. engine_traits.languages[sxng_tag] = eng_tag
  131. countrycodes = set()
  132. for region in country_list:
  133. if region['iso_3166_1'] not in babel_reg_list:
  134. print(f"ERROR: region tag {region['iso_3166_1']} is unknown by babel")
  135. continue
  136. countrycodes.add(region['iso_3166_1'])
  137. countrycodes = list(countrycodes)
  138. countrycodes.sort()
  139. engine_traits.custom['countrycodes'] = countrycodes