duckduckgo.py 16 KB

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