.oO SearXNG Developer Documentation Oo.
Loading...
Searching...
No Matches
mullvad_leta.py
Go to the documentation of this file.
1# SPDX-License-Identifier: AGPL-3.0-or-later
2
3"""This is the implementation of the Mullvad-Leta meta-search engine.
4
5This engine **REQUIRES** that searxng operate within a Mullvad VPN
6
7If using docker, consider using gluetun for easily connecting to the Mullvad
8
9- https://github.com/qdm12/gluetun
10
11Otherwise, follow instructions provided by Mullvad for enabling the VPN on Linux
12
13- https://mullvad.net/en/help/install-mullvad-app-linux
14
15.. hint::
16
17 The :py:obj:`EngineTraits` is empty by default. Maintainers have to run
18 ``make data.traits`` (in the Mullvad VPN / :py:obj:`fetch_traits`) and rebase
19 the modified JSON file ``searx/data/engine_traits.json`` on every single
20 update of SearXNG!
21"""
22
23from __future__ import annotations
24
25from typing import TYPE_CHECKING
26from httpx import Response
27from lxml import html
28from searx.enginelib.traits import EngineTraits
29from searx.locales import region_tag, get_official_locales
30from searx.utils import eval_xpath, extract_text, eval_xpath_list
31from searx.exceptions import SearxEngineResponseException
32
33if TYPE_CHECKING:
34 import logging
35
36 logger = logging.getLogger()
37
38traits: EngineTraits
39
40use_cache: bool = True # non-cache use only has 100 searches per day!
41
42leta_engine: str = 'google'
43
44search_url = "https://leta.mullvad.net"
45
46# about
47about = {
48 "website": search_url,
49 "wikidata_id": 'Q47008412', # the Mullvad id - not leta, but related
50 "official_api_documentation": 'https://leta.mullvad.net/faq',
51 "use_official_api": False,
52 "require_api_key": False,
53 "results": 'HTML',
54}
55
56# engine dependent config
57categories = ['general', 'web']
58paging = True
59max_page = 50
60time_range_support = True
61time_range_dict = {
62 "day": "d1",
63 "week": "w1",
64 "month": "m1",
65 "year": "y1",
66}
67
68available_leta_engines = [
69 'google', # first will be default if provided engine is invalid
70 'brave',
71]
72
73
74def is_vpn_connected(dom: html.HtmlElement) -> bool:
75 """Returns true if the VPN is connected, False otherwise"""
76 connected_text = extract_text(eval_xpath(dom, '//main/div/p[1]'))
77 return connected_text != 'You are not connected to Mullvad VPN.'
78
79
80def assign_headers(headers: dict) -> dict:
81 """Assigns the headers to make a request to Mullvad Leta"""
82 headers['Accept'] = "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8"
83 headers['Content-Type'] = "application/x-www-form-urlencoded"
84 headers['Host'] = "leta.mullvad.net"
85 headers['Origin'] = "https://leta.mullvad.net"
86 return headers
87
88
89def request(query: str, params: dict):
90 country = traits.get_region(params.get('searxng_locale', 'all'), traits.all_locale) # type: ignore
91
92 result_engine = leta_engine
93 if leta_engine not in available_leta_engines:
94 result_engine = available_leta_engines[0]
95 logger.warning(
96 'Configured engine "%s" not one of the available engines %s, defaulting to "%s"',
97 leta_engine,
98 available_leta_engines,
99 result_engine,
100 )
101
102 params['url'] = search_url
103 params['method'] = 'POST'
104 params['data'] = {
105 "q": query,
106 "gl": country if country is str else '',
107 'engine': result_engine,
108 }
109 # pylint: disable=undefined-variable
110 if use_cache:
111 params['data']['oc'] = "on"
112 # pylint: enable=undefined-variable
113
114 if params['time_range'] in time_range_dict:
115 params['dateRestrict'] = time_range_dict[params['time_range']]
116 else:
117 params['dateRestrict'] = ''
118
119 if params['pageno'] > 1:
120 # Page 1 is n/a, Page 2 is 11, page 3 is 21, ...
121 params['data']['start'] = ''.join([str(params['pageno'] - 1), "1"])
122
123 if params['headers'] is None:
124 params['headers'] = {}
125
126 assign_headers(params['headers'])
127 return params
128
129
130def extract_result(dom_result: list[html.HtmlElement]):
131 # Infoboxes sometimes appear in the beginning and will have a length of 0
132 if len(dom_result) == 3:
133 [a_elem, h3_elem, p_elem] = dom_result
134 elif len(dom_result) == 4:
135 [_, a_elem, h3_elem, p_elem] = dom_result
136 else:
137 return None
138
139 return {
140 'url': extract_text(a_elem.text),
141 'title': extract_text(h3_elem),
142 'content': extract_text(p_elem),
143 }
144
145
146def extract_results(search_results: html.HtmlElement):
147 for search_result in search_results:
148 dom_result = eval_xpath_list(search_result, 'div/div/*')
149 result = extract_result(dom_result)
150 if result is not None:
151 yield result
152
153
154def response(resp: Response):
155 """Checks if connected to Mullvad VPN, then extracts the search results from
156 the DOM resp: requests response object"""
157
158 dom = html.fromstring(resp.text)
159 if not is_vpn_connected(dom):
160 raise SearxEngineResponseException('Not connected to Mullvad VPN')
161 search_results = eval_xpath(dom.body, '//main/div[2]/div')
162 return list(extract_results(search_results))
163
164
165def fetch_traits(engine_traits: EngineTraits):
166 """Fetch languages and regions from Mullvad-Leta
167
168 .. warning::
169
170 Fetching the engine traits also requires a Mullvad VPN connection. If
171 not connected, then an error message will print and no traits will be
172 updated.
173 """
174 # pylint: disable=import-outside-toplevel
175 # see https://github.com/searxng/searxng/issues/762
176 from searx.network import post as http_post
177
178 # pylint: enable=import-outside-toplevel
179 resp = http_post(search_url, headers=assign_headers({}))
180 if not isinstance(resp, Response):
181 print("ERROR: failed to get response from mullvad-leta. Are you connected to the VPN?")
182 return
183 if not resp.ok:
184 print("ERROR: response from mullvad-leta is not OK. Are you connected to the VPN?")
185 return
186 dom = html.fromstring(resp.text)
187 if not is_vpn_connected(dom):
188 print('ERROR: Not connected to Mullvad VPN')
189 return
190 # supported region codes
191 options = eval_xpath_list(dom.body, '//main/div/form/div[2]/div/select[1]/option')
192 if options is None or len(options) <= 0:
193 print('ERROR: could not find any results. Are you connected to the VPN?')
194 for x in options:
195 eng_country = x.get("value")
196
197 sxng_locales = get_official_locales(eng_country, engine_traits.languages.keys(), regional=True)
198
199 if not sxng_locales:
200 print(
201 "ERROR: can't map from Mullvad-Leta country %s (%s) to a babel region."
202 % (x.get('data-name'), eng_country)
203 )
204 continue
205
206 for sxng_locale in sxng_locales:
207 engine_traits.regions[region_tag(sxng_locale)] = eng_country
bool is_vpn_connected(html.HtmlElement dom)
extract_results(html.HtmlElement search_results)
request(str query, dict params)
extract_result(list[html.HtmlElement] dom_result)
dict assign_headers(dict headers)
fetch_traits(EngineTraits engine_traits)