stract.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """Stract is an independent open source search engine. At this state, it's
  3. still in beta and hence this implementation will need to be updated once beta
  4. ends.
  5. """
  6. from json import dumps
  7. from searx.utils import searx_useragent
  8. from searx.enginelib.traits import EngineTraits
  9. about = {
  10. "website": "https://stract.com/",
  11. "use_official_api": True,
  12. "official_api_documentation": "https://stract.com/beta/api/docs/#/search/api",
  13. "require_api_key": False,
  14. "results": "JSON",
  15. }
  16. categories = ['general']
  17. paging = True
  18. base_url = "https://stract.com/beta/api"
  19. search_url = base_url + "/search"
  20. traits: EngineTraits
  21. def request(query, params):
  22. params['url'] = search_url
  23. params['method'] = "POST"
  24. params['headers'] = {
  25. 'Accept': 'application/json',
  26. 'Content-Type': 'application/json',
  27. 'User-Agent': searx_useragent(),
  28. }
  29. region = traits.get_region(params["searxng_locale"], default=traits.all_locale)
  30. params['data'] = dumps(
  31. {
  32. 'query': query,
  33. 'page': params['pageno'] - 1,
  34. 'selectedRegion': region,
  35. }
  36. )
  37. return params
  38. def response(resp):
  39. results = []
  40. for result in resp.json()["webpages"]:
  41. results.append(
  42. {
  43. 'url': result['url'],
  44. 'title': result['title'],
  45. 'content': ''.join(fragment['text'] for fragment in result['snippet']['text']['fragments']),
  46. }
  47. )
  48. return results
  49. def fetch_traits(engine_traits: EngineTraits):
  50. # pylint: disable=import-outside-toplevel
  51. from searx import network
  52. from babel import Locale, languages
  53. from searx.locales import region_tag
  54. territories = Locale("en").territories
  55. json = network.get(base_url + "/docs/openapi.json").json()
  56. regions = json['components']['schemas']['Region']['enum']
  57. engine_traits.all_locale = regions[0]
  58. for region in regions[1:]:
  59. for code, name in territories.items():
  60. if region not in (code, name):
  61. continue
  62. for lang in languages.get_official_languages(code, de_facto=True):
  63. engine_traits.regions[region_tag(Locale(lang, code))] = region