duckduckgo.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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. from urllib.parse import urlencode
  9. import json
  10. import babel
  11. import lxml.html
  12. from searx import (
  13. network,
  14. locales,
  15. redislib,
  16. )
  17. from searx import redisdb
  18. from searx.utils import (
  19. eval_xpath,
  20. eval_xpath_getindex,
  21. extract_text,
  22. )
  23. from searx.enginelib.traits import EngineTraits
  24. from searx.exceptions import SearxEngineAPIException
  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. The vqd value depends on the query string and is needed for the follow up
  53. pages or the images loaded by a XMLHttpRequest:
  54. - DuckDuckGo Web: `https://links.duckduckgo.com/d.js?q=...&vqd=...`
  55. - DuckDuckGo Images: `https://duckduckgo.com/i.js??q=...&vqd=...`
  56. """
  57. c = redisdb.client()
  58. if c:
  59. logger.debug("cache vqd value: %s", value)
  60. key = 'SearXNG_ddg_vqd' + redislib.secret_hash(query)
  61. c.set(key, value, ex=600)
  62. def get_vqd(query, headers):
  63. """Returns the ``vqd`` that fits to the *query*. If there is no ``vqd`` cached
  64. (:py:obj:`cache_vqd`) the query is sent to DDG to get a vqd value from the
  65. response.
  66. """
  67. value = None
  68. c = redisdb.client()
  69. if c:
  70. key = 'SearXNG_ddg_vqd' + redislib.secret_hash(query)
  71. value = c.get(key)
  72. if value:
  73. value = value.decode('utf-8')
  74. logger.debug("re-use cached vqd value: %s", value)
  75. return value
  76. query_url = 'https://duckduckgo.com/?{query}&iar=images'.format(query=urlencode({'q': query}))
  77. res = network.get(query_url, headers=headers)
  78. content = res.text
  79. if content.find('vqd=\'') == -1:
  80. raise SearxEngineAPIException('Request failed')
  81. value = content[content.find('vqd=\'') + 5 :]
  82. value = value[: value.find('\'')]
  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 lanaguages 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(sxng_locale, eng_traits.get_language(sxng_locale, default))
  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. eng_region = traits.get_region(params['searxng_locale'], traits.all_locale)
  163. # eng_lang = get_ddg_lang(traits, params['searxng_locale'])
  164. params['url'] = url
  165. params['method'] = 'POST'
  166. params['data']['q'] = query
  167. # The API is not documented, so we do some reverse engineering and emulate
  168. # what https://lite.duckduckgo.com/lite/ does when you press "next Page"
  169. # link again and again ..
  170. params['headers']['Content-Type'] = 'application/x-www-form-urlencoded'
  171. params['headers']['Referer'] = 'https://google.com/'
  172. # initial page does not have an offset
  173. if params['pageno'] == 2:
  174. # second page does have an offset of 30
  175. offset = (params['pageno'] - 1) * 30
  176. params['data']['s'] = offset
  177. params['data']['dc'] = offset + 1
  178. elif params['pageno'] > 2:
  179. # third and following pages do have an offset of 30 + n*50
  180. offset = 30 + (params['pageno'] - 2) * 50
  181. params['data']['s'] = offset
  182. params['data']['dc'] = offset + 1
  183. # request needs a vqd argument
  184. params['data']['vqd'] = get_vqd(query, params["headers"])
  185. # initial page does not have additional data in the input form
  186. if params['pageno'] > 1:
  187. params['data']['o'] = form_data.get('o', 'json')
  188. params['data']['api'] = form_data.get('api', 'd.js')
  189. params['data']['nextParams'] = form_data.get('nextParams', '')
  190. params['data']['v'] = form_data.get('v', 'l')
  191. params['data']['kl'] = eng_region
  192. params['cookies']['kl'] = eng_region
  193. params['data']['df'] = ''
  194. if params['time_range'] in time_range_dict:
  195. params['data']['df'] = time_range_dict[params['time_range']]
  196. params['cookies']['df'] = time_range_dict[params['time_range']]
  197. logger.debug("param data: %s", params['data'])
  198. logger.debug("param cookies: %s", params['cookies'])
  199. return params
  200. def response(resp):
  201. if resp.status_code == 303:
  202. return []
  203. results = []
  204. doc = lxml.html.fromstring(resp.text)
  205. result_table = eval_xpath(doc, '//html/body/form/div[@class="filters"]/table')
  206. if len(result_table) == 2:
  207. # some locales (at least China) does not have a "next page" button and
  208. # the layout of the HTML tables is different.
  209. result_table = result_table[1]
  210. elif not len(result_table) >= 3:
  211. # no more results
  212. return []
  213. else:
  214. result_table = result_table[2]
  215. # update form data from response
  216. form = eval_xpath(doc, '//html/body/form/div[@class="filters"]/table//input/..')
  217. if len(form):
  218. form = form[0]
  219. form_data['v'] = eval_xpath(form, '//input[@name="v"]/@value')[0]
  220. form_data['api'] = eval_xpath(form, '//input[@name="api"]/@value')[0]
  221. form_data['o'] = eval_xpath(form, '//input[@name="o"]/@value')[0]
  222. logger.debug('form_data: %s', form_data)
  223. value = eval_xpath(form, '//input[@name="vqd"]/@value')[0]
  224. query = resp.search_params['data']['q']
  225. cache_vqd(query, value)
  226. tr_rows = eval_xpath(result_table, './/tr')
  227. # In the last <tr> is the form of the 'previous/next page' links
  228. tr_rows = tr_rows[:-1]
  229. len_tr_rows = len(tr_rows)
  230. offset = 0
  231. while len_tr_rows >= offset + 4:
  232. # assemble table rows we need to scrap
  233. tr_title = tr_rows[offset]
  234. tr_content = tr_rows[offset + 1]
  235. offset += 4
  236. # ignore sponsored Adds <tr class="result-sponsored">
  237. if tr_content.get('class') == 'result-sponsored':
  238. continue
  239. a_tag = eval_xpath_getindex(tr_title, './/td//a[@class="result-link"]', 0, None)
  240. if a_tag is None:
  241. continue
  242. td_content = eval_xpath_getindex(tr_content, './/td[@class="result-snippet"]', 0, None)
  243. if td_content is None:
  244. continue
  245. results.append(
  246. {
  247. 'title': a_tag.text_content(),
  248. 'content': extract_text(td_content),
  249. 'url': a_tag.get('href'),
  250. }
  251. )
  252. return results
  253. def fetch_traits(engine_traits: EngineTraits):
  254. """Fetch languages & regions from DuckDuckGo.
  255. SearXNG's ``all`` locale maps DuckDuckGo's "Alle regions" (``wt-wt``).
  256. DuckDuckGo's language "Browsers prefered language" (``wt_WT``) makes no
  257. sense in a SearXNG request since SearXNG's ``all`` will not add a
  258. ``Accept-Language`` HTTP header. The value in ``engine_traits.all_locale``
  259. is ``wt-wt`` (the region).
  260. Beside regions DuckDuckGo also defines its lanaguages by region codes. By
  261. example these are the english languages in DuckDuckGo:
  262. - en_US
  263. - en_AU
  264. - en_CA
  265. - en_GB
  266. The function :py:obj:`get_ddg_lang` evaluates DuckDuckGo's language from
  267. SearXNG's locale.
  268. """
  269. # pylint: disable=too-many-branches, too-many-statements
  270. # fetch regions
  271. engine_traits.all_locale = 'wt-wt'
  272. # updated from u588 to u661 / should be updated automatically?
  273. resp = network.get('https://duckduckgo.com/util/u661.js')
  274. if not resp.ok:
  275. print("ERROR: response from DuckDuckGo is not OK.")
  276. pos = resp.text.find('regions:{') + 8
  277. js_code = resp.text[pos:]
  278. pos = js_code.find('}') + 1
  279. regions = json.loads(js_code[:pos])
  280. for eng_tag, name in regions.items():
  281. if eng_tag == 'wt-wt':
  282. engine_traits.all_locale = 'wt-wt'
  283. continue
  284. region = ddg_reg_map.get(eng_tag)
  285. if region == 'skip':
  286. continue
  287. if not region:
  288. eng_territory, eng_lang = eng_tag.split('-')
  289. region = eng_lang + '_' + eng_territory.upper()
  290. try:
  291. sxng_tag = locales.region_tag(babel.Locale.parse(region))
  292. except babel.UnknownLocaleError:
  293. print("ERROR: %s (%s) -> %s is unknown by babel" % (name, eng_tag, region))
  294. continue
  295. conflict = engine_traits.regions.get(sxng_tag)
  296. if conflict:
  297. if conflict != eng_tag:
  298. print("CONFLICT: babel %s --> %s, %s" % (sxng_tag, conflict, eng_tag))
  299. continue
  300. engine_traits.regions[sxng_tag] = eng_tag
  301. # fetch languages
  302. engine_traits.custom['lang_region'] = {}
  303. pos = resp.text.find('languages:{') + 10
  304. js_code = resp.text[pos:]
  305. pos = js_code.find('}') + 1
  306. js_code = '{"' + js_code[1:pos].replace(':', '":').replace(',', ',"')
  307. languages = json.loads(js_code)
  308. for eng_lang, name in languages.items():
  309. if eng_lang == 'wt_WT':
  310. continue
  311. babel_tag = ddg_lang_map.get(eng_lang, eng_lang)
  312. if babel_tag == 'skip':
  313. continue
  314. try:
  315. if babel_tag == 'lang_region':
  316. sxng_tag = locales.region_tag(babel.Locale.parse(eng_lang))
  317. engine_traits.custom['lang_region'][sxng_tag] = eng_lang
  318. continue
  319. sxng_tag = locales.language_tag(babel.Locale.parse(babel_tag))
  320. except babel.UnknownLocaleError:
  321. print("ERROR: language %s (%s) is unknown by babel" % (name, eng_lang))
  322. continue
  323. conflict = engine_traits.languages.get(sxng_tag)
  324. if conflict:
  325. if conflict != eng_lang:
  326. print("CONFLICT: babel %s --> %s, %s" % (sxng_tag, conflict, eng_lang))
  327. continue
  328. engine_traits.languages[sxng_tag] = eng_lang