duckduckgo.py 13 KB

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