.oO SearXNG Developer Documentation Oo.
Loading...
Searching...
No Matches
json_engine.py
Go to the documentation of this file.
1# SPDX-License-Identifier: AGPL-3.0-or-later
2"""The JSON engine is a *generic* engine with which it is possible to configure
3engines in the settings.
4
5Configuration
6=============
7
8Request:
9
10- :py:obj:`search_url`
11- :py:obj:`lang_all`
12- :py:obj:`soft_max_redirects`
13- :py:obj:`method`
14- :py:obj:`request_body`
15- :py:obj:`cookies`
16- :py:obj:`headers`
17
18Paging:
19
20- :py:obj:`paging`
21- :py:obj:`page_size`
22- :py:obj:`first_page_num`
23
24Time Range:
25
26- :py:obj:`time_range_support`
27- :py:obj:`time_range_url`
28- :py:obj:`time_range_map`
29
30Safe-Search:
31
32- :py:obj:`safe_search_support`
33- :py:obj:`safe_search_map`
34
35Response:
36
37- :py:obj:`title_html_to_text`
38- :py:obj:`content_html_to_text`
39- :py:obj:`no_result_for_http_status`
40
41JSON query:
42
43- :py:obj:`results_query`
44- :py:obj:`url_query`
45- :py:obj:`url_prefix`
46- :py:obj:`title_query`
47- :py:obj:`content_query`
48- :py:obj:`thumbnail_query`
49- :py:obj:`thumbnail_prefix`
50- :py:obj:`suggestion_query`
51
52
53Example
54=======
55
56Here is a simple example of a JSON engine configure in the :ref:`settings
57engine` section, further read :ref:`engines-dev`.
58
59.. code:: yaml
60
61 - name : mdn
62 engine : json_engine
63 paging : True
64 search_url : https://developer.mozilla.org/api/v1/search?q={query}&page={pageno}
65 results_query : documents
66 url_query : mdn_url
67 url_prefix : https://developer.mozilla.org
68 title_query : title
69 content_query : summary
70
71Implementations
72===============
73
74"""
75
76from collections.abc import Iterable
77from json import loads
78from urllib.parse import urlencode
79from searx.utils import to_string, html_to_text
80from searx.network import raise_for_httperror
81
82search_url = None
83"""
84Search URL of the engine. Example::
85
86 https://example.org/?search={query}&page={pageno}{time_range}{safe_search}
87
88Replacements are:
89
90``{query}``:
91 Search terms from user.
92
93``{pageno}``:
94 Page number if engine supports paging :py:obj:`paging`
95
96``{lang}``:
97 ISO 639-1 language code (en, de, fr ..)
98
99``{time_range}``:
100 :py:obj:`URL parameter <time_range_url>` if engine :py:obj:`supports time
101 range <time_range_support>`. The value for the parameter is taken from
102 :py:obj:`time_range_map`.
103
104``{safe_search}``:
105 Safe-search :py:obj:`URL parameter <safe_search_map>` if engine
106 :py:obj:`supports safe-search <safe_search_support>`. The ``{safe_search}``
107 replacement is taken from the :py:obj:`safes_search_map`. Filter results::
108
109 0: none, 1: moderate, 2:strict
110
111 If not supported, the URL parameter is an empty string.
112
113"""
114
115lang_all = 'en'
116'''Replacement ``{lang}`` in :py:obj:`search_url` if language ``all`` is
117selected.
118'''
119
120no_result_for_http_status = []
121'''Return empty result for these HTTP status codes instead of throwing an error.
122
123.. code:: yaml
124
125 no_result_for_http_status: []
126'''
127
128soft_max_redirects = 0
129'''Maximum redirects, soft limit. Record an error but don't stop the engine'''
130
131method = 'GET'
132'''Some engines might require to do POST requests for search.'''
133
134request_body = ''
135'''The body of the request. This can only be used if different :py:obj:`method`
136is set, e.g. ``POST``. For formatting see the documentation of :py:obj:`search_url`.
137
138Note: Curly brackets which aren't encapsulating a replacement placeholder
139must be escaped by doubling each ``{`` and ``}``.
140
141.. code:: yaml
142
143 request_body: >-
144 {{
145 "search": "{query}",
146 "page": {pageno},
147 "extra": {{
148 "time_range": {time_range},
149 "rating": "{safe_search}"
150 }}
151 }}
152'''
153
154cookies = {}
155'''Some engines might offer different result based on cookies.
156Possible use-case: To set safesearch cookie.'''
157
158headers = {}
159'''Some engines might offer different result based on cookies or headers.
160Possible use-case: To set safesearch cookie or header to moderate.'''
161
162paging = False
163'''Engine supports paging [True or False].'''
164
165page_size = 1
166'''Number of results on each page. Only needed if the site requires not a page
167number, but an offset.'''
168
169first_page_num = 1
170'''Number of the first page (usually 0 or 1).'''
171
172results_query = ''
173'''JSON query for the list of result items.
174
175The query string is a slash `/` separated path of JSON key names.
176Array entries can be specified using the index or can be omitted entirely,
177in which case each entry is considered -
178most implementations will default to the first entry in this case.
179'''
180
181url_query = None
182'''JSON query of result's ``url``. For the query string documentation see :py:obj:`results_query`'''
183
184url_prefix = ""
185'''String to prepend to the result's ``url``.'''
186
187title_query = None
188'''JSON query of result's ``title``. For the query string documentation see :py:obj:`results_query`'''
189
190content_query = None
191'''JSON query of result's ``content``. For the query string documentation see :py:obj:`results_query`'''
192
193thumbnail_query = False
194'''JSON query of result's ``thumbnail``. For the query string documentation see :py:obj:`results_query`'''
195
196thumbnail_prefix = ''
197'''String to prepend to the result's ``thumbnail``.'''
198
199suggestion_query = ''
200'''JSON query of result's ``suggestion``. For the query string documentation see :py:obj:`results_query`'''
201
202title_html_to_text = False
203'''Extract text from a HTML title string'''
204
205content_html_to_text = False
206'''Extract text from a HTML content string'''
207
208time_range_support = False
209'''Engine supports search time range.'''
210
211time_range_url = '&hours={time_range_val}'
212'''Time range URL parameter in the in :py:obj:`search_url`. If no time range is
213requested by the user, the URL parameter is an empty string. The
214``{time_range_val}`` replacement is taken from the :py:obj:`time_range_map`.
215
216.. code:: yaml
217
218 time_range_url : '&days={time_range_val}'
219'''
220
221time_range_map = {
222 'day': 24,
223 'week': 24 * 7,
224 'month': 24 * 30,
225 'year': 24 * 365,
226}
227'''Maps time range value from user to ``{time_range_val}`` in
228:py:obj:`time_range_url`.
229
230.. code:: yaml
231
232 time_range_map:
233 day: 1
234 week: 7
235 month: 30
236 year: 365
237'''
238
239safe_search_support = False
240'''Engine supports safe-search.'''
241
242safe_search_map = {0: '&filter=none', 1: '&filter=moderate', 2: '&filter=strict'}
243'''Maps safe-search value to ``{safe_search}`` in :py:obj:`search_url`.
244
245.. code:: yaml
246
247 safesearch: true
248 safes_search_map:
249 0: '&filter=none'
250 1: '&filter=moderate'
251 2: '&filter=strict'
252
253'''
254
255
256def iterate(iterable):
257 if isinstance(iterable, dict):
258 items = iterable.items()
259
260 else:
261 items = enumerate(iterable)
262 for index, value in items:
263 yield str(index), value
264
265
266def is_iterable(obj):
267 if isinstance(obj, str):
268 return False
269 return isinstance(obj, Iterable)
270
271
272def parse(query): # pylint: disable=redefined-outer-name
273 q = [] # pylint: disable=invalid-name
274 for part in query.split('/'):
275 if part == '':
276 continue
277 q.append(part)
278 return q
279
280
281def do_query(data, q): # pylint: disable=invalid-name
282 ret = []
283 if not q:
284 return ret
285
286 qkey = q[0]
287
288 for key, value in iterate(data):
289
290 if len(q) == 1:
291 if key == qkey:
292 ret.append(value)
293 elif is_iterable(value):
294 ret.extend(do_query(value, q))
295 else:
296 if not is_iterable(value):
297 continue
298 if key == qkey:
299 ret.extend(do_query(value, q[1:]))
300 else:
301 ret.extend(do_query(value, q))
302 return ret
303
304
305def query(data, query_string):
306 q = parse(query_string)
307
308 return do_query(data, q)
309
310
311def request(query, params): # pylint: disable=redefined-outer-name
312 '''Build request parameters (see :ref:`engine request`).'''
313 lang = lang_all
314 if params['language'] != 'all':
315 lang = params['language'][:2]
316
317 time_range = ''
318 if params.get('time_range'):
319 time_range_val = time_range_map.get(params.get('time_range'))
320 time_range = time_range_url.format(time_range_val=time_range_val)
321
322 safe_search = ''
323 if params['safesearch']:
324 safe_search = safe_search_map[params['safesearch']]
325
326 fp = { # pylint: disable=invalid-name
327 'query': urlencode({'q': query})[2:],
328 'lang': lang,
329 'pageno': (params['pageno'] - 1) * page_size + first_page_num,
330 'time_range': time_range,
331 'safe_search': safe_search,
332 }
333
334 params['cookies'].update(cookies)
335 params['headers'].update(headers)
336
337 params['url'] = search_url.format(**fp)
338 params['method'] = method
339
340 if request_body:
341 # don't url-encode the query if it's in the request body
342 fp['query'] = query
343 params['data'] = request_body.format(**fp)
344
345 params['soft_max_redirects'] = soft_max_redirects
346 params['raise_for_httperror'] = False
347
348 return params
349
350
351def identity(arg):
352 return arg
353
354
356 title_filter = html_to_text if title_html_to_text else identity
357 content_filter = html_to_text if content_html_to_text else identity
358
359 tmp_result = {}
360
361 try:
362 url = query(result, url_query)[0]
363 tmp_result['url'] = url_prefix + to_string(url)
364
365 title = query(result, title_query)[0]
366 tmp_result['title'] = title_filter(to_string(title))
367 except: # pylint: disable=bare-except
368 return None
369
370 try:
371 content = query(result, content_query)[0]
372 tmp_result['content'] = content_filter(to_string(content))
373 except: # pylint: disable=bare-except
374 tmp_result['content'] = ""
375
376 try:
377 if thumbnail_query:
378 thumbnail_query_result = query(result, thumbnail_query)[0]
379 tmp_result['thumbnail'] = thumbnail_prefix + to_string(thumbnail_query_result)
380 except: # pylint: disable=bare-except
381 pass
382
383 return tmp_result
384
385
386def response(resp):
387 '''Scrap *results* from the response (see :ref:`engine results`).'''
388 results = []
389
390 if no_result_for_http_status and resp.status_code in no_result_for_http_status:
391 return results
392
393 raise_for_httperror(resp)
394
395 if not resp.text:
396 return results
397
398 json = loads(resp.text)
399 is_onion = 'onions' in categories
400
401 if results_query:
402 rs = query(json, results_query) # pylint: disable=invalid-name
403 if not rs:
404 return results
405 rs = rs[0] # pylint: disable=invalid-name
406 else:
407 rs = json # pylint: disable=invalid-name
408
409 for result in rs:
410 tmp_result = extract_response_info(result)
411 if not tmp_result:
412 continue
413
414 if is_onion:
415 tmp_result['is_onion'] = True
416
417 results.append(tmp_result)
418
419 if not suggestion_query:
420 return results
421 for suggestion in query(json, suggestion_query):
422 results.append({'suggestion': suggestion})
423 return results