mojeek.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """Mojeek (general, images, news)"""
  3. from typing import TYPE_CHECKING
  4. from datetime import datetime
  5. from urllib.parse import urlencode
  6. from lxml import html
  7. from dateutil.relativedelta import relativedelta
  8. from searx.utils import eval_xpath, eval_xpath_list, extract_text
  9. from searx.enginelib.traits import EngineTraits
  10. about = {
  11. 'website': 'https://mojeek.com',
  12. 'wikidata_id': 'Q60747299',
  13. 'official_api_documentation': 'https://www.mojeek.com/support/api/search/request_parameters.html',
  14. 'use_official_api': False,
  15. 'require_api_key': False,
  16. 'results': 'HTML',
  17. }
  18. paging = True # paging is only supported for general search
  19. safesearch = True
  20. time_range_support = True # time range search is supported for general and news
  21. max_page = 10
  22. base_url = "https://www.mojeek.com"
  23. categories = ["general", "web"]
  24. search_type = "" # leave blank for general, other possible values: images, news
  25. results_xpath = '//ul[@class="results-standard"]/li/a[@class="ob"]'
  26. url_xpath = './@href'
  27. title_xpath = '../h2/a'
  28. content_xpath = '..//p[@class="s"]'
  29. suggestion_xpath = '//div[@class="top-info"]/p[@class="top-info spell"]/em/a'
  30. image_results_xpath = '//div[@id="results"]/div[contains(@class, "image")]'
  31. image_url_xpath = './a/@href'
  32. image_title_xpath = './a/@data-title'
  33. image_img_src_xpath = './a/img/@src'
  34. news_results_xpath = '//section[contains(@class, "news-search-result")]//article'
  35. news_url_xpath = './/h2/a/@href'
  36. news_title_xpath = './/h2/a'
  37. news_content_xpath = './/p[@class="s"]'
  38. language_param = 'lb'
  39. region_param = 'arc'
  40. _delta_kwargs = {'day': 'days', 'week': 'weeks', 'month': 'months', 'year': 'years'}
  41. if TYPE_CHECKING:
  42. import logging
  43. logger = logging.getLogger()
  44. traits: EngineTraits
  45. def init(_):
  46. if search_type not in ('', 'images', 'news'):
  47. raise ValueError(f"Invalid search type {search_type}")
  48. def request(query, params):
  49. args = {
  50. 'q': query,
  51. 'safe': min(params['safesearch'], 1),
  52. 'fmt': search_type,
  53. language_param: traits.get_language(params['searxng_locale'], traits.custom['language_all']),
  54. region_param: traits.get_region(params['searxng_locale'], traits.custom['region_all']),
  55. }
  56. if search_type == '':
  57. args['s'] = 10 * (params['pageno'] - 1)
  58. if params['time_range'] and search_type != 'images':
  59. kwargs = {_delta_kwargs[params['time_range']]: 1}
  60. args["since"] = (datetime.now() - relativedelta(**kwargs)).strftime("%Y%m%d") # type: ignore
  61. logger.debug(args["since"])
  62. params['url'] = f"{base_url}/search?{urlencode(args)}"
  63. return params
  64. def _general_results(dom):
  65. results = []
  66. for result in eval_xpath_list(dom, results_xpath):
  67. results.append(
  68. {
  69. 'url': extract_text(eval_xpath(result, url_xpath)),
  70. 'title': extract_text(eval_xpath(result, title_xpath)),
  71. 'content': extract_text(eval_xpath(result, content_xpath)),
  72. }
  73. )
  74. for suggestion in eval_xpath(dom, suggestion_xpath):
  75. results.append({'suggestion': extract_text(suggestion)})
  76. return results
  77. def _image_results(dom):
  78. results = []
  79. for result in eval_xpath_list(dom, image_results_xpath):
  80. results.append(
  81. {
  82. 'template': 'images.html',
  83. 'url': extract_text(eval_xpath(result, image_url_xpath)),
  84. 'title': extract_text(eval_xpath(result, image_title_xpath)),
  85. 'img_src': base_url + extract_text(eval_xpath(result, image_img_src_xpath)), # type: ignore
  86. 'content': '',
  87. }
  88. )
  89. return results
  90. def _news_results(dom):
  91. results = []
  92. for result in eval_xpath_list(dom, news_results_xpath):
  93. results.append(
  94. {
  95. 'url': extract_text(eval_xpath(result, news_url_xpath)),
  96. 'title': extract_text(eval_xpath(result, news_title_xpath)),
  97. 'content': extract_text(eval_xpath(result, news_content_xpath)),
  98. }
  99. )
  100. return results
  101. def response(resp):
  102. dom = html.fromstring(resp.text)
  103. if search_type == '':
  104. return _general_results(dom)
  105. if search_type == 'images':
  106. return _image_results(dom)
  107. if search_type == 'news':
  108. return _news_results(dom)
  109. raise ValueError(f"Invalid search type {search_type}")
  110. def fetch_traits(engine_traits: EngineTraits):
  111. # pylint: disable=import-outside-toplevel
  112. from searx import network
  113. from searx.locales import get_official_locales, region_tag
  114. from babel import Locale, UnknownLocaleError
  115. import contextlib
  116. resp = network.get(base_url + "/preferences", headers={'Accept-Language': 'en-US,en;q=0.5'})
  117. dom = html.fromstring(resp.text) # type: ignore
  118. languages = eval_xpath_list(dom, f'//select[@name="{language_param}"]/option/@value')
  119. engine_traits.custom['language_all'] = languages[0]
  120. for code in languages[1:]:
  121. with contextlib.suppress(UnknownLocaleError):
  122. locale = Locale(code)
  123. engine_traits.languages[locale.language] = code
  124. regions = eval_xpath_list(dom, f'//select[@name="{region_param}"]/option/@value')
  125. engine_traits.custom['region_all'] = regions[1]
  126. for code in regions[2:]:
  127. for locale in get_official_locales(code, engine_traits.languages):
  128. engine_traits.regions[region_tag(locale)] = code