json_engine.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """The JSON engine is a *generic* engine with which it is possible to configure
  3. engines in the settings.
  4. Configuration
  5. =============
  6. Request:
  7. - :py:obj:`search_url`
  8. - :py:obj:`lang_all`
  9. - :py:obj:`soft_max_redirects`
  10. - :py:obj:`method`
  11. - :py:obj:`request_body`
  12. - :py:obj:`cookies`
  13. - :py:obj:`headers`
  14. Paging:
  15. - :py:obj:`paging`
  16. - :py:obj:`page_size`
  17. - :py:obj:`first_page_num`
  18. Time Range:
  19. - :py:obj:`time_range_support`
  20. - :py:obj:`time_range_url`
  21. - :py:obj:`time_range_map`
  22. Safe-Search:
  23. - :py:obj:`safe_search_support`
  24. - :py:obj:`safe_search_map`
  25. Response:
  26. - :py:obj:`title_html_to_text`
  27. - :py:obj:`content_html_to_text`
  28. - :py:obj:`no_result_for_http_status`
  29. JSON query:
  30. - :py:obj:`results_query`
  31. - :py:obj:`url_query`
  32. - :py:obj:`url_prefix`
  33. - :py:obj:`title_query`
  34. - :py:obj:`content_query`
  35. - :py:obj:`thumbnail_query`
  36. - :py:obj:`thumbnail_prefix`
  37. - :py:obj:`suggestion_query`
  38. Example
  39. =======
  40. Here is a simple example of a JSON engine configure in the :ref:`settings
  41. engine` section, further read :ref:`engines-dev`.
  42. .. code:: yaml
  43. - name : mdn
  44. engine : json_engine
  45. paging : True
  46. search_url : https://developer.mozilla.org/api/v1/search?q={query}&page={pageno}
  47. results_query : documents
  48. url_query : mdn_url
  49. url_prefix : https://developer.mozilla.org
  50. title_query : title
  51. content_query : summary
  52. Implementations
  53. ===============
  54. """
  55. from collections.abc import Iterable
  56. from json import loads
  57. from urllib.parse import urlencode
  58. from searx.utils import to_string, html_to_text
  59. from searx.network import raise_for_httperror
  60. search_url = None
  61. """
  62. Search URL of the engine. Example::
  63. https://example.org/?search={query}&page={pageno}{time_range}{safe_search}
  64. Replacements are:
  65. ``{query}``:
  66. Search terms from user.
  67. ``{pageno}``:
  68. Page number if engine supports paging :py:obj:`paging`
  69. ``{lang}``:
  70. ISO 639-1 language code (en, de, fr ..)
  71. ``{time_range}``:
  72. :py:obj:`URL parameter <time_range_url>` if engine :py:obj:`supports time
  73. range <time_range_support>`. The value for the parameter is taken from
  74. :py:obj:`time_range_map`.
  75. ``{safe_search}``:
  76. Safe-search :py:obj:`URL parameter <safe_search_map>` if engine
  77. :py:obj:`supports safe-search <safe_search_support>`. The ``{safe_search}``
  78. replacement is taken from the :py:obj:`safes_search_map`. Filter results::
  79. 0: none, 1: moderate, 2:strict
  80. If not supported, the URL parameter is an empty string.
  81. """
  82. lang_all = 'en'
  83. '''Replacement ``{lang}`` in :py:obj:`search_url` if language ``all`` is
  84. selected.
  85. '''
  86. no_result_for_http_status = []
  87. '''Return empty result for these HTTP status codes instead of throwing an error.
  88. .. code:: yaml
  89. no_result_for_http_status: []
  90. '''
  91. soft_max_redirects = 0
  92. '''Maximum redirects, soft limit. Record an error but don't stop the engine'''
  93. method = 'GET'
  94. '''Some engines might require to do POST requests for search.'''
  95. request_body = ''
  96. '''The body of the request. This can only be used if different :py:obj:`method`
  97. is set, e.g. ``POST``. For formatting see the documentation of :py:obj:`search_url`.
  98. Note: Curly brackets which aren't encapsulating a replacement placeholder
  99. must be escaped by doubling each ``{`` and ``}``.
  100. .. code:: yaml
  101. request_body: >-
  102. {{
  103. "search": "{query}",
  104. "page": {pageno},
  105. "extra": {{
  106. "time_range": {time_range},
  107. "rating": "{safe_search}"
  108. }}
  109. }}
  110. '''
  111. cookies = {}
  112. '''Some engines might offer different result based on cookies.
  113. Possible use-case: To set safesearch cookie.'''
  114. headers = {}
  115. '''Some engines might offer different result based on cookies or headers.
  116. Possible use-case: To set safesearch cookie or header to moderate.'''
  117. paging = False
  118. '''Engine supports paging [True or False].'''
  119. page_size = 1
  120. '''Number of results on each page. Only needed if the site requires not a page
  121. number, but an offset.'''
  122. first_page_num = 1
  123. '''Number of the first page (usually 0 or 1).'''
  124. results_query = ''
  125. '''JSON query for the list of result items.
  126. The query string is a slash `/` separated path of JSON key names.
  127. Array entries can be specified using the index or can be omitted entirely,
  128. in which case each entry is considered -
  129. most implementations will default to the first entry in this case.
  130. '''
  131. url_query = None
  132. '''JSON query of result's ``url``. For the query string documentation see :py:obj:`results_query`'''
  133. url_prefix = ""
  134. '''String to prepend to the result's ``url``.'''
  135. title_query = None
  136. '''JSON query of result's ``title``. For the query string documentation see :py:obj:`results_query`'''
  137. content_query = None
  138. '''JSON query of result's ``content``. For the query string documentation see :py:obj:`results_query`'''
  139. thumbnail_query = False
  140. '''JSON query of result's ``thumbnail``. For the query string documentation see :py:obj:`results_query`'''
  141. thumbnail_prefix = ''
  142. '''String to prepend to the result's ``thumbnail``.'''
  143. suggestion_query = ''
  144. '''JSON query of result's ``suggestion``. For the query string documentation see :py:obj:`results_query`'''
  145. title_html_to_text = False
  146. '''Extract text from a HTML title string'''
  147. content_html_to_text = False
  148. '''Extract text from a HTML content string'''
  149. time_range_support = False
  150. '''Engine supports search time range.'''
  151. time_range_url = '&hours={time_range_val}'
  152. '''Time range URL parameter in the in :py:obj:`search_url`. If no time range is
  153. requested by the user, the URL parameter is an empty string. The
  154. ``{time_range_val}`` replacement is taken from the :py:obj:`time_range_map`.
  155. .. code:: yaml
  156. time_range_url : '&days={time_range_val}'
  157. '''
  158. time_range_map = {
  159. 'day': 24,
  160. 'week': 24 * 7,
  161. 'month': 24 * 30,
  162. 'year': 24 * 365,
  163. }
  164. '''Maps time range value from user to ``{time_range_val}`` in
  165. :py:obj:`time_range_url`.
  166. .. code:: yaml
  167. time_range_map:
  168. day: 1
  169. week: 7
  170. month: 30
  171. year: 365
  172. '''
  173. safe_search_support = False
  174. '''Engine supports safe-search.'''
  175. safe_search_map = {0: '&filter=none', 1: '&filter=moderate', 2: '&filter=strict'}
  176. '''Maps safe-search value to ``{safe_search}`` in :py:obj:`search_url`.
  177. .. code:: yaml
  178. safesearch: true
  179. safes_search_map:
  180. 0: '&filter=none'
  181. 1: '&filter=moderate'
  182. 2: '&filter=strict'
  183. '''
  184. def iterate(iterable):
  185. if isinstance(iterable, dict):
  186. items = iterable.items()
  187. else:
  188. items = enumerate(iterable)
  189. for index, value in items:
  190. yield str(index), value
  191. def is_iterable(obj):
  192. if isinstance(obj, str):
  193. return False
  194. return isinstance(obj, Iterable)
  195. def parse(query): # pylint: disable=redefined-outer-name
  196. q = [] # pylint: disable=invalid-name
  197. for part in query.split('/'):
  198. if part == '':
  199. continue
  200. q.append(part)
  201. return q
  202. def do_query(data, q): # pylint: disable=invalid-name
  203. ret = []
  204. if not q:
  205. return ret
  206. qkey = q[0]
  207. for key, value in iterate(data):
  208. if len(q) == 1:
  209. if key == qkey:
  210. ret.append(value)
  211. elif is_iterable(value):
  212. ret.extend(do_query(value, q))
  213. else:
  214. if not is_iterable(value):
  215. continue
  216. if key == qkey:
  217. ret.extend(do_query(value, q[1:]))
  218. else:
  219. ret.extend(do_query(value, q))
  220. return ret
  221. def query(data, query_string):
  222. q = parse(query_string)
  223. return do_query(data, q)
  224. def request(query, params): # pylint: disable=redefined-outer-name
  225. '''Build request parameters (see :ref:`engine request`).'''
  226. lang = lang_all
  227. if params['language'] != 'all':
  228. lang = params['language'][:2]
  229. time_range = ''
  230. if params.get('time_range'):
  231. time_range_val = time_range_map.get(params.get('time_range'))
  232. time_range = time_range_url.format(time_range_val=time_range_val)
  233. safe_search = ''
  234. if params['safesearch']:
  235. safe_search = safe_search_map[params['safesearch']]
  236. fp = { # pylint: disable=invalid-name
  237. 'query': urlencode({'q': query})[2:],
  238. 'lang': lang,
  239. 'pageno': (params['pageno'] - 1) * page_size + first_page_num,
  240. 'time_range': time_range,
  241. 'safe_search': safe_search,
  242. }
  243. params['cookies'].update(cookies)
  244. params['headers'].update(headers)
  245. params['url'] = search_url.format(**fp)
  246. params['method'] = method
  247. if request_body:
  248. # don't url-encode the query if it's in the request body
  249. fp['query'] = query
  250. params['data'] = request_body.format(**fp)
  251. params['soft_max_redirects'] = soft_max_redirects
  252. params['raise_for_httperror'] = False
  253. return params
  254. def identity(arg):
  255. return arg
  256. def extract_response_info(result):
  257. title_filter = html_to_text if title_html_to_text else identity
  258. content_filter = html_to_text if content_html_to_text else identity
  259. tmp_result = {}
  260. try:
  261. url = query(result, url_query)[0]
  262. tmp_result['url'] = url_prefix + to_string(url)
  263. title = query(result, title_query)[0]
  264. tmp_result['title'] = title_filter(to_string(title))
  265. except: # pylint: disable=bare-except
  266. return None
  267. try:
  268. content = query(result, content_query)[0]
  269. tmp_result['content'] = content_filter(to_string(content))
  270. except: # pylint: disable=bare-except
  271. tmp_result['content'] = ""
  272. try:
  273. if thumbnail_query:
  274. thumbnail_query_result = query(result, thumbnail_query)[0]
  275. tmp_result['thumbnail'] = thumbnail_prefix + to_string(thumbnail_query_result)
  276. except: # pylint: disable=bare-except
  277. pass
  278. return tmp_result
  279. def response(resp):
  280. '''Scrap *results* from the response (see :ref:`engine results`).'''
  281. results = []
  282. if no_result_for_http_status and resp.status_code in no_result_for_http_status:
  283. return results
  284. raise_for_httperror(resp)
  285. if not resp.text:
  286. return results
  287. json = loads(resp.text)
  288. is_onion = 'onions' in categories
  289. if results_query:
  290. rs = query(json, results_query) # pylint: disable=invalid-name
  291. if not rs:
  292. return results
  293. rs = rs[0] # pylint: disable=invalid-name
  294. else:
  295. rs = json # pylint: disable=invalid-name
  296. for result in rs:
  297. tmp_result = extract_response_info(result)
  298. if not tmp_result:
  299. continue
  300. if is_onion:
  301. tmp_result['is_onion'] = True
  302. results.append(tmp_result)
  303. if not suggestion_query:
  304. return results
  305. for suggestion in query(json, suggestion_query):
  306. results.append({'suggestion': suggestion})
  307. return results