.oO SearXNG Developer Documentation Oo.
Loading...
Searching...
No Matches
duckduckgo_extra.py
Go to the documentation of this file.
1# SPDX-License-Identifier: AGPL-3.0-or-later
2"""
3DuckDuckGo Extra (images, videos, news)
4~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
5"""
6
7from __future__ import annotations
8
9from datetime import datetime
10from typing import TYPE_CHECKING
11from urllib.parse import urlencode
12from searx.utils import get_embeded_stream_url
13
14from searx.engines.duckduckgo import fetch_traits # pylint: disable=unused-import
15from searx.engines.duckduckgo import get_ddg_lang, get_vqd
16from searx.enginelib.traits import EngineTraits
17
18if TYPE_CHECKING:
19 import logging
20
21 logger: logging.Logger
22
23traits: EngineTraits
24
25# about
26about = {
27 "website": 'https://duckduckgo.com/',
28 "wikidata_id": 'Q12805',
29 "use_official_api": False,
30 "require_api_key": False,
31 "results": 'JSON (site requires js to get images)',
32}
33
34# engine dependent config
35categories = ['images', 'web']
36ddg_category = 'images'
37"""The category must be any of ``images``, ``videos`` and ``news``
38"""
39paging = True
40safesearch = True
41send_accept_language_header = True
42
43safesearch_cookies = {0: '-2', 1: None, 2: '1'}
44safesearch_args = {0: '1', 1: None, 2: '1'}
45
46search_path_map = {'images': 'i', 'videos': 'v', 'news': 'news'}
47
48
49def request(query, params):
50 eng_region: str = traits.get_region(params['searxng_locale'], traits.all_locale) # type: ignore
51
52 # request needs a vqd argument
53 vqd = get_vqd(query, eng_region, force_request=True)
54
55 if not vqd:
56 # some search terms do not have results and therefore no vqd value
57 params['url'] = None
58 return params
59
60 eng_lang = get_ddg_lang(traits, params['searxng_locale'])
61
62 args = {
63 'q': query,
64 'o': 'json',
65 # 'u': 'bing',
66 'l': eng_region,
67 'f': ',,,,,',
68 'vqd': vqd,
69 }
70
71 if params['pageno'] > 1:
72 args['s'] = (params['pageno'] - 1) * 100
73
74 params['cookies']['ad'] = eng_lang # zh_CN
75 params['cookies']['ah'] = eng_region # "us-en,de-de"
76 params['cookies']['l'] = eng_region # "hk-tzh"
77
78 safe_search = safesearch_cookies.get(params['safesearch'])
79 if safe_search is not None:
80 params['cookies']['p'] = safe_search # "-2", "1"
81 safe_search = safesearch_args.get(params['safesearch'])
82 if safe_search is not None:
83 args['p'] = safe_search # "-1", "1"
84
85 logger.debug("cookies: %s", params['cookies'])
86
87 params['url'] = f'https://duckduckgo.com/{search_path_map[ddg_category]}.js?{urlencode(args)}'
88
89 # sending these two headers prevents rate limiting for the query
90 params['headers'] = {
91 'Referer': 'https://duckduckgo.com/',
92 'X-Requested-With': 'XMLHttpRequest',
93 }
94
95 return params
96
97
98def _image_result(result):
99 return {
100 'template': 'images.html',
101 'url': result['url'],
102 'title': result['title'],
103 'content': '',
104 'thumbnail_src': result['thumbnail'],
105 'img_src': result['image'],
106 'resolution': '%s x %s' % (result['width'], result['height']),
107 'source': result['source'],
108 }
109
110
111def _video_result(result):
112 return {
113 'template': 'videos.html',
114 'url': result['content'],
115 'title': result['title'],
116 'content': result['description'],
117 'thumbnail': result['images'].get('small') or result['images'].get('medium'),
118 'iframe_src': get_embeded_stream_url(result['content']),
119 'source': result['provider'],
120 'length': result['duration'],
121 'metadata': result.get('uploader'),
122 }
123
124
125def _news_result(result):
126 return {
127 'url': result['url'],
128 'title': result['title'],
129 'content': result['excerpt'],
130 'source': result['source'],
131 'publishedDate': datetime.utcfromtimestamp(result['date']),
132 }
133
134
135def response(resp):
136 results = []
137 res_json = resp.json()
138
139 for result in res_json['results']:
140 if ddg_category == 'images':
141 results.append(_image_result(result))
142 elif ddg_category == 'videos':
143 results.append(_video_result(result))
144 elif ddg_category == 'news':
145 results.append(_news_result(result))
146 else:
147 raise ValueError(f"Invalid duckduckgo category: {ddg_category}")
148
149 return results