duckduckgo.py 13 KB

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