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