qwant.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. """Qwant (Web, News, Images, Videos)
  4. This engine uses the Qwant API (https://api.qwant.com/v3). The API is
  5. undocumented but can be reverse engineered by reading the network log of
  6. https://www.qwant.com/ queries.
  7. This implementation is used by different qwant engines in the settings.yml::
  8. - name: qwant
  9. categories: general
  10. ...
  11. - name: qwant news
  12. categories: news
  13. ...
  14. - name: qwant images
  15. categories: images
  16. ...
  17. - name: qwant videos
  18. categories: videos
  19. ...
  20. """
  21. from datetime import (
  22. datetime,
  23. timedelta,
  24. )
  25. from json import loads
  26. from urllib.parse import urlencode
  27. from flask_babel import gettext
  28. # from searx import logger
  29. from searx.utils import match_language
  30. from searx.exceptions import SearxEngineAPIException
  31. from searx.network import raise_for_httperror
  32. #logger = logger.getChild('qwant')
  33. # about
  34. about = {
  35. "website": 'https://www.qwant.com/',
  36. "wikidata_id": 'Q14657870',
  37. "official_api_documentation": None,
  38. "use_official_api": True,
  39. "require_api_key": False,
  40. "results": 'JSON',
  41. }
  42. # engine dependent config
  43. categories = []
  44. paging = True
  45. supported_languages_url = about['website']
  46. category_to_keyword = {
  47. 'general': 'web',
  48. 'news': 'news',
  49. 'images': 'images',
  50. 'videos': 'videos',
  51. }
  52. # search-url
  53. url = 'https://api.qwant.com/v3/search/{keyword}?q={query}&count={count}&offset={offset}'
  54. def request(query, params):
  55. """Qwant search request"""
  56. keyword = category_to_keyword[categories[0]]
  57. count = 10 # web: count must be equal to 10
  58. if keyword == 'images':
  59. count = 50
  60. offset = (params['pageno'] - 1) * count
  61. # count + offset must be lower than 250
  62. offset = min(offset, 199)
  63. else:
  64. offset = (params['pageno'] - 1) * count
  65. # count + offset must be lower than 50
  66. offset = min(offset, 40)
  67. params['url'] = url.format(
  68. keyword = keyword,
  69. query = urlencode({'q': query}),
  70. offset = offset,
  71. count = count,
  72. )
  73. # add language tag
  74. if params['language'] != 'all':
  75. language = match_language(
  76. params['language'],
  77. # pylint: disable=undefined-variable
  78. supported_languages,
  79. language_aliases,
  80. )
  81. params['url'] += '&locale=' + language.replace('-', '_')
  82. params['raise_for_httperror'] = False
  83. return params
  84. def response(resp):
  85. """Get response from Qwant's search request"""
  86. # pylint: disable=too-many-locals, too-many-branches, too-many-statements
  87. keyword = category_to_keyword[categories[0]]
  88. results = []
  89. # load JSON result
  90. search_results = loads(resp.text)
  91. data = search_results.get('data', {})
  92. # check for an API error
  93. if search_results.get('status') != 'success':
  94. msg = ",".join(data.get('message', ['unknown', ]))
  95. raise SearxEngineAPIException('API error::' + msg)
  96. # raise for other errors
  97. raise_for_httperror(resp)
  98. if keyword == 'web':
  99. # The WEB query contains a list named 'mainline'. This list can contain
  100. # different result types (e.g. mainline[0]['type'] returns type of the
  101. # result items in mainline[0]['items']
  102. mainline = data.get('result', {}).get('items', {}).get('mainline', {})
  103. else:
  104. # Queries on News, Images and Videos do not have a list named 'mainline'
  105. # in the response. The result items are directly in the list
  106. # result['items'].
  107. mainline = data.get('result', {}).get('items', [])
  108. mainline = [
  109. {'type' : keyword, 'items' : mainline },
  110. ]
  111. # return empty array if there are no results
  112. if not mainline:
  113. return []
  114. for row in mainline:
  115. mainline_type = row.get('type', 'web')
  116. if mainline_type == 'ads':
  117. # ignore adds
  118. continue
  119. mainline_items = row.get('items', [])
  120. for item in mainline_items:
  121. title = item['title']
  122. res_url = item['url']
  123. if mainline_type == 'web':
  124. content = item['desc']
  125. results.append({
  126. 'title': title,
  127. 'url': res_url,
  128. 'content': content,
  129. })
  130. elif mainline_type == 'news':
  131. pub_date = datetime.fromtimestamp(item['date'], None)
  132. news_media = item.get('media', [])
  133. img_src = None
  134. if news_media:
  135. img_src = news_media[0].get('pict', {}).get('url', None)
  136. results.append({
  137. 'title': title,
  138. 'url': res_url,
  139. 'publishedDate': pub_date,
  140. 'img_src': img_src,
  141. })
  142. elif mainline_type == 'images':
  143. thumbnail = item['thumbnail']
  144. img_src = item['media']
  145. results.append({
  146. 'title': title,
  147. 'url': res_url,
  148. 'template': 'images.html',
  149. 'thumbnail_src': thumbnail,
  150. 'img_src': img_src,
  151. })
  152. elif mainline_type == 'videos':
  153. # some videos do not have a description: while quant-video
  154. # returns an empty string, such video from a quant-web query
  155. # miss the 'desc' key.
  156. content = item.get('desc', '')
  157. s, c = item.get('source',''), item.get('channel','')
  158. if content and (s or c):
  159. content += " // "
  160. if s:
  161. content += "%s: %s " % (gettext("Source"), s)
  162. if c:
  163. content += "//"
  164. if c:
  165. content += " %s: %s " % (gettext("Channel"), c)
  166. length = timedelta(seconds=item['duration'])
  167. pub_date = datetime.fromtimestamp(item['date'])
  168. thumbnail = item['thumbnail']
  169. # from some locations (DE and others?) the s2 link do
  170. # response a 'Please wait ..' but does not deliver the thumbnail
  171. thumbnail = thumbnail.replace(
  172. 'https://s2.qwant.com',
  173. 'https://s1.qwant.com', 1
  174. )
  175. results.append({
  176. 'title': title,
  177. 'url': res_url,
  178. 'content': content,
  179. 'publishedDate': pub_date,
  180. 'thumbnail': thumbnail,
  181. 'template': 'videos.html',
  182. 'length': length,
  183. })
  184. return results
  185. # get supported languages from their site
  186. def _fetch_supported_languages(resp):
  187. # list of regions is embedded in page as a js object
  188. response_text = resp.text
  189. response_text = response_text[response_text.find('INITIAL_PROPS'):]
  190. response_text = response_text[response_text.find('{'):response_text.find('</script>')]
  191. regions_json = loads(response_text)
  192. supported_languages = []
  193. for country, langs in regions_json['locales'].items():
  194. for lang in langs['langs']:
  195. lang_code = "{lang}-{country}".format(lang=lang, country=country)
  196. supported_languages.append(lang_code)
  197. return supported_languages