qwant.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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. import babel
  29. from searx.exceptions import SearxEngineAPIException
  30. from searx.network import raise_for_httperror
  31. from searx.locales import get_engine_locale
  32. # about
  33. about = {
  34. "website": 'https://www.qwant.com/',
  35. "wikidata_id": 'Q14657870',
  36. "official_api_documentation": None,
  37. "use_official_api": True,
  38. "require_api_key": False,
  39. "results": 'JSON',
  40. }
  41. # engine dependent config
  42. categories = []
  43. paging = True
  44. supported_languages_url = about['website']
  45. qwant_categ = None # web|news|inages|videos
  46. # fmt: off
  47. qwant_news_locales = [
  48. 'ca_ad', 'ca_es', 'ca_fr', 'co_fr', 'de_at', 'de_ch', 'de_de', 'en_au',
  49. 'en_ca', 'en_gb', 'en_ie', 'en_my', 'en_nz', 'en_us', 'es_ad', 'es_ar',
  50. 'es_cl', 'es_co', 'es_es', 'es_mx', 'es_pe', 'eu_es', 'eu_fr', 'fc_ca',
  51. 'fr_ad', 'fr_be', 'fr_ca', 'fr_ch', 'fr_fr', 'it_ch', 'it_it', 'nl_be',
  52. 'nl_nl', 'pt_ad', 'pt_pt',
  53. ]
  54. # fmt: on
  55. # search-url
  56. url = 'https://api.qwant.com/v3/search/{keyword}?{query}&count={count}&offset={offset}'
  57. def request(query, params):
  58. """Qwant search request"""
  59. if not query:
  60. return None
  61. count = 10 # web: count must be equal to 10
  62. if qwant_categ == 'images':
  63. count = 50
  64. offset = (params['pageno'] - 1) * count
  65. # count + offset must be lower than 250
  66. offset = min(offset, 199)
  67. else:
  68. offset = (params['pageno'] - 1) * count
  69. # count + offset must be lower than 50
  70. offset = min(offset, 40)
  71. params['url'] = url.format(
  72. keyword=qwant_categ,
  73. query=urlencode({'q': query}),
  74. offset=offset,
  75. count=count,
  76. )
  77. # add quant's locale
  78. q_locale = get_engine_locale(params['language'], supported_languages, default='en_US')
  79. params['url'] += '&locale=' + q_locale
  80. params['raise_for_httperror'] = False
  81. return params
  82. def response(resp):
  83. """Get response from Qwant's search request"""
  84. # pylint: disable=too-many-locals, too-many-branches, too-many-statements
  85. results = []
  86. # load JSON result
  87. search_results = loads(resp.text)
  88. data = search_results.get('data', {})
  89. # check for an API error
  90. if search_results.get('status') != 'success':
  91. msg = ",".join(
  92. data.get(
  93. 'message',
  94. [
  95. 'unknown',
  96. ],
  97. )
  98. )
  99. raise SearxEngineAPIException('API error::' + msg)
  100. # raise for other errors
  101. raise_for_httperror(resp)
  102. if qwant_categ == 'web':
  103. # The WEB query contains a list named 'mainline'. This list can contain
  104. # different result types (e.g. mainline[0]['type'] returns type of the
  105. # result items in mainline[0]['items']
  106. mainline = data.get('result', {}).get('items', {}).get('mainline', {})
  107. else:
  108. # Queries on News, Images and Videos do not have a list named 'mainline'
  109. # in the response. The result items are directly in the list
  110. # result['items'].
  111. mainline = data.get('result', {}).get('items', [])
  112. mainline = [
  113. {'type': qwant_categ, 'items': mainline},
  114. ]
  115. # return empty array if there are no results
  116. if not mainline:
  117. return []
  118. for row in mainline:
  119. mainline_type = row.get('type', 'web')
  120. if mainline_type != qwant_categ:
  121. continue
  122. if mainline_type == 'ads':
  123. # ignore adds
  124. continue
  125. mainline_items = row.get('items', [])
  126. for item in mainline_items:
  127. title = item.get('title', None)
  128. res_url = item.get('url', None)
  129. if mainline_type == 'web':
  130. content = item['desc']
  131. results.append(
  132. {
  133. 'title': title,
  134. 'url': res_url,
  135. 'content': content,
  136. }
  137. )
  138. elif mainline_type == 'news':
  139. pub_date = item['date']
  140. if pub_date is not None:
  141. pub_date = datetime.fromtimestamp(pub_date)
  142. news_media = item.get('media', [])
  143. img_src = None
  144. if news_media:
  145. img_src = news_media[0].get('pict', {}).get('url', None)
  146. results.append(
  147. {
  148. 'title': title,
  149. 'url': res_url,
  150. 'publishedDate': pub_date,
  151. 'img_src': img_src,
  152. }
  153. )
  154. elif mainline_type == 'images':
  155. thumbnail = item['thumbnail']
  156. img_src = item['media']
  157. results.append(
  158. {
  159. 'title': title,
  160. 'url': res_url,
  161. 'template': 'images.html',
  162. 'thumbnail_src': thumbnail,
  163. 'img_src': img_src,
  164. }
  165. )
  166. elif mainline_type == 'videos':
  167. # some videos do not have a description: while qwant-video
  168. # returns an empty string, such video from a qwant-web query
  169. # miss the 'desc' key.
  170. d, s, c = item.get('desc'), item.get('source'), item.get('channel')
  171. content_parts = []
  172. if d:
  173. content_parts.append(d)
  174. if s:
  175. content_parts.append("%s: %s " % (gettext("Source"), s))
  176. if c:
  177. content_parts.append("%s: %s " % (gettext("Channel"), c))
  178. content = ' // '.join(content_parts)
  179. length = item['duration']
  180. if length is not None:
  181. length = timedelta(milliseconds=length)
  182. pub_date = item['date']
  183. if pub_date is not None:
  184. pub_date = datetime.fromtimestamp(pub_date)
  185. thumbnail = item['thumbnail']
  186. # from some locations (DE and others?) the s2 link do
  187. # response a 'Please wait ..' but does not deliver the thumbnail
  188. thumbnail = thumbnail.replace('https://s2.qwant.com', 'https://s1.qwant.com', 1)
  189. results.append(
  190. {
  191. 'title': title,
  192. 'url': res_url,
  193. 'content': content,
  194. 'publishedDate': pub_date,
  195. 'thumbnail': thumbnail,
  196. 'template': 'videos.html',
  197. 'length': length,
  198. }
  199. )
  200. return results
  201. def _fetch_supported_languages(resp):
  202. text = resp.text
  203. text = text[text.find('INITIAL_PROPS') :]
  204. text = text[text.find('{') : text.find('</script>')]
  205. q_initial_props = loads(text)
  206. q_locales = q_initial_props.get('locales')
  207. q_valid_locales = []
  208. for country, v in q_locales.items():
  209. for lang in v['langs']:
  210. _locale = "{lang}_{country}".format(lang=lang, country=country)
  211. if qwant_categ == 'news' and _locale.lower() not in qwant_news_locales:
  212. # qwant-news does not support all locales from qwant-web:
  213. continue
  214. q_valid_locales.append(_locale)
  215. supported_languages = {}
  216. for q_locale in q_valid_locales:
  217. try:
  218. locale = babel.Locale.parse(q_locale, sep='_')
  219. except babel.core.UnknownLocaleError:
  220. print("ERROR: can't determine babel locale of quant's locale %s" % q_locale)
  221. continue
  222. # note: supported_languages (dict)
  223. #
  224. # dict's key is a string build up from a babel.Locale object / the
  225. # notation 'xx-XX' (and 'xx') conforms to SearXNG's locale (and
  226. # language) notation and dict's values are the locale strings used by
  227. # the engine.
  228. searxng_locale = locale.language + '-' + locale.territory # --> params['language']
  229. supported_languages[searxng_locale] = q_locale
  230. return supported_languages