.oO SearXNG Developer Documentation Oo.
Loading...
Searching...
No Matches
duckduckgo.py
Go to the documentation of this file.
1# SPDX-License-Identifier: AGPL-3.0-or-later
2"""
3DuckDuckGo WEB
4~~~~~~~~~~~~~~
5"""
6
7from __future__ import annotations
8
9from typing import TYPE_CHECKING
10import re
11from urllib.parse import urlencode, quote_plus
12import json
13import babel
14import lxml.html
15
16from searx import (
17 locales,
18 redislib,
19 external_bang,
20)
21from searx.utils import (
22 eval_xpath,
23 extr,
24 extract_text,
25)
26from searx.network import get # see https://github.com/searxng/searxng/issues/762
27from searx import redisdb
28from searx.enginelib.traits import EngineTraits
29from searx.exceptions import SearxEngineCaptchaException
30
31if TYPE_CHECKING:
32 import logging
33
34 logger: logging.Logger
35
36traits: EngineTraits
37
38about = {
39 "website": 'https://lite.duckduckgo.com/lite/',
40 "wikidata_id": 'Q12805',
41 "use_official_api": False,
42 "require_api_key": False,
43 "results": 'HTML',
44}
45
46send_accept_language_header = True
47"""DuckDuckGo-Lite tries to guess user's preferred language from the HTTP
48``Accept-Language``. Optional the user can select a region filter (but not a
49language).
50"""
51
52# engine dependent config
53categories = ['general', 'web']
54paging = True
55time_range_support = True
56safesearch = True # user can't select but the results are filtered
57
58url = "https://html.duckduckgo.com/html"
59
60time_range_dict = {'day': 'd', 'week': 'w', 'month': 'm', 'year': 'y'}
61form_data = {'v': 'l', 'api': 'd.js', 'o': 'json'}
62__CACHE = []
63
64
65def _cache_key(query: str, region: str):
66 return 'SearXNG_ddg_web_vqd' + redislib.secret_hash(f"{query}//{region}")
67
68
69def cache_vqd(query: str, region: str, value: str):
70 """Caches a ``vqd`` value from a query."""
71 c = redisdb.client()
72 if c:
73 logger.debug("VALKEY cache vqd value: %s (%s)", value, region)
74 c.set(_cache_key(query, region), value, ex=600)
75
76 else:
77 logger.debug("MEM cache vqd value: %s (%s)", value, region)
78 if len(__CACHE) > 100: # cache vqd from last 100 queries
79 __CACHE.pop(0)
80 __CACHE.append((_cache_key(query, region), value))
81
82
83def get_vqd(query: str, region: str, force_request: bool = False):
84 """Returns the ``vqd`` that fits to the *query*.
85
86 :param query: The query term
87 :param region: DDG's region code
88 :param force_request: force a request to get a vqd value from DDG
89
90 TL;DR; the ``vqd`` value is needed to pass DDG's bot protection and is used
91 by all request to DDG:
92
93 - DuckDuckGo Lite: ``https://lite.duckduckgo.com/lite`` (POST form data)
94 - DuckDuckGo Web: ``https://links.duckduckgo.com/d.js?q=...&vqd=...``
95 - DuckDuckGo Images: ``https://duckduckgo.com/i.js??q=...&vqd=...``
96 - DuckDuckGo Videos: ``https://duckduckgo.com/v.js??q=...&vqd=...``
97 - DuckDuckGo News: ``https://duckduckgo.com/news.js??q=...&vqd=...``
98
99 DDG's bot detection is sensitive to the ``vqd`` value. For some search terms
100 (such as extremely long search terms that are often sent by bots), no ``vqd``
101 value can be determined.
102
103 If SearXNG cannot determine a ``vqd`` value, then no request should go out
104 to DDG.
105
106 .. attention::
107
108 A request with a wrong ``vqd`` value leads to DDG temporarily putting
109 SearXNG's IP on a block list.
110
111 Requests from IPs in this block list run into timeouts. Not sure, but it
112 seems the block list is a sliding window: to get my IP rid from the bot list
113 I had to cool down my IP for 1h (send no requests from that IP to DDG).
114 """
115 key = _cache_key(query, region)
116
117 c = redisdb.client()
118 if c:
119 value = c.get(key)
120 if value or value == b'':
121 value = value.decode('utf-8') # type: ignore
122 logger.debug("re-use CACHED vqd value: %s", value)
123 return value
124
125 for k, value in __CACHE:
126 if k == key:
127 logger.debug("MEM re-use CACHED vqd value: %s", value)
128 return value
129
130 if force_request:
131 resp = get(f'https://duckduckgo.com/?q={quote_plus(query)}')
132 if resp.status_code == 200: # type: ignore
133 value = extr(resp.text, 'vqd="', '"') # type: ignore
134 if value:
135 logger.debug("vqd value from DDG request: %s", value)
136 cache_vqd(query, region, value)
137 return value
138
139 return None
140
141
142def get_ddg_lang(eng_traits: EngineTraits, sxng_locale, default='en_US'):
143 """Get DuckDuckGo's language identifier from SearXNG's locale.
144
145 DuckDuckGo defines its languages by region codes (see
146 :py:obj:`fetch_traits`).
147
148 To get region and language of a DDG service use:
149
150 .. code: python
151
152 eng_region = traits.get_region(params['searxng_locale'], traits.all_locale)
153 eng_lang = get_ddg_lang(traits, params['searxng_locale'])
154
155 It might confuse, but the ``l`` value of the cookie is what SearXNG calls
156 the *region*:
157
158 .. code:: python
159
160 # !ddi paris :es-AR --> {'ad': 'es_AR', 'ah': 'ar-es', 'l': 'ar-es'}
161 params['cookies']['ad'] = eng_lang
162 params['cookies']['ah'] = eng_region
163 params['cookies']['l'] = eng_region
164
165 .. hint::
166
167 `DDG-lite <https://lite.duckduckgo.com/lite>`__ and the *no Javascript*
168 page https://html.duckduckgo.com/html do not offer a language selection
169 to the user, only a region can be selected by the user (``eng_region``
170 from the example above). DDG-lite and *no Javascript* store the selected
171 region in a cookie::
172
173 params['cookies']['kl'] = eng_region # 'ar-es'
174
175 """
176 return eng_traits.custom['lang_region'].get( # type: ignore
177 sxng_locale, eng_traits.get_language(sxng_locale, default)
178 )
179
180
181ddg_reg_map = {
182 'tw-tzh': 'zh_TW',
183 'hk-tzh': 'zh_HK',
184 'ct-ca': 'skip', # ct-ca and es-ca both map to ca_ES
185 'es-ca': 'ca_ES',
186 'id-en': 'id_ID',
187 'no-no': 'nb_NO',
188 'jp-jp': 'ja_JP',
189 'kr-kr': 'ko_KR',
190 'xa-ar': 'ar_SA',
191 'sl-sl': 'sl_SI',
192 'th-en': 'th_TH',
193 'vn-en': 'vi_VN',
194}
195
196ddg_lang_map = {
197 # use ar --> ar_EG (Egypt's arabic)
198 "ar_DZ": 'lang_region',
199 "ar_JO": 'lang_region',
200 "ar_SA": 'lang_region',
201 # use bn --> bn_BD
202 'bn_IN': 'lang_region',
203 # use de --> de_DE
204 'de_CH': 'lang_region',
205 # use en --> en_US,
206 'en_AU': 'lang_region',
207 'en_CA': 'lang_region',
208 'en_GB': 'lang_region',
209 # Esperanto
210 'eo_XX': 'eo',
211 # use es --> es_ES,
212 'es_AR': 'lang_region',
213 'es_CL': 'lang_region',
214 'es_CO': 'lang_region',
215 'es_CR': 'lang_region',
216 'es_EC': 'lang_region',
217 'es_MX': 'lang_region',
218 'es_PE': 'lang_region',
219 'es_UY': 'lang_region',
220 'es_VE': 'lang_region',
221 # use fr --> rf_FR
222 'fr_CA': 'lang_region',
223 'fr_CH': 'lang_region',
224 'fr_BE': 'lang_region',
225 # use nl --> nl_NL
226 'nl_BE': 'lang_region',
227 # use pt --> pt_PT
228 'pt_BR': 'lang_region',
229 # skip these languages
230 'od_IN': 'skip',
231 'io_XX': 'skip',
232 'tokipona_XX': 'skip',
233}
234
235
236def quote_ddg_bangs(query):
237 # quote ddg bangs
238 query_parts = []
239
240 # for val in re.split(r'(\s+)', query):
241 for val in re.split(r'(\s+)', query):
242 if not val.strip():
243 continue
244 if val.startswith('!') and external_bang.get_node(external_bang.EXTERNAL_BANGS, val[1:]):
245 val = f"'{val}'"
246 query_parts.append(val)
247 return ' '.join(query_parts)
248
249
250def request(query, params):
251
252 query = quote_ddg_bangs(query)
253
254 if len(query) >= 500:
255 # DDG does not accept queries with more than 499 chars
256 params["url"] = None
257 return
258
259 # Advanced search syntax ends in CAPTCHA
260 # https://duckduckgo.com/duckduckgo-help-pages/results/syntax/
261 query = " ".join(
262 [
263 x.removeprefix("site:").removeprefix("intitle:").removeprefix("inurl:").removeprefix("filetype:")
264 for x in query.split()
265 ]
266 )
267 eng_region: str = traits.get_region(params['searxng_locale'], traits.all_locale) # type: ignore
268 if eng_region == "wt-wt":
269 # https://html.duckduckgo.com/html sets an empty value for "all".
270 eng_region = ""
271
272 params['data']['kl'] = eng_region
273 params['cookies']['kl'] = eng_region
274
275 # eng_lang = get_ddg_lang(traits, params['searxng_locale'])
276
277 params['url'] = url
278 params['method'] = 'POST'
279 params['data']['q'] = query
280
281 # The API is not documented, so we do some reverse engineering and emulate
282 # what https://html.duckduckgo.com/html does when you press "next Page" link
283 # again and again ..
284
285 params['headers']['Content-Type'] = 'application/x-www-form-urlencoded'
286
287 params['headers']['Sec-Fetch-Dest'] = "document"
288 params['headers']['Sec-Fetch-Mode'] = "navigate" # at least this one is used by ddg's bot detection
289 params['headers']['Sec-Fetch-Site'] = "same-origin"
290 params['headers']['Sec-Fetch-User'] = "?1"
291
292 # Form of the initial search page does have empty values in the form
293 if params['pageno'] == 1:
294
295 params['data']['b'] = ""
296
297 params['data']['df'] = ''
298 if params['time_range'] in time_range_dict:
299
300 params['data']['df'] = time_range_dict[params['time_range']]
301 params['cookies']['df'] = time_range_dict[params['time_range']]
302
303 if params['pageno'] == 2:
304
305 # second page does have an offset of 20
306 offset = (params['pageno'] - 1) * 20
307 params['data']['s'] = offset
308 params['data']['dc'] = offset + 1
309
310 elif params['pageno'] > 2:
311
312 # third and following pages do have an offset of 20 + n*50
313 offset = 20 + (params['pageno'] - 2) * 50
314 params['data']['s'] = offset
315 params['data']['dc'] = offset + 1
316
317 if params['pageno'] > 1:
318
319 # initial page does not have these additional data in the input form
320 params['data']['o'] = form_data.get('o', 'json')
321 params['data']['api'] = form_data.get('api', 'd.js')
322 params['data']['nextParams'] = form_data.get('nextParams', '')
323 params['data']['v'] = form_data.get('v', 'l')
324 params['headers']['Referer'] = url
325
326 vqd = get_vqd(query, eng_region, force_request=False)
327
328 # Certain conditions must be met in order to call up one of the
329 # following pages ...
330
331 if vqd:
332 params['data']['vqd'] = vqd # follow up pages / requests needs a vqd argument
333 else:
334 # Don't try to call follow up pages without a vqd value. DDG
335 # recognizes this as a request from a bot. This lowers the
336 # reputation of the SearXNG IP and DDG starts to activate CAPTCHAs.
337 params["url"] = None
338 return
339
340 if params['searxng_locale'].startswith("zh"):
341 # Some locales (at least China) do not have a "next page" button and ddg
342 # will return a HTTP/2 403 Forbidden for a request of such a page.
343 params["url"] = None
344 return
345
346 logger.debug("param data: %s", params['data'])
347 logger.debug("param cookies: %s", params['cookies'])
348
349
350def is_ddg_captcha(dom):
351 """In case of CAPTCHA ddg response its own *not a Robot* dialog and is not
352 redirected to a CAPTCHA page."""
353
354 return bool(eval_xpath(dom, "//form[@id='challenge-form']"))
355
356
357def response(resp):
358
359 if resp.status_code == 303:
360 return []
361
362 results = []
363 doc = lxml.html.fromstring(resp.text)
364
365 if is_ddg_captcha(doc):
366 # set suspend time to zero is OK --> ddg does not block the IP
367 raise SearxEngineCaptchaException(suspended_time=0, message=f"CAPTCHA ({resp.search_params['data'].get('kl')})")
368
369 form = eval_xpath(doc, '//input[@name="vqd"]/..')
370 if len(form):
371 # some locales (at least China) does not have a "next page" button
372 form = form[0]
373 form_vqd = eval_xpath(form, '//input[@name="vqd"]/@value')[0]
374
375 cache_vqd(resp.search_params['data']['q'], resp.search_params['data']['kl'], form_vqd)
376
377 # just select "web-result" and ignore results of class "result--ad result--ad--small"
378 for div_result in eval_xpath(doc, '//div[@id="links"]/div[contains(@class, "web-result")]'):
379
380 item = {}
381 title = eval_xpath(div_result, './/h2/a')
382 if not title:
383 # this is the "No results." item in the result list
384 continue
385 item["title"] = extract_text(title)
386 item["url"] = eval_xpath(div_result, './/h2/a/@href')[0]
387 item["content"] = extract_text(eval_xpath(div_result, './/a[contains(@class, "result__snippet")]')[0])
388
389 results.append(item)
390
391 zero_click_info_xpath = '//div[@id="zero_click_abstract"]'
392 zero_click = extract_text(eval_xpath(doc, zero_click_info_xpath)).strip() # type: ignore
393
394 if zero_click and (
395 "Your IP address is" not in zero_click
396 and "Your user agent:" not in zero_click
397 and "URL Decoded:" not in zero_click
398 ):
399 current_query = resp.search_params["data"].get("q")
400
401 results.append(
402 {
403 'answer': zero_click,
404 'url': "https://duckduckgo.com/?" + urlencode({"q": current_query}),
405 }
406 )
407
408 return results
409
410
411def fetch_traits(engine_traits: EngineTraits):
412 """Fetch languages & regions from DuckDuckGo.
413
414 SearXNG's ``all`` locale maps DuckDuckGo's "Alle regions" (``wt-wt``).
415 DuckDuckGo's language "Browsers preferred language" (``wt_WT``) makes no
416 sense in a SearXNG request since SearXNG's ``all`` will not add a
417 ``Accept-Language`` HTTP header. The value in ``engine_traits.all_locale``
418 is ``wt-wt`` (the region).
419
420 Beside regions DuckDuckGo also defines its languages by region codes. By
421 example these are the english languages in DuckDuckGo:
422
423 - en_US
424 - en_AU
425 - en_CA
426 - en_GB
427
428 The function :py:obj:`get_ddg_lang` evaluates DuckDuckGo's language from
429 SearXNG's locale.
430
431 """
432 # pylint: disable=too-many-branches, too-many-statements, disable=import-outside-toplevel
433 from searx.utils import js_variable_to_python
434
435 # fetch regions
436
437 engine_traits.all_locale = 'wt-wt'
438
439 # updated from u661.js to u.7669f071a13a7daa57cb / should be updated automatically?
440 resp = get('https://duckduckgo.com/dist/util/u.7669f071a13a7daa57cb.js')
441
442 if not resp.ok: # type: ignore
443 print("ERROR: response from DuckDuckGo is not OK.")
444
445 js_code = extr(resp.text, 'regions:', ',snippetLengths') # type: ignore
446
447 regions = json.loads(js_code)
448 for eng_tag, name in regions.items():
449
450 if eng_tag == 'wt-wt':
451 engine_traits.all_locale = 'wt-wt'
452 continue
453
454 region = ddg_reg_map.get(eng_tag)
455 if region == 'skip':
456 continue
457
458 if not region:
459 eng_territory, eng_lang = eng_tag.split('-')
460 region = eng_lang + '_' + eng_territory.upper()
461
462 try:
463 sxng_tag = locales.region_tag(babel.Locale.parse(region))
464 except babel.UnknownLocaleError:
465 print("ERROR: %s (%s) -> %s is unknown by babel" % (name, eng_tag, region))
466 continue
467
468 conflict = engine_traits.regions.get(sxng_tag)
469 if conflict:
470 if conflict != eng_tag:
471 print("CONFLICT: babel %s --> %s, %s" % (sxng_tag, conflict, eng_tag))
472 continue
473 engine_traits.regions[sxng_tag] = eng_tag
474
475 # fetch languages
476
477 engine_traits.custom['lang_region'] = {}
478
479 js_code = extr(resp.text, 'languages:', ',regions') # type: ignore
480
481 languages = js_variable_to_python(js_code)
482 for eng_lang, name in languages.items():
483
484 if eng_lang == 'wt_WT':
485 continue
486
487 babel_tag = ddg_lang_map.get(eng_lang, eng_lang)
488 if babel_tag == 'skip':
489 continue
490
491 try:
492
493 if babel_tag == 'lang_region':
494 sxng_tag = locales.region_tag(babel.Locale.parse(eng_lang))
495 engine_traits.custom['lang_region'][sxng_tag] = eng_lang
496 continue
497
498 sxng_tag = locales.language_tag(babel.Locale.parse(babel_tag))
499
500 except babel.UnknownLocaleError:
501 print("ERROR: language %s (%s) is unknown by babel" % (name, eng_lang))
502 continue
503
504 conflict = engine_traits.languages.get(sxng_tag)
505 if conflict:
506 if conflict != eng_lang:
507 print("CONFLICT: babel %s --> %s, %s" % (sxng_tag, conflict, eng_lang))
508 continue
509 engine_traits.languages[sxng_tag] = eng_lang
get_vqd(str query, str region, bool force_request=False)
Definition duckduckgo.py:83
get_ddg_lang(EngineTraits eng_traits, sxng_locale, default='en_US')
_cache_key(str query, str region)
Definition duckduckgo.py:65
cache_vqd(str query, str region, str value)
Definition duckduckgo.py:69