external_bang.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import json
  2. from os.path import join
  3. from searx import searx_dir
  4. # bangs data coming from the following url convert to json with
  5. # https://raw.githubusercontent.com/jivesearch/jivesearch/master/bangs/bangs.toml
  6. # https://pseitz.github.io/toml-to-json-online-converter/
  7. # NOTE only use the get_bang_url
  8. bangs_data = {}
  9. with open(join(searx_dir, 'data/bangs.json')) as json_file:
  10. for bang in json.load(json_file)['bang']:
  11. for trigger in bang["triggers"]:
  12. bangs_data[trigger] = {x: y for x, y in bang.items() if x != "triggers"}
  13. def get_bang_url(search_query):
  14. """
  15. Redirects if the user supplied a correct bang search.
  16. :param search_query: This is a search_query object which contains preferences and the submitted queries.
  17. :return: None if the bang was invalid, else a string of the redirect url.
  18. """
  19. if search_query.external_bang:
  20. query = search_query.query.decode('utf-8', 'ignore')
  21. bang = _get_bang(search_query.external_bang)
  22. if bang and query:
  23. # TODO add region support.
  24. bang_url = bang["regions"]["default"]
  25. return bang_url.replace("{{{term}}}", query)
  26. return None
  27. def _get_bang(user_bang):
  28. """
  29. Searches if the supplied user bang is available. Returns None if not found.
  30. :param user_bang: The parsed user bang. For example yt
  31. :return: Returns a dict with bangs data (check bangs_data.json for the structure)
  32. """
  33. return bangs_data.get(user_bang)