7from typing
import TYPE_CHECKING
9from urllib.parse
import urlencode, quote_plus
24from searx
import redisdb
32 logger: logging.Logger
37 "website":
'https://lite.duckduckgo.com/lite/',
38 "wikidata_id":
'Q12805',
39 "use_official_api":
False,
40 "require_api_key":
False,
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
51categories = [
'general',
'web']
53time_range_support =
True
56url =
"https://html.duckduckgo.com/html"
58time_range_dict = {
'day':
'd',
'week':
'w',
'month':
'm',
'year':
'y'}
59form_data = {
'v':
'l',
'api':
'd.js',
'o':
'json'}
64 return 'SearXNG_ddg_web_vqd' + redislib.secret_hash(f
"{data['q']}//{data['kl']}")
68 """Caches a ``vqd`` value from a query."""
71 logger.debug(
"cache vqd value: %s", value)
75 logger.debug(
"MEM cache vqd value: %s", value)
76 if len(__CACHE) > 100:
82 """Returns the ``vqd`` that fits to the *query* (``data`` from HTTP POST).
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.
88 If SearXNG cannot determine a ``vqd`` value, then no request should go out
91 A request with a wrong ``vqd`` value leads to DDG temporarily putting
92 SearXNG's IP on a block list.
94 Requests from IPs in this block list run into timeouts.
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
100 TL;DR; the ``vqd`` value is needed to pass DDG's bot protection and is used
101 by all request to DDG:
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=...``
116 if value
or value == b
'':
117 value = value.decode(
'utf-8')
118 logger.debug(
"re-use CACHED vqd value: %s", value)
122 for k, value
in __CACHE:
124 logger.debug(
"MEM re-use CACHED vqd value: %s", value)
129def get_ddg_lang(eng_traits: EngineTraits, sxng_locale, default=
'en_US'):
130 """Get DuckDuckGo's language identifier from SearXNG's locale.
132 DuckDuckGo defines its languages by region codes (see
133 :py:obj:`fetch_traits`).
135 To get region and language of a DDG service use:
139 eng_region = traits.get_region(params['searxng_locale'], traits.all_locale)
140 eng_lang = get_ddg_lang(traits, params['searxng_locale'])
142 It might confuse, but the ``l`` value of the cookie is what SearXNG calls
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
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
160 params['cookies']['kl'] = eng_region # 'ar-es'
163 return eng_traits.custom[
'lang_region'].get(
164 sxng_locale, eng_traits.get_language(sxng_locale, default)
185 "ar_DZ":
'lang_region',
186 "ar_JO":
'lang_region',
187 "ar_SA":
'lang_region',
189 'bn_IN':
'lang_region',
191 'de_CH':
'lang_region',
193 'en_AU':
'lang_region',
194 'en_CA':
'lang_region',
195 'en_GB':
'lang_region',
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',
209 'fr_CA':
'lang_region',
210 'fr_CH':
'lang_region',
211 'fr_BE':
'lang_region',
213 'nl_BE':
'lang_region',
215 'pt_BR':
'lang_region',
219 'tokipona_XX':
'skip',
223def quote_ddg_bangs(query):
228 for val
in re.split(
r'(\s+)', query):
231 if val.startswith(
'!')
and external_bang.get_node(external_bang.EXTERNAL_BANGS, val[1:]):
233 query_parts.append(val)
234 return ' '.join(query_parts)
237def request(query, params):
239 query = quote_ddg_bangs(query)
241 if len(query) >= 500:
250 x.removeprefix(
"site:").removeprefix(
"intitle:").removeprefix(
"inurl:").removeprefix(
"filetype:")
251 for x
in query.split()
254 eng_region = traits.get_region(params[
'searxng_locale'], traits.all_locale)
255 if eng_region ==
"wt-wt":
259 params[
'data'][
'kl'] = eng_region
260 params[
'cookies'][
'kl'] = eng_region
265 params[
'method'] =
'POST'
266 params[
'data'][
'q'] = quote_plus(query)
272 params[
'headers'][
'Content-Type'] =
'application/x-www-form-urlencoded'
274 params[
'headers'][
'Sec-Fetch-Dest'] =
"document"
275 params[
'headers'][
'Sec-Fetch-Mode'] =
"navigate"
276 params[
'headers'][
'Sec-Fetch-Site'] =
"same-origin"
277 params[
'headers'][
'Sec-Fetch-User'] =
"?1"
280 if params[
'pageno'] == 1:
282 params[
'data'][
'b'] =
""
284 params[
'data'][
'df'] =
''
285 if params[
'time_range']
in time_range_dict:
287 params[
'data'][
'df'] = time_range_dict[params[
'time_range']]
288 params[
'cookies'][
'df'] = time_range_dict[params[
'time_range']]
290 if params[
'pageno'] == 2:
293 offset = (params[
'pageno'] - 1) * 20
294 params[
'data'][
's'] = offset
295 params[
'data'][
'dc'] = offset + 1
297 elif params[
'pageno'] > 2:
300 offset = 20 + (params[
'pageno'] - 2) * 50
301 params[
'data'][
's'] = offset
302 params[
'data'][
'dc'] = offset + 1
304 if params[
'pageno'] > 1:
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
316 vqd = get_vqd(params[
'data'])
322 params[
'data'][
'vqd'] = vqd
330 if params[
'searxng_locale'].startswith(
"zh"):
336 logger.debug(
"param data: %s", params[
'data'])
337 logger.debug(
"param cookies: %s", params[
'cookies'])
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."""
344 return bool(eval_xpath(dom,
"//form[@id='challenge-form']"))
349 if resp.status_code == 303:
353 doc = lxml.html.fromstring(resp.text)
355 if is_ddg_captcha(doc):
359 form = eval_xpath(doc,
'//input[@name="vqd"]/..')
363 form_vqd = eval_xpath(form,
'//input[@name="vqd"]/@value')[0]
365 cache_vqd(resp.search_params[
"data"], form_vqd)
368 for div_result
in eval_xpath(doc,
'//div[@id="links"]/div[contains(@class, "web-result")]'):
371 title = eval_xpath(div_result,
'.//h2/a')
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])
381 zero_click_info_xpath =
'//div[@id="zero_click_abstract"]'
382 zero_click = extract_text(eval_xpath(doc, zero_click_info_xpath)).strip()
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")
389 'answer': zero_click,
390 'url':
"https://duckduckgo.com/?" + urlencode({
"q": current_query}),
397def fetch_traits(engine_traits: EngineTraits):
398 """Fetch languages & regions from DuckDuckGo.
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).
406 Beside regions DuckDuckGo also defines its languages by region codes. By
407 example these are the english languages in DuckDuckGo:
414 The function :py:obj:`get_ddg_lang` evaluates DuckDuckGo's language from
423 engine_traits.all_locale =
'wt-wt'
426 resp = get(
'https://duckduckgo.com/dist/util/u.7669f071a13a7daa57cb.js')
429 print(
"ERROR: response from DuckDuckGo is not OK.")
431 js_code = extr(resp.text,
'regions:',
',snippetLengths')
433 regions = json.loads(js_code)
434 for eng_tag, name
in regions.items():
436 if eng_tag ==
'wt-wt':
437 engine_traits.all_locale =
'wt-wt'
440 region = ddg_reg_map.get(eng_tag)
445 eng_territory, eng_lang = eng_tag.split(
'-')
446 region = eng_lang +
'_' + eng_territory.upper()
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))
454 conflict = engine_traits.regions.get(sxng_tag)
456 if conflict != eng_tag:
457 print(
"CONFLICT: babel %s --> %s, %s" % (sxng_tag, conflict, eng_tag))
459 engine_traits.regions[sxng_tag] = eng_tag
463 engine_traits.custom[
'lang_region'] = {}
465 js_code = extr(resp.text,
'languages:',
',regions')
467 languages = js_variable_to_python(js_code)
468 for eng_lang, name
in languages.items():
470 if eng_lang ==
'wt_WT':
473 babel_tag = ddg_lang_map.get(eng_lang, eng_lang)
474 if babel_tag ==
'skip':
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
484 sxng_tag = locales.language_tag(babel.Locale.parse(babel_tag))
486 except babel.UnknownLocaleError:
487 print(
"ERROR: language %s (%s) is unknown by babel" % (name, eng_lang))
490 conflict = engine_traits.languages.get(sxng_tag)
492 if conflict != eng_lang:
493 print(
"CONFLICT: babel %s --> %s, %s" % (sxng_tag, conflict, eng_lang))
495 engine_traits.languages[sxng_tag] = eng_lang
cache_vqd(dict data, value)
get_ddg_lang(EngineTraits eng_traits, sxng_locale, default='en_US')