duckduckgo.py 16 KB

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