qwant.py 7.6 KB

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