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