duckduckgo.py 15 KB

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