on master help sign in
Merge pull request #2225 from dalf/processors

Processors

commit9b27935f71ea94ba034d73c09c1f18df05fd33b6 authorAlexandre Flament <alex@al-f.net> dateThu 17 Dec 2020, 11:49 (6 years ago) parent13a2b1a02fc414
20 files changed+786−667
docs/admin/engines.rst+6−6 docs/dev/engine_overview.rst+47−19 searx/engines/__init__.py+6−4 searx/engines/command.py+1−1 searx/engines/currency_convert.py+2−40 searx/engines/dictzone.py+6−18 searx/engines/translated.py+4−22 searx/search.py−541 searx/search/__init__.py+265 searx/search/processors/__init__.py+41 searx/search/processors/abstract.py+39 searx/search/processors/offline.py+51 searx/search/processors/online.py+211 searx/search/processors/online_currency.py+57 searx/search/processors/online_dictionary.py+37 searx/webapp.py+3−3 tests/unit/test_search.py+1−2 tests/unit/test_standalone_searx.py+2−3 tests/unit/test_webadapter.py+2−2 utils/standalone_searx.py+5−6
docs/admin/engines.rst+6−6
@@ -33,7 +33,7 @@ Engine .. Paging support **P**
3333------------------------- -------------------- ------------
3434Shortcut **S** Language support **L**
3535Timeout **TO** Time range support **TR**
36−Disabled **D** Offline **O**
36+Disabled **D** Engine type **ET**
3737------------- ----------- -------------------- ------------
3838Safe search **SS**
3939------------- ----------- ---------------------------------
@@ -62,10 +62,10 @@ Show errors **DE**
6262 - SS
6363 - D
6464 - TR
65− - O
66− - W
67− - D
68− - DE
65+ - ET
66+ - W
67+ - D
68+ - DE
6969
7070 {% for name, mod in engines.items() %}
7171
@@ -79,7 +79,7 @@ Show errors **DE**
7979 - {{(mod.safesearch and "y") or ""}}
8080 - {{(mod.disabled and "y") or ""}}
8181 - {{(mod.time_range_support and "y") or ""}}
82− - {{(mod.offline and "y") or ""}}
82+ - {{mod.engine_type or ""}}
8383 - {{mod.weight or 1 }}
8484 - {{(mod.disabled and "y") or ""}}
8585 - {{(mod.display_error_messages and "y") or ""}}
docs/dev/engine_overview.rst+47−19
@@ -37,15 +37,16 @@ settings. However, the standard way is the following:
3737engine file
3838-----------
3939
40−======================= =========== ===========================================
40+======================= =========== ========================================================
4141argument type information
42−======================= =========== ===========================================
42+======================= =========== ========================================================
4343categories list pages, in which the engine is working
4444paging boolean support multible pages
4545language_support boolean support language choosing
4646time_range_support boolean support search time range
47−offline boolean engine runs offline
48−======================= =========== ===========================================
47+engine_type str ``online`` by default, other possibles values are
48+ ``offline``, ``online_dictionnary``, ``online_currency``
49+======================= =========== ========================================================
4950
5051.. _engine settings:
5152
@@ -111,22 +112,49 @@ passed arguments
111112These arguments can be used to construct the search query. Furthermore,
112113parameters with default value can be redefined for special purposes.
113114
115+If the ``engine_type`` is ``online```:
116+
117+====================== ============== ========================================================================
118+argument type default-value, information
119+====================== ============== ========================================================================
120+url str ``''``
121+method str ``'GET'``
122+headers set ``{}``
123+data set ``{}``
124+cookies set ``{}``
125+verify bool ``True``
126+headers.User-Agent str a random User-Agent
127+category str current category, like ``'general'``
128+safesearch int ``0``, between ``0`` and ``2`` (normal, moderate, strict)
129+time_range Optional[str] ``None``, can be ``day``, ``week``, ``month``, ``year``
130+pageno int current pagenumber
131+language str specific language code like ``'en_US'``, or ``'all'`` if unspecified
132+====================== ============== ========================================================================
133+
134+
135+If the ``engine_type`` is ``online_dictionnary```, in addition to the ``online`` arguments:
136+
114137====================== ============ ========================================================================
115138argument type default-value, information
116139====================== ============ ========================================================================
117−url string ``''``
118−method string ``'GET'``
119−headers set ``{}``
120−data set ``{}``
121−cookies set ``{}``
122−verify boolean ``True``
123−headers.User-Agent string a random User-Agent
124−category string current category, like ``'general'``
125−started datetime current date-time
126−pageno int current pagenumber
127−language string specific language code like ``'en_US'``, or ``'all'`` if unspecified
140+from_lang str specific language code like ``'en_US'``
141+to_lang str specific language code like ``'en_US'``
142+query str the text query without the languages
128143====================== ============ ========================================================================
129144
145+If the ``engine_type`` is ``online_currency```, in addition to the ``online`` arguments:
146+
147+====================== ============ ========================================================================
148+argument type default-value, information
149+====================== ============ ========================================================================
150+amount float the amount to convert
151+from str ISO 4217 code
152+to str ISO 4217 code
153+from_name str currency name
154+to_name str currency name
155+====================== ============ ========================================================================
156+
157+
130158parsed arguments
131159----------------
132160
@@ -137,12 +165,12 @@ request:
137165=================== =========== ==========================================================================
138166argument type information
139167=================== =========== ==========================================================================
140−url string requested url
141−method string HTTP request method
168+url str requested url
169+method str HTTP request method
142170headers set HTTP header information
143−data set HTTP data information (parsed if ``method != 'GET'``)
171+data set HTTP data information
144172cookies set HTTP cookies
145−verify boolean Performing SSL-Validity check
173+verify bool Performing SSL-Validity check
146174max_redirects int maximum redirects, hard limit
147175soft_max_redirects int maximum redirects, soft limit. Record an error but don't stop the engine
148176raise_for_httperror bool True by default: raise an exception if the HTTP code of response is >= 300
searx/engines/__init__.py+6−4
@@ -53,7 +53,7 @@ engine_default_args = {'paging': False,
5353 'suspend_end_time': 0,
5454 'continuous_errors': 0,
5555 'time_range_support': False,
56− 'offline': False,
56+ 'engine_type': 'online',
5757 'display_error_messages': True,
5858 'tokens': []}
5959
@@ -142,7 +142,9 @@ def load_engine(engine_data):
142142 'errors': 0
143143 }
144144
145− if not engine.offline:
145+ engine_type = getattr(engine, 'engine_type', 'online')
146+
147+ if engine_type != 'offline':
146148 engine.stats['page_load_time'] = 0
147149 engine.stats['page_load_count'] = 0
148150
@@ -209,7 +211,7 @@ def get_engines_stats(preferences):
209211 else:
210212 score = score_per_result = 0.0
211213
212− if not engine.offline:
214+ if engine.engine_type != 'offline':
213215 load_times = 0
214216 if engine.stats['page_load_count'] != 0:
215217 load_times = engine.stats['page_load_time'] / float(engine.stats['page_load_count']) # noqa
@@ -300,7 +302,7 @@ def initialize_engines(engine_list):
300302
301303def _set_https_support_for_engine(engine):
302304 # check HTTPS support if it is not disabled
303− if not engine.offline and not hasattr(engine, 'https_support'):
305+ if engine.engine_type != 'offline' and not hasattr(engine, 'https_support'):
304306 params = engine.request('http_test', {
305307 'method': 'GET',
306308 'headers': {},
searx/engines/command.py+1−1
@@ -23,7 +23,7 @@ from threading import Thread
2323from searx import logger
2424
2525
26−offline = True
26+engine_type = 'offline'
2727paging = True
2828command = []
2929delimiter = {}
searx/engines/currency_convert.py+2−40
@@ -1,54 +1,16 @@
11import json
2−import re
3−import unicodedata
4−from searx.data import CURRENCIES # NOQA
52
63
4+engine_type = 'online_currency'
75categories = []
86url = 'https://duckduckgo.com/js/spice/currency/1/{0}/{1}'
97weight = 100
108
11−parser_re = re.compile('.*?(\\d+(?:\\.\\d+)?) ([^.0-9]+) (?:in|to) ([^.0-9]+)', re.I)
129https_support = True
1310
1411
15−def normalize_name(name):
16− name = name.lower().replace('-', ' ').rstrip('s')
17− name = re.sub(' +', ' ', name)
18− return unicodedata.normalize('NFKD', name).lower()
19−
20−
21−def name_to_iso4217(name):
22− global CURRENCIES
23−
24− name = normalize_name(name)
25− currency = CURRENCIES['names'].get(name, [name])
26− return currency[0]
27−
28−
29−def iso4217_to_name(iso4217, language):
30− global CURRENCIES
31−
32− return CURRENCIES['iso4217'].get(iso4217, {}).get(language, iso4217)
33−
34−
3512def request(query, params):
36− m = parser_re.match(query)
37− if not m:
38− # wrong query
39− return params
40− amount, from_currency, to_currency = m.groups()
41− amount = float(amount)
42− from_currency = name_to_iso4217(from_currency.strip())
43− to_currency = name_to_iso4217(to_currency.strip())
44−
45− params['url'] = url.format(from_currency, to_currency)
46− params['amount'] = amount
47− params['from'] = from_currency
48− params['to'] = to_currency
49− params['from_name'] = iso4217_to_name(from_currency, 'en')
50− params['to_name'] = iso4217_to_name(to_currency, 'en')
51−
13+ params['url'] = url.format(params['from'], params['to'])
5214 return params
5315
5416
searx/engines/dictzone.py+6−18
@@ -9,36 +9,24 @@
99 @parse url, title, content
1010"""
1111
12−import re
1312from urllib.parse import urljoin
1413from lxml import html
15−from searx.utils import is_valid_lang, eval_xpath
14+from searx.utils import eval_xpath
1615
16+
17+engine_type = 'online_dictionnary'
1718categories = ['general']
1819url = 'https://dictzone.com/{from_lang}-{to_lang}-dictionary/{query}'
1920weight = 100
2021
21−parser_re = re.compile('.*?([a-z]+)-([a-z]+) ([^ ]+)$', re.I)
2222results_xpath = './/table[@id="r"]/tr'
2323https_support = True
2424
2525
2626def request(query, params):
27− m = parser_re.match(query)
28− if not m:
29− return params
30−
31− from_lang, to_lang, query = m.groups()
32−
33− from_lang = is_valid_lang(from_lang)
34− to_lang = is_valid_lang(to_lang)
35−
36− if not from_lang or not to_lang:
37− return params
38−
39− params['url'] = url.format(from_lang=from_lang[2],
40− to_lang=to_lang[2],
41− query=query)
27+ params['url'] = url.format(from_lang=params['from_lang'][2],
28+ to_lang=params['to_lang'][2],
29+ query=params['query'])
4230
4331 return params
4432
searx/engines/translated.py+4−22
@@ -8,44 +8,26 @@
88 @stable yes
99 @parse url, title, content
1010"""
11−import re
12−from searx.utils import is_valid_lang
1311
12+engine_type = 'online_dictionnary'
1413categories = ['general']
1514url = 'https://api.mymemory.translated.net/get?q={query}&langpair={from_lang}|{to_lang}{key}'
1615web_url = 'https://mymemory.translated.net/en/{from_lang}/{to_lang}/{query}'
1716weight = 100
1817https_support = True
1918
20−parser_re = re.compile('.*?([a-z]+)-([a-z]+) (.{2,})$', re.I)
2119api_key = ''
2220
2321
2422def request(query, params):
25− m = parser_re.match(query)
26− if not m:
27− return params
28−
29− from_lang, to_lang, query = m.groups()
30−
31− from_lang = is_valid_lang(from_lang)
32− to_lang = is_valid_lang(to_lang)
33−
34− if not from_lang or not to_lang:
35− return params
36−
3723 if api_key:
3824 key_form = '&key=' + api_key
3925 else:
4026 key_form = ''
41− params['url'] = url.format(from_lang=from_lang[1],
42− to_lang=to_lang[1],
43− query=query,
27+ params['url'] = url.format(from_lang=params['from_lang'][1],
28+ to_lang=params['to_lang'][1],
29+ query=params['query'],
4430 key=key_form)
45− params['query'] = query
46− params['from_lang'] = from_lang
47− params['to_lang'] = to_lang
48−
4931 return params
5032
5133
searx/search.pydeleted−541
@@ -1,541 +0,0 @@
1−'''
2−searx is free software: you can redistribute it and/or modify
3−it under the terms of the GNU Affero General Public License as published by
4−the Free Software Foundation, either version 3 of the License, or
5−(at your option) any later version.
6−
7−searx is distributed in the hope that it will be useful,
8−but WITHOUT ANY WARRANTY; without even the implied warranty of
9−MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10−GNU Affero General Public License for more details.
11−
12−You should have received a copy of the GNU Affero General Public License
13−along with searx. If not, see < http://www.gnu.org/licenses/ >.
14−
15−(C) 2013- by Adam Tauber, <asciimoo@gmail.com>
16−'''
17−
18−import typing
19−import gc
20−import threading
21−from time import time
22−from uuid import uuid4
23−from urllib.parse import urlparse
24−from _thread import start_new_thread
25−
26−import requests.exceptions
27−import searx.poolrequests as requests_lib
28−from searx.engines import engines, settings
29−from searx.answerers import ask
30−from searx.external_bang import get_bang_url
31−from searx.utils import gen_useragent
32−from searx.results import ResultContainer
33−from searx import logger
34−from searx.plugins import plugins
35−from searx.exceptions import (SearxEngineAccessDeniedException, SearxEngineCaptchaException,
36− SearxEngineTooManyRequestsException,)
37−from searx.metrology.error_recorder import record_exception, record_error
38−
39−
40−logger = logger.getChild('search')
41−
42−max_request_timeout = settings.get('outgoing', {}).get('max_request_timeout' or None)
43−if max_request_timeout is None:
44− logger.info('max_request_timeout={0}'.format(max_request_timeout))
45−else:
46− if isinstance(max_request_timeout, float):
47− logger.info('max_request_timeout={0} second(s)'.format(max_request_timeout))
48− else:
49− logger.critical('outgoing.max_request_timeout if defined has to be float')
50− import sys
51− sys.exit(1)
52−
53−
54−class EngineRef:
55−
56− __slots__ = 'name', 'category', 'from_bang'
57−
58− def __init__(self, name: str, category: str, from_bang: bool=False):
59− self.name = name
60− self.category = category
61− self.from_bang = from_bang
62−
63− def __repr__(self):
64− return "EngineRef({!r}, {!r}, {!r})".format(self.name, self.category, self.from_bang)
65−
66− def __eq__(self, other):
67− return self.name == other.name and self.category == other.category and self.from_bang == other.from_bang
68−
69−
70−class SearchQuery:
71− """container for all the search parameters (query, language, etc...)"""
72−
73− __slots__ = 'query', 'engineref_list', 'categories', 'lang', 'safesearch', 'pageno', 'time_range',\
74− 'timeout_limit', 'external_bang'
75−
76− def __init__(self,
77− query: str,
78− engineref_list: typing.List[EngineRef],
79− categories: typing.List[str],
80− lang: str,
81− safesearch: int,
82− pageno: int,
83− time_range: typing.Optional[str],
84− timeout_limit: typing.Optional[float]=None,
85− external_bang: typing.Optional[str]=None):
86− self.query = query
87− self.engineref_list = engineref_list
88− self.categories = categories
89− self.lang = lang
90− self.safesearch = safesearch
91− self.pageno = pageno
92− self.time_range = time_range
93− self.timeout_limit = timeout_limit
94− self.external_bang = external_bang
95−
96− def __repr__(self):
97− return "SearchQuery({!r}, {!r}, {!r}, {!r}, {!r}, {!r}, {!r}, {!r}, {!r})".\
98− format(self.query, self.engineref_list, self.categories, self.lang, self.safesearch,
99− self.pageno, self.time_range, self.timeout_limit, self.external_bang)
100−
101− def __eq__(self, other):
102− return self.query == other.query\
103− and self.engineref_list == other.engineref_list\
104− and self.categories == self.categories\
105− and self.lang == other.lang\
106− and self.safesearch == other.safesearch\
107− and self.pageno == other.pageno\
108− and self.time_range == other.time_range\
109− and self.timeout_limit == other.timeout_limit\
110− and self.external_bang == other.external_bang
111−
112−
113−def send_http_request(engine, request_params):
114− # create dictionary which contain all
115− # informations about the request
116− request_args = dict(
117− headers=request_params['headers'],
118− cookies=request_params['cookies'],
119− verify=request_params['verify'],
120− auth=request_params['auth']
121− )
122−
123− # setting engine based proxies
124− if hasattr(engine, 'proxies'):
125− request_args['proxies'] = requests_lib.get_proxies(engine.proxies)
126−
127− # max_redirects
128− max_redirects = request_params.get('max_redirects')
129− if max_redirects:
130− request_args['max_redirects'] = max_redirects
131−
132− # soft_max_redirects
133− soft_max_redirects = request_params.get('soft_max_redirects', max_redirects or 0)
134−
135− # raise_for_status
136− request_args['raise_for_httperror'] = request_params.get('raise_for_httperror', False)
137−
138− # specific type of request (GET or POST)
139− if request_params['method'] == 'GET':
140− req = requests_lib.get
141− else:
142− req = requests_lib.post
143−
144− request_args['data'] = request_params['data']
145−
146− # send the request
147− response = req(request_params['url'], **request_args)
148−
149− # check soft limit of the redirect count
150− if len(response.history) > soft_max_redirects:
151− # unexpected redirect : record an error
152− # but the engine might still return valid results.
153− status_code = str(response.status_code or '')
154− reason = response.reason or ''
155− hostname = str(urlparse(response.url or '').netloc)
156− record_error(engine.name,
157− '{} redirects, maximum: {}'.format(len(response.history), soft_max_redirects),
158− (status_code, reason, hostname))
159−
160− return response
161−
162−
163−def search_one_http_request(engine, query, request_params):
164− # update request parameters dependent on
165− # search-engine (contained in engines folder)
166− engine.request(query, request_params)
167−
168− # ignoring empty urls
169− if request_params['url'] is None:
170− return None
171−
172− if not request_params['url']:
173− return None
174−
175− # send request
176− response = send_http_request(engine, request_params)
177−
178− # parse the response
179− response.search_params = request_params
180− return engine.response(response)
181−
182−
183−def search_one_http_request_safe(engine_name, query, request_params, result_container, start_time, timeout_limit):
184− # set timeout for all HTTP requests
185− requests_lib.set_timeout_for_thread(timeout_limit, start_time=start_time)
186− # reset the HTTP total time
187− requests_lib.reset_time_for_thread()
188−
189− #
190− engine = engines[engine_name]
191−
192− # suppose everything will be alright
193− requests_exception = False
194− suspended_time = None
195−
196− try:
197− # send requests and parse the results
198− search_results = search_one_http_request(engine, query, request_params)
199−
200− # check if the engine accepted the request
201− if search_results is not None:
202− # yes, so add results
203− result_container.extend(engine_name, search_results)
204−
205− # update engine time when there is no exception
206− engine_time = time() - start_time
207− page_load_time = requests_lib.get_time_for_thread()
208− result_container.add_timing(engine_name, engine_time, page_load_time)
209− with threading.RLock():
210− engine.stats['engine_time'] += engine_time
211− engine.stats['engine_time_count'] += 1
212− # update stats with the total HTTP time
213− engine.stats['page_load_time'] += page_load_time
214− engine.stats['page_load_count'] += 1
215− except Exception as e:
216− record_exception(engine_name, e)
217−
218− # Timing
219− engine_time = time() - start_time
220− page_load_time = requests_lib.get_time_for_thread()
221− result_container.add_timing(engine_name, engine_time, page_load_time)
222−
223− # Record the errors
224− with threading.RLock():
225− engine.stats['errors'] += 1
226−
227− if (issubclass(e.__class__, requests.exceptions.Timeout)):
228− result_container.add_unresponsive_engine(engine_name, 'HTTP timeout')
229− # requests timeout (connect or read)
230− logger.error("engine {0} : HTTP requests timeout"
231− "(search duration : {1} s, timeout: {2} s) : {3}"
232− .format(engine_name, engine_time, timeout_limit, e.__class__.__name__))
233− requests_exception = True
234− elif (issubclass(e.__class__, requests.exceptions.RequestException)):
235− result_container.add_unresponsive_engine(engine_name, 'HTTP error')
236− # other requests exception
237− logger.exception("engine {0} : requests exception"
238− "(search duration : {1} s, timeout: {2} s) : {3}"
239− .format(engine_name, engine_time, timeout_limit, e))
240− requests_exception = True
241− elif (issubclass(e.__class__, SearxEngineCaptchaException)):
242− result_container.add_unresponsive_engine(engine_name, 'CAPTCHA required')
243− logger.exception('engine {0} : CAPTCHA')
244− suspended_time = e.suspended_time # pylint: disable=no-member
245− elif (issubclass(e.__class__, SearxEngineTooManyRequestsException)):
246− result_container.add_unresponsive_engine(engine_name, 'too many requests')
247− logger.exception('engine {0} : Too many requests')
248− suspended_time = e.suspended_time # pylint: disable=no-member
249− elif (issubclass(e.__class__, SearxEngineAccessDeniedException)):
250− result_container.add_unresponsive_engine(engine_name, 'blocked')
251− logger.exception('engine {0} : Searx is blocked')
252− suspended_time = e.suspended_time # pylint: disable=no-member
253− else:
254− result_container.add_unresponsive_engine(engine_name, 'unexpected crash')
255− # others errors
256− logger.exception('engine {0} : exception : {1}'.format(engine_name, e))
257− else:
258− if getattr(threading.current_thread(), '_timeout', False):
259− record_error(engine_name, 'Timeout')
260−
261− # suspend the engine if there is an HTTP error
262− # or suspended_time is defined
263− with threading.RLock():
264− if requests_exception or suspended_time:
265− # update continuous_errors / suspend_end_time
266− engine.continuous_errors += 1
267− if suspended_time is None:
268− suspended_time = min(settings['search']['max_ban_time_on_fail'],
269− engine.continuous_errors * settings['search']['ban_time_on_fail'])
270− engine.suspend_end_time = time() + suspended_time
271− else:
272− # reset the suspend variables
273− engine.continuous_errors = 0
274− engine.suspend_end_time = 0
275−
276−
277−def record_offline_engine_stats_on_error(engine, result_container, start_time):
278− engine_time = time() - start_time
279− result_container.add_timing(engine.name, engine_time, engine_time)
280−
281− with threading.RLock():
282− engine.stats['errors'] += 1
283−
284−
285−def search_one_offline_request(engine, query, request_params):
286− return engine.search(query, request_params)
287−
288−
289−def search_one_offline_request_safe(engine_name, query, request_params, result_container, start_time, timeout_limit):
290− engine = engines[engine_name]
291−
292− try:
293− search_results = search_one_offline_request(engine, query, request_params)
294−
295− if search_results:
296− result_container.extend(engine_name, search_results)
297−
298− engine_time = time() - start_time
299− result_container.add_timing(engine_name, engine_time, engine_time)
300− with threading.RLock():
301− engine.stats['engine_time'] += engine_time
302− engine.stats['engine_time_count'] += 1
303−
304− except ValueError as e:
305− record_exception(engine_name, e)
306− record_offline_engine_stats_on_error(engine, result_container, start_time)
307− logger.exception('engine {0} : invalid input : {1}'.format(engine_name, e))
308− except Exception as e:
309− record_exception(engine_name, e)
310− record_offline_engine_stats_on_error(engine, result_container, start_time)
311− result_container.add_unresponsive_engine(engine_name, 'unexpected crash', str(e))
312− logger.exception('engine {0} : exception : {1}'.format(engine_name, e))
313− else:
314− if getattr(threading.current_thread(), '_timeout', False):
315− record_error(engine_name, 'Timeout')
316−
317−
318−def search_one_request_safe(engine_name, query, request_params, result_container, start_time, timeout_limit):
319− if engines[engine_name].offline:
320− return search_one_offline_request_safe(engine_name, query, request_params, result_container, start_time, timeout_limit) # noqa
321− return search_one_http_request_safe(engine_name, query, request_params, result_container, start_time, timeout_limit)
322−
323−
324−def search_multiple_requests(requests, result_container, start_time, timeout_limit):
325− search_id = uuid4().__str__()
326−
327− for engine_name, query, request_params in requests:
328− th = threading.Thread(
329− target=search_one_request_safe,
330− args=(engine_name, query, request_params, result_container, start_time, timeout_limit),
331− name=search_id,
332− )
333− th._timeout = False
334− th._engine_name = engine_name
335− th.start()
336−
337− for th in threading.enumerate():
338− if th.name == search_id:
339− remaining_time = max(0.0, timeout_limit - (time() - start_time))
340− th.join(remaining_time)
341− if th.is_alive():
342− th._timeout = True
343− result_container.add_unresponsive_engine(th._engine_name, 'timeout')
344− logger.warning('engine timeout: {0}'.format(th._engine_name))
345−
346−
347−# get default reqest parameter
348−def default_request_params():
349− return {
350− 'method': 'GET',
351− 'headers': {},
352− 'data': {},
353− 'url': '',
354− 'cookies': {},
355− 'verify': True,
356− 'auth': None,
357− 'raise_for_httperror': True
358− }
359−
360−
361−class Search:
362− """Search information container"""
363−
364− __slots__ = "search_query", "result_container", "start_time", "actual_timeout"
365−
366− def __init__(self, search_query):
367− # init vars
368− super().__init__()
369− self.search_query = search_query
370− self.result_container = ResultContainer()
371− self.start_time = None
372− self.actual_timeout = None
373−
374− def search_external_bang(self):
375− """
376− Check if there is a external bang.
377− If yes, update self.result_container and return True
378− """
379− if self.search_query.external_bang:
380− self.result_container.redirect_url = get_bang_url(self.search_query)
381−
382− # This means there was a valid bang and the
383− # rest of the search does not need to be continued
384− if isinstance(self.result_container.redirect_url, str):
385− return True
386− return False
387−
388− def search_answerers(self):
389− """
390− Check if an answer return a result.
391− If yes, update self.result_container and return True
392− """
393− answerers_results = ask(self.search_query)
394−
395− if answerers_results:
396− for results in answerers_results:
397− self.result_container.extend('answer', results)
398− return True
399− return False
400−
401− def _is_accepted(self, engine_name, engine):
402− # skip suspended engines
403− if engine.suspend_end_time >= time():
404− logger.debug('Engine currently suspended: %s', engine_name)
405− return False
406−
407− # if paging is not supported, skip
408− if self.search_query.pageno > 1 and not engine.paging:
409− return False
410−
411− # if time_range is not supported, skip
412− if self.search_query.time_range and not engine.time_range_support:
413− return False
414−
415− return True
416−
417− def _get_params(self, engineref, user_agent):
418− if engineref.name not in engines:
419− return None, None
420−
421− engine = engines[engineref.name]
422−
423− if not self._is_accepted(engineref.name, engine):
424− return None, None
425−
426− # set default request parameters
427− request_params = {}
428− if not engine.offline:
429− request_params = default_request_params()
430− request_params['headers']['User-Agent'] = user_agent
431−
432− if hasattr(engine, 'language') and engine.language:
433− request_params['language'] = engine.language
434− else:
435− request_params['language'] = self.search_query.lang
436−
437− request_params['safesearch'] = self.search_query.safesearch
438− request_params['time_range'] = self.search_query.time_range
439−
440− request_params['category'] = engineref.category
441− request_params['pageno'] = self.search_query.pageno
442−
443− with threading.RLock():
444− engine.stats['sent_search_count'] += 1
445−
446− return request_params, engine.timeout
447−
448− # do search-request
449− def _get_requests(self):
450− # init vars
451− requests = []
452−
453− # set default useragent
454− # user_agent = request.headers.get('User-Agent', '')
455− user_agent = gen_useragent()
456−
457− # max of all selected engine timeout
458− default_timeout = 0
459−
460− # start search-reqest for all selected engines
461− for engineref in self.search_query.engineref_list:
462− # set default request parameters
463− request_params, engine_timeout = self._get_params(engineref, user_agent)
464− if request_params is None:
465− continue
466−
467− # append request to list
468− requests.append((engineref.name, self.search_query.query, request_params))
469−
470− # update default_timeout
471− default_timeout = max(default_timeout, engine_timeout)
472−
473− # adjust timeout
474− actual_timeout = default_timeout
475− query_timeout = self.search_query.timeout_limit
476−
477− if max_request_timeout is None and query_timeout is None:
478− # No max, no user query: default_timeout
479− pass
480− elif max_request_timeout is None and query_timeout is not None:
481− # No max, but user query: From user query except if above default
482− actual_timeout = min(default_timeout, query_timeout)
483− elif max_request_timeout is not None and query_timeout is None:
484− # Max, no user query: Default except if above max
485− actual_timeout = min(default_timeout, max_request_timeout)
486− elif max_request_timeout is not None and query_timeout is not None:
487− # Max & user query: From user query except if above max
488− actual_timeout = min(query_timeout, max_request_timeout)
489−
490− logger.debug("actual_timeout={0} (default_timeout={1}, ?timeout_limit={2}, max_request_timeout={3})"
491− .format(actual_timeout, default_timeout, query_timeout, max_request_timeout))
492−
493− return requests, actual_timeout
494−
495− def search_standard(self):
496− """
497− Update self.result_container, self.actual_timeout
498− """
499− requests, self.actual_timeout = self._get_requests()
500−
501− # send all search-request
502− if requests:
503− search_multiple_requests(requests, self.result_container, self.start_time, self.actual_timeout)
504− start_new_thread(gc.collect, tuple())
505−
506− # return results, suggestions, answers and infoboxes
507− return True
508−
509− # do search-request
510− def search(self):
511− self.start_time = time()
512−
513− if not self.search_external_bang():
514− if not self.search_answerers():
515− self.search_standard()
516−
517− return self.result_container
518−
519−
520−class SearchWithPlugins(Search):
521− """Similar to the Search class but call the plugins."""
522−
523− __slots__ = 'ordered_plugin_list', 'request'
524−
525− def __init__(self, search_query, ordered_plugin_list, request):
526− super().__init__(search_query)
527− self.ordered_plugin_list = ordered_plugin_list
528− self.request = request
529−
530− def search(self):
531− if plugins.call(self.ordered_plugin_list, 'pre_search', self.request, self):
532− super().search()
533−
534− plugins.call(self.ordered_plugin_list, 'post_search', self.request, self)
535−
536− results = self.result_container.get_ordered_results()
537−
538− for result in results:
539− plugins.call(self.ordered_plugin_list, 'on_result', self.request, self, result)
540−
541− return self.result_container
searx/search/__init__.pynew file+265
@@ -0,0 +1,265 @@
1+'''
2+searx is free software: you can redistribute it and/or modify
3+it under the terms of the GNU Affero General Public License as published by
4+the Free Software Foundation, either version 3 of the License, or
5+(at your option) any later version.
6+
7+searx is distributed in the hope that it will be useful,
8+but WITHOUT ANY WARRANTY; without even the implied warranty of
9+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10+GNU Affero General Public License for more details.
11+
12+You should have received a copy of the GNU Affero General Public License
13+along with searx. If not, see < http://www.gnu.org/licenses/ >.
14+
15+(C) 2013- by Adam Tauber, <asciimoo@gmail.com>
16+'''
17+
18+import typing
19+import gc
20+import threading
21+from time import time
22+from uuid import uuid4
23+from _thread import start_new_thread
24+
25+from searx import settings
26+from searx.answerers import ask
27+from searx.external_bang import get_bang_url
28+from searx.results import ResultContainer
29+from searx import logger
30+from searx.plugins import plugins
31+from searx.search.processors import processors, initialize as initialize_processors
32+
33+
34+logger = logger.getChild('search')
35+
36+max_request_timeout = settings.get('outgoing', {}).get('max_request_timeout' or None)
37+if max_request_timeout is None:
38+ logger.info('max_request_timeout={0}'.format(max_request_timeout))
39+else:
40+ if isinstance(max_request_timeout, float):
41+ logger.info('max_request_timeout={0} second(s)'.format(max_request_timeout))
42+ else:
43+ logger.critical('outgoing.max_request_timeout if defined has to be float')
44+ import sys
45+ sys.exit(1)
46+
47+
48+def initialize(settings_engines=None):
49+ settings_engines = settings_engines or settings['engines']
50+ initialize_processors(settings_engines)
51+
52+
53+class EngineRef:
54+
55+ __slots__ = 'name', 'category', 'from_bang'
56+
57+ def __init__(self, name: str, category: str, from_bang: bool=False):
58+ self.name = name
59+ self.category = category
60+ self.from_bang = from_bang
61+
62+ def __repr__(self):
63+ return "EngineRef({!r}, {!r}, {!r})".format(self.name, self.category, self.from_bang)
64+
65+ def __eq__(self, other):
66+ return self.name == other.name and self.category == other.category and self.from_bang == other.from_bang
67+
68+
69+class SearchQuery:
70+ """container for all the search parameters (query, language, etc...)"""
71+
72+ __slots__ = 'query', 'engineref_list', 'categories', 'lang', 'safesearch', 'pageno', 'time_range',\
73+ 'timeout_limit', 'external_bang'
74+
75+ def __init__(self,
76+ query: str,
77+ engineref_list: typing.List[EngineRef],
78+ categories: typing.List[str],
79+ lang: str,
80+ safesearch: int,
81+ pageno: int,
82+ time_range: typing.Optional[str],
83+ timeout_limit: typing.Optional[float]=None,
84+ external_bang: typing.Optional[str]=None):
85+ self.query = query
86+ self.engineref_list = engineref_list
87+ self.categories = categories
88+ self.lang = lang
89+ self.safesearch = safesearch
90+ self.pageno = pageno
91+ self.time_range = time_range
92+ self.timeout_limit = timeout_limit
93+ self.external_bang = external_bang
94+
95+ def __repr__(self):
96+ return "SearchQuery({!r}, {!r}, {!r}, {!r}, {!r}, {!r}, {!r}, {!r}, {!r})".\
97+ format(self.query, self.engineref_list, self.categories, self.lang, self.safesearch,
98+ self.pageno, self.time_range, self.timeout_limit, self.external_bang)
99+
100+ def __eq__(self, other):
101+ return self.query == other.query\
102+ and self.engineref_list == other.engineref_list\
103+ and self.categories == self.categories\
104+ and self.lang == other.lang\
105+ and self.safesearch == other.safesearch\
106+ and self.pageno == other.pageno\
107+ and self.time_range == other.time_range\
108+ and self.timeout_limit == other.timeout_limit\
109+ and self.external_bang == other.external_bang
110+
111+
112+class Search:
113+ """Search information container"""
114+
115+ __slots__ = "search_query", "result_container", "start_time", "actual_timeout"
116+
117+ def __init__(self, search_query):
118+ # init vars
119+ super().__init__()
120+ self.search_query = search_query
121+ self.result_container = ResultContainer()
122+ self.start_time = None
123+ self.actual_timeout = None
124+
125+ def search_external_bang(self):
126+ """
127+ Check if there is a external bang.
128+ If yes, update self.result_container and return True
129+ """
130+ if self.search_query.external_bang:
131+ self.result_container.redirect_url = get_bang_url(self.search_query)
132+
133+ # This means there was a valid bang and the
134+ # rest of the search does not need to be continued
135+ if isinstance(self.result_container.redirect_url, str):
136+ return True
137+ return False
138+
139+ def search_answerers(self):
140+ """
141+ Check if an answer return a result.
142+ If yes, update self.result_container and return True
143+ """
144+ answerers_results = ask(self.search_query)
145+
146+ if answerers_results:
147+ for results in answerers_results:
148+ self.result_container.extend('answer', results)
149+ return True
150+ return False
151+
152+ # do search-request
153+ def _get_requests(self):
154+ # init vars
155+ requests = []
156+
157+ # max of all selected engine timeout
158+ default_timeout = 0
159+
160+ # start search-reqest for all selected engines
161+ for engineref in self.search_query.engineref_list:
162+ processor = processors[engineref.name]
163+
164+ # set default request parameters
165+ request_params = processor.get_params(self.search_query, engineref.category)
166+ if request_params is None:
167+ continue
168+
169+ # append request to list
170+ requests.append((engineref.name, self.search_query.query, request_params))
171+
172+ # update default_timeout
173+ default_timeout = max(default_timeout, processor.engine.timeout)
174+
175+ # adjust timeout
176+ actual_timeout = default_timeout
177+ query_timeout = self.search_query.timeout_limit
178+
179+ if max_request_timeout is None and query_timeout is None:
180+ # No max, no user query: default_timeout
181+ pass
182+ elif max_request_timeout is None and query_timeout is not None:
183+ # No max, but user query: From user query except if above default
184+ actual_timeout = min(default_timeout, query_timeout)
185+ elif max_request_timeout is not None and query_timeout is None:
186+ # Max, no user query: Default except if above max
187+ actual_timeout = min(default_timeout, max_request_timeout)
188+ elif max_request_timeout is not None and query_timeout is not None:
189+ # Max & user query: From user query except if above max
190+ actual_timeout = min(query_timeout, max_request_timeout)
191+
192+ logger.debug("actual_timeout={0} (default_timeout={1}, ?timeout_limit={2}, max_request_timeout={3})"
193+ .format(actual_timeout, default_timeout, query_timeout, max_request_timeout))
194+
195+ return requests, actual_timeout
196+
197+ def search_multiple_requests(self, requests):
198+ search_id = uuid4().__str__()
199+
200+ for engine_name, query, request_params in requests:
201+ th = threading.Thread(
202+ target=processors[engine_name].search,
203+ args=(query, request_params, self.result_container, self.start_time, self.actual_timeout),
204+ name=search_id,
205+ )
206+ th._timeout = False
207+ th._engine_name = engine_name
208+ th.start()
209+
210+ for th in threading.enumerate():
211+ if th.name == search_id:
212+ remaining_time = max(0.0, self.actual_timeout - (time() - self.start_time))
213+ th.join(remaining_time)
214+ if th.is_alive():
215+ th._timeout = True
216+ self.result_container.add_unresponsive_engine(th._engine_name, 'timeout')
217+ logger.warning('engine timeout: {0}'.format(th._engine_name))
218+
219+ def search_standard(self):
220+ """
221+ Update self.result_container, self.actual_timeout
222+ """
223+ requests, self.actual_timeout = self._get_requests()
224+
225+ # send all search-request
226+ if requests:
227+ self.search_multiple_requests(requests)
228+ start_new_thread(gc.collect, tuple())
229+
230+ # return results, suggestions, answers and infoboxes
231+ return True
232+
233+ # do search-request
234+ def search(self):
235+ self.start_time = time()
236+
237+ if not self.search_external_bang():
238+ if not self.search_answerers():
239+ self.search_standard()
240+
241+ return self.result_container
242+
243+
244+class SearchWithPlugins(Search):
245+ """Similar to the Search class but call the plugins."""
246+
247+ __slots__ = 'ordered_plugin_list', 'request'
248+
249+ def __init__(self, search_query, ordered_plugin_list, request):
250+ super().__init__(search_query)
251+ self.ordered_plugin_list = ordered_plugin_list
252+ self.request = request
253+
254+ def search(self):
255+ if plugins.call(self.ordered_plugin_list, 'pre_search', self.request, self):
256+ super().search()
257+
258+ plugins.call(self.ordered_plugin_list, 'post_search', self.request, self)
259+
260+ results = self.result_container.get_ordered_results()
261+
262+ for result in results:
263+ plugins.call(self.ordered_plugin_list, 'on_result', self.request, self, result)
264+
265+ return self.result_container
searx/search/processors/__init__.pynew file+41
@@ -0,0 +1,41 @@
1+# SPDX-License-Identifier: AGPL-3.0-or-later
2+
3+from .online import OnlineProcessor
4+from .offline import OfflineProcessor
5+from .online_dictionary import OnlineDictionaryProcessor
6+from .online_currency import OnlineCurrencyProcessor
7+from .abstract import EngineProcessor
8+from searx import logger
9+import searx.engines as engines
10+
11+
12+__all__ = ['EngineProcessor', 'OfflineProcessor', 'OnlineProcessor',
13+ 'OnlineDictionaryProcessor', 'OnlineCurrencyProcessor', 'processors']
14+logger = logger.getChild('search.processors')
15+processors = {}
16+
17+
18+def get_processor_class(engine_type):
19+ for c in [OnlineProcessor, OfflineProcessor, OnlineDictionaryProcessor, OnlineCurrencyProcessor]:
20+ if c.engine_type == engine_type:
21+ return c
22+ return None
23+
24+
25+def get_processor(engine, engine_name):
26+ engine_type = getattr(engine, 'engine_type', 'online')
27+ processor_class = get_processor_class(engine_type)
28+ if processor_class:
29+ return processor_class(engine, engine_name)
30+ else:
31+ return None
32+
33+
34+def initialize(engine_list):
35+ engines.initialize_engines(engine_list)
36+ for engine_name, engine in engines.engines.items():
37+ processor = get_processor(engine, engine_name)
38+ if processor is None:
39+ logger.error('Error get processor for engine %s', engine_name)
40+ else:
41+ processors[engine_name] = processor
searx/search/processors/abstract.pynew file+39
@@ -0,0 +1,39 @@
1+# SPDX-License-Identifier: AGPL-3.0-or-later
2+
3+from abc import abstractmethod
4+from searx import logger
5+
6+
7+logger = logger.getChild('searx.search.processor')
8+
9+
10+class EngineProcessor:
11+
12+ def __init__(self, engine, engine_name):
13+ self.engine = engine
14+ self.engine_name = engine_name
15+
16+ def get_params(self, search_query, engine_category):
17+ # if paging is not supported, skip
18+ if search_query.pageno > 1 and not self.engine.paging:
19+ return None
20+
21+ # if time_range is not supported, skip
22+ if search_query.time_range and not self.engine.time_range_support:
23+ return None
24+
25+ params = {}
26+ params['category'] = engine_category
27+ params['pageno'] = search_query.pageno
28+ params['safesearch'] = search_query.safesearch
29+ params['time_range'] = search_query.time_range
30+
31+ if hasattr(self.engine, 'language') and self.engine.language:
32+ params['language'] = self.engine.language
33+ else:
34+ params['language'] = search_query.lang
35+ return params
36+
37+ @abstractmethod
38+ def search(self, query, params, result_container, start_time, timeout_limit):
39+ pass
searx/search/processors/offline.pynew file+51
@@ -0,0 +1,51 @@
1+# SPDX-License-Identifier: AGPL-3.0-or-later
2+
3+import threading
4+from time import time
5+from searx import logger
6+from searx.metrology.error_recorder import record_exception, record_error
7+from searx.search.processors.abstract import EngineProcessor
8+
9+
10+logger = logger.getChild('search.processor.offline')
11+
12+
13+class OfflineProcessor(EngineProcessor):
14+
15+ engine_type = 'offline'
16+
17+ def _record_stats_on_error(self, result_container, start_time):
18+ engine_time = time() - start_time
19+ result_container.add_timing(self.engine_name, engine_time, engine_time)
20+
21+ with threading.RLock():
22+ self.engine.stats['errors'] += 1
23+
24+ def _search_basic(self, query, params):
25+ return self.engine.search(query, params)
26+
27+ def search(self, query, params, result_container, start_time, timeout_limit):
28+ try:
29+ search_results = self._search_basic(query, params)
30+
31+ if search_results:
32+ result_container.extend(self.engine_name, search_results)
33+
34+ engine_time = time() - start_time
35+ result_container.add_timing(self.engine_name, engine_time, engine_time)
36+ with threading.RLock():
37+ self.engine.stats['engine_time'] += engine_time
38+ self.engine.stats['engine_time_count'] += 1
39+
40+ except ValueError as e:
41+ record_exception(self.engine_name, e)
42+ self._record_stats_on_error(result_container, start_time)
43+ logger.exception('engine {0} : invalid input : {1}'.format(self.engine_name, e))
44+ except Exception as e:
45+ record_exception(self.engine_name, e)
46+ self._record_stats_on_error(result_container, start_time)
47+ result_container.add_unresponsive_engine(self.engine_name, 'unexpected crash', str(e))
48+ logger.exception('engine {0} : exception : {1}'.format(self.engine_name, e))
49+ else:
50+ if getattr(threading.current_thread(), '_timeout', False):
51+ record_error(self.engine_name, 'Timeout')
searx/search/processors/online.pynew file+211
@@ -0,0 +1,211 @@
1+# SPDX-License-Identifier: AGPL-3.0-or-later
2+
3+from urllib.parse import urlparse
4+from time import time
5+import threading
6+
7+import requests.exceptions
8+
9+import searx.poolrequests as poolrequests
10+from searx.engines import settings
11+from searx import logger
12+from searx.utils import gen_useragent
13+from searx.exceptions import (SearxEngineAccessDeniedException, SearxEngineCaptchaException,
14+ SearxEngineTooManyRequestsException,)
15+from searx.metrology.error_recorder import record_exception, record_error
16+
17+from searx.search.processors.abstract import EngineProcessor
18+
19+
20+logger = logger.getChild('search.processor.online')
21+
22+DEFAULT_PARAMS = {
23+ 'method': 'GET',
24+ 'headers': {},
25+ 'data': {},
26+ 'url': '',
27+ 'cookies': {},
28+ 'verify': True,
29+ 'auth': None
30+}
31+
32+
33+class OnlineProcessor(EngineProcessor):
34+
35+ engine_type = 'online'
36+
37+ def get_params(self, search_query, engine_category):
38+ params = super().get_params(search_query, engine_category)
39+ if params is None:
40+ return None
41+
42+ # skip suspended engines
43+ if self.engine.suspend_end_time >= time():
44+ logger.debug('Engine currently suspended: %s', self.engine_name)
45+ return None
46+
47+ # add default params
48+ params.update(DEFAULT_PARAMS)
49+
50+ # add an user agent
51+ params['headers']['User-Agent'] = gen_useragent()
52+
53+ return params
54+
55+ def _send_http_request(self, params):
56+ # create dictionary which contain all
57+ # informations about the request
58+ request_args = dict(
59+ headers=params['headers'],
60+ cookies=params['cookies'],
61+ verify=params['verify'],
62+ auth=params['auth']
63+ )
64+
65+ # setting engine based proxies
66+ if hasattr(self.engine, 'proxies'):
67+ request_args['proxies'] = poolrequests.get_proxies(self.engine.proxies)
68+
69+ # max_redirects
70+ max_redirects = params.get('max_redirects')
71+ if max_redirects:
72+ request_args['max_redirects'] = max_redirects
73+
74+ # soft_max_redirects
75+ soft_max_redirects = params.get('soft_max_redirects', max_redirects or 0)
76+
77+ # raise_for_status
78+ request_args['raise_for_httperror'] = params.get('raise_for_httperror', False)
79+
80+ # specific type of request (GET or POST)
81+ if params['method'] == 'GET':
82+ req = poolrequests.get
83+ else:
84+ req = poolrequests.post
85+
86+ request_args['data'] = params['data']
87+
88+ # send the request
89+ response = req(params['url'], **request_args)
90+
91+ # check soft limit of the redirect count
92+ if len(response.history) > soft_max_redirects:
93+ # unexpected redirect : record an error
94+ # but the engine might still return valid results.
95+ status_code = str(response.status_code or '')
96+ reason = response.reason or ''
97+ hostname = str(urlparse(response.url or '').netloc)
98+ record_error(self.engine_name,
99+ '{} redirects, maximum: {}'.format(len(response.history), soft_max_redirects),
100+ (status_code, reason, hostname))
101+
102+ return response
103+
104+ def _search_basic(self, query, params):
105+ # update request parameters dependent on
106+ # search-engine (contained in engines folder)
107+ self.engine.request(query, params)
108+
109+ # ignoring empty urls
110+ if params['url'] is None:
111+ return None
112+
113+ if not params['url']:
114+ return None
115+
116+ # send request
117+ response = self._send_http_request(params)
118+
119+ # parse the response
120+ response.search_params = params
121+ return self.engine.response(response)
122+
123+ def search(self, query, params, result_container, start_time, timeout_limit):
124+ # set timeout for all HTTP requests
125+ poolrequests.set_timeout_for_thread(timeout_limit, start_time=start_time)
126+ # reset the HTTP total time
127+ poolrequests.reset_time_for_thread()
128+
129+ # suppose everything will be alright
130+ requests_exception = False
131+ suspended_time = None
132+
133+ try:
134+ # send requests and parse the results
135+ search_results = self._search_basic(query, params)
136+
137+ # check if the engine accepted the request
138+ if search_results is not None:
139+ # yes, so add results
140+ result_container.extend(self.engine_name, search_results)
141+
142+ # update engine time when there is no exception
143+ engine_time = time() - start_time
144+ page_load_time = poolrequests.get_time_for_thread()
145+ result_container.add_timing(self.engine_name, engine_time, page_load_time)
146+ with threading.RLock():
147+ self.engine.stats['engine_time'] += engine_time
148+ self.engine.stats['engine_time_count'] += 1
149+ # update stats with the total HTTP time
150+ self.engine.stats['page_load_time'] += page_load_time
151+ self.engine.stats['page_load_count'] += 1
152+ except Exception as e:
153+ record_exception(self.engine_name, e)
154+
155+ # Timing
156+ engine_time = time() - start_time
157+ page_load_time = poolrequests.get_time_for_thread()
158+ result_container.add_timing(self.engine_name, engine_time, page_load_time)
159+
160+ # Record the errors
161+ with threading.RLock():
162+ self.engine.stats['errors'] += 1
163+
164+ if (issubclass(e.__class__, requests.exceptions.Timeout)):
165+ result_container.add_unresponsive_engine(self.engine_name, 'HTTP timeout')
166+ # requests timeout (connect or read)
167+ logger.error("engine {0} : HTTP requests timeout"
168+ "(search duration : {1} s, timeout: {2} s) : {3}"
169+ .format(self.engine_name, engine_time, timeout_limit, e.__class__.__name__))
170+ requests_exception = True
171+ elif (issubclass(e.__class__, requests.exceptions.RequestException)):
172+ result_container.add_unresponsive_engine(self.engine_name, 'HTTP error')
173+ # other requests exception
174+ logger.exception("engine {0} : requests exception"
175+ "(search duration : {1} s, timeout: {2} s) : {3}"
176+ .format(self.engine_name, engine_time, timeout_limit, e))
177+ requests_exception = True
178+ elif (issubclass(e.__class__, SearxEngineCaptchaException)):
179+ result_container.add_unresponsive_engine(self.engine_name, 'CAPTCHA required')
180+ logger.exception('engine {0} : CAPTCHA')
181+ suspended_time = e.suspended_time # pylint: disable=no-member
182+ elif (issubclass(e.__class__, SearxEngineTooManyRequestsException)):
183+ result_container.add_unresponsive_engine(self.engine_name, 'too many requests')
184+ logger.exception('engine {0} : Too many requests')
185+ suspended_time = e.suspended_time # pylint: disable=no-member
186+ elif (issubclass(e.__class__, SearxEngineAccessDeniedException)):
187+ result_container.add_unresponsive_engine(self.engine_name, 'blocked')
188+ logger.exception('engine {0} : Searx is blocked')
189+ suspended_time = e.suspended_time # pylint: disable=no-member
190+ else:
191+ result_container.add_unresponsive_engine(self.engine_name, 'unexpected crash')
192+ # others errors
193+ logger.exception('engine {0} : exception : {1}'.format(self.engine_name, e))
194+ else:
195+ if getattr(threading.current_thread(), '_timeout', False):
196+ record_error(self.engine_name, 'Timeout')
197+
198+ # suspend the engine if there is an HTTP error
199+ # or suspended_time is defined
200+ with threading.RLock():
201+ if requests_exception or suspended_time:
202+ # update continuous_errors / suspend_end_time
203+ self.engine.continuous_errors += 1
204+ if suspended_time is None:
205+ suspended_time = min(settings['search']['max_ban_time_on_fail'],
206+ self.engine.continuous_errors * settings['search']['ban_time_on_fail'])
207+ self.engine.suspend_end_time = time() + suspended_time
208+ else:
209+ # reset the suspend variables
210+ self.engine.continuous_errors = 0
211+ self.engine.suspend_end_time = 0
searx/search/processors/online_currency.pynew file+57
@@ -0,0 +1,57 @@
1+# SPDX-License-Identifier: AGPL-3.0-or-later
2+
3+import unicodedata
4+import re
5+
6+from searx.data import CURRENCIES
7+from .online import OnlineProcessor
8+
9+
10+parser_re = re.compile('.*?(\\d+(?:\\.\\d+)?) ([^.0-9]+) (?:in|to) ([^.0-9]+)', re.I)
11+
12+
13+def normalize_name(name):
14+ name = name.lower().replace('-', ' ').rstrip('s')
15+ name = re.sub(' +', ' ', name)
16+ return unicodedata.normalize('NFKD', name).lower()
17+
18+
19+def name_to_iso4217(name):
20+ global CURRENCIES
21+ name = normalize_name(name)
22+ currency = CURRENCIES['names'].get(name, [name])
23+ return currency[0]
24+
25+
26+def iso4217_to_name(iso4217, language):
27+ global CURRENCIES
28+ return CURRENCIES['iso4217'].get(iso4217, {}).get(language, iso4217)
29+
30+
31+class OnlineCurrencyProcessor(OnlineProcessor):
32+
33+ engine_type = 'online_currency'
34+
35+ def get_params(self, search_query, engine_category):
36+ params = super().get_params(search_query, engine_category)
37+ if params is None:
38+ return None
39+
40+ m = parser_re.match(search_query.query)
41+ if not m:
42+ return None
43+
44+ amount_str, from_currency, to_currency = m.groups()
45+ try:
46+ amount = float(amount_str)
47+ except ValueError:
48+ return None
49+ from_currency = name_to_iso4217(from_currency.strip())
50+ to_currency = name_to_iso4217(to_currency.strip())
51+
52+ params['amount'] = amount
53+ params['from'] = from_currency
54+ params['to'] = to_currency
55+ params['from_name'] = iso4217_to_name(from_currency, 'en')
56+ params['to_name'] = iso4217_to_name(to_currency, 'en')
57+ return params
searx/search/processors/online_dictionary.pynew file+37
@@ -0,0 +1,37 @@
1+# SPDX-License-Identifier: AGPL-3.0-or-later
2+
3+import re
4+
5+from searx.utils import is_valid_lang
6+from .online import OnlineProcessor
7+
8+
9+parser_re = re.compile('.*?([a-z]+)-([a-z]+) ([^ ]+)$', re.I)
10+
11+
12+class OnlineDictionaryProcessor(OnlineProcessor):
13+
14+ engine_type = 'online_dictionnary'
15+
16+ def get_params(self, search_query, engine_category):
17+ params = super().get_params(search_query, engine_category)
18+ if params is None:
19+ return None
20+
21+ m = parser_re.match(search_query.query)
22+ if not m:
23+ return None
24+
25+ from_lang, to_lang, query = m.groups()
26+
27+ from_lang = is_valid_lang(from_lang)
28+ to_lang = is_valid_lang(to_lang)
29+
30+ if not from_lang or not to_lang:
31+ return None
32+
33+ params['from_lang'] = from_lang
34+ params['to_lang'] = to_lang
35+ params['query'] = query
36+
37+ return params
searx/webapp.py+3−3
@@ -60,7 +60,7 @@ from searx import brand, static_path
6060from searx import settings, searx_dir, searx_debug
6161from searx.exceptions import SearxParameterException
6262from searx.engines import (
63− categories, engines, engine_shortcuts, get_engines_stats, initialize_engines
63+ categories, engines, engine_shortcuts, get_engines_stats
6464)
6565from searx.webutils import (
6666 UnicodeWriter, highlight_content, get_resources_directory,
@@ -71,7 +71,7 @@ from searx.webadapter import get_search_query_from_webapp, get_selected_categori
7171from searx.utils import html_to_text, gen_useragent, dict_subset, match_language
7272from searx.version import VERSION_STRING
7373from searx.languages import language_codes as languages
74−from searx.search import SearchWithPlugins
74+from searx.search import SearchWithPlugins, initialize
7575from searx.query import RawTextQuery
7676from searx.autocomplete import searx_bang, backends as autocomplete_backends
7777from searx.plugins import plugins
@@ -131,7 +131,7 @@ werkzeug_reloader = flask_run_development or (searx_debug and __name__ == "__mai
131131# initialize the engines except on the first run of the werkzeug server.
132132if not werkzeug_reloader\
133133 or (werkzeug_reloader and os.environ.get("WERKZEUG_RUN_MAIN") == "true"):
134− initialize_engines(settings['engines'])
134+ initialize()
135135
136136babel = Babel(app)
137137
tests/unit/test_search.py+1−2
@@ -3,7 +3,6 @@
33from searx.testing import SearxTestCase
44from searx.search import SearchQuery, EngineRef
55import searx.search
6−import searx.engines
76
87
98SAFESEARCH = 0
@@ -39,7 +38,7 @@ class SearchTestCase(SearxTestCase):
3938
4039 @classmethod
4140 def setUpClass(cls):
42− searx.engines.initialize_engines(TEST_ENGINES)
41+ searx.search.initialize(TEST_ENGINES)
4342
4443 def test_timeout_simple(self):
4544 searx.search.max_request_timeout = None
tests/unit/test_standalone_searx.py+2−3
@@ -8,8 +8,7 @@ import sys
88from mock import Mock, patch
99from nose2.tools import params
1010
11−from searx.search import SearchQuery, EngineRef
12−from searx.engines import initialize_engines
11+from searx.search import SearchQuery, EngineRef, initialize
1312from searx.testing import SearxTestCase
1413
1514
@@ -30,7 +29,7 @@ class StandaloneSearx(SearxTestCase):
3029 def setUpClass(cls):
3130 engine_list = [{'engine': 'dummy', 'name': 'engine1', 'shortcut': 'e1'}]
3231
33− initialize_engines(engine_list)
32+ initialize(engine_list)
3433
3534 def test_parse_argument_no_args(self):
3635 """Test parse argument without args."""
tests/unit/test_webadapter.py+2−2
@@ -17,7 +17,7 @@ TEST_ENGINES = [
1717 'categories': 'general',
1818 'shortcut': 'do',
1919 'timeout': 3.0,
20− 'offline': True,
20+ 'engine_type': 'offline',
2121 'tokens': ['my-token'],
2222 },
2323]
@@ -28,7 +28,7 @@ class ValidateQueryCase(SearxTestCase):
2828
2929 @classmethod
3030 def setUpClass(cls):
31− searx.engines.initialize_engines(TEST_ENGINES)
31+ searx.search.initialize(TEST_ENGINES)
3232
3333 def test_query_private_engine_without_token(self):
3434 preferences = Preferences(['oscar'], ['general'], engines, [])
utils/standalone_searx.py+5−6
@@ -6,8 +6,8 @@ Getting categories without initiate the engine will only return `['general']`
66>>> import searx.engines
77... list(searx.engines.categories.keys())
88['general']
9−>>> import searx
10−... searx.engines.initialize_engines(searx.settings['engines'])
9+>>> import searx.search
10+... searx.search.initialize()
1111... list(searx.engines.categories.keys())
1212['general', 'it', 'science', 'images', 'news', 'videos', 'music', 'files', 'social media', 'map']
1313
@@ -22,11 +22,11 @@ Example to run it from python:
2222>>> import importlib
2323... import json
2424... import sys
25−... import searx
2625... import searx.engines
26+... import searx.search
2727... search_query = 'rain'
2828... # initialize engines
29−... searx.engines.initialize_engines(searx.settings['engines'])
29+... searx.search.initialize()
3030... # load engines categories once instead of each time the function called
3131... engine_cs = list(searx.engines.categories.keys())
3232... # load module
@@ -82,7 +82,6 @@ from json import dumps
8282from typing import Any, Dict, List, Optional
8383
8484import searx
85−import searx.engines
8685import searx.preferences
8786import searx.query
8887import searx.search
@@ -208,7 +207,7 @@ def parse_argument(
208207
209208
210209if __name__ == '__main__':
211− searx.engines.initialize_engines(searx.settings['engines'])
210+ searx.search.initialize()
212211 engine_cs = list(searx.engines.categories.keys())
213212 prog_args = parse_argument(category_choices=engine_cs)
214213 search_q = get_search_query(prog_args, engine_categories=engine_cs)