webadapter.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. from typing import Dict, List, Optional, Tuple
  2. from searx.exceptions import SearxParameterException
  3. from searx.webutils import VALID_LANGUAGE_CODE
  4. from searx.query import RawTextQuery
  5. from searx.engines import categories, engines
  6. from searx.search import SearchQuery, EngineRef
  7. from searx.preferences import Preferences, is_locked
  8. # remove duplicate queries.
  9. # FIXME: does not fix "!music !soundcloud", because the categories are 'none' and 'music'
  10. def deduplicate_engineref_list(engineref_list: List[EngineRef]) -> List[EngineRef]:
  11. engineref_dict = {q.category + '|' + q.name: q for q in engineref_list}
  12. return list(engineref_dict.values())
  13. def validate_engineref_list(engineref_list: List[EngineRef], preferences: Preferences)\
  14. -> Tuple[List[EngineRef], List[EngineRef], List[EngineRef]]:
  15. """Validate query_engines according to the preferences
  16. Returns:
  17. List[EngineRef]: list of existing engines with a validated token
  18. List[EngineRef]: list of unknown engine
  19. List[EngineRef]: list of engine with invalid token according to the preferences
  20. """
  21. valid = []
  22. unknown = []
  23. no_token = []
  24. for engineref in engineref_list:
  25. if engineref.name not in engines:
  26. unknown.append(engineref)
  27. continue
  28. engine = engines[engineref.name]
  29. if not preferences.validate_token(engine):
  30. no_token.append(engineref)
  31. continue
  32. valid.append(engineref)
  33. return valid, unknown, no_token
  34. def parse_pageno(form: Dict[str, str]) -> int:
  35. pageno_param = form.get('pageno', '1')
  36. if not pageno_param.isdigit() or int(pageno_param) < 1:
  37. raise SearxParameterException('pageno', pageno_param)
  38. return int(pageno_param)
  39. def parse_lang(preferences: Preferences, form: Dict[str, str], raw_text_query: RawTextQuery) -> str:
  40. if is_locked('language'):
  41. return preferences.get_value('langueage')
  42. # get language
  43. # set specific language if set on request, query or preferences
  44. # TODO support search with multible languages
  45. if len(raw_text_query.languages):
  46. query_lang = raw_text_query.languages[-1]
  47. elif 'language' in form:
  48. query_lang = form.get('language')
  49. else:
  50. query_lang = preferences.get_value('language')
  51. # check language
  52. if not VALID_LANGUAGE_CODE.match(query_lang):
  53. raise SearxParameterException('language', query_lang)
  54. return query_lang
  55. def parse_safesearch(preferences: Preferences, form: Dict[str, str]) -> int:
  56. if is_locked('safesearch'):
  57. return preferences.get_value('safesearch')
  58. if 'safesearch' in form:
  59. query_safesearch = form.get('safesearch')
  60. # first check safesearch
  61. if not query_safesearch.isdigit():
  62. raise SearxParameterException('safesearch', query_safesearch)
  63. query_safesearch = int(query_safesearch)
  64. else:
  65. query_safesearch = preferences.get_value('safesearch')
  66. # safesearch : second check
  67. if query_safesearch < 0 or query_safesearch > 2:
  68. raise SearxParameterException('safesearch', query_safesearch)
  69. return query_safesearch
  70. def parse_time_range(form: Dict[str, str]) -> Optional[str]:
  71. query_time_range = form.get('time_range')
  72. # check time_range
  73. query_time_range = None if query_time_range in ('', 'None') else query_time_range
  74. if query_time_range not in (None, 'day', 'week', 'month', 'year'):
  75. raise SearxParameterException('time_range', query_time_range)
  76. return query_time_range
  77. def parse_timeout(form: Dict[str, str], raw_text_query: RawTextQuery) -> Optional[float]:
  78. timeout_limit = raw_text_query.timeout_limit
  79. if timeout_limit is None:
  80. timeout_limit = form.get('timeout_limit')
  81. if timeout_limit is None or timeout_limit in ['None', '']:
  82. return None
  83. try:
  84. return float(timeout_limit)
  85. except ValueError as e:
  86. raise SearxParameterException('timeout_limit', timeout_limit) from e
  87. def parse_category_form(query_categories: List[str], name: str, value: str) -> None:
  88. if name == 'categories':
  89. query_categories.extend(categ for categ in map(str.strip, value.split(',')) if categ in categories)
  90. elif name.startswith('category_'):
  91. category = name[9:]
  92. # if category is not found in list, skip
  93. if category not in categories:
  94. return
  95. if value != 'off':
  96. # add category to list
  97. query_categories.append(category)
  98. elif category in query_categories:
  99. # remove category from list if property is set to 'off'
  100. query_categories.remove(category)
  101. def get_selected_categories(preferences: Preferences, form: Optional[Dict[str, str]]) -> List[str]:
  102. selected_categories = []
  103. if not is_locked('categories') and form is not None:
  104. for name, value in form.items():
  105. parse_category_form(selected_categories, name, value)
  106. # if no category is specified for this search,
  107. # using user-defined default-configuration which
  108. # (is stored in cookie)
  109. if not selected_categories:
  110. cookie_categories = preferences.get_value('categories')
  111. for ccateg in cookie_categories:
  112. selected_categories.append(ccateg)
  113. # if still no category is specified, using general
  114. # as default-category
  115. if not selected_categories:
  116. selected_categories = ['general']
  117. return selected_categories
  118. def get_engineref_from_category_list(category_list: List[str], disabled_engines: List[str]) -> List[EngineRef]:
  119. result = []
  120. for categ in category_list:
  121. result.extend(EngineRef(engine.name, categ)
  122. for engine in categories[categ]
  123. if (engine.name, categ) not in disabled_engines)
  124. return result
  125. def parse_generic(preferences: Preferences, form: Dict[str, str], disabled_engines: List[str]) -> List[EngineRef]:
  126. query_engineref_list = []
  127. query_categories = []
  128. # set categories/engines
  129. explicit_engine_list = False
  130. if not is_locked('categories'):
  131. # parse the form only if the categories are not locked
  132. for pd_name, pd in form.items():
  133. if pd_name == 'engines':
  134. pd_engines = [EngineRef(engine_name, engines[engine_name].categories[0])
  135. for engine_name in map(str.strip, pd.split(',')) if engine_name in engines]
  136. if pd_engines:
  137. query_engineref_list.extend(pd_engines)
  138. explicit_engine_list = True
  139. else:
  140. parse_category_form(query_categories, pd_name, pd)
  141. if explicit_engine_list:
  142. # explicit list of engines with the "engines" parameter in the form
  143. if query_categories:
  144. # add engines from referenced by the "categories" parameter and the "category_*"" parameters
  145. query_engineref_list.extend(get_engineref_from_category_list(query_categories, disabled_engines))
  146. else:
  147. # no "engines" parameters in the form
  148. if not query_categories:
  149. # and neither "categories" parameter nor "category_*"" parameters in the form
  150. # -> get the categories from the preferences (the cookies or the settings)
  151. query_categories = get_selected_categories(preferences, None)
  152. # using all engines for that search, which are
  153. # declared under the specific categories
  154. query_engineref_list.extend(get_engineref_from_category_list(query_categories, disabled_engines))
  155. return query_engineref_list
  156. def get_search_query_from_webapp(preferences: Preferences, form: Dict[str, str])\
  157. -> Tuple[SearchQuery, RawTextQuery, List[EngineRef], List[EngineRef]]:
  158. # no text for the query ?
  159. if not form.get('q'):
  160. raise SearxParameterException('q', '')
  161. # set blocked engines
  162. disabled_engines = preferences.engines.get_disabled()
  163. # parse query, if tags are set, which change
  164. # the serch engine or search-language
  165. raw_text_query = RawTextQuery(form['q'], disabled_engines)
  166. # set query
  167. query = raw_text_query.getQuery()
  168. query_pageno = parse_pageno(form)
  169. query_lang = parse_lang(preferences, form, raw_text_query)
  170. query_safesearch = parse_safesearch(preferences, form)
  171. query_time_range = parse_time_range(form)
  172. query_timeout = parse_timeout(form, raw_text_query)
  173. external_bang = raw_text_query.external_bang
  174. if not is_locked('categories') and raw_text_query.enginerefs and raw_text_query.specific:
  175. # if engines are calculated from query,
  176. # set categories by using that informations
  177. query_engineref_list = raw_text_query.enginerefs
  178. else:
  179. # otherwise, using defined categories to
  180. # calculate which engines should be used
  181. query_engineref_list = parse_generic(preferences, form, disabled_engines)
  182. query_engineref_list = deduplicate_engineref_list(query_engineref_list)
  183. query_engineref_list, query_engineref_list_unknown, query_engineref_list_notoken =\
  184. validate_engineref_list(query_engineref_list, preferences)
  185. return (SearchQuery(query, query_engineref_list, query_lang, query_safesearch, query_pageno,
  186. query_time_range, query_timeout, external_bang=external_bang),
  187. raw_text_query,
  188. query_engineref_list_unknown,
  189. query_engineref_list_notoken)