mojeek.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  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. language_param: traits.get_language(params['searxng_locale'], traits.custom['language_all']),
  53. region_param: traits.get_region(params['searxng_locale'], traits.custom['region_all']),
  54. }
  55. if search_type:
  56. args['fmt'] = search_type
  57. if search_type == '':
  58. args['s'] = 10 * (params['pageno'] - 1)
  59. if params['time_range'] and search_type != 'images':
  60. kwargs = {_delta_kwargs[params['time_range']]: 1}
  61. args["since"] = (datetime.now() - relativedelta(**kwargs)).strftime("%Y%m%d") # type: ignore
  62. logger.debug(args["since"])
  63. params['url'] = f"{base_url}/search?{urlencode(args)}"
  64. return params
  65. def _general_results(dom):
  66. results = []
  67. for result in eval_xpath_list(dom, results_xpath):
  68. results.append(
  69. {
  70. 'url': extract_text(eval_xpath(result, url_xpath)),
  71. 'title': extract_text(eval_xpath(result, title_xpath)),
  72. 'content': extract_text(eval_xpath(result, content_xpath)),
  73. }
  74. )
  75. for suggestion in eval_xpath(dom, suggestion_xpath):
  76. results.append({'suggestion': extract_text(suggestion)})
  77. return results
  78. def _image_results(dom):
  79. results = []
  80. for result in eval_xpath_list(dom, image_results_xpath):
  81. results.append(
  82. {
  83. 'template': 'images.html',
  84. 'url': extract_text(eval_xpath(result, image_url_xpath)),
  85. 'title': extract_text(eval_xpath(result, image_title_xpath)),
  86. 'img_src': base_url + extract_text(eval_xpath(result, image_img_src_xpath)), # type: ignore
  87. 'content': '',
  88. }
  89. )
  90. return results
  91. def _news_results(dom):
  92. results = []
  93. for result in eval_xpath_list(dom, news_results_xpath):
  94. results.append(
  95. {
  96. 'url': extract_text(eval_xpath(result, news_url_xpath)),
  97. 'title': extract_text(eval_xpath(result, news_title_xpath)),
  98. 'content': extract_text(eval_xpath(result, news_content_xpath)),
  99. }
  100. )
  101. return results
  102. def response(resp):
  103. dom = html.fromstring(resp.text)
  104. if search_type == '':
  105. return _general_results(dom)
  106. if search_type == 'images':
  107. return _image_results(dom)
  108. if search_type == 'news':
  109. return _news_results(dom)
  110. raise ValueError(f"Invalid search type {search_type}")
  111. def fetch_traits(engine_traits: EngineTraits):
  112. # pylint: disable=import-outside-toplevel
  113. from searx import network
  114. from searx.locales import get_official_locales, region_tag
  115. from babel import Locale, UnknownLocaleError
  116. import contextlib
  117. resp = network.get(base_url + "/preferences", headers={'Accept-Language': 'en-US,en;q=0.5'})
  118. dom = html.fromstring(resp.text) # type: ignore
  119. languages = eval_xpath_list(dom, f'//select[@name="{language_param}"]/option/@value')
  120. engine_traits.custom['language_all'] = languages[0]
  121. for code in languages[1:]:
  122. with contextlib.suppress(UnknownLocaleError):
  123. locale = Locale(code)
  124. engine_traits.languages[locale.language] = code
  125. regions = eval_xpath_list(dom, f'//select[@name="{region_param}"]/option/@value')
  126. engine_traits.custom['region_all'] = regions[1]
  127. for code in regions[2:]:
  128. for locale in get_official_locales(code, engine_traits.languages):
  129. engine_traits.regions[region_tag(locale)] = code