radio_browser.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """Search radio stations from RadioBrowser by `Advanced station search API`_.
  3. .. _Advanced station search API:
  4. https://de1.api.radio-browser.info/#Advanced_station_search
  5. """
  6. import random
  7. import socket
  8. from urllib.parse import urlencode
  9. import babel
  10. from flask_babel import gettext
  11. from searx.network import get
  12. from searx.enginelib.traits import EngineTraits
  13. from searx.locales import language_tag
  14. traits: EngineTraits
  15. about = {
  16. "website": 'https://www.radio-browser.info/',
  17. "wikidata_id": 'Q111664849',
  18. "official_api_documentation": 'https://de1.api.radio-browser.info/',
  19. "use_official_api": True,
  20. "require_api_key": False,
  21. "results": 'JSON',
  22. }
  23. paging = True
  24. categories = ['music', 'radio']
  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. servers = []
  42. def init(_):
  43. # see https://api.radio-browser.info
  44. ips = socket.getaddrinfo("all.api.radio-browser.info", 80, 0, 0, socket.IPPROTO_TCP)
  45. for ip_tuple in ips:
  46. _ip: str = ip_tuple[4][0] # type: ignore
  47. url = socket.gethostbyaddr(_ip)[0]
  48. srv = "https://" + url
  49. if srv not in servers:
  50. servers.append(srv)
  51. def request(query, params):
  52. args = {
  53. 'name': query,
  54. 'order': 'votes',
  55. 'offset': (params['pageno'] - 1) * number_of_results,
  56. 'limit': number_of_results,
  57. 'hidebroken': 'true',
  58. 'reverse': 'true',
  59. }
  60. if 'language' in station_filters:
  61. lang = traits.get_language(params['searxng_locale']) # type: ignore
  62. if lang:
  63. args['language'] = lang
  64. if 'countrycode' in station_filters:
  65. if len(params['searxng_locale'].split('-')) > 1:
  66. countrycode = params['searxng_locale'].split('-')[-1].upper()
  67. if countrycode in traits.custom['countrycodes']: # type: ignore
  68. args['countrycode'] = countrycode
  69. params['url'] = f"{random.choice(servers)}/json/stations/search?{urlencode(args)}"
  70. return params
  71. def response(resp):
  72. results = []
  73. json_resp = resp.json()
  74. for result in json_resp:
  75. url = result['homepage']
  76. if not url:
  77. url = result['url_resolved']
  78. content = []
  79. tags = ', '.join(result.get('tags', '').split(','))
  80. if tags:
  81. content.append(tags)
  82. for x in ['state', 'country']:
  83. v = result.get(x)
  84. if v:
  85. v = str(v).strip()
  86. content.append(v)
  87. metadata = []
  88. codec = result.get('codec')
  89. if codec and codec.lower() != 'unknown':
  90. metadata.append(f'{codec} ' + gettext('radio'))
  91. for x, y in [
  92. (gettext('bitrate'), 'bitrate'),
  93. (gettext('votes'), 'votes'),
  94. (gettext('clicks'), 'clickcount'),
  95. ]:
  96. v = result.get(y)
  97. if v:
  98. v = str(v).strip()
  99. metadata.append(f"{x} {v}")
  100. results.append(
  101. {
  102. 'url': url,
  103. 'title': result['name'],
  104. 'thumbnail': result.get('favicon', '').replace("http://", "https://"),
  105. 'content': ' | '.join(content),
  106. 'metadata': ' | '.join(metadata),
  107. 'iframe_src': result['url_resolved'].replace("http://", "https://"),
  108. }
  109. )
  110. return results
  111. def fetch_traits(engine_traits: EngineTraits):
  112. """Fetch languages and countrycodes from RadioBrowser
  113. - ``traits.languages``: `list of languages API`_
  114. - ``traits.custom['countrycodes']``: `list of countries API`_
  115. .. _list of countries API: https://de1.api.radio-browser.info/#List_of_countries
  116. .. _list of languages API: https://de1.api.radio-browser.info/#List_of_languages
  117. """
  118. # pylint: disable=import-outside-toplevel
  119. init(None)
  120. from babel.core import get_global
  121. babel_reg_list = get_global("territory_languages").keys()
  122. language_list = get(f'{servers[0]}/json/languages').json() # type: ignore
  123. country_list = get(f'{servers[0]}/json/countries').json() # type: ignore
  124. for lang in language_list:
  125. babel_lang = lang.get('iso_639')
  126. if not babel_lang:
  127. # the language doesn't have any iso code, and hence can't be parsed
  128. # print(f"ERROR: lang - no iso code in {lang}")
  129. continue
  130. try:
  131. sxng_tag = language_tag(babel.Locale.parse(babel_lang, sep="-"))
  132. except babel.UnknownLocaleError:
  133. # print(f"ERROR: language tag {babel_lang} is unknown by babel")
  134. continue
  135. eng_tag = lang['name']
  136. conflict = engine_traits.languages.get(sxng_tag)
  137. if conflict:
  138. if conflict != eng_tag:
  139. print("CONFLICT: babel %s --> %s, %s" % (sxng_tag, conflict, eng_tag))
  140. continue
  141. engine_traits.languages[sxng_tag] = eng_tag
  142. countrycodes = set()
  143. for region in country_list:
  144. # country_list contains duplicates that differ only in upper/lower case
  145. _reg = region['iso_3166_1'].upper()
  146. if _reg not in babel_reg_list:
  147. print(f"ERROR: region tag {region['iso_3166_1']} is unknown by babel")
  148. continue
  149. countrycodes.add(_reg)
  150. countrycodes = list(countrycodes)
  151. countrycodes.sort()
  152. engine_traits.custom['countrycodes'] = countrycodes