duckduckgo.py 13 KB

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