presearch.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """Presearch supports the search types listed in :py:obj:`search_type` (general,
  3. images, videos, news).
  4. Configured ``presarch`` engines:
  5. .. code:: yaml
  6. - name: presearch
  7. engine: presearch
  8. search_type: search
  9. categories: [general, web]
  10. - name: presearch images
  11. ...
  12. search_type: images
  13. categories: [images, web]
  14. - name: presearch videos
  15. ...
  16. search_type: videos
  17. categories: [general, web]
  18. - name: presearch news
  19. ...
  20. search_type: news
  21. categories: [news, web]
  22. .. hint::
  23. By default Presearch's video category is intentionally placed into::
  24. categories: [general, web]
  25. Search type ``video``
  26. =====================
  27. The results in the video category are most often links to pages that contain a
  28. video, for instance many links from Preasearch's video category link content
  29. from facebook (aka Meta) or Twitter (aka X). Since these are not real links to
  30. video streams SearXNG can't use the video template for this and if SearXNG can't
  31. use this template, then the user doesn't want to see these hits in the videos
  32. category.
  33. Languages & Regions
  34. ===================
  35. In Presearch there are languages for the UI and regions for narrowing down the
  36. search. If we set "auto" for the region in the WEB-UI of Presearch and cookie
  37. ``use_local_search_results=false``, then the defaults are set for both (the
  38. language and the region) from the ``Accept-Language`` header.
  39. Since the region is already "auto" by default, we only need to set the
  40. ``use_local_search_results`` cookie and send the ``Accept-Language`` header. We
  41. have to set these values in both requests we send to Presearch; in the first
  42. request to get the request-ID from Presearch and in the final request to get the
  43. result list (see ``send_accept_language_header``).
  44. Implementations
  45. ===============
  46. """
  47. from urllib.parse import urlencode
  48. from searx import locales
  49. from searx.network import get
  50. from searx.utils import gen_useragent, html_to_text
  51. about = {
  52. "website": "https://presearch.io",
  53. "wikidiata_id": "Q7240905",
  54. "official_api_documentation": "https://docs.presearch.io/nodes/api",
  55. "use_official_api": False,
  56. "require_api_key": False,
  57. "results": "JSON",
  58. }
  59. paging = True
  60. safesearch = True
  61. time_range_support = True
  62. send_accept_language_header = True
  63. categories = ["general", "web"] # general, images, videos, news
  64. search_type = "search"
  65. """must be any of ``search``, ``images``, ``videos``, ``news``"""
  66. base_url = "https://presearch.com"
  67. safesearch_map = {0: 'false', 1: 'true', 2: 'true'}
  68. def init(_):
  69. if search_type not in ['search', 'images', 'videos', 'news']:
  70. raise ValueError(f'presearch search_type: {search_type}')
  71. def _get_request_id(query, params):
  72. args = {
  73. "q": query,
  74. "page": params["pageno"],
  75. }
  76. if params["time_range"]:
  77. args["time"] = params["time_range"]
  78. url = f"{base_url}/{search_type}?{urlencode(args)}"
  79. headers = {
  80. 'User-Agent': gen_useragent(),
  81. 'Cookie': (
  82. f"b=1;"
  83. f" presearch_session=;"
  84. f" use_local_search_results=false;"
  85. f" use_safe_search={safesearch_map[params['safesearch']]}"
  86. ),
  87. }
  88. if params['searxng_locale'] != 'all':
  89. l = locales.get_locale(params['searxng_locale'])
  90. # Presearch narrows down the search by region. In SearXNG when the user
  91. # does not set a region (e.g. 'en-CA' / canada) we cannot hand over a region.
  92. # We could possibly use searx.locales.get_official_locales to determine
  93. # in which regions this language is an official one, but then we still
  94. # wouldn't know which region should be given more weight / Presearch
  95. # performs an IP-based geolocation of the user, we don't want that in
  96. # SearXNG ;-)
  97. if l.territory:
  98. headers['Accept-Language'] = f"{l.language}-{l.territory},{l.language};" "q=0.9,*;" "q=0.5"
  99. resp_text = get(url, headers=headers).text # type: ignore
  100. for line in resp_text.split("\n"):
  101. if "window.searchId = " in line:
  102. return line.split("= ")[1][:-1].replace('"', "")
  103. return None
  104. def request(query, params):
  105. request_id = _get_request_id(query, params)
  106. params["headers"]["Accept"] = "application/json"
  107. params["url"] = f"{base_url}/results?id={request_id}"
  108. return params
  109. def _strip_leading_strings(text):
  110. for x in ['wikipedia', 'google']:
  111. if text.lower().endswith(x):
  112. text = text[: -len(x)]
  113. return text.strip()
  114. def parse_search_query(json_results):
  115. results = []
  116. for item in json_results.get('specialSections', {}).get('topStoriesCompact', {}).get('data', []):
  117. result = {
  118. 'url': item['link'],
  119. 'title': item['title'],
  120. 'thumbnail': item['image'],
  121. 'content': '',
  122. 'metadata': item.get('source'),
  123. }
  124. results.append(result)
  125. for item in json_results.get('standardResults', []):
  126. result = {
  127. 'url': item['link'],
  128. 'title': item['title'],
  129. 'content': html_to_text(item['description']),
  130. }
  131. results.append(result)
  132. info = json_results.get('infoSection', {}).get('data')
  133. if info:
  134. attributes = []
  135. for item in info.get('about', []):
  136. text = html_to_text(item)
  137. if ':' in text:
  138. # split text into key / value
  139. label, value = text.split(':', 1)
  140. else:
  141. # In other languages (tested with zh-TW) a colon is represented
  142. # by a different symbol --> then we split at the first space.
  143. label, value = text.split(' ', 1)
  144. label = label[:-1]
  145. value = _strip_leading_strings(value)
  146. attributes.append({'label': label, 'value': value})
  147. content = []
  148. for item in [info.get('subtitle'), info.get('description')]:
  149. if not item:
  150. continue
  151. item = _strip_leading_strings(html_to_text(item))
  152. if item:
  153. content.append(item)
  154. results.append(
  155. {
  156. 'infobox': info['title'],
  157. 'id': info['title'],
  158. 'img_src': info.get('image'),
  159. 'content': ' | '.join(content),
  160. 'attributes': attributes,
  161. }
  162. )
  163. return results
  164. def response(resp):
  165. results = []
  166. json_resp = resp.json()
  167. if search_type == 'search':
  168. results = parse_search_query(json_resp.get('results'))
  169. elif search_type == 'images':
  170. for item in json_resp.get('images', []):
  171. results.append(
  172. {
  173. 'template': 'images.html',
  174. 'title': item['title'],
  175. 'url': item.get('link'),
  176. 'img_src': item.get('image'),
  177. 'thumbnail_src': item.get('thumbnail'),
  178. }
  179. )
  180. elif search_type == 'videos':
  181. # The results in the video category are most often links to pages that contain
  182. # a video and not to a video stream --> SearXNG can't use the video template.
  183. for item in json_resp.get('videos', []):
  184. metadata = [x for x in [item.get('description'), item.get('duration')] if x]
  185. results.append(
  186. {
  187. 'title': item['title'],
  188. 'url': item.get('link'),
  189. 'content': '',
  190. 'metadata': ' / '.join(metadata),
  191. 'thumbnail': item.get('image'),
  192. }
  193. )
  194. elif search_type == 'news':
  195. for item in json_resp.get('news', []):
  196. metadata = [x for x in [item.get('source'), item.get('time')] if x]
  197. results.append(
  198. {
  199. 'title': item['title'],
  200. 'url': item.get('link'),
  201. 'content': item.get('description', ''),
  202. 'metadata': ' / '.join(metadata),
  203. 'thumbnail': item.get('image'),
  204. }
  205. )
  206. return results