duckduckgo.py 13 KB

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