.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 datetime import datetime
8from typing import TYPE_CHECKING
9from urllib.parse import urlencode
10from searx.utils import get_embeded_stream_url
11
12from searx.engines.duckduckgo import fetch_traits # pylint: disable=unused-import
13from searx.engines.duckduckgo import (
14 get_ddg_lang,
15 get_vqd,
16)
17from searx.enginelib.traits import EngineTraits
18
19if TYPE_CHECKING:
20 import logging
21
22 logger: logging.Logger
23
24traits: EngineTraits
25
26# about
27about = {
28 "website": 'https://duckduckgo.com/',
29 "wikidata_id": 'Q12805',
30 "use_official_api": False,
31 "require_api_key": False,
32 "results": 'JSON (site requires js to get images)',
33}
34
35# engine dependent config
36categories = ['images', 'web']
37ddg_category = 'images'
38"""The category must be any of ``images``, ``videos`` and ``news``
39"""
40paging = True
41safesearch = True
42send_accept_language_header = True
43
44safesearch_cookies = {0: '-2', 1: None, 2: '1'}
45safesearch_args = {0: '1', 1: None, 2: '1'}
46
47search_path_map = {'images': 'i', 'videos': 'v', 'news': 'news'}
48
49
50def request(query, params):
51
52 # request needs a vqd argument
53 vqd = get_vqd(query)
54 if not vqd:
55 # some search terms do not have results and therefore no vqd value
56 params['url'] = None
57 return params
58
59 eng_region = traits.get_region(params['searxng_locale'], traits.all_locale)
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 return params
90
91
92def _image_result(result):
93 return {
94 'template': 'images.html',
95 'url': result['url'],
96 'title': result['title'],
97 'content': '',
98 'thumbnail_src': result['thumbnail'],
99 'img_src': result['image'],
100 'resolution': '%s x %s' % (result['width'], result['height']),
101 'source': result['source'],
102 }
103
104
105def _video_result(result):
106 return {
107 'template': 'videos.html',
108 'url': result['content'],
109 'title': result['title'],
110 'content': result['description'],
111 'thumbnail': result['images'].get('small') or result['images'].get('medium'),
112 'iframe_src': get_embeded_stream_url(result['content']),
113 'source': result['provider'],
114 'length': result['duration'],
115 'metadata': result.get('uploader'),
116 }
117
118
119def _news_result(result):
120 return {
121 'url': result['url'],
122 'title': result['title'],
123 'content': result['excerpt'],
124 'source': result['source'],
125 'publishedDate': datetime.utcfromtimestamp(result['date']),
126 }
127
128
129def response(resp):
130 results = []
131 res_json = resp.json()
132
133 for result in res_json['results']:
134 if ddg_category == 'images':
135 results.append(_image_result(result))
136 elif ddg_category == 'videos':
137 results.append(_video_result(result))
138 elif ddg_category == 'news':
139 results.append(_news_result(result))
140 else:
141 raise ValueError(f"Invalid duckduckgo category: {ddg_category}")
142
143 return results