7from __future__
import annotations
9from typing
import TYPE_CHECKING
11from urllib.parse
import urlencode, quote_plus
27from searx
import redisdb
34 logger: logging.Logger
39 "website":
'https://lite.duckduckgo.com/lite/',
40 "wikidata_id":
'Q12805',
41 "use_official_api":
False,
42 "require_api_key":
False,
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
53categories = [
'general',
'web']
55time_range_support =
True
58url =
"https://html.duckduckgo.com/html"
60time_range_dict = {
'day':
'd',
'week':
'w',
'month':
'm',
'year':
'y'}
61form_data = {
'v':
'l',
'api':
'd.js',
'o':
'json'}
66 return 'SearXNG_ddg_web_vqd' + redislib.secret_hash(f
"{query}//{region}")
70 """Caches a ``vqd`` value from a query."""
73 logger.debug(
"VALKEY cache vqd value: %s (%s)", value, region)
74 c.set(
_cache_key(query, region), value, ex=600)
77 logger.debug(
"MEM cache vqd value: %s (%s)", value, region)
78 if len(__CACHE) > 100:
80 __CACHE.append((
_cache_key(query, region), value))
83def get_vqd(query: str, region: str, force_request: bool =
False):
84 """Returns the ``vqd`` that fits to the *query*.
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
90 TL;DR; the ``vqd`` value is needed to pass DDG's bot protection and is used
91 by all request to DDG:
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=...``
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.
103 If SearXNG cannot determine a ``vqd`` value, then no request should go out
108 A request with a wrong ``vqd`` value leads to DDG temporarily putting
109 SearXNG's IP on a block list.
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).
120 if value
or value == b
'':
121 value = value.decode(
'utf-8')
122 logger.debug(
"re-use CACHED vqd value: %s", value)
125 for k, value
in __CACHE:
127 logger.debug(
"MEM re-use CACHED vqd value: %s", value)
131 resp = get(f
'https://duckduckgo.com/?q={quote_plus(query)}')
132 if resp.status_code == 200:
133 value = extr(resp.text,
'vqd="',
'"')
135 logger.debug(
"vqd value from DDG request: %s", value)
142def get_ddg_lang(eng_traits: EngineTraits, sxng_locale, default=
'en_US'):
143 """Get DuckDuckGo's language identifier from SearXNG's locale.
145 DuckDuckGo defines its languages by region codes (see
146 :py:obj:`fetch_traits`).
148 To get region and language of a DDG service use:
152 eng_region = traits.get_region(params['searxng_locale'], traits.all_locale)
153 eng_lang = get_ddg_lang(traits, params['searxng_locale'])
155 It might confuse, but the ``l`` value of the cookie is what SearXNG calls
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
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
173 params['cookies']['kl'] = eng_region # 'ar-es'
176 return eng_traits.custom[
'lang_region'].get(
177 sxng_locale, eng_traits.get_language(sxng_locale, default)
198 "ar_DZ":
'lang_region',
199 "ar_JO":
'lang_region',
200 "ar_SA":
'lang_region',
202 'bn_IN':
'lang_region',
204 'de_CH':
'lang_region',
206 'en_AU':
'lang_region',
207 'en_CA':
'lang_region',
208 'en_GB':
'lang_region',
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',
222 'fr_CA':
'lang_region',
223 'fr_CH':
'lang_region',
224 'fr_BE':
'lang_region',
226 'nl_BE':
'lang_region',
228 'pt_BR':
'lang_region',
232 'tokipona_XX':
'skip',
236def quote_ddg_bangs(query):
241 for val
in re.split(
r'(\s+)', query):
244 if val.startswith(
'!')
and external_bang.get_node(external_bang.EXTERNAL_BANGS, val[1:]):
246 query_parts.append(val)
247 return ' '.join(query_parts)
250def request(query, params):
252 query = quote_ddg_bangs(query)
254 if len(query) >= 500:
263 x.removeprefix(
"site:").removeprefix(
"intitle:").removeprefix(
"inurl:").removeprefix(
"filetype:")
264 for x
in query.split()
267 eng_region: str = traits.get_region(params[
'searxng_locale'], traits.all_locale)
268 if eng_region ==
"wt-wt":
272 params[
'data'][
'kl'] = eng_region
273 params[
'cookies'][
'kl'] = eng_region
278 params[
'method'] =
'POST'
279 params[
'data'][
'q'] = query
285 params[
'headers'][
'Content-Type'] =
'application/x-www-form-urlencoded'
287 params[
'headers'][
'Sec-Fetch-Dest'] =
"document"
288 params[
'headers'][
'Sec-Fetch-Mode'] =
"navigate"
289 params[
'headers'][
'Sec-Fetch-Site'] =
"same-origin"
290 params[
'headers'][
'Sec-Fetch-User'] =
"?1"
293 if params[
'pageno'] == 1:
295 params[
'data'][
'b'] =
""
297 params[
'data'][
'df'] =
''
298 if params[
'time_range']
in time_range_dict:
300 params[
'data'][
'df'] = time_range_dict[params[
'time_range']]
301 params[
'cookies'][
'df'] = time_range_dict[params[
'time_range']]
303 if params[
'pageno'] == 2:
306 offset = (params[
'pageno'] - 1) * 20
307 params[
'data'][
's'] = offset
308 params[
'data'][
'dc'] = offset + 1
310 elif params[
'pageno'] > 2:
313 offset = 20 + (params[
'pageno'] - 2) * 50
314 params[
'data'][
's'] = offset
315 params[
'data'][
'dc'] = offset + 1
317 if params[
'pageno'] > 1:
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
326 vqd = get_vqd(query, eng_region, force_request=
False)
332 params[
'data'][
'vqd'] = vqd
340 if params[
'searxng_locale'].startswith(
"zh"):
346 logger.debug(
"param data: %s", params[
'data'])
347 logger.debug(
"param cookies: %s", params[
'cookies'])
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."""
354 return bool(eval_xpath(dom,
"//form[@id='challenge-form']"))
359 if resp.status_code == 303:
363 doc = lxml.html.fromstring(resp.text)
365 if is_ddg_captcha(doc):
369 form = eval_xpath(doc,
'//input[@name="vqd"]/..')
373 form_vqd = eval_xpath(form,
'//input[@name="vqd"]/@value')[0]
375 cache_vqd(resp.search_params[
'data'][
'q'], resp.search_params[
'data'][
'kl'], form_vqd)
378 for div_result
in eval_xpath(doc,
'//div[@id="links"]/div[contains(@class, "web-result")]'):
381 title = eval_xpath(div_result,
'.//h2/a')
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])
391 zero_click_info_xpath =
'//div[@id="zero_click_abstract"]'
392 zero_click = extract_text(eval_xpath(doc, zero_click_info_xpath)).strip()
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
399 current_query = resp.search_params[
"data"].get(
"q")
403 'answer': zero_click,
404 'url':
"https://duckduckgo.com/?" + urlencode({
"q": current_query}),
411def fetch_traits(engine_traits: EngineTraits):
412 """Fetch languages & regions from DuckDuckGo.
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).
420 Beside regions DuckDuckGo also defines its languages by region codes. By
421 example these are the english languages in DuckDuckGo:
428 The function :py:obj:`get_ddg_lang` evaluates DuckDuckGo's language from
437 engine_traits.all_locale =
'wt-wt'
440 resp = get(
'https://duckduckgo.com/dist/util/u.7669f071a13a7daa57cb.js')
443 print(
"ERROR: response from DuckDuckGo is not OK.")
445 js_code = extr(resp.text,
'regions:',
',snippetLengths')
447 regions = json.loads(js_code)
448 for eng_tag, name
in regions.items():
450 if eng_tag ==
'wt-wt':
451 engine_traits.all_locale =
'wt-wt'
454 region = ddg_reg_map.get(eng_tag)
459 eng_territory, eng_lang = eng_tag.split(
'-')
460 region = eng_lang +
'_' + eng_territory.upper()
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))
468 conflict = engine_traits.regions.get(sxng_tag)
470 if conflict != eng_tag:
471 print(
"CONFLICT: babel %s --> %s, %s" % (sxng_tag, conflict, eng_tag))
473 engine_traits.regions[sxng_tag] = eng_tag
477 engine_traits.custom[
'lang_region'] = {}
479 js_code = extr(resp.text,
'languages:',
',regions')
481 languages = js_variable_to_python(js_code)
482 for eng_lang, name
in languages.items():
484 if eng_lang ==
'wt_WT':
487 babel_tag = ddg_lang_map.get(eng_lang, eng_lang)
488 if babel_tag ==
'skip':
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
498 sxng_tag = locales.language_tag(babel.Locale.parse(babel_tag))
500 except babel.UnknownLocaleError:
501 print(
"ERROR: language %s (%s) is unknown by babel" % (name, eng_lang))
504 conflict = engine_traits.languages.get(sxng_tag)
506 if conflict != eng_lang:
507 print(
"CONFLICT: babel %s --> %s, %s" % (sxng_tag, conflict, eng_lang))
509 engine_traits.languages[sxng_tag] = eng_lang
get_vqd(str query, str region, bool force_request=False)
get_ddg_lang(EngineTraits eng_traits, sxng_locale, default='en_US')
_cache_key(str query, str region)
cache_vqd(str query, str region, str value)