duckduckgo.py 14 KB

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