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